1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License as published by
4  *  the Free Software Foundation; either version 2 of the License, or
5  *  (at your option) any later version.
6  *
7  *  This program is distributed in the hope that it will be useful,
8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *  GNU General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  *
16  *  Author : Richard GAYRAUD - 04 Nov 2003
17  *           Marc LAMBERTON
18  *           Olivier JACQUES
19  *           Herve PELLAN
20  *           David MANSUTTI
21  *           Francois-Xavier Kowalski
22  *           Gerard Lyonnaz
23  *           Francois Draperi (for dynamic_id)
24  *           From Hewlett Packard Company.
25  *           F. Tarek Rogers
26  *           Peter Higginson
27  *           Vincent Luba
28  *           Shriram Natarajan
29  *           Guillaume Teissier from FTR&D
30  *           Clement Chen
31  *           Wolfgang Beck
32  *           Charles P Wright from IBM Research
33  *           Martin Van Leeuwen
34  *           Andy Aicken
35  *           Michael Hirschbichler
36  */
37 
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include "sipp.hpp"
42 #include "socket.hpp"
43 #include "logger.hpp"
44 
45 extern bool do_hide;
46 extern bool show_index;
47 
48 struct sipp_socket *ctrl_socket = NULL;
49 struct sipp_socket *stdin_socket = NULL;
50 
51 static int stdin_mode;
52 
53 /******************** Recv Poll Processing *********************/
54 
55 int pollnfds;
56 #ifdef HAVE_EPOLL
57 int epollfd;
58 struct epoll_event   epollfiles[SIPP_MAXFDS];
59 struct epoll_event*  epollevents;
60 #else
61 struct pollfd        pollfiles[SIPP_MAXFDS];
62 #endif
63 struct sipp_socket  *sockets[SIPP_MAXFDS];
64 
65 int pending_messages = 0;
66 
67 map<string, struct sipp_socket *>     map_perip_fd;
68 
process_set(char * what)69 static void process_set(char* what)
70 {
71     char *rest = strchr(what, ' ');
72     if (rest) {
73         *rest++ = '\0';
74         trim(rest);
75     } else {
76         WARNING("The set command requires two arguments (attribute and value)");
77         return;
78     }
79 
80     if (!strcmp(what, "rate")) {
81         char *end;
82         double drest = strtod(rest, &end);
83 
84         if (users >= 0) {
85             WARNING("Rates can not be set in a user-based benchmark.");
86         } else if (*end) {
87             WARNING("Invalid rate value: \"%s\"", rest);
88         } else {
89             CallGenerationTask::set_rate(drest);
90         }
91     } else if (!strcmp(what, "rate-scale")) {
92         char *end;
93         double drest = strtod(rest, &end);
94         if (*end) {
95             WARNING("Invalid rate-scale value: \"%s\"", rest);
96         } else {
97             rate_scale = drest;
98         }
99     } else if (!strcmp(what, "users")) {
100         char *end;
101         int urest = strtol(rest, &end, 0);
102 
103         if (users < 0) {
104             WARNING("Users can not be changed at run time for a rate-based benchmark.");
105         } else if (*end) {
106             WARNING("Invalid users value: \"%s\"", rest);
107         } else if (urest < 0) {
108             WARNING("Invalid users value: \"%s\"", rest);
109         } else {
110             CallGenerationTask::set_users(urest);
111         }
112     } else if (!strcmp(what, "limit")) {
113         char *end;
114         unsigned long lrest = strtoul(rest, &end, 0);
115         if (users >= 0) {
116             WARNING("Can not set call limit for a user-based benchmark.");
117         } else if (*end) {
118             WARNING("Invalid limit value: \"%s\"", rest);
119         } else {
120             open_calls_allowed = lrest;
121             open_calls_user_setting = 1;
122         }
123     } else if (!strcmp(what, "display")) {
124         if (!strcmp(rest, "main")) {
125             display_scenario = main_scenario;
126         } else if (!strcmp(rest, "ooc")) {
127             display_scenario = ooc_scenario;
128         } else {
129             WARNING("Unknown display scenario: %s", rest);
130         }
131     } else if (!strcmp(what, "hide")) {
132         if (!strcmp(rest, "true")) {
133             do_hide = true;
134         } else if (!strcmp(rest, "false")) {
135             do_hide = false;
136         } else {
137             WARNING("Invalid bool: %s", rest);
138         }
139     } else if (!strcmp(what, "index")) {
140         if (!strcmp(rest, "true")) {
141             show_index = true;
142         } else if (!strcmp(rest, "false")) {
143             show_index = false;
144         } else {
145             WARNING("Invalid bool: %s", rest);
146         }
147     } else {
148         WARNING("Unknown set attribute: %s", what);
149     }
150 }
151 
process_trace(char * what)152 static void process_trace(char* what)
153 {
154     bool on = false;
155     char *rest = strchr(what, ' ');
156     if (rest) {
157         *rest++ = '\0';
158         trim(rest);
159     } else {
160         WARNING("The trace command requires two arguments (log and [on|off])");
161         return;
162     }
163 
164     if (!strcmp(rest, "on")) {
165         on = true;
166     } else if (!strcmp(rest, "off")) {
167         on = false;
168     } else if (!strcmp(rest, "true")) {
169         on = true;
170     } else if (!strcmp(rest, "false")) {
171         on = false;
172     } else {
173         WARNING("The trace command's second argument must be on or off.");
174         return;
175     }
176 
177     if (!strcmp(what, "error")) {
178         if (on == !!print_all_responses) {
179             return;
180         }
181         if (on) {
182             print_all_responses = 1;
183         } else {
184             print_all_responses = 0;
185             log_off(&error_lfi);
186         }
187     } else if (!strcmp(what, "logs")) {
188         if (on == !!log_lfi.fptr) {
189             return;
190         }
191         if (on) {
192             useLogf = 1;
193             rotate_logfile();
194         } else {
195             useLogf = 0;
196             log_off(&log_lfi);
197         }
198     } else if (!strcmp(what, "messages")) {
199         if (on == !!message_lfi.fptr) {
200             return;
201         }
202         if (on) {
203             useMessagef = 1;
204             rotate_logfile();
205         } else {
206             useMessagef = 0;
207             log_off(&message_lfi);
208         }
209     } else if (!strcmp(what, "shortmessages")) {
210         if (on == !!shortmessage_lfi.fptr) {
211             return;
212         }
213 
214         if (on) {
215             useShortMessagef = 1;
216             rotate_shortmessagef();
217         } else {
218             useShortMessagef = 0;
219             log_off(&shortmessage_lfi);
220         }
221     } else {
222         WARNING("Unknown log file: %s", what);
223     }
224 }
225 
process_dump(char * what)226 static void process_dump(char* what)
227 {
228     if (!strcmp(what, "tasks")) {
229         dump_tasks();
230     } else if (!strcmp(what, "variables")) {
231         display_scenario->allocVars->dump();
232     } else {
233         WARNING("Unknown dump type: %s", what);
234     }
235 }
236 
process_reset(char * what)237 static void process_reset(char* what)
238 {
239     if (!strcmp(what, "stats")) {
240         main_scenario->stats->computeStat(CStat::E_RESET_C_COUNTERS);
241     } else {
242         WARNING("Unknown reset type: %s", what);
243     }
244 }
245 
process_command(char * command)246 static bool process_command(char* command)
247 {
248     trim(command);
249 
250     char *rest = strchr(command, ' ');
251     if (rest) {
252         *rest++ = '\0';
253         trim(rest);
254     }
255 
256     if (!rest) {
257         WARNING("The %s command requires at least one argument", command);
258     } else if (!strcmp(command, "set")) {
259         process_set(rest);
260     } else if (!strcmp(command, "trace")) {
261         process_trace(rest);
262     } else if (!strcmp(command, "dump")) {
263         process_dump(rest);
264     } else if (!strcmp(command, "reset")) {
265         process_reset(rest);
266     } else {
267         WARNING("Unrecognized command: \"%s\"", command);
268     }
269 
270     return false;
271 }
272 
273 int command_mode = 0;
274 char *command_buffer = NULL;
275 
276 extern bool sipMsgCheck (const char *P_msg, struct sipp_socket *socket);
277 
get_trimmed_call_id(const char * msg)278 static const char* get_trimmed_call_id(const char* msg)
279 {
280     /* A call_id identifies a call and is generated by SIPp for each
281      * new call.  In client mode, it is mandatory to use the value
282      * generated by SIPp in the "Call-ID" header.  Otherwise, SIPp will
283      * not recognise the answer to the message sent as being part of an
284      * existing call.
285      *
286      * Note: [call_id] can be pre-pended with an arbitrary string using
287      * '///'.
288      * Example: Call-ID: ABCDEFGHIJ///[call_id]
289      * - it will still be recognized by SIPp as part of the same call.
290      */
291     const char *call_id = get_call_id(msg);
292     const char *slashes = strstr(call_id, "///");
293     if ((!callidSlash) && slashes) {
294         return slashes + 3;
295     }
296     return call_id;
297 }
298 
299 #ifdef USE_OPENSSL
300 SSL_CTX  *sip_trp_ssl_ctx = NULL; /* For SSL cserver context */
301 SSL_CTX  *sip_trp_ssl_ctx_client = NULL; /* For SSL cserver context */
302 SSL_CTX  *twinSipp_sip_trp_ssl_ctx_client = NULL; /* For SSL cserver context */
303 
304 #define CALL_BACK_USER_DATA "ksgr"
305 
passwd_call_back_routine(char * buf,int size,int,void * passwd)306 int passwd_call_back_routine(char *buf, int size, int /*flag*/, void *passwd)
307 {
308     strncpy(buf, (char *)(passwd), size);
309     buf[size - 1] = '\0';
310     return(strlen(buf));
311 }
312 
313 /****** SSL error handling *************/
sip_tls_error_string(SSL * ssl,int size)314 const char *sip_tls_error_string(SSL *ssl, int size)
315 {
316     int err;
317     err=SSL_get_error(ssl, size);
318     switch(err) {
319     case SSL_ERROR_NONE:
320         return "No error";
321     case SSL_ERROR_WANT_WRITE:
322         return "SSL_read returned SSL_ERROR_WANT_WRITE";
323     case SSL_ERROR_WANT_READ:
324         return "SSL_read returned SSL_ERROR_WANT_READ";
325     case SSL_ERROR_WANT_X509_LOOKUP:
326         return "SSL_read returned SSL_ERROR_WANT_X509_LOOKUP";
327     case SSL_ERROR_SYSCALL:
328         if (size < 0) { /* not EOF */
329             return strerror(errno);
330         } else { /* EOF */
331             return "SSL socket closed on SSL_read";
332         }
333     }
334     return "Unknown SSL Error.";
335 }
336 
337 #endif
338 
get_inet_address(const struct sockaddr_storage * addr,char * dst,int len)339 static char* get_inet_address(const struct sockaddr_storage* addr, char* dst, int len)
340 {
341     if (getnameinfo(_RCAST(struct sockaddr*, addr), SOCK_ADDR_SIZE(addr),
342                     dst, len, NULL, 0, NI_NUMERICHOST) != 0) {
343         snprintf(dst, len, "addr not supported");
344     }
345     return dst;
346 }
347 
process_key(int c)348 static bool process_key(int c)
349 {
350     switch (c) {
351     case '1':
352         currentScreenToDisplay = DISPLAY_SCENARIO_SCREEN;
353         print_statistics(0);
354         break;
355 
356     case '2':
357         currentScreenToDisplay = DISPLAY_STAT_SCREEN;
358         print_statistics(0);
359         break;
360 
361     case '3':
362         currentScreenToDisplay = DISPLAY_REPARTITION_SCREEN;
363         print_statistics(0);
364         break;
365 
366     case '4':
367         currentScreenToDisplay = DISPLAY_VARIABLE_SCREEN;
368         print_statistics(0);
369         break;
370 
371     case '5':
372         if (use_tdmmap) {
373             currentScreenToDisplay = DISPLAY_TDM_MAP_SCREEN;
374             print_statistics(0);
375         }
376         break;
377 
378         /* Screens 6, 7, 8, 9  are for the extra RTD repartitions. */
379     case '6':
380     case '7':
381     case '8':
382     case '9':
383         currentScreenToDisplay = DISPLAY_SECONDARY_REPARTITION_SCREEN;
384         currentRepartitionToDisplay = (c - '6') + 2;
385         print_statistics(0);
386         break;
387 
388     case '+':
389         if (users >= 0) {
390             CallGenerationTask::set_users((int)(users + 1 * rate_scale));
391         } else {
392             CallGenerationTask::set_rate(rate + 1 * rate_scale);
393         }
394         print_statistics(0);
395         break;
396 
397     case '-':
398         if (users >= 0) {
399             CallGenerationTask::set_users((int)(users - 1 * rate_scale));
400         } else {
401             CallGenerationTask::set_rate(rate - 1 * rate_scale);
402         }
403         print_statistics(0);
404         break;
405 
406     case '*':
407         if (users >= 0) {
408             CallGenerationTask::set_users((int)(users + 10 * rate_scale));
409         } else {
410             CallGenerationTask::set_rate(rate + 10 * rate_scale);
411         }
412         print_statistics(0);
413         break;
414 
415     case '/':
416         if (users >= 0) {
417             CallGenerationTask::set_users((int)(users - 10 * rate_scale));
418         } else {
419             CallGenerationTask::set_rate(rate - 10 * rate_scale);
420         }
421         print_statistics(0);
422         break;
423 
424     case 'p':
425         if (paused) {
426             CallGenerationTask::set_paused(false);
427         } else {
428             CallGenerationTask::set_paused(true);
429         }
430         print_statistics(0);
431         break;
432 
433     case 's':
434         if (screenf) {
435             print_screens();
436         }
437         break;
438 
439     case 'q':
440         quitting+=10;
441         print_statistics(0);
442         break;
443 
444     case 'Q':
445         /* We are going to break, so we never have a chance to press q twice. */
446         quitting+=20;
447         print_statistics(0);
448         break;
449     }
450     return false;
451 }
452 
handle_ctrl_socket()453 int handle_ctrl_socket()
454 {
455     unsigned char bufrcv [SIPP_MAX_MSG_SIZE];
456 
457     int ret = recv(ctrl_socket->ss_fd, bufrcv, sizeof(bufrcv) - 1, 0);
458     if (ret <= 0) {
459         return ret;
460     }
461 
462     if (bufrcv[0] == 'c') {
463         /* No 'c', but we need one for '\0'. */
464         char *command = (char *)malloc(ret);
465         if (!command) {
466             ERROR("Out of memory allocated command buffer.");
467         }
468         memcpy(command, bufrcv + 1, ret - 1);
469         command[ret - 1] = '\0';
470         process_command(command);
471         free(command);
472     } else {
473         process_key(bufrcv[0]);
474     }
475     return 0;
476 }
477 
setup_ctrl_socket()478 void setup_ctrl_socket()
479 {
480     int port, firstport;
481     int try_counter = 60;
482     struct sockaddr_storage ctl_sa;
483 
484     int sock = socket(AF_INET, SOCK_DGRAM, 0);
485     if (sock == -1) {
486         ERROR_NO("Unable to create remote control socket!");
487     }
488 
489     if (control_port) {
490         port = control_port;
491         /* If the user specified the control port, then we must assume they know
492          * what they want, and should not cycle. */
493         try_counter = 1;
494     } else {
495         /* Allow 60 control sockets on the same system */
496         /* (several SIPp instances)                   */
497         port = DEFAULT_CTRL_SOCKET_PORT;
498     }
499     firstport = port;
500 
501     memset(&ctl_sa, 0, sizeof(struct sockaddr_storage));
502     if (control_ip[0]) {
503         struct addrinfo hints;
504         struct addrinfo *addrinfo;
505 
506         memset((char*)&hints, 0, sizeof(hints));
507         hints.ai_flags  = AI_PASSIVE;
508         hints.ai_family = PF_UNSPEC;
509 
510         if (getaddrinfo(control_ip, NULL, &hints, &addrinfo) != 0) {
511             ERROR("Unknown control address '%s'.\n"
512                   "Use 'sipp -h' for details", control_ip);
513         }
514 
515         memcpy(&ctl_sa, addrinfo->ai_addr, SOCK_ADDR_SIZE(_RCAST(struct sockaddr_storage *, addrinfo->ai_addr)));
516         freeaddrinfo(addrinfo);
517     } else {
518         ((struct sockaddr_in *)&ctl_sa)->sin_family = AF_INET;
519         ((struct sockaddr_in *)&ctl_sa)->sin_addr.s_addr = INADDR_ANY;
520     }
521 
522     while (try_counter) {
523         ((struct sockaddr_in *)&ctl_sa)->sin_port = htons(port);
524         if (!::bind(sock, (struct sockaddr *)&ctl_sa, sizeof(struct sockaddr_in))) {
525             /* Bind successful */
526             break;
527         }
528         try_counter--;
529         port++;
530     }
531 
532     if (try_counter == 0) {
533         if (control_port) {
534             ERROR_NO("Unable to bind remote control socket to UDP port %d",
535                      control_port);
536         } else {
537             WARNING("Unable to bind remote control socket (tried UDP ports %d-%d): %s",
538                     firstport, port - 1, strerror(errno));
539         }
540         return;
541     }
542 
543     ctrl_socket = sipp_allocate_socket(0, T_UDP, sock, 0);
544     if (!ctrl_socket) {
545         ERROR_NO("Could not setup control socket!\n");
546     }
547 }
548 
reset_stdin()549 static void reset_stdin() {
550   fcntl(fileno(stdin), F_SETFL, stdin_mode);
551 }
552 
setup_stdin_socket()553 void setup_stdin_socket()
554 {
555     stdin_mode = fcntl(fileno(stdin), F_GETFL);
556     fcntl(fileno(stdin), F_SETFL, stdin_mode | O_NONBLOCK);
557     atexit(reset_stdin);
558     stdin_socket = sipp_allocate_socket(0, T_UDP, fileno(stdin), 0);
559     if (!stdin_socket) {
560         ERROR_NO("Could not setup keyboard (stdin) socket!\n");
561     }
562 }
563 
564 #define SIPP_ENDL "\r\n"
handle_stdin_socket()565 void handle_stdin_socket()
566 {
567     int c;
568     int chars = 0;
569 
570     if (feof(stdin)) {
571         sipp_close_socket(stdin_socket);
572         stdin_socket = NULL;
573         return;
574     }
575 
576     while (((c = screen_readkey()) != -1)) {
577         chars++;
578         if (command_mode) {
579             if (c == '\n') {
580                 bool quit = process_command(command_buffer);
581                 if (quit) {
582                     return;
583                 }
584                 command_buffer[0] = '\0';
585                 command_mode = 0;
586                 printf(SIPP_ENDL);
587             }
588 #ifndef __SUNOS
589             else if (c == KEY_BACKSPACE || c == KEY_DC)
590 #else
591             else if (c == 14)
592 #endif
593             {
594                 int command_len = strlen(command_buffer);
595                 if (command_len > 0) {
596                     command_buffer[command_len--] = '\0';
597                 }
598             } else {
599                 int command_len = strlen(command_buffer);
600                 char *realloc_ptr = (char *)realloc(command_buffer, command_len + 2);
601                 if (realloc_ptr) {
602                     command_buffer = realloc_ptr;
603                 } else {
604                     free(command_buffer);
605                     ERROR("Out of memory");
606                     return;
607                 }
608                 command_buffer[command_len++] = c;
609                 command_buffer[command_len] = '\0';
610                 putchar(c);
611                 fflush(stdout);
612             }
613         } else if (c == 'c') {
614             command_mode = 1;
615             char *realloc_ptr = (char *)realloc(command_buffer, 1);
616             if (realloc_ptr) {
617                 command_buffer = realloc_ptr;
618             } else {
619                 free(command_buffer);
620                 ERROR("Out of memory");
621                 return;
622             }
623             command_buffer[0] = '\0';
624             printf("Command: ");
625             fflush(stdout);
626         } else {
627             process_key(c);
628         }
629     }
630     if (chars == 0) {
631         /* We did not read any characters, even though we should have. */
632         sipp_close_socket(stdin_socket);
633         stdin_socket = NULL;
634     }
635 }
636 
637 /****************************** Network Interface *******************/
638 
639 /* Our message detection states: */
640 #define CFM_NORMAL 0 /* No CR Found, searchign for \r\n\r\n. */
641 #define CFM_CONTROL 1 /* Searching for 27 */
642 #define CFM_CR 2 /* CR Found, Searching for \n\r\n */
643 #define CFM_CRLF 3 /* CRLF Found, Searching for \r\n */
644 #define CFM_CRLFCR 4 /* CRLFCR Found, Searching for \n */
645 #define CFM_CRLFCRLF 5 /* We've found the end of the headers! */
646 
merge_socketbufs(struct socketbuf * socketbuf)647 static void merge_socketbufs(struct socketbuf* socketbuf)
648 {
649     struct socketbuf *next = socketbuf->next;
650     int newsize;
651     char *newbuf;
652 
653     if (!next) {
654         return;
655     }
656 
657     if (next->offset) {
658         ERROR("Internal error: can not merge a socketbuf with a non-zero offset.");
659     }
660 
661     if (socketbuf->offset) {
662         memmove(socketbuf->buf, socketbuf->buf + socketbuf->offset, socketbuf->len - socketbuf->offset);
663         socketbuf->len -= socketbuf->offset;
664         socketbuf->offset = 0;
665     }
666 
667     newsize = socketbuf->len + next->len;
668 
669     newbuf = (char *)realloc(socketbuf->buf, newsize);
670     if (!newbuf) {
671         ERROR("Could not allocate memory to merge socket buffers!");
672     }
673     memcpy(newbuf + socketbuf->len, next->buf, next->len);
674     socketbuf->buf = newbuf;
675     socketbuf->len = newsize;
676     socketbuf->next = next->next;
677     free_socketbuf(next);
678 }
679 
680 /* Check for a message in the socket and return the length of the first
681  * message.  If this is UDP, the only check is if we have buffers.  If this is
682  * TCP or TLS we need to parse out the content-length. */
check_for_message(struct sipp_socket * socket)683 static int check_for_message(struct sipp_socket* socket)
684 {
685     struct socketbuf *socketbuf = socket->ss_in;
686     int state = socket->ss_control ? CFM_CONTROL : CFM_NORMAL;
687     const char *l;
688 
689     if (!socketbuf)
690         return 0;
691 
692     if (socket->ss_transport == T_UDP || socket->ss_transport == T_SCTP) {
693         return socketbuf->len;
694     }
695 
696     int len = 0;
697 
698     while (socketbuf->offset + len < socketbuf->len) {
699         char c = socketbuf->buf[socketbuf->offset + len];
700 
701         switch(state) {
702         case CFM_CONTROL:
703             /* For CMD Message the escape char is the end of message */
704             if (c == 27) {
705                 return len + 1; /* The plus one includes the control character. */
706             }
707             break;
708         case CFM_NORMAL:
709             if (c == '\r') {
710                 state = CFM_CR;
711             }
712             break;
713         case CFM_CR:
714             if (c == '\n') {
715                 state = CFM_CRLF;
716             } else {
717                 state = CFM_NORMAL;
718             }
719             break;
720         case CFM_CRLF:
721             if (c == '\r') {
722                 state = CFM_CRLFCR;
723             } else {
724                 state = CFM_NORMAL;
725             }
726             break;
727         case CFM_CRLFCR:
728             if (c == '\n') {
729                 state = CFM_CRLFCRLF;
730             } else {
731                 state = CFM_NORMAL;
732             }
733             break;
734         }
735 
736         /* Head off failing because the buffer does not contain the whole header. */
737         if (socketbuf->offset + len == socketbuf->len - 1) {
738             merge_socketbufs(socketbuf);
739         }
740 
741         if (state == CFM_CRLFCRLF) {
742             break;
743         }
744 
745         len++;
746     }
747 
748     /* We did not find the end-of-header marker. */
749     if (state != CFM_CRLFCRLF) {
750         return 0;
751     }
752 
753     /* Find the content-length header. */
754     if ((l = strncasestr(socketbuf->buf + socketbuf->offset, "\r\nContent-Length:", len))) {
755         l += strlen("\r\nContent-Length:");
756     } else if ((l = strncasestr(socketbuf->buf + socketbuf->offset, "\r\nl:", len))) {
757         l += strlen("\r\nl:");
758     } else {
759         /* There is no header, so the content-length is zero. */
760         return len + 1;
761     }
762 
763     /* Skip spaces. */
764     while (isspace(*l)) {
765         if (*l == '\r' || *l == '\n') {
766             /* We ran into an end-of-line, so there is no content-length. */
767             return len + 1;
768         }
769         l++;
770     }
771 
772     /* Do the integer conversion, we only allow '\r' or spaces after the integer. */
773     char *endptr;
774     int content_length = strtol(l, &endptr, 10);
775     if (*endptr != '\r' && !isspace(*endptr)) {
776         content_length = 0;
777     }
778 
779     /* Now that we know how large this message is, we make sure we have the whole thing. */
780     do {
781         /* It is in this buffer. */
782         if (socketbuf->offset + len + content_length < socketbuf->len) {
783             return len + content_length + 1;
784         }
785         if (socketbuf->next == NULL) {
786             /* There is no buffer to merge, so we fail. */
787             return 0;
788         }
789         /* We merge ourself with the next buffer. */
790         merge_socketbufs(socketbuf);
791     } while (1);
792 }
793 
794 #ifdef USE_SCTP
handleSCTPNotify(struct sipp_socket * socket,char * buffer)795 static int handleSCTPNotify(struct sipp_socket* socket, char* buffer)
796 {
797     union sctp_notification *notifMsg;
798 
799     notifMsg = (union sctp_notification *)buffer;
800 
801     TRACE_MSG("SCTP Notification: %d\n",
802               ntohs(notifMsg->sn_header.sn_type));
803     if (notifMsg->sn_header.sn_type == SCTP_ASSOC_CHANGE) {
804         TRACE_MSG("SCTP_ASSOC_CHANGE\n");
805         if (notifMsg->sn_assoc_change.sac_state == SCTP_COMM_UP) {
806             TRACE_MSG("SCTP_COMM_UP\n");
807             socket->sctpstate = SCTP_UP;
808             sipp_sctp_peer_params(socket);
809 
810             /* Send SCTP message right after association is up */
811             socket->ss_congested = false;
812             flush_socket(socket);
813             return -2;
814         } else {
815             TRACE_MSG("else: %d\n", notifMsg->sn_assoc_change.sac_state);
816             return 0;
817         }
818     } else if (notifMsg->sn_header.sn_type == SCTP_SHUTDOWN_EVENT) {
819         TRACE_MSG("SCTP_SHUTDOWN_EVENT\n");
820         return 0;
821     }
822     return -2;
823 }
824 
set_multihome_addr(struct sipp_socket * socket,int port)825 void set_multihome_addr(struct sipp_socket* socket, int port)
826 {
827     if (strlen(multihome_ip)>0) {
828         struct addrinfo * multi_addr;
829         struct addrinfo   hints;
830         memset((char*)&hints, 0, sizeof(hints));
831         hints.ai_flags  = AI_PASSIVE;
832         hints.ai_family = PF_UNSPEC;
833 
834         if (getaddrinfo(multihome_ip, NULL, &hints, &multi_addr) != 0) {
835             ERROR("Can't get multihome IP address in getaddrinfo, multihome_ip='%s'", multihome_ip);
836         }
837 
838         struct sockaddr_storage secondaryaddress;
839         memset(&secondaryaddress, 0, sizeof(secondaryaddress));
840 
841         memcpy(&secondaryaddress, multi_addr->ai_addr, SOCK_ADDR_SIZE(_RCAST(struct sockaddr_storage *, multi_addr->ai_addr)));
842         freeaddrinfo(multi_addr);
843 
844         if (port>0) {
845             if (secondaryaddress.ss_family==AF_INET) ((struct sockaddr_in*)&secondaryaddress)->sin_port=htons(port);
846             else if (secondaryaddress.ss_family==AF_INET6) ((struct sockaddr_in6*)&secondaryaddress)->sin6_port=htons(port);
847         }
848 
849         int ret = sctp_bindx(socket->ss_fd, (struct sockaddr *) &secondaryaddress,
850                              1, SCTP_BINDX_ADD_ADDR);
851         if (ret < 0) {
852             WARNING("Can't bind to multihome address, errno='%d'", errno);
853         }
854     }
855 }
856 #endif
857 
858 /* Pull up to tcp_readsize data bytes out of the socket into our local buffer. */
empty_socket(struct sipp_socket * socket)859 int empty_socket(struct sipp_socket *socket)
860 {
861 
862     int readsize=0;
863     if (socket->ss_transport == T_UDP || socket->ss_transport == T_SCTP) {
864         readsize = SIPP_MAX_MSG_SIZE;
865     } else {
866         readsize = tcp_readsize;
867     }
868 
869     struct socketbuf *socketbuf;
870     char *buffer;
871     int ret = -1;
872     /* Where should we start sending packets to, ideally we should begin to parse
873      * the Via, Contact, and Route headers.  But for now SIPp always sends to the
874      * host specified on the command line; or for UAS mode to the address that
875      * sent the last message. */
876     sipp_socklen_t addrlen = sizeof(struct sockaddr_storage);
877 
878     buffer = (char *)malloc(readsize);
879     if (!buffer) {
880         ERROR("Could not allocate memory for read!");
881     }
882     socketbuf = alloc_socketbuf(buffer, readsize, NO_COPY, NULL);
883 
884     switch(socket->ss_transport) {
885     case T_TCP:
886     case T_UDP:
887         ret = recvfrom(socket->ss_fd, buffer, readsize, 0, (struct sockaddr *)&socketbuf->addr,  &addrlen);
888         break;
889     case T_TLS:
890 #ifdef USE_OPENSSL
891         ret = SSL_read(socket->ss_ssl, buffer, readsize);
892         /* XXX: Check for clean shutdown. */
893 #else
894         ERROR("TLS support is not enabled!");
895 #endif
896         break;
897     case T_SCTP:
898 #ifdef USE_SCTP
899         struct sctp_sndrcvinfo recvinfo;
900         memset(&recvinfo, 0, sizeof(recvinfo));
901         int msg_flags = 0;
902 
903         ret = sctp_recvmsg(socket->ss_fd, (void*)buffer, readsize,
904                            (struct sockaddr *) &socketbuf->addr, &addrlen, &recvinfo, &msg_flags);
905 
906         if (MSG_NOTIFICATION & msg_flags) {
907             errno = 0;
908             handleSCTPNotify(socket, buffer);
909             ret = -2;
910         }
911 #else
912         ERROR("SCTP support is not enabled!");
913 #endif
914         break;
915     }
916     if (ret <= 0) {
917         free_socketbuf(socketbuf);
918         return ret;
919     }
920 
921     socketbuf->len = ret;
922 
923     buffer_read(socket, socketbuf);
924 
925     /* Do we have a complete SIP message? */
926     if (!socket->ss_msglen) {
927         if (int msg_len = check_for_message(socket)) {
928             socket->ss_msglen = msg_len;
929             pending_messages++;
930         }
931     }
932 
933     return ret;
934 }
935 
sipp_socket_invalidate(struct sipp_socket * socket)936 void sipp_socket_invalidate(struct sipp_socket *socket)
937 {
938     int pollidx;
939 
940     if (socket->ss_invalid) {
941         return;
942     }
943 
944 #ifdef USE_OPENSSL
945     if (SSL *ssl = socket->ss_ssl) {
946         SSL_set_shutdown(ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
947         SSL_free(ssl);
948     }
949 #endif
950 
951     /* In some error conditions, the socket FD has already been closed - if it hasn't, do so now. */
952     if (socket->ss_fd != -1) {
953 #ifdef HAVE_EPOLL
954         int rc = epoll_ctl(epollfd, EPOLL_CTL_DEL, socket->ss_fd, NULL);
955         if (rc == -1) {
956             WARNING_NO("Failed to delete FD from epoll");
957         }
958 #endif
959         shutdown(socket->ss_fd, SHUT_RDWR);
960 
961 #ifdef USE_SCTP
962         if (socket->ss_transport == T_SCTP && !gracefulclose) {
963             struct linger ling = {1, 0};
964             if (setsockopt(socket->ss_fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) {
965                 WARNING("Unable to set SO_LINGER option for SCTP close");
966             }
967         }
968 #endif
969 
970         sipp_abort_connection(socket->ss_fd);
971         socket->ss_fd = -1;
972     }
973 
974     if ((pollidx = socket->ss_pollidx) >= pollnfds) {
975         ERROR("Pollset error: index %d is greater than number of fds %d!", pollidx, pollnfds);
976     }
977 
978     socket->ss_invalid = true;
979     socket->ss_pollidx = -1;
980 
981     /* Adds call sockets in the array */
982     assert(pollnfds > 0);
983 
984     pollnfds--;
985 #ifdef HAVE_EPOLL
986     if (pollidx < pollnfds) {
987         epollfiles[pollidx] = epollfiles[pollnfds];
988         epollfiles[pollidx].data.u32 = pollidx;
989         if (sockets[pollnfds]->ss_fd != -1) {
990             int rc = epoll_ctl(epollfd, EPOLL_CTL_MOD, sockets[pollnfds]->ss_fd, &epollfiles[pollidx]);
991             if ((rc == -1) && (errno != EPERM)) {
992                 // Ignore "Operation not supported"  errors -
993                 // otherwise we get log spam when redirecting stdout
994                 // to /dev/null
995                 WARNING_NO("Failed to update FD within epoll");
996             }
997         }
998     }
999 #else
1000     pollfiles[pollidx] = pollfiles[pollnfds];
1001 #endif
1002     sockets[pollidx] = sockets[pollnfds];
1003     sockets[pollidx]->ss_pollidx = pollidx;
1004     sockets[pollnfds] = NULL;
1005 
1006     if (socket->ss_msglen) {
1007         pending_messages--;
1008     }
1009 
1010 #ifdef USE_SCTP
1011     if (socket->ss_transport == T_SCTP) {
1012         socket->sctpstate = SCTP_DOWN;
1013     }
1014 #endif
1015 }
1016 
sipp_abort_connection(int fd)1017 void sipp_abort_connection(int fd) {
1018     /* Disable linger - we'll send a RST when we close. */
1019     struct linger flush;
1020     flush.l_onoff = 1;
1021     flush.l_linger = 0;
1022     setsockopt(fd, SOL_SOCKET, SO_LINGER, &flush, sizeof(flush));
1023 
1024     /* Mark the socket as non-blocking.  It's not clear whether this is required but can't hurt. */
1025     int flags = fcntl(fd, F_GETFL, 0);
1026     fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1027 
1028     /* Actually close the socket. */
1029     close(fd);
1030 }
1031 
sipp_close_socket(struct sipp_socket * socket)1032 void sipp_close_socket (struct sipp_socket *socket)
1033 {
1034     int count = --socket->ss_count;
1035 
1036     if (count > 0) {
1037         return;
1038     }
1039 
1040     sipp_socket_invalidate(socket);
1041     sockets_pending_reset.erase(socket);
1042     free(socket);
1043 }
1044 
read_message(struct sipp_socket * socket,char * buf,size_t len,struct sockaddr_storage * src)1045 ssize_t read_message(struct sipp_socket *socket, char *buf, size_t len, struct sockaddr_storage *src)
1046 {
1047     size_t avail;
1048 
1049     if (!socket->ss_msglen)
1050         return 0;
1051     if (socket->ss_msglen > len)
1052         ERROR("There is a message waiting in sockfd(%d) that is bigger (%zu bytes) than the read size.",
1053               socket->ss_fd, socket->ss_msglen);
1054 
1055     len = socket->ss_msglen;
1056 
1057     avail = socket->ss_in->len - socket->ss_in->offset;
1058     if (avail > len) {
1059         avail = len;
1060     }
1061 
1062     memcpy(buf, socket->ss_in->buf + socket->ss_in->offset, avail);
1063     memcpy(src, &socket->ss_in->addr, SOCK_ADDR_SIZE(&socket->ss_in->addr));
1064 
1065     /* Update our buffer and return value. */
1066     buf[avail] = '\0';
1067     /* For CMD Message the escape char is the end of message */
1068     if ((socket->ss_control) && buf[avail-1] == 27)
1069         buf[avail-1] = '\0';
1070 
1071     socket->ss_in->offset += avail;
1072 
1073     /* Have we emptied the buffer? */
1074     if (socket->ss_in->offset == socket->ss_in->len) {
1075         struct socketbuf *next = socket->ss_in->next;
1076         free_socketbuf(socket->ss_in);
1077         socket->ss_in = next;
1078     }
1079 
1080     if (int msg_len = check_for_message(socket)) {
1081         socket->ss_msglen = msg_len;
1082     } else {
1083         socket->ss_msglen = 0;
1084         pending_messages--;
1085     }
1086 
1087     return avail;
1088 }
1089 
process_message(struct sipp_socket * socket,char * msg,ssize_t msg_size,struct sockaddr_storage * src)1090 void process_message(struct sipp_socket *socket, char *msg, ssize_t msg_size, struct sockaddr_storage *src)
1091 {
1092     // TRACE_MSG(" msg_size %d and pollset_index is %d \n", msg_size, pollset_index));
1093     if (msg_size <= 0) {
1094         return;
1095     }
1096     if (sipMsgCheck(msg, socket) == false) {
1097         if (msg_size == 4 &&
1098                 (memcmp(msg, "\r\n\r\n", 4) == 0 || memcmp(msg, "\x00\x00\x00\x00", 4) == 0)) {
1099             /* Common keepalives */;
1100         } else {
1101             WARNING("non SIP message discarded: \"%.*s\" (%zu)", (int)msg_size, msg, msg_size);
1102         }
1103         return;
1104     }
1105 
1106     const char *call_id = get_trimmed_call_id(msg);
1107     if (call_id[0] == '\0') {
1108         WARNING("SIP message without Call-ID discarded");
1109         return;
1110     }
1111     listener *listener_ptr = get_listener(call_id);
1112     struct timeval currentTime;
1113     GET_TIME (&currentTime);
1114 
1115     if (useShortMessagef == 1) {
1116         TRACE_SHORTMSG("%s\tR\t%s\tCSeq:%s\t%s\n",
1117                        CStat::formatTime(&currentTime), call_id, get_header_content(msg, "CSeq:"), get_first_line(msg));
1118     }
1119 
1120     if (useMessagef == 1) {
1121         TRACE_MSG("----------------------------------------------- %s\n"
1122                   "%s %smessage received [%zu] bytes :\n\n%s\n",
1123                   CStat::formatTime(&currentTime, true),
1124                   TRANSPORT_TO_STRING(socket->ss_transport),
1125                   socket->ss_control ? "control " : "",
1126                   msg_size, msg);
1127     }
1128 
1129     if (!listener_ptr) {
1130         if (thirdPartyMode == MODE_3PCC_CONTROLLER_B || thirdPartyMode == MODE_3PCC_A_PASSIVE ||
1131                 thirdPartyMode == MODE_MASTER_PASSIVE || thirdPartyMode == MODE_SLAVE) {
1132             // Adding a new OUTGOING call !
1133             main_scenario->stats->computeStat(CStat::E_CREATE_OUTGOING_CALL);
1134             call *new_ptr = new call(call_id, local_ip_is_ipv6, 0, use_remote_sending_addr ? &remote_sending_sockaddr : &remote_sockaddr);
1135             if (!new_ptr) {
1136                 ERROR("Out of memory allocating a call!");
1137             }
1138 
1139             outbound_congestion = false;
1140             if ((socket != main_socket) &&
1141                     (socket != tcp_multiplex) &&
1142                     (socket != localTwinSippSocket) &&
1143                     (socket != twinSippSocket) &&
1144                     (!is_a_local_socket(socket))) {
1145                 new_ptr->associate_socket(socket);
1146                 socket->ss_count++;
1147             } else {
1148                 /* We need to hook this call up to a real *call* socket. */
1149                 if (!multisocket) {
1150                     switch(transport) {
1151                     case T_UDP:
1152                         new_ptr->associate_socket(main_socket);
1153                         main_socket->ss_count++;
1154                         break;
1155                     case T_TCP:
1156                     case T_SCTP:
1157                     case T_TLS:
1158                         new_ptr->associate_socket(tcp_multiplex);
1159                         tcp_multiplex->ss_count++;
1160                         break;
1161                     }
1162                 }
1163             }
1164             listener_ptr = new_ptr;
1165         } else if (creationMode == MODE_SERVER) {
1166             if (quitting >= 1) {
1167                 CStat::globalStat(CStat::E_OUT_OF_CALL_MSGS);
1168                 TRACE_MSG("Discarded message for new calls while quitting\n");
1169                 return;
1170             }
1171 
1172             // Adding a new INCOMING call !
1173             main_scenario->stats->computeStat(CStat::E_CREATE_INCOMING_CALL);
1174             listener_ptr = new call(call_id, socket, use_remote_sending_addr ? &remote_sending_sockaddr : src);
1175             if (!listener_ptr) {
1176                 ERROR("Out of memory allocating a call!");
1177             }
1178         } else { // mode != from SERVER and 3PCC Controller B
1179             // This is a message that is not relating to any known call
1180             if (ooc_scenario) {
1181                 if (!get_reply_code(msg)) {
1182                     char *msg_start = strdup(msg);
1183                     char *msg_start_end = msg_start;
1184                     while (!isspace(*msg_start_end) && (*msg_start_end != '\0')) {
1185                         msg_start_end++;
1186                     }
1187                     *msg_start_end = '\0';
1188                     ooc_scenario->stats->computeStat(CStat::E_CREATE_INCOMING_CALL);
1189                     WARNING("Received out-of-call %s message, using the out-of-call scenario", msg_start);
1190                     free(msg_start);
1191                     /* This should have the real address that the message came from. */
1192                     call *call_ptr = new call(ooc_scenario, socket, use_remote_sending_addr ? &remote_sending_sockaddr : src, call_id, 0 /* no user. */, socket->ss_ipv6, true, false);
1193                     if (!call_ptr) {
1194                         ERROR("Out of memory allocating a call!");
1195                     }
1196                     CStat::globalStat(CStat::E_AUTO_ANSWERED);
1197                     call_ptr->process_incoming(msg, src);
1198                 } else {
1199                     /* We received a response not relating to any known call */
1200                     /* Do nothing, even if in auto answer mode */
1201                     CStat::globalStat(CStat::E_OUT_OF_CALL_MSGS);
1202                 }
1203             } else if (auto_answer &&
1204                        ((strstr(msg, "INFO") == msg) ||
1205                         (strstr(msg, "NOTIFY") == msg) ||
1206                         (strstr(msg, "OPTIONS") == msg) ||
1207                         (strstr(msg, "UPDATE") == msg))) {
1208                 // If auto answer mode, try to answer the incoming message
1209                 // with automaticResponseMode
1210                 // call is discarded before exiting the block
1211                 if (!get_reply_code(msg)) {
1212                     aa_scenario->stats->computeStat(CStat::E_CREATE_INCOMING_CALL);
1213                     /* This should have the real address that the message came from. */
1214                     call *call_ptr = new call(aa_scenario, socket, use_remote_sending_addr ? &remote_sending_sockaddr : src, call_id, 0 /* no user. */, socket->ss_ipv6, true, false);
1215                     if (!call_ptr) {
1216                         ERROR("Out of memory allocating a call!");
1217                     }
1218                     CStat::globalStat(CStat::E_AUTO_ANSWERED);
1219                     call_ptr->process_incoming(msg, src);
1220                 } else {
1221                     fprintf(stderr, "%s", msg);
1222                     /* We received a response not relating to any known call */
1223                     /* Do nothing, even if in auto answer mode */
1224                     CStat::globalStat(CStat::E_OUT_OF_CALL_MSGS);
1225                 }
1226             } else {
1227                 CStat::globalStat(CStat::E_OUT_OF_CALL_MSGS);
1228                 WARNING("Discarding message which can't be mapped to a known SIPp call:\n%s", msg);
1229             }
1230         }
1231     }
1232 
1233     /* If the call was not created above, we just drop this message. */
1234     if (!listener_ptr) {
1235         return;
1236     }
1237 
1238     if ((socket == localTwinSippSocket) || (socket == twinSippSocket) || (is_a_local_socket(socket))) {
1239         listener_ptr -> process_twinSippCom(msg);
1240     } else {
1241         listener_ptr -> process_incoming(msg, src);
1242     }
1243 }
1244 
sipp_allocate_socket(bool use_ipv6,int transport,int fd,int accepting)1245 struct sipp_socket *sipp_allocate_socket(bool use_ipv6, int transport, int fd, int accepting) {
1246     struct sipp_socket *ret = (struct sipp_socket *)malloc(sizeof(struct sipp_socket));
1247     if (!ret) {
1248         ERROR("Could not allocate a sipp_socket structure.");
1249     }
1250     memset(ret, 0, sizeof(struct sipp_socket));
1251 
1252     ret->ss_transport = transport;
1253     ret->ss_control = false;
1254     ret->ss_ipv6 = use_ipv6;
1255     ret->ss_fd = fd;
1256     ret->ss_comp_state = NULL;
1257     ret->ss_count = 1;
1258     ret->ss_changed_dest = false;
1259 
1260     /* Initialize all sockets with our destination address. */
1261     memcpy(&ret->ss_remote_sockaddr, &remote_sockaddr, sizeof(ret->ss_remote_sockaddr));
1262 
1263 #ifdef USE_OPENSSL
1264     ret->ss_ssl = NULL;
1265 
1266     if ( transport == T_TLS ) {
1267         if ((ret->ss_bio = BIO_new_socket(fd, BIO_NOCLOSE)) == NULL) {
1268             ERROR("Unable to create BIO object:Problem with BIO_new_socket()\n");
1269         }
1270 
1271         if (!(ret->ss_ssl = SSL_new(accepting ? sip_trp_ssl_ctx : sip_trp_ssl_ctx_client))) {
1272             ERROR("Unable to create SSL object : Problem with SSL_new() \n");
1273         }
1274 
1275         SSL_set_bio(ret->ss_ssl, ret->ss_bio, ret->ss_bio);
1276     }
1277 #endif
1278 
1279     ret->ss_in = NULL;
1280     ret->ss_out = NULL;
1281     ret->ss_msglen = 0;
1282     ret->ss_congested = false;
1283     ret->ss_invalid = false;
1284 
1285     /* Store this socket in the tables. */
1286     ret->ss_pollidx = pollnfds++;
1287     sockets[ret->ss_pollidx] = ret;
1288 #ifdef HAVE_EPOLL
1289     epollfiles[ret->ss_pollidx].data.u32 = ret->ss_pollidx;
1290     epollfiles[ret->ss_pollidx].events   = EPOLLIN;
1291     int rc = epoll_ctl(epollfd, EPOLL_CTL_ADD, ret->ss_fd, &epollfiles[ret->ss_pollidx]);
1292     if (rc == -1) {
1293         if (errno == EPERM) {
1294             // Attempted to use epoll on a file that does not support
1295             // it - this may happen legitimately when stdin/stdout is
1296             // redirected to /dev/null, so don't warn
1297         } else {
1298             ERROR_NO("Failed to add FD to epoll");
1299         }
1300     }
1301 #else
1302      pollfiles[ret->ss_pollidx].fd      = ret->ss_fd;
1303      pollfiles[ret->ss_pollidx].events  = POLLIN | POLLERR;
1304      pollfiles[ret->ss_pollidx].revents = 0;
1305 #endif
1306 
1307     return ret;
1308 }
1309 
sipp_allocate_socket(bool use_ipv6,int transport,int fd)1310 static struct sipp_socket* sipp_allocate_socket(bool use_ipv6, int transport, int fd) {
1311     return sipp_allocate_socket(use_ipv6, transport, fd, 0);
1312 }
1313 
socket_fd(bool use_ipv6,int transport)1314 static int socket_fd(bool use_ipv6, int transport)
1315 {
1316     int socket_type = -1;
1317     int protocol = 0;
1318     int fd;
1319 
1320     switch(transport) {
1321     case T_UDP:
1322         socket_type = SOCK_DGRAM;
1323         protocol = IPPROTO_UDP;
1324         break;
1325     case T_SCTP:
1326 #ifndef USE_SCTP
1327         ERROR("You do not have SCTP support enabled!\n");
1328 #else
1329         socket_type = SOCK_STREAM;
1330         protocol = IPPROTO_SCTP;
1331 #endif
1332         break;
1333     case T_TLS:
1334 #ifndef USE_OPENSSL
1335         ERROR("You do not have TLS support enabled!\n");
1336 #endif
1337     case T_TCP:
1338         socket_type = SOCK_STREAM;
1339         break;
1340     }
1341 
1342     if ((fd = socket(use_ipv6 ? AF_INET6 : AF_INET, socket_type, protocol))== -1) {
1343         ERROR("Unable to get a %s socket (3)", TRANSPORT_TO_STRING(transport));
1344     }
1345 
1346     return fd;
1347 }
1348 
new_sipp_socket(bool use_ipv6,int transport)1349 struct sipp_socket *new_sipp_socket(bool use_ipv6, int transport) {
1350     struct sipp_socket *ret;
1351     int fd = socket_fd(use_ipv6, transport);
1352 
1353 #if defined(__SUNOS)
1354     if (fd < 256) {
1355         int newfd = fcntl(fd, F_DUPFD, 256);
1356         if (newfd <= 0) {
1357             // Typically, (24)(Too many open files) is the error here
1358             WARNING("Unable to get a different %s socket, errno=%d(%s)",
1359                     TRANSPORT_TO_STRING(transport), errno, strerror(errno));
1360 
1361             // Keep the original socket fd.
1362             newfd = fd;
1363         } else {
1364             close(fd);
1365         }
1366         fd = newfd;
1367     }
1368 #endif
1369 
1370     ret = sipp_allocate_socket(use_ipv6, transport, fd);
1371     if (!ret) {
1372         close(fd);
1373         ERROR("Could not allocate new socket structure!");
1374     }
1375     return ret;
1376 }
1377 
new_sipp_call_socket(bool use_ipv6,int transport,bool * existing)1378 struct sipp_socket *new_sipp_call_socket(bool use_ipv6, int transport, bool *existing) {
1379     struct sipp_socket *sock = NULL;
1380     static int next_socket;
1381     if (pollnfds >= max_multi_socket) {  // we must take the main socket into account
1382         /* Find an existing socket that matches transport and ipv6 parameters. */
1383         int first = next_socket;
1384         do {
1385             int test_socket = next_socket;
1386             next_socket = (next_socket + 1) % pollnfds;
1387 
1388             if (sockets[test_socket]->ss_call_socket) {
1389                 /* Here we need to check that the address is the default. */
1390                 if (sockets[test_socket]->ss_ipv6 != use_ipv6) {
1391                     continue;
1392                 }
1393                 if (sockets[test_socket]->ss_transport != transport) {
1394                     continue;
1395                 }
1396                 if (sockets[test_socket]->ss_changed_dest) {
1397                     continue;
1398                 }
1399 
1400                 sock = sockets[test_socket];
1401                 sock->ss_count++;
1402                 *existing = true;
1403                 break;
1404             }
1405         } while (next_socket != first);
1406         if (next_socket == first) {
1407             ERROR("Could not find an existing call socket to re-use!");
1408         }
1409     } else {
1410         sock = new_sipp_socket(use_ipv6, transport);
1411         sock->ss_call_socket = true;
1412         *existing = false;
1413     }
1414     return sock;
1415 }
1416 
sipp_accept_socket(struct sipp_socket * accept_socket)1417 struct sipp_socket *sipp_accept_socket(struct sipp_socket *accept_socket) {
1418     struct sipp_socket *ret;
1419     struct sockaddr_storage remote_sockaddr;
1420     int fd;
1421     sipp_socklen_t addrlen = sizeof(remote_sockaddr);
1422 
1423     if ((fd = accept(accept_socket->ss_fd, (struct sockaddr *)&remote_sockaddr, &addrlen))== -1) {
1424         ERROR("Unable to accept on a %s socket: %s", TRANSPORT_TO_STRING(transport), strerror(errno));
1425     }
1426 
1427 #if defined(__SUNOS)
1428     if (fd < 256) {
1429         int newfd = fcntl(fd, F_DUPFD, 256);
1430         if (newfd <= 0) {
1431             // Typically, (24)(Too many open files) is the error here
1432             WARNING("Unable to get a different %s socket, errno=%d(%s)",
1433                     TRANSPORT_TO_STRING(transport), errno, strerror(errno));
1434 
1435             // Keep the original socket fd.
1436             newfd = fd;
1437         } else {
1438             close(fd);
1439         }
1440         fd = newfd;
1441     }
1442 #endif
1443 
1444 
1445     ret = sipp_allocate_socket(accept_socket->ss_ipv6, accept_socket->ss_transport, fd, 1);
1446     if (!ret) {
1447         close(fd);
1448         ERROR_NO("Could not allocate new socket!");
1449     }
1450 
1451     memcpy(&ret->ss_remote_sockaddr, &remote_sockaddr, sizeof(ret->ss_remote_sockaddr));
1452     /* We should connect back to the address which connected to us if we
1453      * experience a TCP failure. */
1454     memcpy(&ret->ss_dest, &remote_sockaddr, sizeof(ret->ss_remote_sockaddr));
1455 
1456     if (ret->ss_transport == T_TLS) {
1457 #ifdef USE_OPENSSL
1458         int err;
1459         if ((err = SSL_accept(ret->ss_ssl)) < 0) {
1460             ERROR("Error in SSL_accept: %s\n", sip_tls_error_string(accept_socket->ss_ssl, err));
1461         }
1462 #else
1463         ERROR("You need to compile SIPp with TLS support");
1464 #endif
1465     }
1466 
1467     return ret;
1468 }
1469 
sipp_bind_socket(struct sipp_socket * socket,struct sockaddr_storage * saddr,int * port)1470 int sipp_bind_socket(struct sipp_socket *socket, struct sockaddr_storage *saddr, int *port)
1471 {
1472     int ret;
1473     int len;
1474 
1475 
1476 #ifdef USE_SCTP
1477     if (transport==T_SCTP && multisocket==1 && *port==-1) {
1478         if (socket->ss_ipv6) {
1479             (_RCAST(struct sockaddr_in6 *, saddr))->sin6_port=0;
1480         } else {
1481             (_RCAST(struct sockaddr_in *, saddr))->sin_port=0;
1482         }
1483     }
1484 #endif
1485 
1486     if (socket->ss_ipv6) {
1487         len = sizeof(struct sockaddr_in6);
1488     } else {
1489         len = sizeof(struct sockaddr_in);
1490     }
1491 
1492     if ((ret = ::bind(socket->ss_fd, (sockaddr *)saddr, len))) {
1493         return ret;
1494     }
1495 
1496     if (!port) {
1497         return 0;
1498     }
1499 
1500     if ((ret = getsockname(socket->ss_fd, (sockaddr *)saddr, (sipp_socklen_t *) &len))) {
1501         return ret;
1502     }
1503 
1504     if (socket->ss_ipv6) {
1505         *port = ntohs((short)((_RCAST(struct sockaddr_in6 *, saddr))->sin6_port));
1506     } else {
1507         *port = ntohs((short)((_RCAST(struct sockaddr_in *, saddr))->sin_port));
1508     }
1509 
1510 #ifdef USE_SCTP
1511     if (transport == T_SCTP) {
1512         bool isany = false;
1513         if (socket->ss_ipv6) {
1514             if (memcmp(&(_RCAST(struct sockaddr_in6 *, saddr)->sin6_addr), &in6addr_any, sizeof(in6_addr)) == 0)
1515                 isany = true;
1516         } else {
1517             isany = (_RCAST(struct sockaddr_in *, saddr)->sin_addr.s_addr == INADDR_ANY);
1518         }
1519         if (!isany) {
1520             set_multihome_addr(socket, *port);
1521         }
1522     }
1523 #endif
1524 
1525     return 0;
1526 }
1527 
sipp_do_connect_socket(struct sipp_socket * socket)1528 static int sipp_do_connect_socket(struct sipp_socket* socket)
1529 {
1530     int ret;
1531 
1532     assert(socket->ss_transport == T_TCP || socket->ss_transport == T_TLS || socket->ss_transport == T_SCTP);
1533 
1534     if (socket->ss_transport == T_TCP || socket->ss_transport == T_TLS) {
1535         struct sockaddr_storage local_without_port;
1536         int port = -1;
1537         memcpy(&local_without_port, &local_sockaddr, sizeof(struct sockaddr_storage));
1538         if (local_ip_is_ipv6) {
1539             (_RCAST(struct sockaddr_in6 *, &local_without_port))->sin6_port = htons(0);
1540         } else {
1541             (_RCAST(struct sockaddr_in *, &local_without_port))->sin_port = htons(0);
1542         }
1543         sipp_bind_socket(socket, &local_without_port, &port);
1544     }
1545 #ifdef USE_SCTP
1546     if (socket->ss_transport == T_SCTP) {
1547         int port = -1;
1548         sipp_bind_socket(socket, &local_sockaddr, &port);
1549     }
1550 #endif
1551 
1552     int flags = fcntl(socket->ss_fd, F_GETFL, 0);
1553     fcntl(socket->ss_fd, F_SETFL, flags | O_NONBLOCK);
1554 
1555     errno = 0;
1556     ret = connect(socket->ss_fd, (struct sockaddr *)&socket->ss_dest, SOCK_ADDR_SIZE(&socket->ss_dest));
1557     if (ret < 0) {
1558         if (errno == EINPROGRESS) {
1559             /* Block this socket until the connect completes - this is very similar to entering congestion, but we don't want to increment congestion statistics. */
1560             enter_congestion(socket, 0);
1561             nb_net_cong--;
1562         } else {
1563             return ret;
1564         }
1565     }
1566 
1567     fcntl(socket->ss_fd, F_SETFL, flags);
1568 
1569     if (socket->ss_transport == T_TLS) {
1570 #ifdef USE_OPENSSL
1571         int err;
1572         if ((err = SSL_connect(socket->ss_ssl)) < 0) {
1573             ERROR("Error in SSL connection: %s\n", sip_tls_error_string(socket->ss_ssl, err));
1574         }
1575 #else
1576         ERROR("You need to compile SIPp with TLS support");
1577 #endif
1578     }
1579 
1580 #ifdef USE_SCTP
1581     if (socket->ss_transport == T_SCTP) {
1582         socket->sctpstate = SCTP_CONNECTING;
1583     }
1584 #endif
1585 
1586     return 0;
1587 }
1588 
sipp_connect_socket(struct sipp_socket * socket,struct sockaddr_storage * dest)1589 int sipp_connect_socket(struct sipp_socket *socket, struct sockaddr_storage *dest)
1590 {
1591     memcpy(&socket->ss_dest, dest, SOCK_ADDR_SIZE(dest));
1592     return sipp_do_connect_socket(socket);
1593 }
1594 
sipp_reconnect_socket(struct sipp_socket * socket)1595 int sipp_reconnect_socket(struct sipp_socket *socket)
1596 {
1597     if ((!socket->ss_invalid) &&
1598         (socket->ss_fd != -1)) {
1599         WARNING("When reconnecting socket, already have file descriptor %d", socket->ss_fd);
1600         sipp_abort_connection(socket->ss_fd);
1601         socket->ss_fd = -1;
1602     }
1603 
1604     socket->ss_fd = socket_fd(socket->ss_ipv6, socket->ss_transport);
1605     if (socket->ss_fd == -1) {
1606         ERROR_NO("Could not obtain new socket: ");
1607     }
1608 
1609     if (socket->ss_invalid) {
1610 #ifdef USE_OPENSSL
1611         socket->ss_ssl = NULL;
1612 
1613         if (transport == T_TLS) {
1614             if ((socket->ss_bio = BIO_new_socket(socket->ss_fd, BIO_NOCLOSE)) == NULL) {
1615                 ERROR("Unable to create BIO object:Problem with BIO_new_socket()\n");
1616             }
1617 
1618             if (!(socket->ss_ssl = SSL_new(sip_trp_ssl_ctx_client))) {
1619                 ERROR("Unable to create SSL object : Problem with SSL_new() \n");
1620             }
1621 
1622             SSL_set_bio(socket->ss_ssl, socket->ss_bio, socket->ss_bio);
1623         }
1624 #endif
1625 
1626         /* Store this socket in the tables. */
1627         socket->ss_pollidx = pollnfds++;
1628         sockets[socket->ss_pollidx] = socket;
1629 #ifdef HAVE_EPOLL
1630         epollfiles[socket->ss_pollidx].data.u32 = socket->ss_pollidx;
1631         epollfiles[socket->ss_pollidx].events   = EPOLLIN;
1632 #else
1633         pollfiles[socket->ss_pollidx].fd      = socket->ss_fd;
1634         pollfiles[socket->ss_pollidx].events  = POLLIN | POLLERR;
1635         pollfiles[socket->ss_pollidx].revents = 0;
1636 #endif
1637 
1638         socket->ss_invalid = false;
1639     }
1640 
1641 #ifdef HAVE_EPOLL
1642     int rc = epoll_ctl(epollfd, EPOLL_CTL_ADD, socket->ss_fd, &epollfiles[socket->ss_pollidx]);
1643     if (rc == -1) {
1644         ERROR_NO("Failed to add FD to epoll");
1645     }
1646 #endif
1647     return sipp_do_connect_socket(socket);
1648 }
1649 
1650 
1651 /*************************** I/O functions ***************************/
1652 
1653 /* Allocate a socket buffer. */
alloc_socketbuf(char * buffer,size_t size,int copy,struct sockaddr_storage * dest)1654 struct socketbuf *alloc_socketbuf(char *buffer, size_t size, int copy, struct sockaddr_storage *dest)
1655 {
1656     struct socketbuf *socketbuf;
1657 
1658     socketbuf = (struct socketbuf *)malloc(sizeof(struct socketbuf));
1659     if (!socketbuf) {
1660         ERROR("Could not allocate socket buffer!\n");
1661     }
1662     memset(socketbuf, 0, sizeof(struct socketbuf));
1663     if (copy) {
1664         socketbuf->buf = (char *)malloc(size);
1665         if (!socketbuf->buf) {
1666             ERROR("Could not allocate socket buffer data!\n");
1667         }
1668         memcpy(socketbuf->buf, buffer, size);
1669     } else {
1670         socketbuf->buf = buffer;
1671     }
1672     socketbuf->len = size;
1673     socketbuf->offset = 0;
1674     if (dest) {
1675         memcpy(&socketbuf->addr, dest, SOCK_ADDR_SIZE(dest));
1676     }
1677     socketbuf->next = NULL;
1678 
1679     return socketbuf;
1680 }
1681 
1682 /* Free a poll buffer. */
free_socketbuf(struct socketbuf * socketbuf)1683 void free_socketbuf(struct socketbuf *socketbuf)
1684 {
1685     free(socketbuf->buf);
1686     free(socketbuf);
1687 }
1688 
1689 #ifdef USE_SCTP
sipp_sctp_peer_params(struct sipp_socket * socket)1690 void sipp_sctp_peer_params(struct sipp_socket *socket)
1691 {
1692     if (heartbeat > 0 || pathmaxret > 0) {
1693         struct sctp_paddrparams peerparam;
1694         memset(&peerparam, 0, sizeof(peerparam));
1695 
1696         sockaddr* addresses;
1697         int addresscount = sctp_getpaddrs(socket->ss_fd, 0, &addresses);
1698         if (addresscount < 1) WARNING("sctp_getpaddrs, errno=%d", errno);
1699 
1700         for (int i = 0; i < addresscount; i++) {
1701             memset(&peerparam.spp_address, 0, sizeof(peerparam.spp_address));
1702             struct sockaddr_storage* peeraddress = (struct sockaddr_storage*) &addresses[i];
1703             memcpy(&peerparam.spp_address, peeraddress, SOCK_ADDR_SIZE(peeraddress));
1704 
1705             peerparam.spp_hbinterval = heartbeat;
1706             peerparam.spp_pathmaxrxt = pathmaxret;
1707             if (heartbeat > 0) peerparam.spp_flags = SPP_HB_ENABLE;
1708 
1709             if (pmtu > 0) {
1710                 peerparam.spp_pathmtu = pmtu;
1711                 peerparam.spp_flags |= SPP_PMTUD_DISABLE;
1712             }
1713 
1714             if (setsockopt(socket->ss_fd, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS,
1715                            &peerparam, sizeof(peerparam)) == -1) {
1716                 sctp_freepaddrs(addresses);
1717                 WARNING("setsockopt(SCTP_PEER_ADDR_PARAMS) failed, errno=%d", errno);
1718             }
1719         }
1720         sctp_freepaddrs(addresses);
1721     }
1722 }
1723 #endif
1724 
sipp_customize_socket(struct sipp_socket * socket)1725 void sipp_customize_socket(struct sipp_socket *socket)
1726 {
1727     unsigned int buffsize = buff_size;
1728 
1729     /* Allows fast TCP reuse of the socket */
1730     if (socket->ss_transport == T_TCP || socket->ss_transport == T_TLS ||
1731             socket->ss_transport == T_SCTP) {
1732         int sock_opt = 1;
1733 
1734         if (setsockopt(socket->ss_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&sock_opt,
1735                        sizeof (sock_opt)) == -1) {
1736             ERROR_NO("setsockopt(SO_REUSEADDR) failed");
1737         }
1738 
1739 #ifdef USE_SCTP
1740         if (socket->ss_transport == T_SCTP) {
1741             struct sctp_event_subscribe event;
1742             memset(&event, 0, sizeof(event));
1743             event.sctp_data_io_event = 1;
1744             event.sctp_association_event = 1;
1745             event.sctp_shutdown_event = 1;
1746             if (setsockopt(socket->ss_fd, IPPROTO_SCTP, SCTP_EVENTS, &event,
1747                            sizeof(event)) == -1) {
1748                 ERROR_NO("setsockopt(SCTP_EVENTS) failed, errno=%d", errno);
1749             }
1750 
1751             if (assocmaxret > 0) {
1752                 struct sctp_assocparams associnfo;
1753                 memset(&associnfo, 0, sizeof(associnfo));
1754                 associnfo.sasoc_asocmaxrxt = assocmaxret;
1755                 if (setsockopt(socket->ss_fd, IPPROTO_SCTP, SCTP_ASSOCINFO, &associnfo,
1756                                sizeof(associnfo)) == -1) {
1757                     WARNING("setsockopt(SCTP_ASSOCINFO) failed, errno=%d", errno);
1758                 }
1759             }
1760 
1761             if (setsockopt(socket->ss_fd, IPPROTO_SCTP, SCTP_NODELAY,
1762                            (void *)&sock_opt, sizeof (sock_opt)) == -1) {
1763                 WARNING("setsockopt(SCTP_NODELAY) failed, errno=%d", errno);
1764             }
1765         }
1766 #endif
1767 
1768 #ifndef SOL_TCP
1769 #define SOL_TCP 6
1770 #endif
1771         if (socket->ss_transport != T_SCTP) {
1772             if (setsockopt(socket->ss_fd, SOL_TCP, TCP_NODELAY, (void *)&sock_opt,
1773                            sizeof (sock_opt)) == -1) {
1774                 {
1775                     ERROR_NO("setsockopt(TCP_NODELAY) failed");
1776                 }
1777             }
1778         }
1779 
1780         {
1781             struct linger linger;
1782 
1783             linger.l_onoff = 1;
1784             linger.l_linger = 1;
1785             if (setsockopt (socket->ss_fd, SOL_SOCKET, SO_LINGER,
1786                             &linger, sizeof (linger)) < 0) {
1787                 ERROR_NO("Unable to set SO_LINGER option");
1788             }
1789         }
1790     }
1791 
1792     /* Increase buffer sizes for this sockets */
1793     if (setsockopt(socket->ss_fd,
1794                   SOL_SOCKET,
1795                   SO_SNDBUF,
1796                   &buffsize,
1797                   sizeof(buffsize))) {
1798         ERROR_NO("Unable to set socket sndbuf");
1799     }
1800 
1801     buffsize = buff_size;
1802     if (setsockopt(socket->ss_fd,
1803                   SOL_SOCKET,
1804                   SO_RCVBUF,
1805                   &buffsize,
1806                   sizeof(buffsize))) {
1807         ERROR_NO("Unable to set socket rcvbuf");
1808     }
1809 }
1810 
1811 /* This socket is congested, mark it as such and add it to the poll files. */
enter_congestion(struct sipp_socket * socket,int again)1812 int enter_congestion(struct sipp_socket *socket, int again)
1813 {
1814     if (!socket->ss_congested) {
1815       nb_net_cong++;
1816     }
1817     socket->ss_congested = true;
1818 
1819     TRACE_MSG("Problem %s on socket  %d and poll_idx  is %d \n",
1820               again == EWOULDBLOCK ? "EWOULDBLOCK" : "EAGAIN",
1821               socket->ss_fd, socket->ss_pollidx);
1822 #ifdef HAVE_EPOLL
1823     epollfiles[socket->ss_pollidx].events |= EPOLLOUT;
1824     int rc = epoll_ctl(epollfd, EPOLL_CTL_MOD, socket->ss_fd, &epollfiles[socket->ss_pollidx]);
1825     if (rc == -1) {
1826         WARNING_NO("Failed to set EPOLLOUT");
1827     }
1828 #else
1829      pollfiles[socket->ss_pollidx].events |= POLLOUT;
1830 #endif
1831 
1832 #ifdef USE_SCTP
1833     if (socket->ss_transport == T_SCTP && socket->sctpstate == SCTP_CONNECTING)
1834         return 0;
1835 #endif
1836     return -1;
1837 }
1838 
write_error(struct sipp_socket * socket,int ret)1839 static int write_error(struct sipp_socket* socket, int ret)
1840 {
1841     const char *errstring = strerror(errno);
1842 
1843 #ifndef EAGAIN
1844     int again = (errno == EWOULDBLOCK) ? errno : 0;
1845 #else
1846     int again = ((errno == EAGAIN) || (errno == EWOULDBLOCK)) ? errno : 0;
1847 
1848     /* Scrub away EAGAIN from the rest of the code. */
1849     if (errno == EAGAIN) {
1850         errno = EWOULDBLOCK;
1851     }
1852 #endif
1853 
1854     if (again) {
1855         return enter_congestion(socket, again);
1856     }
1857 
1858     if ((socket->ss_transport == T_TCP || socket->ss_transport == T_SCTP)
1859             && errno == EPIPE) {
1860         nb_net_send_errors++;
1861         sipp_abort_connection(socket->ss_fd);
1862         socket->ss_fd = -1;
1863         sockets_pending_reset.insert(socket);
1864         if (reconnect_allowed()) {
1865             WARNING("Broken pipe on TCP connection, remote peer "
1866                     "probably closed the socket");
1867         } else {
1868             ERROR("Broken pipe on TCP connection, remote peer "
1869                   "probably closed the socket");
1870         }
1871         return -1;
1872     }
1873 
1874 #ifdef USE_OPENSSL
1875     if (socket->ss_transport == T_TLS) {
1876         errstring = sip_tls_error_string(socket->ss_ssl, ret);
1877     }
1878 #endif
1879 
1880     WARNING("Unable to send %s message: %s", TRANSPORT_TO_STRING(socket->ss_transport), errstring);
1881     nb_net_send_errors++;
1882     return -1;
1883 }
1884 
read_error(struct sipp_socket * socket,int ret)1885 int read_error(struct sipp_socket *socket, int ret)
1886 {
1887     const char *errstring = strerror(errno);
1888 #ifdef USE_OPENSSL
1889     if (socket->ss_transport == T_TLS) {
1890         errstring = sip_tls_error_string(socket->ss_ssl, ret);
1891     }
1892 #endif
1893 
1894     assert(ret <= 0);
1895 
1896 #ifdef EAGAIN
1897     /* Scrub away EAGAIN from the rest of the code. */
1898     if (errno == EAGAIN) {
1899         errno = EWOULDBLOCK;
1900     }
1901 #endif
1902 
1903     /* We have only non-blocking reads, so this should not occur. */
1904     if (ret < 0) {
1905         assert(errno != EAGAIN);
1906     }
1907 
1908     if (socket->ss_transport == T_TCP || socket->ss_transport == T_TLS) {
1909         if (ret == 0) {
1910             /* The remote side closed the connection. */
1911             if (socket->ss_control) {
1912                 if (localTwinSippSocket)
1913                     sipp_close_socket(localTwinSippSocket);
1914                 if (extendedTwinSippMode) {
1915                     close_peer_sockets();
1916                     close_local_sockets();
1917                     free_peer_addr_map();
1918                     WARNING("One of the twin instances has ended -> exiting");
1919                     quitting += 20;
1920                 } else if (twinSippMode) {
1921                     if (twinSippSocket)
1922                         sipp_close_socket(twinSippSocket);
1923                     if (thirdPartyMode == MODE_3PCC_CONTROLLER_B) {
1924                         WARNING("3PCC controller A has ended -> exiting");
1925                         quitting += 20;
1926                     } else {
1927                         quitting = 1;
1928                     }
1929                 }
1930             } else {
1931                 /* The socket was closed "cleanly", but we may have calls that need to
1932                  * be destroyed.  Also, if these calls are not complete, and attempt to
1933                  * send again we may "ressurect" the socket by reconnecting it.*/
1934                 sipp_socket_invalidate(socket);
1935                 if (reset_close) {
1936                     close_calls(socket);
1937                 }
1938             }
1939             return 0;
1940         }
1941 
1942         sipp_abort_connection(socket->ss_fd);
1943         socket->ss_fd = -1;
1944         sockets_pending_reset.insert(socket);
1945 
1946         nb_net_recv_errors++;
1947         if (reconnect_allowed()) {
1948             WARNING("Error on TCP connection, remote peer probably closed the socket: %s", errstring);
1949         } else {
1950             ERROR("Error on TCP connection, remote peer probably closed the socket: %s", errstring);
1951         }
1952         return -1;
1953     }
1954 
1955     WARNING("Unable to receive %s message: %s", TRANSPORT_TO_STRING(socket->ss_transport), errstring);
1956     nb_net_recv_errors++;
1957     return -1;
1958 }
1959 
buffer_write(struct sipp_socket * socket,const char * buffer,size_t len,struct sockaddr_storage * dest)1960 void buffer_write(struct sipp_socket *socket, const char *buffer, size_t len, struct sockaddr_storage *dest)
1961 {
1962     struct socketbuf *buf = socket->ss_out;
1963 
1964     if (!buf) {
1965         socket->ss_out = alloc_socketbuf(const_cast<char*>(buffer), len, DO_COPY, dest); /* NO BUG BECAUSE OF DO_COPY */
1966         TRACE_MSG("Added first buffered message to socket %d\n", socket->ss_fd);
1967         return;
1968     }
1969 
1970     while (buf->next) {
1971         buf = buf->next;
1972     }
1973 
1974     buf->next = alloc_socketbuf(const_cast<char*>(buffer), len, DO_COPY, dest); /* NO BUG BECAUSE OF DO_COPY */
1975     TRACE_MSG("Appended buffered message to socket %d\n", socket->ss_fd);
1976 }
1977 
buffer_read(struct sipp_socket * socket,struct socketbuf * newbuf)1978 void buffer_read(struct sipp_socket *socket, struct socketbuf *newbuf)
1979 {
1980     struct socketbuf *buf = socket->ss_in;
1981     struct socketbuf *prev = buf;
1982 
1983     if (!buf) {
1984         socket->ss_in = newbuf;
1985         return;
1986     }
1987 
1988     while (buf->next) {
1989         prev = buf;
1990         buf = buf->next;
1991     }
1992 
1993     prev->next = newbuf;
1994 }
1995 
1996 #ifdef USE_OPENSSL
1997 
1998 /****** Certificate Verification Callback FACILITY *************/
sip_tls_verify_callback(int ok,X509_STORE_CTX * store)1999 int sip_tls_verify_callback(int ok , X509_STORE_CTX *store)
2000 {
2001     char data[512];
2002 
2003     if (!ok) {
2004         X509 *cert = X509_STORE_CTX_get_current_cert(store);
2005 
2006         X509_NAME_oneline(X509_get_issuer_name(cert),
2007                           data, 512);
2008         WARNING("TLS verification error for issuer: '%s'", data);
2009         X509_NAME_oneline(X509_get_subject_name(cert),
2010                           data, 512);
2011         WARNING("TLS verification error for subject: '%s'", data);
2012     }
2013     return ok;
2014 }
2015 
2016 /***********  Load the CRL's into SSL_CTX **********************/
sip_tls_load_crls(SSL_CTX * ctx,const char * crlfile)2017 static int sip_tls_load_crls(SSL_CTX* ctx , const char* crlfile)
2018 {
2019     X509_STORE          *store;
2020     X509_LOOKUP         *lookup;
2021 
2022     /*  Get the X509_STORE from SSL context */
2023     if (!(store = SSL_CTX_get_cert_store(ctx))) {
2024         return (-1);
2025     }
2026 
2027     /* Add lookup file to X509_STORE */
2028     if (!(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()))) {
2029         return (-1);
2030     }
2031 
2032     /* Add the CRLS to the lookpup object */
2033     if (X509_load_crl_file(lookup, crlfile, X509_FILETYPE_PEM) != 1) {
2034         return (-1);
2035     }
2036 
2037     /* Set the flags of the store so that CRLS's are consulted */
2038 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
2039     X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2040 #else
2041 #warning This version of OpenSSL (<0.9.7) cannot handle CRL files in capath
2042     ERROR("This version of OpenSSL (<0.9.7) cannot handle CRL files in capath");
2043 #endif
2044 
2045     return (1);
2046 }
2047 
2048 /************* Prepare the SSL context ************************/
FI_init_ssl_context(void)2049 ssl_init_status FI_init_ssl_context (void)
2050 {
2051     sip_trp_ssl_ctx = SSL_CTX_new( TLSv1_method() );
2052     if ( sip_trp_ssl_ctx == NULL ) {
2053         ERROR("FI_init_ssl_context: SSL_CTX_new with TLSv1_method failed");
2054         return SSL_INIT_ERROR;
2055     }
2056 
2057     sip_trp_ssl_ctx_client = SSL_CTX_new( TLSv1_method() );
2058     if ( sip_trp_ssl_ctx_client == NULL) {
2059         ERROR("FI_init_ssl_context: SSL_CTX_new with TLSv1_method failed");
2060         return SSL_INIT_ERROR;
2061     }
2062 
2063     /*  Load the trusted CA's */
2064     SSL_CTX_load_verify_locations(sip_trp_ssl_ctx, tls_cert_name, NULL);
2065     SSL_CTX_load_verify_locations(sip_trp_ssl_ctx_client, tls_cert_name, NULL);
2066 
2067     /*  CRL load from application specified only if specified on the command line */
2068     if (strlen(tls_crl_name) != 0) {
2069         if (sip_tls_load_crls(sip_trp_ssl_ctx, tls_crl_name) == -1) {
2070             ERROR("FI_init_ssl_context: Unable to load CRL file (%s)", tls_crl_name);
2071             return SSL_INIT_ERROR;
2072         }
2073 
2074         if (sip_tls_load_crls(sip_trp_ssl_ctx_client, tls_crl_name) == -1) {
2075             ERROR("FI_init_ssl_context: Unable to load CRL (client) file (%s)", tls_crl_name);
2076             return SSL_INIT_ERROR;
2077         }
2078         /* The following call forces to process the certificates with the */
2079         /* initialised SSL_CTX                                            */
2080         SSL_CTX_set_verify(sip_trp_ssl_ctx,
2081                            SSL_VERIFY_PEER |
2082                            SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2083                            sip_tls_verify_callback);
2084 
2085         SSL_CTX_set_verify(sip_trp_ssl_ctx_client,
2086                            SSL_VERIFY_PEER |
2087                            SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2088                            sip_tls_verify_callback);
2089     }
2090 
2091 
2092     /* Selection Cipher suits - load the application specified ciphers */
2093     SSL_CTX_set_default_passwd_cb_userdata(sip_trp_ssl_ctx,
2094                                            (void *)CALL_BACK_USER_DATA );
2095     SSL_CTX_set_default_passwd_cb_userdata(sip_trp_ssl_ctx_client,
2096                                            (void *)CALL_BACK_USER_DATA );
2097     SSL_CTX_set_default_passwd_cb( sip_trp_ssl_ctx,
2098                                    passwd_call_back_routine );
2099     SSL_CTX_set_default_passwd_cb( sip_trp_ssl_ctx_client,
2100                                    passwd_call_back_routine );
2101 
2102     if ( SSL_CTX_use_certificate_file(sip_trp_ssl_ctx,
2103                                       tls_cert_name,
2104                                       SSL_FILETYPE_PEM ) != 1 ) {
2105         ERROR("FI_init_ssl_context: SSL_CTX_use_certificate_file failed");
2106         return SSL_INIT_ERROR;
2107     }
2108 
2109     if ( SSL_CTX_use_certificate_file(sip_trp_ssl_ctx_client,
2110                                       tls_cert_name,
2111                                       SSL_FILETYPE_PEM ) != 1 ) {
2112         ERROR("FI_init_ssl_context: SSL_CTX_use_certificate_file (client) failed");
2113         return SSL_INIT_ERROR;
2114     }
2115     if ( SSL_CTX_use_PrivateKey_file(sip_trp_ssl_ctx,
2116                                      tls_key_name,
2117                                      SSL_FILETYPE_PEM ) != 1 ) {
2118         ERROR("FI_init_ssl_context: SSL_CTX_use_PrivateKey_file failed");
2119         return SSL_INIT_ERROR;
2120     }
2121 
2122     if ( SSL_CTX_use_PrivateKey_file(sip_trp_ssl_ctx_client,
2123                                      tls_key_name,
2124                                      SSL_FILETYPE_PEM ) != 1 ) {
2125         ERROR("FI_init_ssl_context: SSL_CTX_use_PrivateKey_file (client) failed");
2126         return SSL_INIT_ERROR;
2127     }
2128 
2129     return SSL_INIT_NORMAL;
2130 }
2131 
send_nowait_tls(SSL * ssl,const void * msg,int len,int)2132 static int send_nowait_tls(SSL* ssl, const void* msg, int len, int /*flags*/)
2133 {
2134     int initial_fd_flags;
2135     int rc;
2136     int fd;
2137     int fd_flags;
2138     if ( (fd = SSL_get_fd(ssl)) == -1 ) {
2139         return (-1);
2140     }
2141     fd_flags = fcntl(fd, F_GETFL, NULL);
2142     initial_fd_flags = fd_flags;
2143     fd_flags |= O_NONBLOCK;
2144     fcntl(fd, F_SETFL, fd_flags);
2145     rc = SSL_write(ssl, msg, len);
2146     if ( rc <= 0 ) {
2147         return(rc);
2148     }
2149     fcntl(fd, F_SETFL, initial_fd_flags);
2150     return rc;
2151 }
2152 #endif
2153 
send_nowait(int s,const void * msg,int len,int flags)2154 static int send_nowait(int s, const void* msg, int len, int flags)
2155 {
2156 #if defined(MSG_DONTWAIT) && !defined(__SUNOS)
2157     return send(s, msg, len, flags | MSG_DONTWAIT);
2158 #else
2159     int fd_flags = fcntl(s, F_GETFL , NULL);
2160     int initial_fd_flags;
2161     int rc;
2162 
2163     initial_fd_flags = fd_flags;
2164     //  fd_flags &= ~O_ACCMODE; // Remove the access mode from the value
2165     fd_flags |= O_NONBLOCK;
2166     fcntl(s, F_SETFL , fd_flags);
2167 
2168     rc = send(s, msg, len, flags);
2169 
2170     fcntl(s, F_SETFL , initial_fd_flags);
2171 
2172     return rc;
2173 #endif
2174 }
2175 
2176 #ifdef USE_SCTP
send_sctp_nowait(int s,const void * msg,int len,int flags)2177 int send_sctp_nowait(int s, const void *msg, int len, int flags)
2178 {
2179     struct sctp_sndrcvinfo sinfo;
2180     memset(&sinfo, 0, sizeof(sinfo));
2181     sinfo.sinfo_flags = SCTP_UNORDERED; // according to RFC4168 5.1
2182     sinfo.sinfo_stream = 0;
2183 
2184 #if defined(MSG_DONTWAIT) && !defined(__SUNOS)
2185     return sctp_send(s, msg, len, &sinfo, flags | MSG_DONTWAIT);
2186 #else
2187     int fd_flags = fcntl(s, F_GETFL, NULL);
2188     int initial_fd_flags;
2189     int rc;
2190 
2191     initial_fd_flags = fd_flags;
2192     fd_flags |= O_NONBLOCK;
2193     fcntl(s, F_SETFL , fd_flags);
2194 
2195     rc = sctp_send(s, msg, len, &sinfo, flags);
2196 
2197     fcntl(s, F_SETFL, initial_fd_flags);
2198 
2199     return rc;
2200 #endif
2201 }
2202 #endif
2203 
socket_write_primitive(struct sipp_socket * socket,const char * buffer,size_t len,struct sockaddr_storage * dest)2204 static ssize_t socket_write_primitive(struct sipp_socket* socket, const char* buffer, size_t len,
2205                                       struct sockaddr_storage* dest)
2206 {
2207     ssize_t rc;
2208 
2209     /* Refuse to write to invalid sockets. */
2210     if (socket->ss_invalid) {
2211         WARNING("Returning EPIPE on invalid socket: %p (%d)\n", _RCAST(void*, socket), socket->ss_fd);
2212         errno = EPIPE;
2213         return -1;
2214     }
2215 
2216     /* Always check congestion before sending. */
2217     if (socket->ss_congested) {
2218         errno = EWOULDBLOCK;
2219         return -1;
2220     }
2221 
2222     switch(socket->ss_transport) {
2223     case T_TLS:
2224 #ifdef USE_OPENSSL
2225         rc = send_nowait_tls(socket->ss_ssl, buffer, len, 0);
2226 #else
2227         errno = EOPNOTSUPP;
2228         rc = -1;
2229 #endif
2230         break;
2231     case T_SCTP:
2232 #ifdef USE_SCTP
2233     {
2234         TRACE_MSG("socket_write_primitive %d\n", socket->sctpstate);
2235         if (socket->sctpstate == SCTP_DOWN) {
2236             errno = EPIPE;
2237             return -1;
2238         } else if (socket->sctpstate == SCTP_CONNECTING) {
2239             errno = EWOULDBLOCK;
2240             return -1;
2241         }
2242         rc = send_sctp_nowait(socket->ss_fd, buffer, len, 0);
2243     }
2244 #else
2245     errno = EOPNOTSUPP;
2246     rc = -1;
2247 #endif
2248         break;
2249     case T_TCP:
2250         rc = send_nowait(socket->ss_fd, buffer, len, 0);
2251         break;
2252 
2253     case T_UDP:
2254         if (compression) {
2255             static char comp_msg[SIPP_MAX_MSG_SIZE];
2256             strncpy(comp_msg, buffer, sizeof(comp_msg) - 1);
2257             if (comp_compress(&socket->ss_comp_state,
2258                              comp_msg,
2259                              (unsigned int *) &len) != COMP_OK) {
2260                 ERROR("Compression plugin error");
2261             }
2262             buffer = (char *)comp_msg;
2263 
2264             TRACE_MSG("---\nCompressed message len: %zu\n", len);
2265         }
2266 
2267         rc = sendto(socket->ss_fd, buffer, len, 0, (struct sockaddr *)dest, SOCK_ADDR_SIZE(dest));
2268         break;
2269 
2270     default:
2271         ERROR("Internal error, unknown transport type %d\n", socket->ss_transport);
2272     }
2273 
2274     return rc;
2275 }
2276 
2277 /* Flush any output buffers for this socket. */
flush_socket(struct sipp_socket * socket)2278 int flush_socket(struct sipp_socket *socket)
2279 {
2280     struct socketbuf *buf;
2281     int ret;
2282 
2283     while ((buf = socket->ss_out)) {
2284         ssize_t size = buf->len - buf->offset;
2285         ret = socket_write_primitive(socket, buf->buf + buf->offset, size, &buf->addr);
2286         TRACE_MSG("Wrote %d of %zu bytes in an output buffer.\n", ret, size);
2287         if (ret == size) {
2288             /* Everything is great, throw away this buffer. */
2289             socket->ss_out = buf->next;
2290             free_socketbuf(buf);
2291         } else if (ret <= 0) {
2292             /* Handle connection closes and errors. */
2293             return write_error(socket, ret);
2294         } else {
2295             /* We have written more of the partial buffer. */
2296             buf->offset += ret;
2297             errno = EWOULDBLOCK;
2298             enter_congestion(socket, EWOULDBLOCK);
2299             return -1;
2300         }
2301     }
2302 
2303     return 0;
2304 }
2305 
2306 /* Write data to a socket. */
write_socket(struct sipp_socket * socket,const char * buffer,ssize_t len,int flags,struct sockaddr_storage * dest)2307 int write_socket(struct sipp_socket *socket, const char *buffer, ssize_t len, int flags, struct sockaddr_storage *dest)
2308 {
2309     int rc;
2310     if ( socket == NULL ) {
2311         //FIX coredump when trying to send data but no master yet ... ( for example after unexpected mesdsage)
2312         return 0;
2313     }
2314 
2315     if (socket->ss_out) {
2316         rc = flush_socket(socket);
2317         TRACE_MSG("Attempted socket flush returned %d\r\n", rc);
2318         if (rc < 0) {
2319             if ((errno == EWOULDBLOCK) && (flags & WS_BUFFER)) {
2320                 buffer_write(socket, buffer, len, dest);
2321                 return len;
2322             } else {
2323                 return rc;
2324             }
2325         }
2326     }
2327 
2328     rc = socket_write_primitive(socket, buffer, len, dest);
2329     struct timeval currentTime;
2330     GET_TIME (&currentTime);
2331 
2332     if (rc == len) {
2333         /* Everything is great. */
2334         if (useMessagef == 1) {
2335             TRACE_MSG("----------------------------------------------- %s\n"
2336                       "%s %smessage sent (%zu bytes):\n\n%.*s\n",
2337                       CStat::formatTime(&currentTime, true),
2338                       TRANSPORT_TO_STRING(socket->ss_transport),
2339                       socket->ss_control ? "control " : "",
2340                       len, (int)len, buffer);
2341         }
2342 
2343         if (useShortMessagef == 1) {
2344             char *msg = strdup(buffer);
2345             const char *call_id = get_trimmed_call_id(msg);
2346             TRACE_SHORTMSG("%s\tS\t%s\tCSeq:%s\t%s\n",
2347                            CStat::formatTime(&currentTime), call_id, get_header_content(msg, "CSeq:"), get_first_line(msg));
2348             free(msg);
2349         }
2350 
2351     } else if (rc <= 0) {
2352         if ((errno == EWOULDBLOCK) && (flags & WS_BUFFER)) {
2353             buffer_write(socket, buffer, len, dest);
2354             enter_congestion(socket, errno);
2355             return len;
2356         }
2357         if (useMessagef == 1) {
2358             TRACE_MSG("----------------------------------------------- %s\n"
2359                       "Error sending %s message:\n\n%.*s\n",
2360                       CStat::formatTime(&currentTime, true),
2361                       TRANSPORT_TO_STRING(socket->ss_transport),
2362                       (int)len, buffer);
2363         }
2364         return write_error(socket, errno);
2365     } else {
2366         /* We have a truncated message, which must be handled internally to the write function. */
2367         if (useMessagef == 1) {
2368             TRACE_MSG("----------------------------------------------- %s\n"
2369                       "Truncation sending %s message (%d of %zu sent):\n\n%.*s\n",
2370                       CStat::formatTime(&currentTime, true),
2371                       TRANSPORT_TO_STRING(socket->ss_transport),
2372                       rc, len, (int)len, buffer);
2373         }
2374         buffer_write(socket, buffer + rc, len - rc, dest);
2375         enter_congestion(socket, errno);
2376     }
2377 
2378     return rc;
2379 }
2380 
reconnect_allowed()2381 bool reconnect_allowed()
2382 {
2383     if (reset_number == -1) {
2384         return true;
2385     }
2386     return (reset_number > 0);
2387 }
2388 
reset_connection(struct sipp_socket * socket)2389 void reset_connection(struct sipp_socket *socket)
2390 {
2391     if (!reconnect_allowed()) {
2392         ERROR_NO("Max number of reconnections reached");
2393     }
2394 
2395     if (reset_number != -1) {
2396         reset_number--;
2397     }
2398 
2399     if (reset_close) {
2400         WARNING("Closing calls, because of TCP reset or close!");
2401         close_calls(socket);
2402     }
2403 
2404     /* Sleep for some period of time before the reconnection. */
2405     usleep(1000 * reset_sleep);
2406 
2407     if (sipp_reconnect_socket(socket) < 0) {
2408         WARNING_NO("Could not reconnect TCP socket");
2409         close_calls(socket);
2410     } else {
2411         WARNING("Socket required a reconnection.");
2412     }
2413 }
2414 
2415 /* Close just those calls for a given socket (e.g., if the remote end closes
2416  * the connection. */
close_calls(struct sipp_socket * socket)2417 void close_calls(struct sipp_socket *socket)
2418 {
2419     owner_list *owners = get_owners_for_socket(socket);
2420     owner_list::iterator owner_it;
2421     socketowner *owner_ptr = NULL;
2422 
2423     for (owner_it = owners->begin(); owner_it != owners->end(); owner_it++) {
2424         owner_ptr = *owner_it;
2425         if (owner_ptr) {
2426             owner_ptr->tcpClose();
2427         }
2428     }
2429 
2430     delete owners;
2431 }
2432 
open_connections()2433 int open_connections()
2434 {
2435     int status=0;
2436     local_port = 0;
2437 
2438     if (!strlen(remote_host)) {
2439         if ((sendMode != MODE_SERVER)) {
2440             ERROR("Missing remote host parameter. This scenario requires it");
2441         }
2442     } else {
2443         int temp_remote_port;
2444         get_host_and_port(remote_host, remote_host, &temp_remote_port);
2445         if (temp_remote_port != 0) {
2446             remote_port = temp_remote_port;
2447         }
2448 
2449         /* Resolving the remote IP */
2450         {
2451             struct addrinfo   hints;
2452             struct addrinfo * local_addr;
2453 
2454             fprintf(stderr, "Resolving remote host '%s'... ", remote_host);
2455 
2456             memset((char*)&hints, 0, sizeof(hints));
2457             hints.ai_flags  = AI_PASSIVE;
2458             hints.ai_family = PF_UNSPEC;
2459 
2460             /* FIXME: add DNS SRV support using liburli? */
2461             if (getaddrinfo(remote_host,
2462                             NULL,
2463                             &hints,
2464                             &local_addr) != 0) {
2465                 ERROR("Unknown remote host '%s'.\n"
2466                       "Use 'sipp -h' for details", remote_host);
2467             }
2468 
2469             memset(&remote_sockaddr, 0, sizeof( remote_sockaddr ));
2470             memcpy(&remote_sockaddr, local_addr->ai_addr,
2471                    SOCK_ADDR_SIZE(_RCAST(struct sockaddr_storage*, local_addr->ai_addr)));
2472             freeaddrinfo(local_addr);
2473 
2474             get_inet_address(&remote_sockaddr, remote_ip, sizeof(remote_ip));
2475             if (remote_sockaddr.ss_family == AF_INET) {
2476                 (_RCAST(struct sockaddr_in *, &remote_sockaddr))->sin_port =
2477                     htons((short)remote_port);
2478                 strcpy(remote_ip_escaped, remote_ip);
2479             } else {
2480                 (_RCAST(struct sockaddr_in6 *, &remote_sockaddr))->sin6_port =
2481                     htons((short)remote_port);
2482                 sprintf(remote_ip_escaped, "[%s]", remote_ip);
2483             }
2484             fprintf(stderr, "Done.\n");
2485         }
2486     }
2487 
2488     if (gethostname(hostname, 64) != 0) {
2489         ERROR_NO("Can't get local hostname in 'gethostname(hostname, 64)'");
2490     }
2491 
2492     {
2493         char            * local_host = NULL;
2494         struct addrinfo * local_addr;
2495         struct addrinfo   hints;
2496 
2497         if (!strlen(local_ip)) {
2498             local_host = (char *)hostname;
2499         } else {
2500             local_host = (char *)local_ip;
2501         }
2502 
2503         memset((char*)&hints, 0, sizeof(hints));
2504         hints.ai_flags  = AI_PASSIVE;
2505         hints.ai_family = PF_UNSPEC;
2506 
2507         /* Resolving local IP */
2508         if (getaddrinfo(local_host, NULL, &hints, &local_addr) != 0) {
2509             ERROR("Can't get local IP address in getaddrinfo, local_host='%s', local_ip='%s'",
2510                   local_host,
2511                   local_ip);
2512         }
2513         // store local addr info for rsa option
2514         getaddrinfo(local_host, NULL, &hints, &local_addr_storage);
2515 
2516         memset(&local_sockaddr, 0, sizeof(struct sockaddr_storage));
2517         local_sockaddr.ss_family = local_addr->ai_addr->sa_family;
2518 
2519         if (!strlen(local_ip)) {
2520             get_inet_address(_RCAST(struct sockaddr_storage*, local_addr->ai_addr),
2521 			     local_ip, sizeof(local_ip));
2522         } else {
2523             memcpy(&local_sockaddr,
2524                    local_addr->ai_addr,
2525                    SOCK_ADDR_SIZE(
2526                        _RCAST(struct sockaddr_storage *, local_addr->ai_addr)));
2527         }
2528         freeaddrinfo(local_addr);
2529 
2530         if (local_sockaddr.ss_family == AF_INET6) {
2531             local_ip_is_ipv6 = true;
2532             sprintf(local_ip_escaped, "[%s]", local_ip);
2533         } else {
2534             strcpy(local_ip_escaped, local_ip);
2535         }
2536     }
2537 
2538     /* Creating and binding the local socket */
2539     if ((main_socket = new_sipp_socket(local_ip_is_ipv6, transport)) == NULL) {
2540         ERROR_NO("Unable to get the local socket");
2541     }
2542 
2543     sipp_customize_socket(main_socket);
2544 
2545     /* Trying to bind local port */
2546     char peripaddr[256];
2547     if (!user_port) {
2548         unsigned short l_port;
2549         for (l_port = DEFAULT_PORT;
2550              l_port < (DEFAULT_PORT + 60);
2551              l_port++) {
2552 
2553             // Bind socket to local_ip
2554             if (bind_local || peripsocket) {
2555                 struct addrinfo * local_addr;
2556                 struct addrinfo   hints;
2557                 memset((char*)&hints, 0, sizeof(hints));
2558                 hints.ai_flags  = AI_PASSIVE;
2559                 hints.ai_family = PF_UNSPEC;
2560 
2561                 if (peripsocket) {
2562                     // On some machines it fails to bind to the self computed local
2563                     // IP address.
2564                     // For the socket per IP mode, bind the main socket to the
2565                     // first IP address specified in the inject file.
2566                     inFiles[ip_file]->getField(0, peripfield, peripaddr, sizeof(peripaddr));
2567                     if (getaddrinfo(peripaddr,
2568                                     NULL,
2569                                     &hints,
2570                                     &local_addr) != 0) {
2571                         ERROR("Unknown host '%s'.\n"
2572                               "Use 'sipp -h' for details", peripaddr);
2573                     }
2574                 } else {
2575                     if (getaddrinfo(local_ip,
2576                                     NULL,
2577                                     &hints,
2578                                     &local_addr) != 0) {
2579                         ERROR("Unknown host '%s'.\n"
2580                               "Use 'sipp -h' for details", peripaddr);
2581                     }
2582                 }
2583                 memcpy(&local_sockaddr,
2584                        local_addr->ai_addr,
2585                        SOCK_ADDR_SIZE(
2586                            _RCAST(struct sockaddr_storage *, local_addr->ai_addr)));
2587                 freeaddrinfo(local_addr);
2588             }
2589             if (local_ip_is_ipv6) {
2590                 (_RCAST(struct sockaddr_in6 *, &local_sockaddr))->sin6_port
2591                     = htons((short)l_port);
2592             } else {
2593                 (_RCAST(struct sockaddr_in *, &local_sockaddr))->sin_port
2594                     = htons((short)l_port);
2595             }
2596             if (sipp_bind_socket(main_socket, &local_sockaddr, &local_port) == 0) {
2597                 break;
2598             }
2599         }
2600     }
2601 
2602     if (!local_port) {
2603         /* Not already bound, use user_port of 0 to leave
2604          * the system choose a port. */
2605 
2606         if (bind_local || peripsocket) {
2607             struct addrinfo * local_addr;
2608             struct addrinfo   hints;
2609             memset((char*)&hints, 0, sizeof(hints));
2610             hints.ai_flags  = AI_PASSIVE;
2611             hints.ai_family = PF_UNSPEC;
2612 
2613             if (peripsocket) {
2614                 // On some machines it fails to bind to the self computed local
2615                 // IP address.
2616                 // For the socket per IP mode, bind the main socket to the
2617                 // first IP address specified in the inject file.
2618                 inFiles[ip_file]->getField(0, peripfield, peripaddr, sizeof(peripaddr));
2619                 if (getaddrinfo(peripaddr,
2620                                 NULL,
2621                                 &hints,
2622                                 &local_addr) != 0) {
2623                     ERROR("Unknown host '%s'.\n"
2624                           "Use 'sipp -h' for details", peripaddr);
2625                 }
2626             } else {
2627                 if (getaddrinfo(local_ip,
2628                                 NULL,
2629                                 &hints,
2630                                 &local_addr) != 0) {
2631                     ERROR("Unknown host '%s'.\n"
2632                           "Use 'sipp -h' for details", peripaddr);
2633                 }
2634             }
2635             memcpy(&local_sockaddr,
2636                    local_addr->ai_addr,
2637                    SOCK_ADDR_SIZE(
2638                        _RCAST(struct sockaddr_storage *, local_addr->ai_addr)));
2639             freeaddrinfo(local_addr);
2640         }
2641 
2642         if (local_ip_is_ipv6) {
2643             (_RCAST(struct sockaddr_in6 *, &local_sockaddr))->sin6_port
2644                 = htons((short)user_port);
2645         } else {
2646             (_RCAST(struct sockaddr_in *, &local_sockaddr))->sin_port
2647                 = htons((short)user_port);
2648         }
2649         if (sipp_bind_socket(main_socket, &local_sockaddr, &local_port)) {
2650             ERROR_NO("Unable to bind main socket");
2651         }
2652     }
2653 
2654     if (peripsocket) {
2655         // Add the main socket to the socket per subscriber map
2656         map_perip_fd[peripaddr] = main_socket;
2657     }
2658 
2659     // Create additional server sockets when running in socket per
2660     // IP address mode.
2661     if (peripsocket && sendMode == MODE_SERVER) {
2662         struct sockaddr_storage server_sockaddr;
2663         struct addrinfo * local_addr;
2664         struct addrinfo   hints;
2665         memset((char*)&hints, 0, sizeof(hints));
2666         hints.ai_flags  = AI_PASSIVE;
2667         hints.ai_family = PF_UNSPEC;
2668 
2669         char peripaddr[256];
2670         struct sipp_socket *sock;
2671         unsigned int lines = inFiles[ip_file]->numLines();
2672         for (unsigned int i = 0; i < lines; i++) {
2673             inFiles[ip_file]->getField(i, peripfield, peripaddr, sizeof(peripaddr));
2674             map<string, struct sipp_socket *>::iterator j;
2675             j = map_perip_fd.find(peripaddr);
2676 
2677             if (j == map_perip_fd.end()) {
2678                 if ((sock = new_sipp_socket(is_ipv6, transport)) == NULL) {
2679                     ERROR_NO("Unable to get server socket");
2680                 }
2681 
2682                 if (getaddrinfo(peripaddr,
2683                                 NULL,
2684                                 &hints,
2685                                 &local_addr) != 0) {
2686                     ERROR("Unknown remote host '%s'.\n"
2687                           "Use 'sipp -h' for details", peripaddr);
2688                 }
2689 
2690                 memcpy(&server_sockaddr,
2691                        local_addr->ai_addr,
2692                        SOCK_ADDR_SIZE(
2693                            _RCAST(struct sockaddr_storage *, local_addr->ai_addr)));
2694                 freeaddrinfo(local_addr);
2695 
2696                 if (is_ipv6) {
2697                     (_RCAST(struct sockaddr_in6 *, &server_sockaddr))->sin6_port
2698                         = htons((short)local_port);
2699                 } else {
2700                     (_RCAST(struct sockaddr_in *, &server_sockaddr))->sin_port
2701                         = htons((short)local_port);
2702                 }
2703 
2704                 sipp_customize_socket(sock);
2705                 if (sipp_bind_socket(sock, &server_sockaddr, NULL)) {
2706                     ERROR_NO("Unable to bind server socket");
2707                 }
2708 
2709                 map_perip_fd[peripaddr] = sock;
2710             }
2711         }
2712     }
2713 
2714     if ((!multisocket) && (transport == T_TCP || transport == T_TLS || transport == T_SCTP) &&
2715             (sendMode != MODE_SERVER)) {
2716         if ((tcp_multiplex = new_sipp_socket(local_ip_is_ipv6, transport)) == NULL) {
2717             ERROR_NO("Unable to get a TCP socket");
2718         }
2719 
2720         /* OJA FIXME: is it correct? */
2721         if (use_remote_sending_addr) {
2722             remote_sockaddr = remote_sending_sockaddr;
2723         }
2724         sipp_customize_socket(tcp_multiplex);
2725 
2726         if (user_port) {
2727             int sock_opt = 1;
2728 
2729             if (setsockopt(tcp_multiplex->ss_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&sock_opt,
2730                            sizeof (sock_opt)) == -1) {
2731                 ERROR_NO("setsockopt(SO_REUSEADDR) failed");
2732             }
2733 
2734             if (tcp_multiplex->ss_ipv6) {
2735                 struct sockaddr_in6 sa_loc = {AF_INET6};
2736                 sa_loc.sin6_port = htons(local_port);
2737                 sipp_bind_socket(tcp_multiplex, (struct sockaddr_storage*)&sa_loc, NULL);
2738             } else {
2739                 struct sockaddr_in sa_loc = {AF_INET};
2740                 sa_loc.sin_port = htons(local_port);
2741                 sipp_bind_socket(tcp_multiplex, (struct sockaddr_storage*)&sa_loc, NULL);
2742             }
2743         }
2744 
2745         if (sipp_connect_socket(tcp_multiplex, &remote_sockaddr)) {
2746             if (reset_number > 0) {
2747                 WARNING("Failed to reconnect\n");
2748                 sipp_close_socket(main_socket);
2749                 reset_number--;
2750                 return 1;
2751             } else {
2752                 if (errno == EINVAL) {
2753                     /* This occurs sometime on HPUX but is not a true INVAL */
2754                     ERROR_NO("Unable to connect a TCP socket, remote peer error.\n"
2755                              "Use 'sipp -h' for details");
2756                 } else {
2757                     ERROR_NO("Unable to connect a TCP socket.\n"
2758                              "Use 'sipp -h' for details");
2759                 }
2760             }
2761         }
2762 
2763     }
2764 
2765 
2766     if (transport == T_TCP || transport == T_TLS || transport == T_SCTP) {
2767         if (listen(main_socket->ss_fd, 100)) {
2768             ERROR_NO("Unable to listen main socket");
2769         }
2770     }
2771 
2772     /* Trying to connect to Twin Sipp in 3PCC mode */
2773     if (twinSippMode) {
2774         if (thirdPartyMode == MODE_3PCC_CONTROLLER_A || thirdPartyMode == MODE_3PCC_A_PASSIVE) {
2775             connect_to_peer(twinSippHost, twinSippPort, &twinSipp_sockaddr, twinSippIp, &twinSippSocket);
2776         } else if (thirdPartyMode == MODE_3PCC_CONTROLLER_B) {
2777             connect_local_twin_socket(twinSippHost);
2778         } else {
2779             ERROR("TwinSipp Mode enabled but thirdPartyMode is different "
2780                   "from 3PCC_CONTROLLER_B and 3PCC_CONTROLLER_A\n");
2781         }
2782     } else if (extendedTwinSippMode) {
2783         if (thirdPartyMode == MODE_MASTER || thirdPartyMode == MODE_MASTER_PASSIVE) {
2784             strncpy(twinSippHost, get_peer_addr(master_name), sizeof(twinSippHost) - 1);
2785             get_host_and_port(twinSippHost, twinSippHost, &twinSippPort);
2786             connect_local_twin_socket(twinSippHost);
2787             connect_to_all_peers();
2788         } else if (thirdPartyMode == MODE_SLAVE) {
2789             strncpy(twinSippHost, get_peer_addr(slave_number), sizeof(twinSippHost) - 1);
2790             get_host_and_port(twinSippHost, twinSippHost, &twinSippPort);
2791             connect_local_twin_socket(twinSippHost);
2792         } else {
2793             ERROR("extendedTwinSipp Mode enabled but thirdPartyMode is different "
2794                   "from MASTER and SLAVE\n");
2795         }
2796     }
2797 
2798     return status;
2799 }
2800 
2801 
connect_to_peer(char * peer_host,int peer_port,struct sockaddr_storage * peer_sockaddr,char * peer_ip,struct sipp_socket ** peer_socket)2802 void connect_to_peer(char *peer_host, int peer_port, struct sockaddr_storage *peer_sockaddr, char *peer_ip, struct sipp_socket **peer_socket)
2803 {
2804 
2805     /* Resolving the  peer IP */
2806     printf("Resolving peer address : %s...\n", peer_host);
2807     struct addrinfo   hints;
2808     struct addrinfo * local_addr;
2809     memset((char*)&hints, 0, sizeof(hints));
2810     hints.ai_flags  = AI_PASSIVE;
2811     hints.ai_family = PF_UNSPEC;
2812     is_ipv6 = false;
2813     /* Resolving twin IP */
2814     if (getaddrinfo(peer_host,
2815                     NULL,
2816                     &hints,
2817                     &local_addr) != 0) {
2818 
2819         ERROR("Unknown peer host '%s'.\n"
2820               "Use 'sipp -h' for details", peer_host);
2821     }
2822 
2823     memcpy(peer_sockaddr,
2824            local_addr->ai_addr,
2825            SOCK_ADDR_SIZE(
2826                _RCAST(struct sockaddr_storage *, local_addr->ai_addr)));
2827 
2828     freeaddrinfo(local_addr);
2829 
2830     if (peer_sockaddr->ss_family == AF_INET) {
2831         (_RCAST(struct sockaddr_in *, peer_sockaddr))->sin_port =
2832             htons((short)peer_port);
2833     } else {
2834         (_RCAST(struct sockaddr_in6 *, peer_sockaddr))->sin6_port =
2835             htons((short)peer_port);
2836         is_ipv6 = true;
2837     }
2838     get_inet_address(peer_sockaddr, peer_ip, sizeof(peer_ip));
2839 
2840     if ((*peer_socket = new_sipp_socket(is_ipv6, T_TCP)) == NULL) {
2841         ERROR_NO("Unable to get a twin sipp TCP socket");
2842     }
2843 
2844     /* Mark this as a control socket. */
2845     (*peer_socket)->ss_control = 1;
2846 
2847     if (sipp_connect_socket(*peer_socket, peer_sockaddr)) {
2848         if (errno == EINVAL) {
2849             /* This occurs sometime on HPUX but is not a true INVAL */
2850             ERROR_NO("Unable to connect a twin sipp TCP socket\n "
2851                      ", remote peer error.\n"
2852                      "Use 'sipp -h' for details");
2853         } else {
2854             ERROR_NO("Unable to connect a twin sipp socket "
2855                      "\n"
2856                      "Use 'sipp -h' for details");
2857         }
2858     }
2859 
2860     sipp_customize_socket(*peer_socket);
2861 }
2862 
get_peer_socket(char * peer)2863 struct sipp_socket **get_peer_socket(char * peer) {
2864     peer_map::iterator peer_it;
2865     peer_it = peers.find(peer_map::key_type(peer));
2866     if (peer_it != peers.end()) {
2867         return &peer_it->second.peer_socket;
2868     } else {
2869         ERROR("get_peer_socket: Peer %s not found\n", peer);
2870     }
2871     return NULL;
2872 }
2873 
get_peer_addr(char * peer)2874 char * get_peer_addr(char * peer)
2875 {
2876     char * addr;
2877     peer_addr_map::iterator peer_addr_it;
2878     peer_addr_it = peer_addrs.find(peer_addr_map::key_type(peer));
2879     if (peer_addr_it != peer_addrs.end()) {
2880         addr =  peer_addr_it->second;
2881         return addr;
2882     } else {
2883         ERROR("get_peer_addr: Peer %s not found\n", peer);
2884     }
2885     return NULL;
2886 }
2887 
is_a_peer_socket(struct sipp_socket * peer_socket)2888 bool is_a_peer_socket(struct sipp_socket *peer_socket)
2889 {
2890     peer_socket_map::iterator peer_socket_it;
2891     peer_socket_it = peer_sockets.find(peer_socket_map::key_type(peer_socket));
2892     if (peer_socket_it == peer_sockets.end()) {
2893         return false;
2894     } else {
2895         return true;
2896     }
2897 }
2898 
connect_local_twin_socket(char * twinSippHost)2899 void connect_local_twin_socket(char * twinSippHost)
2900 {
2901     /* Resolving the listener IP */
2902     printf("Resolving listener address : %s...\n", twinSippHost);
2903     struct addrinfo   hints;
2904     struct addrinfo * local_addr;
2905     memset((char*)&hints, 0, sizeof(hints));
2906     hints.ai_flags  = AI_PASSIVE;
2907     hints.ai_family = PF_UNSPEC;
2908     is_ipv6 = false;
2909 
2910     /* Resolving twin IP */
2911     if (getaddrinfo(twinSippHost,
2912                     NULL,
2913                     &hints,
2914                     &local_addr) != 0) {
2915         ERROR("Unknown twin host '%s'.\n"
2916               "Use 'sipp -h' for details", twinSippHost);
2917     }
2918     memcpy(&twinSipp_sockaddr,
2919            local_addr->ai_addr,
2920            SOCK_ADDR_SIZE(
2921                _RCAST(struct sockaddr_storage*, local_addr->ai_addr)));
2922     freeaddrinfo(local_addr);
2923 
2924     if (twinSipp_sockaddr.ss_family == AF_INET) {
2925         (_RCAST(struct sockaddr_in *, &twinSipp_sockaddr))->sin_port =
2926             htons((short)twinSippPort);
2927     } else {
2928         (_RCAST(struct sockaddr_in6 *, &twinSipp_sockaddr))->sin6_port =
2929             htons((short)twinSippPort);
2930         is_ipv6 = true;
2931     }
2932     get_inet_address(&twinSipp_sockaddr, twinSippIp, sizeof(twinSippIp));
2933 
2934     if ((localTwinSippSocket = new_sipp_socket(is_ipv6, T_TCP)) == NULL) {
2935         ERROR_NO("Unable to get a listener TCP socket ");
2936     }
2937 
2938     memset(&localTwin_sockaddr, 0, sizeof(struct sockaddr_storage));
2939     if (!is_ipv6) {
2940         localTwin_sockaddr.ss_family = AF_INET;
2941         (_RCAST(struct sockaddr_in *, &localTwin_sockaddr))->sin_port =
2942             htons((short)twinSippPort);
2943     } else {
2944         localTwin_sockaddr.ss_family = AF_INET6;
2945         (_RCAST(struct sockaddr_in6 *, &localTwin_sockaddr))->sin6_port =
2946             htons((short)twinSippPort);
2947     }
2948 
2949     // add socket option to allow the use of it without the TCP timeout
2950     // This allows to re-start the controller B (or slave) without timeout after its exit
2951     int reuse = 1;
2952     setsockopt(localTwinSippSocket->ss_fd, SOL_SOCKET, SO_REUSEADDR, (int *)&reuse, sizeof(reuse));
2953     sipp_customize_socket(localTwinSippSocket);
2954 
2955     if (sipp_bind_socket(localTwinSippSocket, &localTwin_sockaddr, 0)) {
2956         ERROR_NO("Unable to bind twin sipp socket ");
2957     }
2958 
2959     if (listen(localTwinSippSocket->ss_fd, 100)) {
2960         ERROR_NO("Unable to listen twin sipp socket in ");
2961     }
2962 }
2963 
close_peer_sockets()2964 void close_peer_sockets()
2965 {
2966     peer_map::iterator peer_it;
2967     T_peer_infos infos;
2968 
2969     for (peer_it = peers.begin(); peer_it != peers.end(); peer_it++) {
2970         infos = peer_it->second;
2971         sipp_close_socket(infos.peer_socket);
2972         infos.peer_socket = NULL;
2973         peers[std::string(peer_it->first)] = infos;
2974     }
2975 
2976     peers_connected = 0;
2977 }
2978 
close_local_sockets()2979 void close_local_sockets()
2980 {
2981     for (int i = 0; i< local_nb; i++) {
2982         sipp_close_socket(local_sockets[i]);
2983         local_sockets[i] = NULL;
2984     }
2985 }
2986 
connect_to_all_peers()2987 void connect_to_all_peers()
2988 {
2989     peer_map::iterator peer_it;
2990     T_peer_infos infos;
2991     for (peer_it = peers.begin(); peer_it != peers.end(); peer_it++) {
2992         infos = peer_it->second;
2993         get_host_and_port(infos.peer_host, infos.peer_host, &infos.peer_port);
2994         connect_to_peer(infos.peer_host, infos.peer_port, &(infos.peer_sockaddr), infos.peer_ip, &(infos.peer_socket));
2995         peer_sockets[infos.peer_socket] = peer_it->first;
2996         peers[std::string(peer_it->first)] = infos;
2997     }
2998     peers_connected = 1;
2999 }
3000 
is_a_local_socket(struct sipp_socket * s)3001 bool is_a_local_socket(struct sipp_socket *s)
3002 {
3003     for (int i = 0; i< local_nb + 1; i++) {
3004         if (local_sockets[i] == s)
3005             return true;
3006     }
3007     return (false);
3008 }
3009 
free_peer_addr_map()3010 void free_peer_addr_map()
3011 {
3012     peer_addr_map::iterator peer_addr_it;
3013     for (peer_addr_it = peer_addrs.begin(); peer_addr_it != peer_addrs.end(); peer_addr_it++) {
3014         free(peer_addr_it->second);
3015     }
3016 }
3017 
3018 /***************** Check of the message received ***************/
3019 
sipMsgCheck(const char * P_msg,struct sipp_socket * socket)3020 bool sipMsgCheck (const char *P_msg, struct sipp_socket *socket)
3021 {
3022     const char C_sipHeader[] = "SIP/2.0";
3023 
3024     if (socket == twinSippSocket || socket == localTwinSippSocket ||
3025             is_a_peer_socket(socket) || is_a_local_socket(socket))
3026         return true;
3027 
3028     if (strstr(P_msg, C_sipHeader) !=  NULL) {
3029         return true;
3030     }
3031 
3032     return false;
3033 }
3034 
3035 
3036 #ifdef GTEST
3037 
3038 #include "gtest/gtest.h"
3039 
TEST(get_trimmed_call_id,noslashes)3040 TEST(get_trimmed_call_id, noslashes) {
3041     EXPECT_STREQ("abc", get_trimmed_call_id("OPTIONS..\r\nBla: X\r\nCall-ID: abc\r\nCall-ID: def\r\n\r\n"));
3042 }
3043 
TEST(get_trimmed_call_id,withslashes)3044 TEST(get_trimmed_call_id, withslashes) {
3045     EXPECT_STREQ("abc2", get_trimmed_call_id("OPTIONS..\r\nBla: X\r\nCall-ID: ///abc2\r\nCall-ID: def\r\n\r\n"));
3046     EXPECT_STREQ("abc3", get_trimmed_call_id("OPTIONS..\r\nBla: X\r\nCall-ID: abc2///abc3\r\nCall-ID: def\r\n\r\n"));
3047     EXPECT_STREQ("abc4///abc5", get_trimmed_call_id("OPTIONS..\r\nBla: X\r\nCall-ID: abc3///abc4///abc5\r\nCall-ID: def\r\n\r\n"));
3048 }
3049 
3050 #endif //GTEST
3051