Debian Codegraph @

CodeLite/SocketAPI/clSocketBase.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : clSocketBase.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #include "clSocketBase.h"
27
28 #include "file_logger.h"
29
30 #include <cerrno>
31 #include <cstdio>
32 #include <memory>
33 #include <sstream>
34
35 #ifndef _WIN32
36 #include <fcntl.h>
37 #include <string.h>
38 #include <sys/select.h>
39 #include <sys/socket.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42 #endif
43
44 clSocketBase::clSocketBase(socket_t sockfd)
45 : m_socket(sockfd)
46 , m_closeOnExit(true)
47 {
48 }
49
50 clSocketBase::~clSocketBase() { DestroySocket(); }
51
52 void clSocketBase::Initialize()
53 {
54 #ifdef _WIN32
55 WSADATA wsa;
56 WSAStartup(MAKEWORD(2, 2), &wsa);
57 #endif
58 }
59
60 // Read API
61 int clSocketBase::Read(wxMemoryBuffer& content, long timeout)
62 {
63 content.Clear();
64
65 char buffer[4096];
66 timeout = (timeout * 1000); // convert to MS
67 while(true && timeout) {
68 int rc = SelectReadMS(10);
69 timeout -= 10;
70 if(rc == kSuccess) {
71 memset(buffer, 0x0, sizeof(buffer));
72 int bytesRead = recv(m_socket, buffer, sizeof(buffer), 0);
73 if(bytesRead < 0) {
74 const int err = GetLastError();
75
76 if(eWouldBlock != err) {
77 // Error
78 throw clSocketException("Read failed: " + error(err));
79 }
80
81 } else if(bytesRead == 0) {
82 // connection closed
83 return kError;
84
85 } else {
86 content.AppendData(buffer, bytesRead);
87 continue;
88 }
89 } else {
90 if(content.IsEmpty())
91 continue; // keep waiting until time ends
92 else
93 return kSuccess; // we already read our content
94 }
95 }
96 return kTimeout;
97 }
98
99 int clSocketBase::Read(wxString& content, const wxMBConv& conv, long timeout)
100 {
101 wxMemoryBuffer mb;
102 int rc = Read(mb, timeout);
103 if(rc == kSuccess) {
104 content = wxString((const char*)mb.GetData(), conv, mb.GetDataLen());
105 }
106 return rc;
107 }
108
109 int clSocketBase::Read(char* buffer, size_t bufferSize, size_t& bytesRead, long timeout)
110 {
111 if(SelectRead(timeout) == kTimeout) {
112 return kTimeout;
113 }
114 memset(buffer, 0, bufferSize);
115 const int res = ::recv(m_socket, buffer, bufferSize, 0);
116
117 if(res < 0) {
118 const int err = GetLastError();
119 if(eWouldBlock == err) {
120 return kTimeout;
121 }
122
123 throw clSocketException("Read failed: " + error(err));
124 } else if(0 == res) {
125 throw clSocketException("Read failed: " + error());
126 }
127
128 bytesRead = static_cast<size_t>(res);
129 return kSuccess;
130 }
131
132 int clSocketBase::SelectRead(long seconds)
133 {
134 if(seconds == -1) {
135 return kSuccess;
136 }
137
138 if(m_socket == INVALID_SOCKET) {
139 throw clSocketException("Invalid socket!");
140 }
141
142 struct timeval tv = { seconds, 0 };
143
144 fd_set readfds;
145 FD_ZERO(&readfds);
146 FD_SET(m_socket, &readfds);
147 int rc = select(m_socket + 1, &readfds, NULL, NULL, &tv);
148 if(rc == 0) {
149 // timeout
150 return kTimeout;
151
152 } else if(rc < 0) {
153 // an error occurred
154 throw clSocketException("SelectRead failed: " + error());
155
156 } else {
157 // we got something to read
158 return kSuccess;
159 }
160 }
161
162 // Send API
163 void clSocketBase::Send(const wxString& msg, const wxMBConv& conv)
164 {
165 if(m_socket == INVALID_SOCKET) {
166 throw clSocketException("Invalid socket!");
167 }
168 wxCharBuffer cb = msg.mb_str(conv).data();
169 wxMemoryBuffer mb;
170 mb.AppendData(cb.data(), cb.length());
171 Send(mb);
172 }
173
174 void clSocketBase::Send(const std::string& msg)
175 {
176 if(m_socket == INVALID_SOCKET) {
177 throw clSocketException("Invalid socket!");
178 }
179 wxMemoryBuffer mb;
180 mb.AppendData(msg.c_str(), msg.length());
181 Send(mb);
182 }
183
184 void clSocketBase::Send(const wxMemoryBuffer& msg)
185 {
186 if(m_socket == INVALID_SOCKET) {
187 throw clSocketException("Invalid socket!");
188 }
189 char* pdata = (char*)msg.GetData();
190 int bytesLeft = msg.GetDataLen();
191
192 std::string str(pdata, bytesLeft);
193 LOG_IF_TRACE
194 {
195 clDEBUG1() << "Sending buffer:" << str << endl;
196 clDEBUG1() << "Message length:" << str.length() << endl;
197 }
198 while(bytesLeft) {
199 if(SelectWriteMS(100) == kTimeout) {
200 continue;
201 }
202 int bytesSent = ::send(m_socket, (const char*)pdata, bytesLeft, 0);
203 LOG_IF_TRACE { clDEBUG1() << "::send() completed. number of bytes sent:" << bytesSent << endl; }
204
205 if(bytesSent <= 0) {
206 throw clSocketException("Send error: " + error());
207 }
208 pdata += bytesSent;
209 bytesLeft -= bytesSent;
210 }
211 }
212
213 int clSocketBase::GetLastError()
214 {
215 #ifdef _WIN32
216 return ::WSAGetLastError();
217 #else
218 return errno;
219 #endif
220 }
221
222 std::string clSocketBase::error() { return error(GetLastError()); }
223
224 std::string clSocketBase::error(const int errorCode)
225 {
226 std::string err;
227 #ifdef _WIN32
228 // Get the error message, if any.
229 if(errorCode == 0)
230 return "No error message has been recorded";
231
232 LPSTR messageBuffer = nullptr;
233 size_t size =
234 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
235 NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
236
237 std::string message(messageBuffer, size);
238
239 // Free the buffer.
240 LocalFree(messageBuffer);
241 err = message;
242 #else
243 err = strerror(errorCode);
244 #endif
245 return err;
246 }
247
248 void clSocketBase::DestroySocket()
249 {
250 if(IsCloseOnExit()) {
251 if(m_socket != INVALID_SOCKET) {
252 #ifdef _WIN32
253 ::shutdown(m_socket, 2);
254 ::closesocket(m_socket);
255 #else
256 ::shutdown(m_socket, 2);
257 ::close(m_socket);
258 #endif
259 }
260 }
261 m_socket = INVALID_SOCKET;
262 }
263
264 int clSocketBase::ReadMessage(wxString& message, int timeout)
265 {
266 // send the length in string form to avoid binary / arch differences between remote and local machine
267 char msglen[11];
268 memset(msglen, 0, sizeof(msglen));
269
270 size_t message_len(0);
271 size_t bytesRead(0);
272 int rc = Read((char*)msglen, sizeof(msglen) - 1, bytesRead, timeout);
273 if(rc != kSuccess) {
274 // timeout
275 return rc;
276 }
277
278 // convert the string to int
279 message_len = ::atoi(msglen);
280
281 bytesRead = 0;
282 std::unique_ptr<char> pBuff(new char[message_len]);
283
284 // read the entire amount we need
285 int bytesLeft = message_len;
286 int totalRead = 0;
287 while(bytesLeft > 0) {
288 rc = Read(pBuff.get() + totalRead, bytesLeft, bytesRead, timeout);
289 if(rc != kSuccess) {
290 return rc;
291
292 } else {
293 bytesLeft -= bytesRead;
294 totalRead += bytesRead;
295 bytesRead = 0;
296 }
297 }
298
299 message.assign(pBuff.get(), message_len);
300 return kSuccess;
301 }
302
303 void clSocketBase::WriteMessage(const wxString& message)
304 {
305 if(m_socket == INVALID_SOCKET) {
306 throw clSocketException("Invalid socket!");
307 }
308
309 // Write the message length
310 std::string c_str = message.mb_str(wxConvUTF8).data();
311 int len = c_str.length();
312
313 // send the length in string form to avoid binary / arch differences between remote and local machine
314 char msglen[11];
315 memset(msglen, 0, sizeof(msglen));
316 sprintf(msglen, "%010d", len);
317 // send it without the NULL byte
318 if(::send(m_socket, msglen, sizeof(msglen) - 1, 0) < 0) {
319 throw clSocketException("Send error: " + error(errno));
320 }
321
322 // now send the actual data
323 Send(c_str);
324 }
325
326 socket_t clSocketBase::Release()
327 {
328 int fd = m_socket;
329 m_socket = INVALID_SOCKET;
330 return fd;
331 }
332
333 void clSocketBase::MakeSocketBlocking(bool blocking)
334 {
335 #ifndef __WXMSW__
336 // set socket to non-blocking mode
337 int flags;
338 flags = ::fcntl(m_socket, F_GETFL);
339 if(blocking) {
340 flags &= ~O_NONBLOCK;
341 } else {
342 flags |= O_NONBLOCK;
343 }
344 ::fcntl(m_socket, F_SETFL, flags);
345 #else
346 u_long iMode = blocking ? 0 : 1;
347 ::ioctlsocket(m_socket, FIONBIO, &iMode);
348 #endif
349 }
350
351 int clSocketBase::SelectWriteMS(long milliSeconds)
352 {
353 if(milliSeconds == -1) {
354 return kSuccess;
355 }
356
357 if(m_socket == INVALID_SOCKET) {
358 throw clSocketException("Invalid socket!");
359 }
360
361 struct timeval tv;
362 tv.tv_sec = milliSeconds / 1000;
363 tv.tv_usec = (milliSeconds % 1000) * 1000;
364
365 fd_set write_set;
366 FD_ZERO(&write_set);
367 FD_SET(m_socket, &write_set);
368 errno = 0;
369 int rc = select(m_socket + 1, NULL, &write_set, NULL, &tv);
370 if(rc == 0) {
371 // timeout
372 return kTimeout;
373
374 } else if(rc < 0) {
375 // an error occurred
376 throw clSocketException("SelectWriteMS failed: " + error());
377
378 } else {
379 // we got something to read
380 return kSuccess;
381 }
382 }
383
384 int clSocketBase::SelectWrite(long seconds)
385 {
386 if(seconds == -1) {
387 return kSuccess;
388 }
389
390 if(m_socket == INVALID_SOCKET) {
391 throw clSocketException("Invalid socket!");
392 }
393
394 struct timeval tv = { seconds, 0 };
395
396 fd_set write_set;
397 FD_ZERO(&write_set);
398 FD_SET(m_socket, &write_set);
399 errno = 0;
400 int rc = select(m_socket + 1, NULL, &write_set, NULL, &tv);
401 if(rc == 0) {
402 // timeout
403 return kTimeout;
404
405 } else if(rc < 0) {
406 // an error occurred
407 throw clSocketException("SelectRead failed: " + error());
408
409 } else {
410 // we got something to read
411 return kSuccess;
412 }
413 }
414
415 int clSocketBase::SelectReadMS(long milliSeconds)
416 {
417 if(milliSeconds == -1) {
418 return kSuccess;
419 }
420
421 if(m_socket == INVALID_SOCKET) {
422 throw clSocketException("Invalid socket!");
423 }
424
425 int seconds = milliSeconds / 1000; // convert the number into seconds
426 int ms = milliSeconds % 1000; // the remainder is less than a second
427 struct timeval tv = { seconds, ms * 1000 };
428
429 fd_set readfds;
430 FD_ZERO(&readfds);
431 FD_SET(m_socket, &readfds);
432 int rc = select(m_socket + 1, &readfds, NULL, NULL, &tv);
433 if(rc == 0) {
434 // timeout
435 return kTimeout;
436
437 } else if(rc < 0) {
438 // an error occurred
439 throw clSocketException("SelectRead failed: " + error());
440
441 } else {
442 // we got something to read
443 return kSuccess;
444 }
445 }
446
447 void clSocketBase::SetSocket(socket_t socket)
448 {
449 SetCloseOnExit(false);
450 m_socket = socket;
451 }