Socket.c
Go to the documentation of this file.
1 /*******************************************************************************
2  * Copyright (c) 2009, 2020 IBM Corp. and others
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v2.0
6  * and Eclipse Distribution License v1.0 which accompany this distribution.
7  *
8  * The Eclipse Public License is available at
9  * https://www.eclipse.org/legal/epl-2.0/
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 
31 #include "Socket.h"
32 #include "Log.h"
33 #include "SocketBuffer.h"
34 #include "Messages.h"
35 #include "StackTrace.h"
36 #if defined(OPENSSL)
37 #include "SSLSocket.h"
38 #endif
39 
40 #include <stdlib.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <ctype.h>
44 
45 #include "Heap.h"
46 
48 int Socket_error(char* aString, int sock);
49 int Socket_addSocket(int newSd);
50 int isReady(int socket, fd_set* read_set, fd_set* write_set);
51 int Socket_writev(int socket, iobuf* iovecs, int count, unsigned long* bytes);
52 int Socket_close_only(int socket);
54 int Socket_continueWrites(fd_set* pwset);
55 char* Socket_getaddrname(struct sockaddr* sa, int sock);
56 int Socket_abortWrite(int socket);
57 
58 #if defined(_WIN32) || defined(_WIN64)
59 #define iov_len len
60 #define iov_base buf
61 #endif
62 
67 static fd_set wset;
68 
75 {
76  int rc;
77 #if defined(_WIN32) || defined(_WIN64)
78  u_long flag = 1L;
79 
80  FUNC_ENTRY;
81  rc = ioctl(sock, FIONBIO, &flag);
82 #else
83  int flags;
84 
85  FUNC_ENTRY;
86  if ((flags = fcntl(sock, F_GETFL, 0)))
87  flags = 0;
88  rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
89 #endif
90  FUNC_EXIT_RC(rc);
91  return rc;
92 }
93 
94 
101 int Socket_error(char* aString, int sock)
102 {
103  int err;
104 
105 #if defined(_WIN32) || defined(_WIN64)
106  err = WSAGetLastError();
107 #else
108  err = errno;
109 #endif
110  if (err != EINTR && err != EAGAIN && err != EINPROGRESS && err != EWOULDBLOCK)
111  {
112  if (strcmp(aString, "shutdown") != 0 || (err != ENOTCONN && err != ECONNRESET))
113  Log(TRACE_MINIMUM, -1, "Socket error %s(%d) in %s for socket %d", strerror(err), err, aString, sock);
114  }
115  return err;
116 }
117 
118 
123 {
124 #if defined(_WIN32) || defined(_WIN64)
125  WORD winsockVer = 0x0202;
126  WSADATA wsd;
127 
128  FUNC_ENTRY;
129  WSAStartup(winsockVer, &wsd);
130 #else
131  FUNC_ENTRY;
132  signal(SIGPIPE, SIG_IGN);
133 #endif
134 
136  mod_s.clientsds = ListInitialize();
138  mod_s.write_pending = ListInitialize();
139  mod_s.cur_clientsds = NULL;
140  FD_ZERO(&(mod_s.rset)); /* Initialize the descriptor set */
141  FD_ZERO(&(mod_s.pending_wset));
142  mod_s.maxfdp1 = 0;
143  memcpy((void*)&(mod_s.rset_saved), (void*)&(mod_s.rset), sizeof(mod_s.rset_saved));
144  FUNC_EXIT;
145 }
146 
147 
152 {
153  FUNC_ENTRY;
154  ListFree(mod_s.connect_pending);
155  ListFree(mod_s.write_pending);
156  ListFree(mod_s.clientsds);
158 #if defined(_WIN32) || defined(_WIN64)
159  WSACleanup();
160 #endif
161  FUNC_EXIT;
162 }
163 
164 
169 int Socket_addSocket(int newSd)
170 {
171  int rc = 0;
172 
173  FUNC_ENTRY;
174  if (ListFindItem(mod_s.clientsds, &newSd, intcompare) == NULL) /* make sure we don't add the same socket twice */
175  {
176  if (mod_s.clientsds->count >= FD_SETSIZE)
177  {
178  Log(LOG_ERROR, -1, "addSocket: exceeded FD_SETSIZE %d", FD_SETSIZE);
179  rc = SOCKET_ERROR;
180  }
181  else
182  {
183  int* pnewSd = (int*)malloc(sizeof(newSd));
184 
185  if (!pnewSd)
186  {
187  rc = PAHO_MEMORY_ERROR;
188  goto exit;
189  }
190  *pnewSd = newSd;
191  if (!ListAppend(mod_s.clientsds, pnewSd, sizeof(newSd)))
192  {
193  free(pnewSd);
194  rc = PAHO_MEMORY_ERROR;
195  goto exit;
196  }
197  FD_SET(newSd, &(mod_s.rset_saved));
198  mod_s.maxfdp1 = max(mod_s.maxfdp1, newSd + 1);
199  rc = Socket_setnonblocking(newSd);
200  if (rc == SOCKET_ERROR)
201  Log(LOG_ERROR, -1, "addSocket: setnonblocking");
202  }
203  }
204  else
205  Log(LOG_ERROR, -1, "addSocket: socket %d already in the list", newSd);
206 
207 exit:
208  FUNC_EXIT_RC(rc);
209  return rc;
210 }
211 
212 
221 int isReady(int socket, fd_set* read_set, fd_set* write_set)
222 {
223  int rc = 1;
224 
225  FUNC_ENTRY;
226  if (ListFindItem(mod_s.connect_pending, &socket, intcompare) && FD_ISSET(socket, write_set))
227  ListRemoveItem(mod_s.connect_pending, &socket, intcompare);
228  else
229  rc = FD_ISSET(socket, read_set) && FD_ISSET(socket, write_set) && Socket_noPendingWrites(socket);
230  FUNC_EXIT_RC(rc);
231  return rc;
232 }
233 
234 
242 int Socket_getReadySocket(int more_work, struct timeval *tp, mutex_type mutex)
243 {
244  int rc = 0;
245  static struct timeval zero = {0L, 0L}; /* 0 seconds */
246  static struct timeval one = {1L, 0L}; /* 1 second */
247  struct timeval timeout = one;
248 
249  FUNC_ENTRY;
250  Thread_lock_mutex(mutex);
251  if (mod_s.clientsds->count == 0)
252  goto exit;
253 
254  if (more_work)
255  timeout = zero;
256  else if (tp)
257  timeout = *tp;
258 
259  while (mod_s.cur_clientsds != NULL)
260  {
261  if (isReady(*((int*)(mod_s.cur_clientsds->content)), &(mod_s.rset), &wset))
262  break;
263  ListNextElement(mod_s.clientsds, &mod_s.cur_clientsds);
264  }
265 
266  if (mod_s.cur_clientsds == NULL)
267  {
268  int rc1;
269  fd_set pwset;
270 
271  memcpy((void*)&(mod_s.rset), (void*)&(mod_s.rset_saved), sizeof(mod_s.rset));
272  memcpy((void*)&(pwset), (void*)&(mod_s.pending_wset), sizeof(pwset));
273  /* Prevent performance issue by unlocking the socket_mutex while waiting for a ready socket. */
274  Thread_unlock_mutex(mutex);
275  rc = select(mod_s.maxfdp1, &(mod_s.rset), &pwset, NULL, &timeout);
276  Thread_lock_mutex(mutex);
277  if (rc == SOCKET_ERROR)
278  {
279  Socket_error("read select", 0);
280  goto exit;
281  }
282  Log(TRACE_MAX, -1, "Return code %d from read select", rc);
283 
284  if (Socket_continueWrites(&pwset) == SOCKET_ERROR)
285  {
286  rc = 0;
287  goto exit;
288  }
289 
290  memcpy((void*)&wset, (void*)&(mod_s.rset_saved), sizeof(wset));
291  if ((rc1 = select(mod_s.maxfdp1, NULL, &(wset), NULL, &zero)) == SOCKET_ERROR)
292  {
293  Socket_error("write select", 0);
294  rc = rc1;
295  goto exit;
296  }
297  Log(TRACE_MAX, -1, "Return code %d from write select", rc1);
298 
299  if (rc == 0 && rc1 == 0)
300  goto exit; /* no work to do */
301 
302  mod_s.cur_clientsds = mod_s.clientsds->first;
303  while (mod_s.cur_clientsds != NULL)
304  {
305  int cursock = *((int*)(mod_s.cur_clientsds->content));
306  if (isReady(cursock, &(mod_s.rset), &wset))
307  break;
308  ListNextElement(mod_s.clientsds, &mod_s.cur_clientsds);
309  }
310  }
311 
312  if (mod_s.cur_clientsds == NULL)
313  rc = 0;
314  else
315  {
316  rc = *((int*)(mod_s.cur_clientsds->content));
317  ListNextElement(mod_s.clientsds, &mod_s.cur_clientsds);
318  }
319 exit:
320  Thread_unlock_mutex(mutex);
321  FUNC_EXIT_RC(rc);
322  return rc;
323 } /* end getReadySocket */
324 
325 
332 int Socket_getch(int socket, char* c)
333 {
334  int rc = SOCKET_ERROR;
335 
336  FUNC_ENTRY;
337  if ((rc = SocketBuffer_getQueuedChar(socket, c)) != SOCKETBUFFER_INTERRUPTED)
338  goto exit;
339 
340  if ((rc = recv(socket, c, (size_t)1, 0)) == SOCKET_ERROR)
341  {
342  int err = Socket_error("recv - getch", socket);
343  if (err == EWOULDBLOCK || err == EAGAIN)
344  {
346  SocketBuffer_interrupted(socket, 0);
347  }
348  }
349  else if (rc == 0)
350  rc = SOCKET_ERROR; /* The return value from recv is 0 when the peer has performed an orderly shutdown. */
351  else if (rc == 1)
352  {
353  SocketBuffer_queueChar(socket, *c);
354  rc = TCPSOCKET_COMPLETE;
355  }
356 exit:
357  FUNC_EXIT_RC(rc);
358  return rc;
359 }
360 
361 
370 char *Socket_getdata(int socket, size_t bytes, size_t* actual_len, int *rc)
371 {
372  char* buf;
373 
374  FUNC_ENTRY;
375  if (bytes == 0)
376  {
377  buf = SocketBuffer_complete(socket);
378  goto exit;
379  }
380 
381  buf = SocketBuffer_getQueuedData(socket, bytes, actual_len);
382 
383  if ((*rc = recv(socket, buf + (*actual_len), (int)(bytes - (*actual_len)), 0)) == SOCKET_ERROR)
384  {
385  *rc = Socket_error("recv - getdata", socket);
386  if (*rc != EAGAIN && *rc != EWOULDBLOCK)
387  {
388  buf = NULL;
389  goto exit;
390  }
391  }
392  else if (*rc == 0) /* rc 0 means the other end closed the socket, albeit "gracefully" */
393  {
394  buf = NULL;
395  goto exit;
396  }
397  else
398  *actual_len += *rc;
399 
400  if (*actual_len == bytes)
401  SocketBuffer_complete(socket);
402  else /* we didn't read the whole packet */
403  {
404  SocketBuffer_interrupted(socket, *actual_len);
405  Log(TRACE_MAX, -1, "%d bytes expected but %d bytes now received", (int)bytes, (int)*actual_len);
406  }
407 exit:
408  FUNC_EXIT;
409  return buf;
410 }
411 
412 
418 {
419  int cursock = socket;
420  return ListFindItem(mod_s.write_pending, &cursock, intcompare) == NULL;
421 }
422 
423 
433 int Socket_writev(int socket, iobuf* iovecs, int count, unsigned long* bytes)
434 {
435  int rc;
436 
437  FUNC_ENTRY;
438  *bytes = 0L;
439 #if defined(_WIN32) || defined(_WIN64)
440  rc = WSASend(socket, iovecs, count, (LPDWORD)bytes, 0, NULL, NULL);
441  if (rc == SOCKET_ERROR)
442  {
443  int err = Socket_error("WSASend - putdatas", socket);
444  if (err == EWOULDBLOCK || err == EAGAIN)
446  }
447 #else
448 /*#define TCPSOCKET_INTERRUPTED_TESTING
449 This section forces the occasional return of TCPSOCKET_INTERRUPTED,
450 for testing purposes only!
451 */
452 #if defined(TCPSOCKET_INTERRUPTED_TESTING)
453  static int i = 0;
454  if (++i >= 10 && i < 21)
455  {
456  if (1)
457  {
458  printf("Deliberately simulating TCPSOCKET_INTERRUPTED\n");
459  rc = TCPSOCKET_INTERRUPTED; /* simulate a network wait */
460  }
461  else
462  {
463  printf("Deliberately simulating SOCKET_ERROR\n");
464  rc = SOCKET_ERROR;
465  }
466  /* should *bytes always be 0? */
467  if (i == 20)
468  {
469  printf("Shutdown socket\n");
470  shutdown(socket, SHUT_WR);
471  }
472  }
473  else
474  {
475 #endif
476  rc = writev(socket, iovecs, count);
477  if (rc == SOCKET_ERROR)
478  {
479  int err = Socket_error("writev - putdatas", socket);
480  if (err == EWOULDBLOCK || err == EAGAIN)
482  }
483  else
484  *bytes = rc;
485 #if defined(TCPSOCKET_INTERRUPTED_TESTING)
486  }
487 #endif
488 #endif
489  FUNC_EXIT_RC(rc);
490  return rc;
491 }
492 
493 
505 int Socket_putdatas(int socket, char* buf0, size_t buf0len, PacketBuffers bufs)
506 {
507  unsigned long bytes = 0L;
508  iobuf iovecs[5];
509  int frees1[5];
510  int rc = TCPSOCKET_INTERRUPTED, i;
511  size_t total = buf0len;
512 
513  FUNC_ENTRY;
514  if (!Socket_noPendingWrites(socket))
515  {
516  Log(LOG_SEVERE, -1, "Trying to write to socket %d for which there is already pending output", socket);
517  rc = SOCKET_ERROR;
518  goto exit;
519  }
520 
521  for (i = 0; i < bufs.count; i++)
522  total += bufs.buflens[i];
523 
524  iovecs[0].iov_base = buf0;
525  iovecs[0].iov_len = (ULONG)buf0len;
526  frees1[0] = 1; /* this buffer should be freed by SocketBuffer if the write is interrupted */
527  for (i = 0; i < bufs.count; i++)
528  {
529  iovecs[i+1].iov_base = bufs.buffers[i];
530  iovecs[i+1].iov_len = (ULONG)bufs.buflens[i];
531  frees1[i+1] = bufs.frees[i];
532  }
533 
534  if ((rc = Socket_writev(socket, iovecs, bufs.count+1, &bytes)) != SOCKET_ERROR)
535  {
536  if (bytes == total)
537  rc = TCPSOCKET_COMPLETE;
538  else
539  {
540  int* sockmem = (int*)malloc(sizeof(int));
541 
542  if (!sockmem)
543  {
544  rc = PAHO_MEMORY_ERROR;
545  goto exit;
546  }
547  Log(TRACE_MIN, -1, "Partial write: %lu bytes of %lu actually written on socket %d",
548  bytes, total, socket);
549 #if defined(OPENSSL)
550  SocketBuffer_pendingWrite(socket, NULL, bufs.count+1, iovecs, frees1, total, bytes);
551 #else
552  SocketBuffer_pendingWrite(socket, bufs.count+1, iovecs, frees1, total, bytes);
553 #endif
554  *sockmem = socket;
555  if (!ListAppend(mod_s.write_pending, sockmem, sizeof(int)))
556  {
557  free(sockmem);
558  rc = PAHO_MEMORY_ERROR;
559  goto exit;
560  }
561  FD_SET(socket, &(mod_s.pending_wset));
563  }
564  }
565 exit:
566  FUNC_EXIT_RC(rc);
567  return rc;
568 }
569 
570 
578 {
579  FD_SET(socket, &(mod_s.pending_wset));
580 }
581 
582 
588 {
589  if (FD_ISSET(socket, &(mod_s.pending_wset)))
590  FD_CLR(socket, &(mod_s.pending_wset));
591 }
592 
593 
600 {
601  int rc;
602 
603  FUNC_ENTRY;
604 #if defined(_WIN32) || defined(_WIN64)
605  if (shutdown(socket, SD_BOTH) == SOCKET_ERROR)
606  Socket_error("shutdown", socket);
607  if ((rc = closesocket(socket)) == SOCKET_ERROR)
608  Socket_error("close", socket);
609 #else
610  if (shutdown(socket, SHUT_WR) == SOCKET_ERROR)
611  Socket_error("shutdown", socket);
612  if ((rc = recv(socket, NULL, (size_t)0, 0)) == SOCKET_ERROR)
613  Socket_error("shutdown", socket);
614  if ((rc = close(socket)) == SOCKET_ERROR)
615  Socket_error("close", socket);
616 #endif
617  FUNC_EXIT_RC(rc);
618  return rc;
619 }
620 
621 
628 {
629  FUNC_ENTRY;
630  Socket_close_only(socket);
631  FD_CLR(socket, &(mod_s.rset_saved));
632  if (FD_ISSET(socket, &(mod_s.pending_wset)))
633  FD_CLR(socket, &(mod_s.pending_wset));
634  if (mod_s.cur_clientsds != NULL && *(int*)(mod_s.cur_clientsds->content) == socket)
635  mod_s.cur_clientsds = mod_s.cur_clientsds->next;
636  Socket_abortWrite(socket);
637  SocketBuffer_cleanup(socket);
638  ListRemoveItem(mod_s.connect_pending, &socket, intcompare);
639  ListRemoveItem(mod_s.write_pending, &socket, intcompare);
640 
641  if (ListRemoveItem(mod_s.clientsds, &socket, intcompare))
642  Log(TRACE_MIN, -1, "Removed socket %d", socket);
643  else
644  Log(LOG_ERROR, -1, "Failed to remove socket %d", socket);
645  if (socket + 1 >= mod_s.maxfdp1)
646  {
647  /* now we have to reset mod_s.maxfdp1 */
648  ListElement* cur_clientsds = NULL;
649 
650  mod_s.maxfdp1 = 0;
651  while (ListNextElement(mod_s.clientsds, &cur_clientsds))
652  mod_s.maxfdp1 = max(*((int*)(cur_clientsds->content)), mod_s.maxfdp1);
653  ++(mod_s.maxfdp1);
654  Log(TRACE_MAX, -1, "Reset max fdp1 to %d", mod_s.maxfdp1);
655  }
656  FUNC_EXIT;
657 }
658 
659 
668 #if defined(__GNUC__) && defined(__linux__)
669 int Socket_new(const char* addr, size_t addr_len, int port, int* sock, long timeout)
670 #else
671 int Socket_new(const char* addr, size_t addr_len, int port, int* sock)
672 #endif
673 {
674  int type = SOCK_STREAM;
675  char *addr_mem;
676  struct sockaddr_in address;
677 #if defined(AF_INET6)
678  struct sockaddr_in6 address6;
679 #endif
680  int rc = SOCKET_ERROR;
681 #if defined(_WIN32) || defined(_WIN64)
682  short family;
683 #else
684  sa_family_t family = AF_INET;
685 #endif
686  struct addrinfo *result = NULL;
687  struct addrinfo hints = {0, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL};
688 
689  FUNC_ENTRY;
690  *sock = -1;
691  memset(&address6, '\0', sizeof(address6));
692 
693  if (addr[0] == '[')
694  {
695  ++addr;
696  --addr_len;
697  }
698 
699  if ((addr_mem = malloc( addr_len + 1u )) == NULL)
700  {
701  rc = PAHO_MEMORY_ERROR;
702  goto exit;
703  }
704  memcpy( addr_mem, addr, addr_len );
705  addr_mem[addr_len] = '\0';
706 
707 #if 0 /*defined(__GNUC__) && defined(__linux__)*/
708  /* Commented out because the CI tests get intermittent ECONNABORTED return values
709  * and I don't know why yet.
710  */
711  /* set getaddrinfo timeout if available */
712  struct gaicb ar = {addr_mem, NULL, &hints, NULL};
713  struct gaicb *reqs[] = {&ar};
714 
715  unsigned long int seconds = timeout / 1000L;
716  unsigned long int nanos = (timeout - (seconds * 1000L)) * 1000000L;
717  struct timespec timeoutspec = {seconds, nanos};
718 
719  rc = getaddrinfo_a(GAI_NOWAIT, reqs, 1, NULL);
720  if (rc == 0)
721  rc = gai_suspend((const struct gaicb* const *) reqs, 1, &timeoutspec);
722 
723  if (rc == 0)
724  {
725  rc = gai_error(reqs[0]);
726  result = ar.ar_result;
727  }
728 #else
729  rc = getaddrinfo(addr_mem, NULL, &hints, &result);
730 #endif
731 
732  if (rc == 0)
733  {
734  struct addrinfo* res = result;
735 
736  while (res)
737  { /* prefer ip4 addresses */
738  if (res->ai_family == AF_INET || res->ai_next == NULL)
739  break;
740  res = res->ai_next;
741  }
742 
743  if (res == NULL)
744  rc = -1;
745  else
746 #if defined(AF_INET6)
747  if (res->ai_family == AF_INET6)
748  {
749  address6.sin6_port = htons(port);
750  address6.sin6_family = family = AF_INET6;
751  memcpy(&address6.sin6_addr, &((struct sockaddr_in6*)(res->ai_addr))->sin6_addr, sizeof(address6.sin6_addr));
752  }
753  else
754 #endif
755  if (res->ai_family == AF_INET)
756  {
757  memset(&address.sin_zero, 0, sizeof(address.sin_zero));
758  address.sin_port = htons(port);
759  address.sin_family = family = AF_INET;
760  address.sin_addr = ((struct sockaddr_in*)(res->ai_addr))->sin_addr;
761  }
762  else
763  rc = -1;
764 
765  freeaddrinfo(result);
766  }
767  else
768  Log(LOG_ERROR, -1, "getaddrinfo failed for addr %s with rc %d", addr_mem, rc);
769 
770  if (rc != 0)
771  Log(LOG_ERROR, -1, "%s is not a valid IP address", addr_mem);
772  else
773  {
774  *sock = (int)socket(family, type, 0);
775  if (*sock == INVALID_SOCKET)
776  rc = Socket_error("socket", *sock);
777  else
778  {
779 #if defined(NOSIGPIPE)
780  int opt = 1;
781 
782  if (setsockopt(*sock, SOL_SOCKET, SO_NOSIGPIPE, (void*)&opt, sizeof(opt)) != 0)
783  Log(LOG_ERROR, -1, "Could not set SO_NOSIGPIPE for socket %d", *sock);
784 #endif
785 /*#define SMALL_TCP_BUFFER_TESTING
786  This section sets the TCP send buffer to a small amount to provoke TCPSOCKET_INTERRUPTED
787  return codes from send, for testing only!
788 */
789 #if defined(SMALL_TCP_BUFFER_TESTING)
790  if (1)
791  {
792  int optsend = 100; //2 * 1440;
793  printf("Setting optsend to %d\n", optsend);
794  if (setsockopt(*sock, SOL_SOCKET, SO_SNDBUF, (void*)&optsend, sizeof(optsend)) != 0)
795  Log(LOG_ERROR, -1, "Could not set SO_SNDBUF for socket %d", *sock);
796  }
797 #endif
798  Log(TRACE_MIN, -1, "New socket %d for %s, port %d", *sock, addr, port);
799  if (Socket_addSocket(*sock) == SOCKET_ERROR)
800  rc = Socket_error("addSocket", *sock);
801  else
802  {
803  /* this could complete immmediately, even though we are non-blocking */
804  if (family == AF_INET)
805  rc = connect(*sock, (struct sockaddr*)&address, sizeof(address));
806  #if defined(AF_INET6)
807  else
808  rc = connect(*sock, (struct sockaddr*)&address6, sizeof(address6));
809  #endif
810  if (rc == SOCKET_ERROR)
811  rc = Socket_error("connect", *sock);
812  if (rc == EINPROGRESS || rc == EWOULDBLOCK)
813  {
814  int* pnewSd = (int*)malloc(sizeof(int));
815 
816  if (!pnewSd)
817  {
818  rc = PAHO_MEMORY_ERROR;
819  goto exit;
820  }
821  *pnewSd = *sock;
822  if (!ListAppend(mod_s.connect_pending, pnewSd, sizeof(int)))
823  {
824  free(pnewSd);
825  rc = PAHO_MEMORY_ERROR;
826  goto exit;
827  }
828  Log(TRACE_MIN, 15, "Connect pending");
829  }
830  }
831  /* Prevent socket leak by closing unusable sockets,
832  as reported in https://github.com/eclipse/paho.mqtt.c/issues/135 */
833  if (rc != 0 && (rc != EINPROGRESS) && (rc != EWOULDBLOCK))
834  {
835  Socket_close(*sock); /* close socket and remove from our list of sockets */
836  *sock = -1; /* as initialized before */
837  }
838  }
839  }
840 
841 exit:
842  if (addr_mem)
843  free(addr_mem);
844 
845  FUNC_EXIT_RC(rc);
846  return rc;
847 }
848 
849 
851 
853 {
854  writecomplete = mywritecomplete;
855 }
856 
857 
858 
865 {
866  int rc = 0;
867  pending_writes* pw;
868  unsigned long curbuflen = 0L, /* cumulative total of buffer lengths */
869  bytes = 0L;
870  int curbuf = -1, i;
871  iobuf iovecs1[5];
872 
873  FUNC_ENTRY;
874  pw = SocketBuffer_getWrite(socket);
875 
876 #if defined(OPENSSL)
877  if (pw->ssl)
878  {
879  rc = SSLSocket_continueWrite(pw);
880  goto exit;
881  }
882 #endif
883 
884  for (i = 0; i < pw->count; ++i)
885  {
886  if (pw->bytes <= curbuflen)
887  { /* if previously written length is less than the buffer we are currently looking at,
888  add the whole buffer */
889  iovecs1[++curbuf].iov_len = pw->iovecs[i].iov_len;
890  iovecs1[curbuf].iov_base = pw->iovecs[i].iov_base;
891  }
892  else if (pw->bytes < curbuflen + pw->iovecs[i].iov_len)
893  { /* if previously written length is in the middle of the buffer we are currently looking at,
894  add some of the buffer */
895  size_t offset = pw->bytes - curbuflen;
896  iovecs1[++curbuf].iov_len = pw->iovecs[i].iov_len - (ULONG)offset;
897  iovecs1[curbuf].iov_base = (char*)pw->iovecs[i].iov_base + offset;
898  break;
899  }
900  curbuflen += pw->iovecs[i].iov_len;
901  }
902 
903  if ((rc = Socket_writev(socket, iovecs1, curbuf+1, &bytes)) != SOCKET_ERROR)
904  {
905  pw->bytes += bytes;
906  if ((rc = (pw->bytes == pw->total)))
907  { /* topic and payload buffers are freed elsewhere, when all references to them have been removed */
908  for (i = 0; i < pw->count; i++)
909  {
910  if (pw->frees[i])
911  {
912  free(pw->iovecs[i].iov_base);
913  pw->iovecs[i].iov_base = NULL;
914  }
915  }
916  rc = 1; /* signal complete */
917  Log(TRACE_MIN, -1, "ContinueWrite: partial write now complete for socket %d", socket);
918  }
919  else
920  {
921  rc = 0; /* signal not complete */
922  Log(TRACE_MIN, -1, "ContinueWrite wrote +%lu bytes on socket %d", bytes, socket);
923  }
924  }
925  else /* if we got SOCKET_ERROR we need to clean up anyway - a partial write is no good anymore */
926  {
927  for (i = 0; i < pw->count; i++)
928  {
929  if (pw->frees[i])
930  {
931  free(pw->iovecs[i].iov_base);
932  pw->iovecs[i].iov_base = NULL;
933  }
934  }
935  }
936 #if defined(OPENSSL)
937 exit:
938 #endif
939  FUNC_EXIT_RC(rc);
940  return rc;
941 }
942 
943 
944 
951 {
952  int i = -1, rc = 0;
953  pending_writes* pw;
954 
955  FUNC_ENTRY;
956  if ((pw = SocketBuffer_getWrite(socket)) == NULL)
957  goto exit;
958 
959 #if defined(OPENSSL)
960  if (pw->ssl)
961  goto exit;
962 #endif
963 
964  for (i = 0; i < pw->count; i++)
965  {
966  if (pw->frees[i])
967  {
968  Log(TRACE_MIN, -1, "Cleaning in abortWrite for socket %d", socket);
969  free(pw->iovecs[i].iov_base);
970  }
971  }
972 exit:
973  FUNC_EXIT_RC(rc);
974  return rc;
975 }
976 
977 
983 int Socket_continueWrites(fd_set* pwset)
984 {
985  int rc1 = 0;
986  ListElement* curpending = mod_s.write_pending->first;
987 
988  FUNC_ENTRY;
989  while (curpending && curpending->content)
990  {
991  int socket = *(int*)(curpending->content);
992  int rc = 0;
993 
994  if (FD_ISSET(socket, pwset) && ((rc = Socket_continueWrite(socket)) != 0))
995  {
996  if (!SocketBuffer_writeComplete(socket))
997  Log(LOG_SEVERE, -1, "Failed to remove pending write from socket buffer list");
998  FD_CLR(socket, &(mod_s.pending_wset));
999  if (!ListRemove(mod_s.write_pending, curpending->content))
1000  {
1001  Log(LOG_SEVERE, -1, "Failed to remove pending write from list");
1002  ListNextElement(mod_s.write_pending, &curpending);
1003  }
1004  curpending = mod_s.write_pending->current;
1005 
1006  if (writecomplete)
1007  (*writecomplete)(socket, rc);
1008  }
1009  else
1010  ListNextElement(mod_s.write_pending, &curpending);
1011  }
1012  FUNC_EXIT_RC(rc1);
1013  return rc1;
1014 }
1015 
1016 
1023 char* Socket_getaddrname(struct sockaddr* sa, int sock)
1024 {
1028 #define ADDRLEN INET6_ADDRSTRLEN+1
1029 
1032 #define PORTLEN 10
1033  static char addr_string[ADDRLEN + PORTLEN];
1034 
1035 #if defined(_WIN32) || defined(_WIN64)
1036  int buflen = ADDRLEN*2;
1037  wchar_t buf[ADDRLEN*2];
1038  if (WSAAddressToStringW(sa, sizeof(struct sockaddr_in6), NULL, buf, (LPDWORD)&buflen) == SOCKET_ERROR)
1039  Socket_error("WSAAddressToString", sock);
1040  else
1041  wcstombs(addr_string, buf, sizeof(addr_string));
1042  /* TODO: append the port information - format: [00:00:00::]:port */
1043  /* strcpy(&addr_string[strlen(addr_string)], "what?"); */
1044 #else
1045  struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1046  inet_ntop(sin->sin_family, &sin->sin_addr, addr_string, ADDRLEN);
1047  sprintf(&addr_string[strlen(addr_string)], ":%d", ntohs(sin->sin_port));
1048 #endif
1049  return addr_string;
1050 }
1051 
1052 
1058 char* Socket_getpeer(int sock)
1059 {
1060  struct sockaddr_in6 sa;
1061  socklen_t sal = sizeof(sa);
1062 
1063  if (getpeername(sock, (struct sockaddr*)&sa, &sal) == SOCKET_ERROR)
1064  {
1065  Socket_error("getpeername", sock);
1066  return "unknown";
1067  }
1068 
1069  return Socket_getaddrname((struct sockaddr*)&sa, sock);
1070 }
1071 
1072 
1073 #if defined(Socket_TEST)
1074 
1075 int main(int argc, char *argv[])
1076 {
1077  Socket_connect("127.0.0.1", 1883);
1078  Socket_connect("localhost", 1883);
1079  Socket_connect("loadsadsacalhost", 1883);
1080 }
1081 
1082 #endif
char * SocketBuffer_getQueuedData(int socket, size_t bytes, size_t *actual_len)
Definition: SocketBuffer.c:176
#define INVALID_SOCKET
Definition: Socket.h:48
#define TRACE_MIN
Definition: Log.h:66
int count
Definition: Socket.h:98
#define FUNC_EXIT
Definition: StackTrace.h:59
int Socket_new(const char *addr, size_t addr_len, int port, int *sock)
Definition: Socket.c:671
#define ADDRLEN
struct @73::@74 bytes[4]
ListElement * current
Definition: LinkedList.h:69
int Socket_getch(int socket, char *c)
Definition: Socket.c:332
void select(lua_State *L, Fx &&fx, Args &&...args)
Definition: sol.hpp:18357
int SocketBuffer_initialize(void)
Definition: SocketBuffer.c:102
int Socket_noPendingWrites(int socket)
Definition: Socket.c:417
void Socket_outTerminate(void)
Definition: Socket.c:151
#define PAHO_MEMORY_ERROR
Definition: Heap.h:26
void SocketBuffer_queueChar(int socket, char c)
Definition: SocketBuffer.c:303
int Socket_getReadySocket(int more_work, struct timeval *tp, mutex_type mutex)
Definition: Socket.c:242
int Thread_lock_mutex(mutex_type mutex)
Definition: Thread.c:112
int isReady(int socket, fd_set *read_set, fd_set *write_set)
Definition: Socket.c:221
Sockets mod_s
Definition: Socket.c:66
List * write_pending
Definition: Socket.h:117
#define malloc(x)
Definition: Heap.h:41
#define PORTLEN
int Socket_error(char *aString, int sock)
Definition: Socket.c:101
int ListRemove(List *aList, void *content)
Definition: LinkedList.c:257
void Socket_writeComplete(int socket, int rc)
Definition: Socket.h:142
#define TRACE_MAX
Definition: Log.h:65
struct ListElementStruct * next
Definition: LinkedList.h:58
char ** buffers
Definition: Socket.h:99
size_t * buflens
Definition: Socket.h:100
#define free(x)
Definition: Heap.h:55
void Socket_setWriteCompleteCallback(Socket_writeComplete *mywritecomplete)
Definition: Socket.c:852
void Socket_clearPendingWrite(int socket)
Definition: Socket.c:587
constexpr size_t count()
Definition: core.h:960
#define FUNC_EXIT_RC(x)
Definition: StackTrace.h:63
#define SOCKET_ERROR
Definition: Socket.h:76
int count
Definition: LinkedList.h:72
ListElement * ListNextElement(List *aList, ListElement **pos)
Definition: LinkedList.c:411
char * Socket_getaddrname(struct sockaddr *sa, int sock)
Definition: Socket.c:1023
void SocketBuffer_interrupted(int socket, size_t actual_len)
Definition: SocketBuffer.c:252
Definition: Log.h:42
#define max(A, B)
Definition: Socket.h:88
int ListRemoveItem(List *aList, void *content, int(*callback)(void *, void *))
Definition: LinkedList.c:349
int Thread_unlock_mutex(mutex_type mutex)
Definition: Thread.c:133
ListElement * cur_clientsds
Definition: Socket.h:115
void Log(enum LOG_LEVELS log_level, int msgno, const char *format,...)
Definition: Log.c:417
void Socket_addPendingWrite(int socket)
Definition: Socket.c:577
int Socket_continueWrite(int socket)
Definition: Socket.c:864
fd_set rset_saved
Definition: Socket.h:111
#define mutex_type
Definition: mutex_type.h:22
void SocketBuffer_terminate(void)
Definition: SocketBuffer.c:133
int Socket_addSocket(int newSd)
Definition: Socket.c:169
Definition: Log.h:41
char * Socket_getdata(int socket, size_t bytes, size_t *actual_len, int *rc)
Definition: Socket.c:370
ListElement * ListAppend(List *aList, void *content, size_t size)
Definition: LinkedList.c:90
int Socket_setnonblocking(int sock)
Definition: Socket.c:74
int SocketBuffer_writeComplete(int socket)
Definition: SocketBuffer.c:411
fd_set pending_wset
Definition: Socket.h:118
#define SOCKETBUFFER_INTERRUPTED
Definition: SocketBuffer.h:64
int SocketBuffer_getQueuedChar(int socket, char *c)
Definition: SocketBuffer.c:219
#define FUNC_ENTRY
Definition: StackTrace.h:55
int Socket_continueWrites(fd_set *pwset)
Definition: Socket.c:983
iobuf iovecs[5]
Definition: SocketBuffer.h:56
fd_set rset
Definition: Socket.h:111
char * Socket_getpeer(int sock)
Definition: Socket.c:1058
int * frees
Definition: Socket.h:101
MQTTClient c
Definition: test10.c:1656
int Socket_abortWrite(int socket)
Definition: Socket.c:950
pending_writes * SocketBuffer_getWrite(int socket)
Definition: SocketBuffer.c:399
static fd_set wset
Definition: Socket.c:67
char * SocketBuffer_complete(int socket)
Definition: SocketBuffer.c:281
int Socket_writev(int socket, iobuf *iovecs, int count, unsigned long *bytes)
Definition: Socket.c:433
int Socket_putdatas(int socket, char *buf0, size_t buf0len, PacketBuffers bufs)
Definition: Socket.c:505
int maxfdp1
Definition: Socket.h:113
List * ListInitialize(void)
Definition: LinkedList.c:52
#define TCPSOCKET_COMPLETE
Definition: Socket.h:73
ListElement * ListFindItem(List *aList, void *content, int(*callback)(void *, void *))
Definition: LinkedList.c:154
ListElement * first
Definition: LinkedList.h:69
int Socket_close_only(int socket)
Definition: Socket.c:599
void Socket_close(int socket)
Definition: Socket.c:627
List * connect_pending
Definition: Socket.h:116
int intcompare(void *a, void *b)
Definition: LinkedList.c:436
void ListFree(List *aList)
Definition: LinkedList.c:381
enum MQTTReasonCodes rc
Definition: test10.c:1112
int main(int argc, char **argv)
Definition: lua.c:619
void Socket_outInitialize(void)
Definition: Socket.c:122
struct iovec iobuf
Definition: SocketBuffer.h:34
int SocketBuffer_pendingWrite(int socket, int count, iobuf *iovecs, int *frees, size_t total, size_t bytes)
Definition: SocketBuffer.c:349
static Socket_writeComplete * writecomplete
Definition: Socket.c:850
#define ULONG
Definition: Socket.h:67
#define TCPSOCKET_INTERRUPTED
Definition: Socket.h:79
Definition: format.h:3618
void SocketBuffer_cleanup(int socket)
Definition: SocketBuffer.c:151
int SSLSocket_continueWrite(pending_writes *pw)
List * clientsds
Definition: Socket.h:114


plotjuggler
Author(s): Davide Faconti
autogenerated on Sun Dec 6 2020 03:48:11