Socket.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /*******************************************************************************
  2. * Copyright (c) 2009, 2018 IBM Corp.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial implementation and documentation
  15. * Ian Craggs - async client updates
  16. * Ian Craggs - fix for bug 484496
  17. * Juergen Kosel, Ian Craggs - fix for issue #135
  18. * Ian Craggs - issue #217
  19. * Ian Craggs - fix for issue #186
  20. * Ian Craggs - remove StackTrace print debugging calls
  21. *******************************************************************************/
  22. /**
  23. * @file
  24. * \brief Socket related functions
  25. *
  26. * Some other related functions are in the SocketBuffer module
  27. */
  28. #include "Socket.h"
  29. #include "Log.h"
  30. #include "SocketBuffer.h"
  31. #include "Messages.h"
  32. #include "StackTrace.h"
  33. #if defined(OPENSSL)
  34. #include "SSLSocket.h"
  35. #endif
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <signal.h>
  39. #include <ctype.h>
  40. #include "Heap.h"
  41. int Socket_setnonblocking(int sock);
  42. int Socket_error(char* aString, int sock);
  43. int Socket_addSocket(int newSd);
  44. int isReady(int socket, fd_set* read_set, fd_set* write_set);
  45. int Socket_writev(int socket, iobuf* iovecs, int count, unsigned long* bytes);
  46. int Socket_close_only(int socket);
  47. int Socket_continueWrite(int socket);
  48. int Socket_continueWrites(fd_set* pwset);
  49. char* Socket_getaddrname(struct sockaddr* sa, int sock);
  50. int Socket_abortWrite(int socket);
  51. #if defined(WIN32) || defined(WIN64)
  52. #define iov_len len
  53. #define iov_base buf
  54. #endif
  55. /**
  56. * Structure to hold all socket data for the module
  57. */
  58. Sockets s;
  59. static fd_set wset;
  60. /**
  61. * Set a socket non-blocking, OS independently
  62. * @param sock the socket to set non-blocking
  63. * @return TCP call error code
  64. */
  65. int Socket_setnonblocking(int sock)
  66. {
  67. int rc;
  68. #if defined(WIN32) || defined(WIN64)
  69. u_long flag = 1L;
  70. FUNC_ENTRY;
  71. rc = ioctl(sock, FIONBIO, &flag);
  72. #else
  73. int flags;
  74. FUNC_ENTRY;
  75. if ((flags = fcntl(sock, F_GETFL, 0)))
  76. flags = 0;
  77. rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  78. #endif
  79. FUNC_EXIT_RC(rc);
  80. return rc;
  81. }
  82. /**
  83. * Gets the specific error corresponding to SOCKET_ERROR
  84. * @param aString the function that was being used when the error occurred
  85. * @param sock the socket on which the error occurred
  86. * @return the specific TCP error code
  87. */
  88. int Socket_error(char* aString, int sock)
  89. {
  90. #if defined(WIN32) || defined(WIN64)
  91. int errno;
  92. #endif
  93. #if defined(WIN32) || defined(WIN64)
  94. errno = WSAGetLastError();
  95. #endif
  96. if (errno != EINTR && errno != EAGAIN && errno != EINPROGRESS && errno != EWOULDBLOCK)
  97. {
  98. if (strcmp(aString, "shutdown") != 0 || (errno != ENOTCONN && errno != ECONNRESET))
  99. Log(TRACE_MINIMUM, -1, "Socket error %s(%d) in %s for socket %d", strerror(errno), errno, aString, sock);
  100. }
  101. return errno;
  102. }
  103. /**
  104. * Initialize the socket module
  105. */
  106. void Socket_outInitialize(void)
  107. {
  108. #if defined(WIN32) || defined(WIN64)
  109. WORD winsockVer = 0x0202;
  110. WSADATA wsd;
  111. FUNC_ENTRY;
  112. WSAStartup(winsockVer, &wsd);
  113. #else
  114. FUNC_ENTRY;
  115. signal(SIGPIPE, SIG_IGN);
  116. #endif
  117. SocketBuffer_initialize();
  118. s.clientsds = ListInitialize();
  119. s.connect_pending = ListInitialize();
  120. s.write_pending = ListInitialize();
  121. s.cur_clientsds = NULL;
  122. FD_ZERO(&(s.rset)); /* Initialize the descriptor set */
  123. FD_ZERO(&(s.pending_wset));
  124. s.maxfdp1 = 0;
  125. memcpy((void*)&(s.rset_saved), (void*)&(s.rset), sizeof(s.rset_saved));
  126. FUNC_EXIT;
  127. }
  128. /**
  129. * Terminate the socket module
  130. */
  131. void Socket_outTerminate(void)
  132. {
  133. FUNC_ENTRY;
  134. ListFree(s.connect_pending);
  135. ListFree(s.write_pending);
  136. ListFree(s.clientsds);
  137. SocketBuffer_terminate();
  138. #if defined(WIN32) || defined(WIN64)
  139. WSACleanup();
  140. #endif
  141. FUNC_EXIT;
  142. }
  143. /**
  144. * Add a socket to the list of socket to check with select
  145. * @param newSd the new socket to add
  146. */
  147. int Socket_addSocket(int newSd)
  148. {
  149. int rc = 0;
  150. FUNC_ENTRY;
  151. if (ListFindItem(s.clientsds, &newSd, intcompare) == NULL) /* make sure we don't add the same socket twice */
  152. {
  153. if (s.clientsds->count >= FD_SETSIZE)
  154. {
  155. Log(LOG_ERROR, -1, "addSocket: exceeded FD_SETSIZE %d", FD_SETSIZE);
  156. rc = SOCKET_ERROR;
  157. }
  158. else
  159. {
  160. int* pnewSd = (int*)malloc(sizeof(newSd));
  161. *pnewSd = newSd;
  162. ListAppend(s.clientsds, pnewSd, sizeof(newSd));
  163. FD_SET(newSd, &(s.rset_saved));
  164. s.maxfdp1 = max(s.maxfdp1, newSd + 1);
  165. rc = Socket_setnonblocking(newSd);
  166. if (rc == SOCKET_ERROR)
  167. Log(LOG_ERROR, -1, "addSocket: setnonblocking");
  168. }
  169. }
  170. else
  171. Log(LOG_ERROR, -1, "addSocket: socket %d already in the list", newSd);
  172. FUNC_EXIT_RC(rc);
  173. return rc;
  174. }
  175. /**
  176. * Don't accept work from a client unless it is accepting work back, i.e. its socket is writeable
  177. * this seems like a reasonable form of flow control, and practically, seems to work.
  178. * @param socket the socket to check
  179. * @param read_set the socket read set (see select doc)
  180. * @param write_set the socket write set (see select doc)
  181. * @return boolean - is the socket ready to go?
  182. */
  183. int isReady(int socket, fd_set* read_set, fd_set* write_set)
  184. {
  185. int rc = 1;
  186. FUNC_ENTRY;
  187. if (ListFindItem(s.connect_pending, &socket, intcompare) && FD_ISSET(socket, write_set))
  188. ListRemoveItem(s.connect_pending, &socket, intcompare);
  189. else
  190. rc = FD_ISSET(socket, read_set) && FD_ISSET(socket, write_set) && Socket_noPendingWrites(socket);
  191. FUNC_EXIT_RC(rc);
  192. return rc;
  193. }
  194. /**
  195. * Returns the next socket ready for communications as indicated by select
  196. * @param more_work flag to indicate more work is waiting, and thus a timeout value of 0 should
  197. * be used for the select
  198. * @param tp the timeout to be used for the select, unless overridden
  199. * @return the socket next ready, or 0 if none is ready
  200. */
  201. int Socket_getReadySocket(int more_work, struct timeval *tp, mutex_type mutex)
  202. {
  203. int rc = 0;
  204. static struct timeval zero = {0L, 0L}; /* 0 seconds */
  205. static struct timeval one = {1L, 0L}; /* 1 second */
  206. struct timeval timeout = one;
  207. FUNC_ENTRY;
  208. Thread_lock_mutex(mutex);
  209. if (s.clientsds->count == 0)
  210. goto exit;
  211. if (more_work)
  212. timeout = zero;
  213. else if (tp)
  214. timeout = *tp;
  215. while (s.cur_clientsds != NULL)
  216. {
  217. if (isReady(*((int*)(s.cur_clientsds->content)), &(s.rset), &wset))
  218. break;
  219. ListNextElement(s.clientsds, &s.cur_clientsds);
  220. }
  221. if (s.cur_clientsds == NULL)
  222. {
  223. int rc1;
  224. fd_set pwset;
  225. memcpy((void*)&(s.rset), (void*)&(s.rset_saved), sizeof(s.rset));
  226. memcpy((void*)&(pwset), (void*)&(s.pending_wset), sizeof(pwset));
  227. /* Prevent performance issue by unlocking the socket_mutex while waiting for a ready socket. */
  228. Thread_unlock_mutex(mutex);
  229. rc = select(s.maxfdp1, &(s.rset), &pwset, NULL, &timeout);
  230. Thread_lock_mutex(mutex);
  231. if (rc == SOCKET_ERROR)
  232. {
  233. Socket_error("read select", 0);
  234. goto exit;
  235. }
  236. Log(TRACE_MAX, -1, "Return code %d from read select", rc);
  237. if (Socket_continueWrites(&pwset) == SOCKET_ERROR)
  238. {
  239. rc = 0;
  240. goto exit;
  241. }
  242. memcpy((void*)&wset, (void*)&(s.rset_saved), sizeof(wset));
  243. if ((rc1 = select(s.maxfdp1, NULL, &(wset), NULL, &zero)) == SOCKET_ERROR)
  244. {
  245. Socket_error("write select", 0);
  246. rc = rc1;
  247. goto exit;
  248. }
  249. Log(TRACE_MAX, -1, "Return code %d from write select", rc1);
  250. if (rc == 0 && rc1 == 0)
  251. goto exit; /* no work to do */
  252. s.cur_clientsds = s.clientsds->first;
  253. while (s.cur_clientsds != NULL)
  254. {
  255. int cursock = *((int*)(s.cur_clientsds->content));
  256. if (isReady(cursock, &(s.rset), &wset))
  257. break;
  258. ListNextElement(s.clientsds, &s.cur_clientsds);
  259. }
  260. }
  261. if (s.cur_clientsds == NULL)
  262. rc = 0;
  263. else
  264. {
  265. rc = *((int*)(s.cur_clientsds->content));
  266. ListNextElement(s.clientsds, &s.cur_clientsds);
  267. }
  268. exit:
  269. Thread_unlock_mutex(mutex);
  270. FUNC_EXIT_RC(rc);
  271. return rc;
  272. } /* end getReadySocket */
  273. /**
  274. * Reads one byte from a socket
  275. * @param socket the socket to read from
  276. * @param c the character read, returned
  277. * @return completion code
  278. */
  279. int Socket_getch(int socket, char* c)
  280. {
  281. int rc = SOCKET_ERROR;
  282. FUNC_ENTRY;
  283. if ((rc = SocketBuffer_getQueuedChar(socket, c)) != SOCKETBUFFER_INTERRUPTED)
  284. goto exit;
  285. if ((rc = recv(socket, c, (size_t)1, 0)) == SOCKET_ERROR)
  286. {
  287. int err = Socket_error("recv - getch", socket);
  288. if (err == EWOULDBLOCK || err == EAGAIN)
  289. {
  290. rc = TCPSOCKET_INTERRUPTED;
  291. SocketBuffer_interrupted(socket, 0);
  292. }
  293. }
  294. else if (rc == 0)
  295. rc = SOCKET_ERROR; /* The return value from recv is 0 when the peer has performed an orderly shutdown. */
  296. else if (rc == 1)
  297. {
  298. SocketBuffer_queueChar(socket, *c);
  299. rc = TCPSOCKET_COMPLETE;
  300. }
  301. exit:
  302. FUNC_EXIT_RC(rc);
  303. return rc;
  304. }
  305. /**
  306. * Attempts to read a number of bytes from a socket, non-blocking. If a previous read did not
  307. * finish, then retrieve that data.
  308. * @param socket the socket to read from
  309. * @param bytes the number of bytes to read
  310. * @param actual_len the actual number of bytes read
  311. * @return completion code
  312. */
  313. char *Socket_getdata(int socket, size_t bytes, size_t* actual_len)
  314. {
  315. int rc;
  316. char* buf;
  317. FUNC_ENTRY;
  318. if (bytes == 0)
  319. {
  320. buf = SocketBuffer_complete(socket);
  321. goto exit;
  322. }
  323. buf = SocketBuffer_getQueuedData(socket, bytes, actual_len);
  324. if ((rc = recv(socket, buf + (*actual_len), (int)(bytes - (*actual_len)), 0)) == SOCKET_ERROR)
  325. {
  326. rc = Socket_error("recv - getdata", socket);
  327. if (rc != EAGAIN && rc != EWOULDBLOCK)
  328. {
  329. buf = NULL;
  330. goto exit;
  331. }
  332. }
  333. else if (rc == 0) /* rc 0 means the other end closed the socket, albeit "gracefully" */
  334. {
  335. buf = NULL;
  336. goto exit;
  337. }
  338. else
  339. *actual_len += rc;
  340. if (*actual_len == bytes)
  341. SocketBuffer_complete(socket);
  342. else /* we didn't read the whole packet */
  343. {
  344. SocketBuffer_interrupted(socket, *actual_len);
  345. Log(TRACE_MAX, -1, "%d bytes expected but %d bytes now received", (int)bytes, (int)*actual_len);
  346. }
  347. exit:
  348. FUNC_EXIT;
  349. return buf;
  350. }
  351. /**
  352. * Indicate whether any data is pending outbound for a socket.
  353. * @return boolean - true == data pending.
  354. */
  355. int Socket_noPendingWrites(int socket)
  356. {
  357. int cursock = socket;
  358. return ListFindItem(s.write_pending, &cursock, intcompare) == NULL;
  359. }
  360. /**
  361. * Attempts to write a series of iovec buffers to a socket in *one* system call so that
  362. * they are sent as one packet.
  363. * @param socket the socket to write to
  364. * @param iovecs an array of buffers to write
  365. * @param count number of buffers in iovecs
  366. * @param bytes number of bytes actually written returned
  367. * @return completion code, especially TCPSOCKET_INTERRUPTED
  368. */
  369. int Socket_writev(int socket, iobuf* iovecs, int count, unsigned long* bytes)
  370. {
  371. int rc;
  372. FUNC_ENTRY;
  373. *bytes = 0L;
  374. #if defined(WIN32) || defined(WIN64)
  375. rc = WSASend(socket, iovecs, count, (LPDWORD)bytes, 0, NULL, NULL);
  376. if (rc == SOCKET_ERROR)
  377. {
  378. int err = Socket_error("WSASend - putdatas", socket);
  379. if (err == EWOULDBLOCK || err == EAGAIN)
  380. rc = TCPSOCKET_INTERRUPTED;
  381. }
  382. #else
  383. /*#define TCPSOCKET_INTERRUPTED_TESTING
  384. This section forces the occasional return of TCPSOCKET_INTERRUPTED,
  385. for testing purposes only!
  386. */
  387. #if defined(TCPSOCKET_INTERRUPTED_TESTING)
  388. static int i = 0;
  389. if (++i >= 10 && i < 21)
  390. {
  391. if (1)
  392. {
  393. printf("Deliberately simulating TCPSOCKET_INTERRUPTED\n");
  394. rc = TCPSOCKET_INTERRUPTED; /* simulate a network wait */
  395. }
  396. else
  397. {
  398. printf("Deliberately simulating SOCKET_ERROR\n");
  399. rc = SOCKET_ERROR;
  400. }
  401. /* should *bytes always be 0? */
  402. if (i == 20)
  403. {
  404. printf("Shutdown socket\n");
  405. shutdown(socket, SHUT_WR);
  406. }
  407. }
  408. else
  409. {
  410. #endif
  411. rc = writev(socket, iovecs, count);
  412. if (rc == SOCKET_ERROR)
  413. {
  414. int err = Socket_error("writev - putdatas", socket);
  415. if (err == EWOULDBLOCK || err == EAGAIN)
  416. rc = TCPSOCKET_INTERRUPTED;
  417. }
  418. else
  419. *bytes = rc;
  420. #if defined(TCPSOCKET_INTERRUPTED_TESTING)
  421. }
  422. #endif
  423. #endif
  424. FUNC_EXIT_RC(rc);
  425. return rc;
  426. }
  427. /**
  428. * Attempts to write a series of buffers to a socket in *one* system call so that they are
  429. * sent as one packet.
  430. * @param socket the socket to write to
  431. * @param buf0 the first buffer
  432. * @param buf0len the length of data in the first buffer
  433. * @param count number of buffers
  434. * @param buffers an array of buffers to write
  435. * @param buflens an array of corresponding buffer lengths
  436. * @return completion code, especially TCPSOCKET_INTERRUPTED
  437. */
  438. int Socket_putdatas(int socket, char* buf0, size_t buf0len, int count, char** buffers, size_t* buflens, int* frees)
  439. {
  440. unsigned long bytes = 0L;
  441. iobuf iovecs[5];
  442. int frees1[5];
  443. int rc = TCPSOCKET_INTERRUPTED, i;
  444. size_t total = buf0len;
  445. FUNC_ENTRY;
  446. if (!Socket_noPendingWrites(socket))
  447. {
  448. Log(LOG_SEVERE, -1, "Trying to write to socket %d for which there is already pending output", socket);
  449. rc = SOCKET_ERROR;
  450. goto exit;
  451. }
  452. for (i = 0; i < count; i++)
  453. total += buflens[i];
  454. iovecs[0].iov_base = buf0;
  455. iovecs[0].iov_len = (ULONG)buf0len;
  456. frees1[0] = 1; /* this buffer should be freed by SocketBuffer if the write is interrupted */
  457. for (i = 0; i < count; i++)
  458. {
  459. iovecs[i+1].iov_base = buffers[i];
  460. iovecs[i+1].iov_len = (ULONG)buflens[i];
  461. frees1[i+1] = frees[i];
  462. }
  463. if ((rc = Socket_writev(socket, iovecs, count+1, &bytes)) != SOCKET_ERROR)
  464. {
  465. if (bytes == total)
  466. rc = TCPSOCKET_COMPLETE;
  467. else
  468. {
  469. int* sockmem = (int*)malloc(sizeof(int));
  470. Log(TRACE_MIN, -1, "Partial write: %lu bytes of %lu actually written on socket %d",
  471. bytes, total, socket);
  472. #if defined(OPENSSL)
  473. SocketBuffer_pendingWrite(socket, NULL, count+1, iovecs, frees1, total, bytes);
  474. #else
  475. SocketBuffer_pendingWrite(socket, count+1, iovecs, frees1, total, bytes);
  476. #endif
  477. *sockmem = socket;
  478. ListAppend(s.write_pending, sockmem, sizeof(int));
  479. FD_SET(socket, &(s.pending_wset));
  480. rc = TCPSOCKET_INTERRUPTED;
  481. }
  482. }
  483. exit:
  484. #if 0
  485. if (rc == TCPSOCKET_INTERRUPTED)
  486. {
  487. Log(LOG_ERROR, -1, "Socket_putdatas: TCPSOCKET_INTERRUPTED");
  488. }
  489. #endif
  490. FUNC_EXIT_RC(rc);
  491. return rc;
  492. }
  493. /**
  494. * Add a socket to the pending write list, so that it is checked for writing in select. This is used
  495. * in connect processing when the TCP connect is incomplete, as we need to check the socket for both
  496. * ready to read and write states.
  497. * @param socket the socket to add
  498. */
  499. void Socket_addPendingWrite(int socket)
  500. {
  501. FD_SET(socket, &(s.pending_wset));
  502. }
  503. /**
  504. * Clear a socket from the pending write list - if one was added with Socket_addPendingWrite
  505. * @param socket the socket to remove
  506. */
  507. void Socket_clearPendingWrite(int socket)
  508. {
  509. if (FD_ISSET(socket, &(s.pending_wset)))
  510. FD_CLR(socket, &(s.pending_wset));
  511. }
  512. /**
  513. * Close a socket without removing it from the select list.
  514. * @param socket the socket to close
  515. * @return completion code
  516. */
  517. int Socket_close_only(int socket)
  518. {
  519. int rc;
  520. FUNC_ENTRY;
  521. #if defined(WIN32) || defined(WIN64)
  522. if (shutdown(socket, SD_BOTH) == SOCKET_ERROR)
  523. Socket_error("shutdown", socket);
  524. if ((rc = closesocket(socket)) == SOCKET_ERROR)
  525. Socket_error("close", socket);
  526. #else
  527. if (shutdown(socket, SHUT_WR) == SOCKET_ERROR)
  528. Socket_error("shutdown", socket);
  529. if ((rc = recv(socket, NULL, (size_t)0, 0)) == SOCKET_ERROR)
  530. Socket_error("shutdown", socket);
  531. if ((rc = close(socket)) == SOCKET_ERROR)
  532. Socket_error("close", socket);
  533. #endif
  534. FUNC_EXIT_RC(rc);
  535. return rc;
  536. }
  537. /**
  538. * Close a socket and remove it from the select list.
  539. * @param socket the socket to close
  540. * @return completion code
  541. */
  542. void Socket_close(int socket)
  543. {
  544. FUNC_ENTRY;
  545. Socket_close_only(socket);
  546. FD_CLR(socket, &(s.rset_saved));
  547. if (FD_ISSET(socket, &(s.pending_wset)))
  548. FD_CLR(socket, &(s.pending_wset));
  549. if (s.cur_clientsds != NULL && *(int*)(s.cur_clientsds->content) == socket)
  550. s.cur_clientsds = s.cur_clientsds->next;
  551. Socket_abortWrite(socket);
  552. SocketBuffer_cleanup(socket);
  553. ListRemoveItem(s.connect_pending, &socket, intcompare);
  554. ListRemoveItem(s.write_pending, &socket, intcompare);
  555. if (ListRemoveItem(s.clientsds, &socket, intcompare))
  556. Log(TRACE_MIN, -1, "Removed socket %d", socket);
  557. else
  558. Log(LOG_ERROR, -1, "Failed to remove socket %d", socket);
  559. if (socket + 1 >= s.maxfdp1)
  560. {
  561. /* now we have to reset s.maxfdp1 */
  562. ListElement* cur_clientsds = NULL;
  563. s.maxfdp1 = 0;
  564. while (ListNextElement(s.clientsds, &cur_clientsds))
  565. s.maxfdp1 = max(*((int*)(cur_clientsds->content)), s.maxfdp1);
  566. ++(s.maxfdp1);
  567. Log(TRACE_MAX, -1, "Reset max fdp1 to %d", s.maxfdp1);
  568. }
  569. FUNC_EXIT;
  570. }
  571. /**
  572. * Create a new socket and TCP connect to an address/port
  573. * @param addr the address string
  574. * @param port the TCP port
  575. * @param sock returns the new socket
  576. * @return completion code
  577. */
  578. int Socket_new(const char* addr, size_t addr_len, int port, int* sock)
  579. {
  580. int type = SOCK_STREAM;
  581. char *addr_mem;
  582. struct sockaddr_in address;
  583. #if defined(AF_INET6)
  584. struct sockaddr_in6 address6;
  585. #endif
  586. int rc = SOCKET_ERROR;
  587. #if defined(WIN32) || defined(WIN64)
  588. short family;
  589. #else
  590. sa_family_t family = AF_INET;
  591. #endif
  592. struct addrinfo *result = NULL;
  593. struct addrinfo hints = {0, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL};
  594. FUNC_ENTRY;
  595. *sock = -1;
  596. memset(&address6, '\0', sizeof(address6));
  597. if (addr[0] == '[')
  598. {
  599. ++addr;
  600. --addr_len;
  601. }
  602. addr_mem = malloc( addr_len + 1u );
  603. memcpy( addr_mem, addr, addr_len );
  604. addr_mem[addr_len] = '\0';
  605. if ((rc = getaddrinfo(addr_mem, NULL, &hints, &result)) == 0)
  606. {
  607. struct addrinfo* res = result;
  608. while (res)
  609. { /* prefer ip4 addresses */
  610. if (res->ai_family == AF_INET || res->ai_next == NULL)
  611. break;
  612. res = res->ai_next;
  613. }
  614. if (res == NULL)
  615. rc = -1;
  616. else
  617. #if defined(AF_INET6)
  618. if (res->ai_family == AF_INET6)
  619. {
  620. address6.sin6_port = htons(port);
  621. address6.sin6_family = family = AF_INET6;
  622. memcpy(&address6.sin6_addr, &((struct sockaddr_in6*)(res->ai_addr))->sin6_addr, sizeof(address6.sin6_addr));
  623. }
  624. else
  625. #endif
  626. if (res->ai_family == AF_INET)
  627. {
  628. memset(&address.sin_zero, 0, sizeof(address.sin_zero));
  629. address.sin_port = htons(port);
  630. address.sin_family = family = AF_INET;
  631. address.sin_addr = ((struct sockaddr_in*)(res->ai_addr))->sin_addr;
  632. }
  633. else
  634. rc = -1;
  635. freeaddrinfo(result);
  636. }
  637. else
  638. Log(LOG_ERROR, -1, "getaddrinfo failed for addr %s with rc %d", addr_mem, rc);
  639. if (rc != 0)
  640. Log(LOG_ERROR, -1, "%s is not a valid IP address", addr_mem);
  641. else
  642. {
  643. *sock = (int)socket(family, type, 0);
  644. if (*sock == INVALID_SOCKET)
  645. rc = Socket_error("socket", *sock);
  646. else
  647. {
  648. #if defined(NOSIGPIPE)
  649. int opt = 1;
  650. if (setsockopt(*sock, SOL_SOCKET, SO_NOSIGPIPE, (void*)&opt, sizeof(opt)) != 0)
  651. Log(LOG_ERROR, -1, "Could not set SO_NOSIGPIPE for socket %d", *sock);
  652. #endif
  653. /*#define SMALL_TCP_BUFFER_TESTING
  654. This section sets the TCP send buffer to a small amount to provoke TCPSOCKET_INTERRUPTED
  655. return codes from send, for testing only!
  656. */
  657. #if defined(SMALL_TCP_BUFFER_TESTING)
  658. if (1)
  659. {
  660. int optsend = 100; //2 * 1440;
  661. printf("Setting optsend to %d\n", optsend);
  662. if (setsockopt(*sock, SOL_SOCKET, SO_SNDBUF, (void*)&optsend, sizeof(optsend)) != 0)
  663. Log(LOG_ERROR, -1, "Could not set SO_SNDBUF for socket %d", *sock);
  664. }
  665. #endif
  666. Log(TRACE_MIN, -1, "New socket %d for %s, port %d", *sock, addr, port);
  667. if (Socket_addSocket(*sock) == SOCKET_ERROR)
  668. rc = Socket_error("addSocket", *sock);
  669. else
  670. {
  671. /* this could complete immmediately, even though we are non-blocking */
  672. if (family == AF_INET)
  673. rc = connect(*sock, (struct sockaddr*)&address, sizeof(address));
  674. #if defined(AF_INET6)
  675. else
  676. rc = connect(*sock, (struct sockaddr*)&address6, sizeof(address6));
  677. #endif
  678. if (rc == SOCKET_ERROR)
  679. rc = Socket_error("connect", *sock);
  680. if (rc == EINPROGRESS || rc == EWOULDBLOCK)
  681. {
  682. int* pnewSd = (int*)malloc(sizeof(int));
  683. *pnewSd = *sock;
  684. ListAppend(s.connect_pending, pnewSd, sizeof(int));
  685. Log(TRACE_MIN, 15, "Connect pending");
  686. }
  687. }
  688. /* Prevent socket leak by closing unusable sockets,
  689. * as reported in
  690. * https://github.com/eclipse/paho.mqtt.c/issues/135
  691. */
  692. if (rc != 0 && (rc != EINPROGRESS) && (rc != EWOULDBLOCK))
  693. {
  694. Socket_close(*sock); /* close socket and remove from our list of sockets */
  695. *sock = -1; /* as initialized before */
  696. }
  697. }
  698. }
  699. if (addr_mem)
  700. free(addr_mem);
  701. FUNC_EXIT_RC(rc);
  702. return rc;
  703. }
  704. static Socket_writeComplete* writecomplete = NULL;
  705. void Socket_setWriteCompleteCallback(Socket_writeComplete* mywritecomplete)
  706. {
  707. writecomplete = mywritecomplete;
  708. }
  709. /**
  710. * Continue an outstanding write for a particular socket
  711. * @param socket that socket
  712. * @return completion code: 0=incomplete, 1=complete, -1=socket error
  713. */
  714. int Socket_continueWrite(int socket)
  715. {
  716. int rc = 0;
  717. pending_writes* pw;
  718. unsigned long curbuflen = 0L, /* cumulative total of buffer lengths */
  719. bytes = 0L;
  720. int curbuf = -1, i;
  721. iobuf iovecs1[5];
  722. FUNC_ENTRY;
  723. pw = SocketBuffer_getWrite(socket);
  724. #if defined(OPENSSL)
  725. if (pw->ssl)
  726. {
  727. rc = SSLSocket_continueWrite(pw);
  728. goto exit;
  729. }
  730. #endif
  731. for (i = 0; i < pw->count; ++i)
  732. {
  733. if (pw->bytes <= curbuflen)
  734. { /* if previously written length is less than the buffer we are currently looking at,
  735. add the whole buffer */
  736. iovecs1[++curbuf].iov_len = pw->iovecs[i].iov_len;
  737. iovecs1[curbuf].iov_base = pw->iovecs[i].iov_base;
  738. }
  739. else if (pw->bytes < curbuflen + pw->iovecs[i].iov_len)
  740. { /* if previously written length is in the middle of the buffer we are currently looking at,
  741. add some of the buffer */
  742. size_t offset = pw->bytes - curbuflen;
  743. iovecs1[++curbuf].iov_len = pw->iovecs[i].iov_len - (ULONG)offset;
  744. iovecs1[curbuf].iov_base = (char*)pw->iovecs[i].iov_base + offset;
  745. break;
  746. }
  747. curbuflen += pw->iovecs[i].iov_len;
  748. }
  749. if ((rc = Socket_writev(socket, iovecs1, curbuf+1, &bytes)) != SOCKET_ERROR)
  750. {
  751. pw->bytes += bytes;
  752. if ((rc = (pw->bytes == pw->total)))
  753. { /* topic and payload buffers are freed elsewhere, when all references to them have been removed */
  754. for (i = 0; i < pw->count; i++)
  755. {
  756. if (pw->frees[i])
  757. {
  758. free(pw->iovecs[i].iov_base);
  759. pw->iovecs[i].iov_base = NULL;
  760. }
  761. }
  762. rc = 1; /* signal complete */
  763. Log(TRACE_MIN, -1, "ContinueWrite: partial write now complete for socket %d", socket);
  764. }
  765. else
  766. {
  767. rc = 0; /* signal not complete */
  768. Log(TRACE_MIN, -1, "ContinueWrite wrote +%lu bytes on socket %d", bytes, socket);
  769. }
  770. }
  771. else /* if we got SOCKET_ERROR we need to clean up anyway - a partial write is no good anymore */
  772. {
  773. for (i = 0; i < pw->count; i++)
  774. {
  775. if (pw->frees[i])
  776. {
  777. free(pw->iovecs[i].iov_base);
  778. pw->iovecs[i].iov_base = NULL;
  779. }
  780. }
  781. }
  782. #if defined(OPENSSL)
  783. exit:
  784. #endif
  785. FUNC_EXIT_RC(rc);
  786. return rc;
  787. }
  788. /**
  789. * Continue an outstanding write for a particular socket
  790. * @param socket that socket
  791. * @return completion code: 0=incomplete, 1=complete, -1=socket error
  792. */
  793. int Socket_abortWrite(int socket)
  794. {
  795. int i = -1, rc = 0;
  796. pending_writes* pw;
  797. FUNC_ENTRY;
  798. if ((pw = SocketBuffer_getWrite(socket)) == NULL)
  799. goto exit;
  800. #if defined(OPENSSL)
  801. if (pw->ssl)
  802. goto exit;
  803. #endif
  804. for (i = 0; i < pw->count; i++)
  805. {
  806. if (pw->frees[i])
  807. {
  808. printf("cleaning in abortwrite for socket %d\n", socket);
  809. free(pw->iovecs[i].iov_base);
  810. }
  811. }
  812. exit:
  813. FUNC_EXIT_RC(rc);
  814. return rc;
  815. }
  816. /**
  817. * Continue any outstanding writes for a socket set
  818. * @param pwset the set of sockets
  819. * @return completion code
  820. */
  821. int Socket_continueWrites(fd_set* pwset)
  822. {
  823. int rc1 = 0;
  824. ListElement* curpending = s.write_pending->first;
  825. FUNC_ENTRY;
  826. while (curpending)
  827. {
  828. int socket = *(int*)(curpending->content);
  829. int rc = 0;
  830. if (FD_ISSET(socket, pwset) && ((rc = Socket_continueWrite(socket)) != 0))
  831. {
  832. if (!SocketBuffer_writeComplete(socket))
  833. Log(LOG_SEVERE, -1, "Failed to remove pending write from socket buffer list");
  834. FD_CLR(socket, &(s.pending_wset));
  835. if (!ListRemove(s.write_pending, curpending->content))
  836. {
  837. Log(LOG_SEVERE, -1, "Failed to remove pending write from list");
  838. ListNextElement(s.write_pending, &curpending);
  839. }
  840. curpending = s.write_pending->current;
  841. if (writecomplete)
  842. (*writecomplete)(socket, rc);
  843. }
  844. else
  845. ListNextElement(s.write_pending, &curpending);
  846. }
  847. FUNC_EXIT_RC(rc1);
  848. return rc1;
  849. }
  850. /**
  851. * Convert a numeric address to character string
  852. * @param sa socket numerical address
  853. * @param sock socket
  854. * @return the peer information
  855. */
  856. char* Socket_getaddrname(struct sockaddr* sa, int sock)
  857. {
  858. /**
  859. * maximum length of the address string
  860. */
  861. #define ADDRLEN INET6_ADDRSTRLEN+1
  862. /**
  863. * maximum length of the port string
  864. */
  865. #define PORTLEN 10
  866. static char addr_string[ADDRLEN + PORTLEN];
  867. #if defined(WIN32) || defined(WIN64)
  868. int buflen = ADDRLEN*2;
  869. wchar_t buf[ADDRLEN*2];
  870. if (WSAAddressToStringW(sa, sizeof(struct sockaddr_in6), NULL, buf, (LPDWORD)&buflen) == SOCKET_ERROR)
  871. Socket_error("WSAAddressToString", sock);
  872. else
  873. wcstombs(addr_string, buf, sizeof(addr_string));
  874. /* TODO: append the port information - format: [00:00:00::]:port */
  875. /* strcpy(&addr_string[strlen(addr_string)], "what?"); */
  876. #else
  877. struct sockaddr_in *sin = (struct sockaddr_in *)sa;
  878. inet_ntop(sin->sin_family, &sin->sin_addr, addr_string, ADDRLEN);
  879. sprintf(&addr_string[strlen(addr_string)], ":%d", ntohs(sin->sin_port));
  880. #endif
  881. return addr_string;
  882. }
  883. /**
  884. * Get information about the other end connected to a socket
  885. * @param sock the socket to inquire on
  886. * @return the peer information
  887. */
  888. char* Socket_getpeer(int sock)
  889. {
  890. struct sockaddr_in6 sa;
  891. socklen_t sal = sizeof(sa);
  892. if (getpeername(sock, (struct sockaddr*)&sa, &sal) == SOCKET_ERROR)
  893. {
  894. Socket_error("getpeername", sock);
  895. return "unknown";
  896. }
  897. return Socket_getaddrname((struct sockaddr*)&sa, sock);
  898. }
  899. #if defined(Socket_TEST)
  900. int main(int argc, char *argv[])
  901. {
  902. Socket_connect("127.0.0.1", 1883);
  903. Socket_connect("localhost", 1883);
  904. Socket_connect("loadsadsacalhost", 1883);
  905. }
  906. #endif