forked from kamailio/kamailio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
2929 lines (2703 loc) · 78.6 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2001-2003 FhG Fokus
*
* This file is part of Kamailio, a free SIP server.
*
* Kamailio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version
*
* Kamailio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/** Kamailio core :: main file (init, daemonize, startup)
* @file main.c
* @ingroup core
* Module: core
*/
/*! @defgroup core Kamailio core
*
* sip router core part.
*/
#ifdef KSR_PTHREAD_MUTEX_SHARED
#define _GNU_SOURCE
#include <pthread.h>
#include <dlfcn.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <getopt.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#if defined(HAVE_NETINET_IN_SYSTM)
#include <netinet/in_systm.h>
#endif
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <pwd.h>
#include <grp.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <net/if.h>
#ifdef HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif
#include "core/config.h"
#include "core/dprint.h"
#include "core/daemonize.h"
#include "core/route.h"
#include "core/udp_server.h"
#include "core/globals.h"
#include "core/mem/mem.h"
#include "core/mem/shm_mem.h"
#include "core/shm_init.h"
#include "core/sr_module.h"
#include "core/modparam.h"
#include "core/timer.h"
#include "core/parser/msg_parser.h"
#include "core/ip_addr.h"
#include "core/resolve.h"
#include "core/parser/parse_hname2.h"
#include "core/parser/digest/digest_parser.h"
#include "core/name_alias.h"
#include "core/hash_func.h"
#include "core/pt.h"
#include "core/script_cb.h"
#include "core/nonsip_hooks.h"
#include "core/ut.h"
#include "core/events.h"
#include "core/signals.h"
#ifdef USE_RAW_SOCKS
#include "core/raw_sock.h"
#endif /* USE_RAW_SOCKS */
#ifdef USE_TCP
#include "core/poll_types.h"
#include "core/tcp_init.h"
#include "core/tcp_options.h"
#ifdef CORE_TLS
#include "core/tls/tls_init.h"
#define tls_has_init_si() 1
#define tls_loaded() 1
#else
#include "core/tls_hooks_init.h"
#endif /* CORE_TLS */
#endif /* USE_TCP */
#ifdef USE_SCTP
#include "core/sctp_core.h"
#endif
#include "core/usr_avp.h"
#include "core/rpc_lookup.h"
#include "core/core_cmd.h"
#include "core/flags.h"
#include "core/lock_ops_init.h"
#include "core/atomic_ops_init.h"
#ifdef USE_DNS_CACHE
#include "core/dns_cache.h"
#endif
#ifdef USE_DST_BLACKLIST
#include "core/dst_blacklist.h"
#endif
#include "core/rand/fastrand.h" /* seed */
#include "core/rand/kam_rand.h"
#include "core/rand/cryptorand.h"
#include "core/counters.h"
#include "core/cfg/cfg.h"
#include "core/cfg/cfg_struct.h"
#include "core/cfg_core.h"
#include "core/endianness.h" /* init */
#include "core/basex.h" /* init */
#include "core/pvapi.h" /* init PV api */
#include "core/pv_core.h" /* register core pvars */
#include "core/ppcfg.h"
#include "core/sock_ut.h"
#include "core/async_task.h"
#include "core/dset.h"
#include "core/timer_proc.h"
#include "core/srapi.h"
#include "core/receive.h"
#ifdef DEBUG_DMALLOC
#include <dmalloc.h>
#endif
#include "core/ver.h"
/* define SIG_DEBUG by default */
#ifdef NO_SIG_DEBUG
#undef SIG_DEBUG
#else
#define SIG_DEBUG
#endif
static char help_msg[]= "\
Usage: " NAME " [options]\n\
Options:\n\
-a mode Auto aliases mode: enable with yes or on,\n\
disable with no or off\n\
--alias=val Add an alias, the value has to be '[proto:]hostname[:port]'\n\
(like for 'alias' global parameter)\n\
-A define Add config pre-processor define (e.g., -A WITH_AUTH,\n\
-A 'FLT_ACC=1', -A 'DEFVAL=\"str-val\"')\n\
-b nr Maximum receive buffer size which will not be exceeded by\n\
auto-probing procedure even if OS allows\n\
-c Check configuration file for syntax errors\n\
-d Debugging mode (multiple -d increase the level)\n\
-D Control how daemonize is done:\n\
-D..do not fork (almost) anyway;\n\
-DD..do not daemonize creator;\n\
-DDD..daemonize (default)\n\
-e Log messages printed in terminal colors (requires -E)\n\
-E Log to stderr\n\
-f file Configuration file (default: " CFG_FILE ")\n\
-g gid Change gid (group id)\n\
-G file Create a pgid file\n\
-h This help message\n\
--help Long option for `-h`\n\
-I Print more internal compile flags and options\n\
-K Turn on \"via:\" host checking when forwarding replies\n\
-l address Listen on the specified address/interface (multiple -l\n\
mean listening on more addresses). The address format is\n\
[proto:]addr_lst[:port][/advaddr], \n\
where proto=udp|tcp|tls|sctp, \n\
addr_lst= addr|(addr, addr_lst), \n\
addr=host|ip_address|interface_name and \n\
advaddr=addr[:port] (advertised address). \n\
E.g: -l localhost, -l udp:127.0.0.1:5080, -l eth0:5062,\n\
-l udp:127.0.0.1:5080/1.2.3.4:5060,\n\
-l \"sctp:(eth0)\", -l \"(eth0, eth1, 127.0.0.1):5065\".\n\
The default behaviour is to listen on all the interfaces.\n\
--loadmodule=name load the module specified by name\n\
-L path Modules search path (default: " MODS_DIR ")\n\
-m nr Size of shared memory allocated in Megabytes\n\
--modparam=modname:paramname:type:value set the module parameter\n\
type has to be 's' for string value and 'i' for int value, \n\
example: --modparam=corex:alias_subdomains:s:" NAME ".org\n\
-M nr Size of private memory allocated, in Megabytes\n\
-n processes Number of child processes to fork per interface\n\
(default: 8)\n"
#ifdef USE_TCP
" -N Number of tcp child processes (default: equal to `-n')\n"
#endif
" -O nr Script optimization level (debugging option)\n\
-P file Create a pid file\n"
#ifdef USE_SCTP
" -Q Number of sctp child processes (default: equal to `-n')\n"
#endif /* USE_SCTP */
" -r Use dns to check if is necessary to add a \"received=\"\n\
field to a via\n\
-R Same as `-r` but use reverse dns;\n\
(to use both use `-rR`)\n"
" --server-id=num set the value for server_id\n\
--subst=exp set a subst preprocessor directive\n\
--substdef=exp set a substdef preprocessor directive\n\
--substdefs=exp set a substdefs preprocessor directive\n"
#ifdef USE_SCTP
" -S disable sctp\n"
#endif
" -t dir Chroot to \"dir\"\n"
#ifdef USE_TCP
" -T Disable tcp\n"
#endif
" -u uid Change uid (user id)\n\
-v Version number\n\
--version Long option for `-v`\n\
-V Alternative for `-v`\n\
-x name Specify internal manager for shared memory (shm)\n\
- can be: fm, qm or tlsf\n\
-X name Specify internal manager for private memory (pkg)\n\
- if omitted, the one for shm is used\n\
-Y dir Runtime dir path\n\
-w dir Change the working directory to \"dir\" (default: \"/\")\n"
#ifdef USE_TCP
" -W type poll method (depending on support in OS, it can be: poll,\n\
epoll_lt, epoll_et, sigio_rt, select, kqueue, /dev/poll)\n"
#endif
;
/* print compile-time constants */
void print_ct_constants(void)
{
#ifdef ADAPTIVE_WAIT
printf("ADAPTIVE_WAIT_LOOPS %d, ", ADAPTIVE_WAIT_LOOPS);
#endif
/*
printf("SHM_MEM_SIZE %dMB, ", SHM_MEM_SIZE);
*/
printf("MAX_RECV_BUFFER_SIZE %d,"
" MAX_URI_SIZE %d, BUF_SIZE %d, DEFAULT PKG_SIZE %uMB\n",
MAX_RECV_BUFFER_SIZE, MAX_URI_SIZE,
BUF_SIZE, PKG_MEM_SIZE);
#ifdef USE_TCP
printf("poll method support: %s.\n", poll_support);
#endif
}
/* print compile-time constants */
void print_internals(void)
{
printf("Print out of %s internals\n", NAME);
printf(" Version: %s\n", full_version);
printf(" Default config: %s\n", CFG_FILE);
printf(" Default paths to modules: %s\n", MODS_DIR);
printf(" Compile flags: %s\n", ver_flags );
printf(" MAX_RECV_BUFFER_SIZE=%d\n", MAX_RECV_BUFFER_SIZE);
printf(" MAX_URI_SIZE=%d\n", MAX_URI_SIZE);
printf(" BUF_SIZE=%d\n", BUF_SIZE);
printf(" DEFAULT PKG_SIZE=%uMB\n", PKG_MEM_SIZE);
printf(" DEFAULT SHM_SIZE=%uMB\n", SHM_MEM_SIZE);
#ifdef ADAPTIVE_WAIT
printf(" ADAPTIVE_WAIT_LOOPS=%d\n", ADAPTIVE_WAIT_LOOPS);
#endif
#ifdef USE_TCP
printf(" TCP poll methods: %s\n", poll_support);
#endif
printf(" Source code revision ID: %s\n", ver_id);
printf(" Compiled with: %s\n", ver_compiler);
printf(" Compiled architecture: %s\n", ARCH);
printf(" Compiled on: %s\n", ver_compiled_time);
printf("Thank you for flying %s!\n", NAME);
}
/* debugging function */
/*
void receive_stdin_loop(void)
{
#define BSIZE 1024
char buf[BSIZE+1];
int len;
while(1){
len=fread(buf,1,BSIZE,stdin);
buf[len+1]=0;
receive_msg(buf, len);
printf("-------------------------\n");
}
}
*/
/* global vars */
int own_pgid = 0; /* whether or not we have our own pgid (and it's ok
to use kill(0, sig) */
char* mods_dir = MODS_DIR; /* search path for dyn. loadable modules */
int mods_dir_cmd = 0; /* mods dir path set in command lin e*/
char* cfg_file = 0;
unsigned int maxbuffer = MAX_RECV_BUFFER_SIZE; /* maximum buffer size we do
not want to exceed during the
auto-probing procedure; may
be re-configured */
unsigned int sql_buffer_size = 65535; /* Size for the SQL buffer. Defaults to 64k.
This may be re-configured */
int socket_workers = 0; /* number of workers processing requests for a socket
- it's reset everytime with a new listen socket */
int children_no = 0; /* number of children processing requests */
#ifdef USE_TCP
int tcp_cfg_children_no = 0; /* set via config or command line option */
int tcp_children_no = 0; /* based on socket_workers and tcp_cfg_children_no */
int tcp_disable = 0; /* 1 if tcp is disabled */
#endif
#ifdef USE_TLS
#ifdef CORE_TLS
int tls_disable = 0; /* tls enabled by default */
#else
int tls_disable = 1; /* tls disabled by default */
#endif /* CORE_TLS */
#endif /* USE_TLS */
#ifdef USE_SCTP
int sctp_children_no = 0;
int sctp_disable = 2; /* 1 if sctp is disabled, 2 if auto mode, 0 enabled */
#endif /* USE_SCTP */
struct process_table *pt=0; /*array with children pids, 0= main proc,
alloc'ed in shared mem if possible*/
int *process_count = 0; /* Total number of SER processes currently
running */
gen_lock_t* process_lock; /* lock on the process table */
int process_no = 0; /* index of process in the pt */
time_t up_since;
int sig_flag = 0; /* last signal received */
int dont_fork = 0;
int dont_daemonize = 0;
int log_stderr = 0;
int log_color = 0;
/* set custom app name for syslog printing */
char *log_name = 0;
char *log_prefix_fmt = 0;
pid_t creator_pid = (pid_t) -1;
int config_check = 0;
/* check if reply first via host==us */
int check_via = 0;
/* translate user=phone URIs to TEL URIs */
int phone2tel = 1;
/* debugging level for timer debugging */
int timerlog = L_WARN;
/* should replies include extensive warnings? by default no,
good for trouble-shooting
*/
int sip_warning = 0;
/* should localy-generated messages include server's signature?
be default yes, good for trouble-shooting
*/
int server_signature=1;
str server_hdr = {SERVER_HDR, SERVER_HDR_LEN};
str user_agent_hdr = {USER_AGENT, USER_AGENT_LEN};
str version_table = {VERSION_TABLE, VERSION_TABLE_LEN};
/* should ser try to locate outbound interface on multihomed
* host? by default not -- too expensive
*/
int mhomed=0;
/* use dns and/or rdns or to see if we need to add
a ;received=x.x.x.x to via: */
int received_dns = 0;
/* add or not the rev dns names to aliases list */
int sr_auto_aliases=1;
char* working_dir = 0;
char* chroot_dir = 0;
char* runtime_dir = "" RUN_DIR;
char* user=0;
char* group=0;
int uid = 0;
int gid = 0;
char* sock_user=0;
char* sock_group=0;
int sock_uid= -1;
int sock_gid= -1;
int sock_mode= S_IRUSR| S_IWUSR| S_IRGRP| S_IWGRP; /* rw-rw---- */
int server_id = 0; /* Configurable unique ID of the server */
/* maximum number of branches for transaction */
unsigned int sr_dst_max_branches = MAX_BRANCHES_DEFAULT;
/* set timeval for each received sip message */
int sr_msg_time = 1;
/* onsend_route is executed for replies*/
int onsend_route_reply = 0;
/* more config stuff */
int disable_core_dump=0; /* by default enabled */
int open_files_limit=-1; /* don't touch it by default */
/* memory options */
int shm_force_alloc=0; /* force immediate (on startup) page allocation
(by writting 0 in the pages), useful if
mlock_pages is also 1 */
int mlock_pages=0; /* default off, try to disable swapping */
/* real time options */
int real_time=0; /* default off, flags: 1 on only timer, 2 slow timer,
4 all procs (7=all) */
int rt_prio=0;
int rt_policy=0; /* SCHED_OTHER */
int rt_timer1_prio=0; /* "fast" timer */
int rt_timer2_prio=0; /* "slow" timer */
int rt_timer1_policy=0; /* "fast" timer, SCHED_OTHER */
int rt_timer2_policy=0; /* "slow" timer, SCHED_OTHER */
/* a hint to reply modules whether they should send reply
to IP advertised in Via or IP from which a request came
*/
int reply_to_via=0;
#ifdef USE_MCAST
int mcast_loopback = 0;
int mcast_ttl = -1; /* if -1, don't touch it, use the default (usually 1) */
char* mcast = 0;
#endif /* USE_MCAST */
int tos = IPTOS_LOWDELAY;
int pmtu_discovery = 0;
int auto_bind_ipv6 = 0;
int sr_bind_ipv6_link_local = 0;
struct socket_info* udp_listen=0;
#ifdef USE_TCP
int tcp_main_pid=0; /* set after the tcp main process is started */
struct socket_info* tcp_listen=0;
#endif
#ifdef USE_TLS
struct socket_info* tls_listen=0;
#endif
#ifdef USE_SCTP
struct socket_info* sctp_listen=0;
#endif
struct socket_info* bind_address=0; /* pointer to the crt. proc.
listening address*/
struct socket_info* sendipv4; /* ipv4 socket to use when msg. comes from ipv6*/
struct socket_info* sendipv6; /* same as above for ipv6 */
#ifdef USE_RAW_SOCKS
int raw_udp4_send_sock = -1; /* raw socket used for sending udp4 packets */
#endif /* USE_RAW_SOCKS */
#ifdef USE_TCP
struct socket_info* sendipv4_tcp;
struct socket_info* sendipv6_tcp;
#endif
#ifdef USE_TLS
struct socket_info* sendipv4_tls;
struct socket_info* sendipv6_tls;
#endif
#ifdef USE_SCTP
struct socket_info* sendipv4_sctp;
struct socket_info* sendipv6_sctp;
#endif
unsigned short port_no=0; /* default port*/
#ifdef USE_TLS
unsigned short tls_port_no=0; /* default port */
#endif
struct host_alias* aliases=0; /* name aliases list */
/* Parameter to child_init */
int child_rank = 0;
/* how much to wait for children to terminate, before taking extreme measures*/
int ser_kill_timeout=DEFAULT_SER_KILL_TIMEOUT;
int ksr_verbose_startup = 0;
/* cfg parsing */
int cfg_errors=0;
int cfg_warnings=0;
/* shared memory (in MB) */
unsigned long shm_mem_size=0;
/* private (pkg) memory (in MB) */
unsigned long pkg_mem_size=0;
/* export command-line to anywhere else */
int my_argc;
char **my_argv;
/* set to 1 when the cfg framework and core cfg is initialized/registered */
static int cfg_ok=0;
#define MAX_FD 32 /* maximum number of inherited open file descriptors,
(normally it shouldn't be bigger than 3) */
extern FILE* yyin;
extern int yyparse(void);
int is_main=1; /* flag = is this the "main" process? */
int fixup_complete=0; /* flag = is the fixup complete ? */
char* pid_file = 0; /* filename as asked by use */
char* pgid_file = 0;
/* memory manager */
#define SR_MEMMNG_DEFAULT "qm"
char *sr_memmng_pkg = NULL;
char *sr_memmng_shm = NULL;
static int *_sr_instance_started = NULL;
/**
* return 1 if all child processes were forked
* - note: they might still be in init phase (i.e., child init)
* - note: see also sr_insance_ready()
*/
int sr_instance_started(void)
{
if(_sr_instance_started!=NULL && *_sr_instance_started==1) {
return 1;
}
return 0;
}
/* call it before exiting; if show_status==1, mem status is displayed */
void cleanup(int show_status)
{
int memlog;
/*clean-up*/
#ifndef SHM_SAFE_MALLOC
if(shm_initialized()) {
/* force-unlock the shared memory lock in case some process crashed
* and let it locked; this will allow an almost gracious shutdown */
shm_global_unlock();
}
#endif
destroy_rpcs();
destroy_modules();
#ifdef USE_DNS_CACHE
destroy_dns_cache();
#endif
#ifdef USE_DST_BLACKLIST
destroy_dst_blacklist();
#endif
/* restore the original core configuration before the
* config block is freed, otherwise even logging is unusable,
* it can case segfault */
if (cfg_ok){
cfg_update();
/* copy current config into default_core_cfg */
if (core_cfg)
default_core_cfg=*((struct cfg_group_core*)core_cfg);
}
core_cfg = &default_core_cfg;
cfg_destroy();
#ifdef USE_TCP
destroy_tcp();
#ifdef USE_TLS
destroy_tls();
#endif /* USE_TLS */
#endif /* USE_TCP */
#ifdef USE_SCTP
sctp_core_destroy();
#endif
destroy_timer();
pv_destroy_api();
ksr_route_locks_set_destroy();
destroy_script_cb();
destroy_nonsip_hooks();
destroy_routes();
destroy_atomic_ops();
destroy_counters();
memlog=cfg_get(core, core_cfg, memlog);
#ifdef PKG_MALLOC
if (show_status && memlog <= cfg_get(core, core_cfg, debug)){
if (cfg_get(core, core_cfg, mem_summary) & 1) {
LOG(memlog, "Memory status (pkg):\n");
pkg_status();
}
if (cfg_get(core, core_cfg, mem_summary) & 4) {
LOG(memlog, "Memory still-in-use summary (pkg):\n");
pkg_sums();
}
}
#endif
if (pt) shm_free(pt);
pt=0;
if (show_status && memlog <= cfg_get(core, core_cfg, debug)){
if (cfg_get(core, core_cfg, mem_summary) & 2) {
LOG(memlog, "Memory status (shm):\n");
shm_status();
}
if (cfg_get(core, core_cfg, mem_summary) & 8) {
LOG(memlog, "Memory still-in-use summary (shm):\n");
shm_sums();
}
}
/* zero all shmem alloc vars that we still use */
shm_destroy_manager();
destroy_lock_ops();
if (pid_file) unlink(pid_file);
if (pgid_file) unlink(pgid_file);
pkg_destroy_manager();
}
/* tries to send a signal to all our processes
* if daemonized is ok to send the signal to all the process group,
* however if not daemonized we might end up sending the signal also
* to the shell which launched us => most signals will kill it if
* it's not in interactive mode and we don't want this. The non-daemonized
* case can occur when an error is encountered before daemonize is called
* (e.g. when parsing the config file) or when ser is started in "dont-fork"
* mode. Sending the signal to all the processes in pt[] will not work
* for processes forked from modules (which have no correspondent entry in
* pt), but this can happen only in dont_fork mode (which is only for
* debugging). So in the worst case + "dont-fork" we might leave some
* zombies. -- andrei */
static void kill_all_children(int signum)
{
int r;
if (own_pgid) kill(0, signum);
else if (pt){
/* lock processes table only if this is a child process
* (only main can add processes, so from main is safe not to lock
* and moreover it avoids the lock-holding suicidal children problem)
*/
if (!is_main) lock_get(process_lock);
for (r=1; r<*process_count; r++){
if (r==process_no) continue; /* try not to be suicidal */
if (pt[r].pid) {
kill(pt[r].pid, signum);
}
else LM_CRIT("killing: %s > %d no pid!!!\n",
pt[r].desc, pt[r].pid);
}
if (!is_main) lock_release(process_lock);
}
}
/* if this handler is called, a critical timeout has occurred while
* waiting for the children to finish => we should kill everything and exit */
static void sig_alarm_kill(int signo)
{
kill_all_children(SIGKILL); /* this will kill the whole group
including "this" process;
for debugging replace with SIGABRT
(but warning: it might generate lots
of cores) */
}
/* like sig_alarm_kill, but the timeout has occurred when cleaning up
* => try to leave a core for future diagnostics */
static void sig_alarm_abort(int signo)
{
/* LOG is not signal safe, but who cares, we are abort-ing anyway :-) */
LM_CRIT("shutdown timeout triggered, dying...");
abort();
}
static void shutdown_children(int sig, int show_status)
{
sr_corecb_void_exec(app_shutdown);
kill_all_children(sig);
if (set_sig_h(SIGALRM, sig_alarm_kill) == SIG_ERR ) {
LM_ERR("could not install SIGALARM handler\n");
/* continue, the process will die anyway if no
* alarm is installed which is exactly what we want */
}
alarm(ser_kill_timeout);
while((wait(0) > 0) || (errno==EINTR)); /* wait for all the
children to terminate*/
set_sig_h(SIGALRM, sig_alarm_abort);
cleanup(show_status); /* cleanup & show status*/
alarm(0);
set_sig_h(SIGALRM, SIG_IGN);
}
void handle_sigs(void)
{
pid_t chld;
int chld_status;
int any_chld_stopped;
int memlog;
switch(sig_flag){
case 0: break; /* do nothing*/
case SIGPIPE:
/* SIGPIPE might be rarely received on use of
exec module; simply ignore it
*/
LM_WARN("SIGPIPE received and ignored\n");
break;
case SIGINT:
case SIGTERM:
/* we end the program in all these cases */
if (sig_flag==SIGINT)
LM_DBG("INT received, program terminates\n");
else
LM_DBG("SIGTERM received, program terminates\n");
LM_NOTICE("Thank you for flying " NAME "!!!\n");
/* shutdown/kill all the children */
shutdown_children(SIGTERM, 1);
exit(0);
break;
case SIGUSR1:
memlog=cfg_get(core, core_cfg, memlog);
#ifdef PKG_MALLOC
if (memlog <= cfg_get(core, core_cfg, debug)){
if (cfg_get(core, core_cfg, mem_summary) & 1) {
LOG(memlog, "Memory status (pkg):\n");
pkg_status();
}
if (cfg_get(core, core_cfg, mem_summary) & 4) {
LOG(memlog, "Memory still-in-use summary (pkg):\n");
pkg_sums();
}
}
#endif
if (memlog <= cfg_get(core, core_cfg, debug)){
if (cfg_get(core, core_cfg, mem_summary) & 2) {
LOG(memlog, "Memory status (shm):\n");
shm_status();
}
if (cfg_get(core, core_cfg, mem_summary) & 8) {
LOG(memlog, "Memory still-in-use summary (shm):\n");
shm_sums();
}
}
break;
case SIGCHLD:
any_chld_stopped=0;
while ((chld=waitpid( -1, &chld_status, WNOHANG ))>0) {
any_chld_stopped=1;
if (WIFEXITED(chld_status))
LM_ALERT("child process %ld exited normally,"
" status=%d\n", (long)chld,
WEXITSTATUS(chld_status));
else if (WIFSIGNALED(chld_status)) {
LM_ALERT("child process %ld exited by a signal"
" %d\n", (long)chld, WTERMSIG(chld_status));
#ifdef WCOREDUMP
LM_ALERT("core was %sgenerated\n",
WCOREDUMP(chld_status) ? "" : "not " );
#endif
}else if (WIFSTOPPED(chld_status))
LM_ALERT("child process %ld stopped by a"
" signal %d\n", (long)chld,
WSTOPSIG(chld_status));
}
/* If it appears that no child process has stopped, then do not terminate on SIGCHLD.
Certain modules like app_python can run external scripts which cause child processes to be started and
stopped. That can result in SIGCHLD being received here even though there is no real problem. Therefore,
we do not terminate Kamailio unless we can find the child process which has stopped. */
if (!any_chld_stopped) {
LM_INFO("SIGCHLD received, but no child has stopped, ignoring it\n");
break;
}
#ifndef STOP_JIRIS_CHANGES
if (dont_fork) {
LM_INFO("dont_fork turned on, living on\n");
break;
}
LM_INFO("terminating due to SIGCHLD\n");
#endif
LM_DBG("terminating due to SIGCHLD\n");
/* exit */
shutdown_children(SIGTERM, 1);
if (WIFSIGNALED(chld_status)) {
exit(1);
} else {
exit(0);
}
break;
case SIGHUP: /* ignoring it*/
LM_DBG("SIGHUP received, ignoring it\n");
break;
default:
LM_CRIT("unhandled signal %d\n", sig_flag);
}
sig_flag=0;
}
/* added by jku; allows for regular exit on a specific signal;
good for profiling which only works if exited regularly and
not by default signal handlers
- modified by andrei: moved most of the stuff to handle_sigs,
made it safer for the "fork" case
*/
void sig_usr(int signo)
{
#ifdef PKG_MALLOC
int memlog;
#endif
if (is_main){
if (sig_flag==0) sig_flag=signo;
else /* previous sig. not processed yet, ignoring? */
return; ;
if (dont_fork)
/* only one proc, doing everything from the sig handler,
unsafe, but this is only for debugging mode*/
handle_sigs();
}else{
/* process the important signals */
switch(signo){
case SIGPIPE:
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
LM_INFO("signal %d received\n", signo);
#endif
break;
case SIGINT:
case SIGTERM:
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
LM_INFO("signal %d received\n", signo);
/* print memory stats for non-main too */
#ifdef PKG_MALLOC
/* make sure we have current cfg values, but update only
the safe part (values not requiring callbacks), to
account for processes that might not have registered
config support */
cfg_update_no_cbs();
memlog=cfg_get(core, core_cfg, memlog);
if (memlog <= cfg_get(core, core_cfg, debug)){
if (cfg_get(core, core_cfg, mem_summary) & 1) {
LOG(memlog, "Memory status (pkg):\n");
pkg_status();
}
if (cfg_get(core, core_cfg, mem_summary) & 4) {
LOG(memlog, "Memory still-in-use summary (pkg):"
"\n");
pkg_sums();
}
}
#endif
#endif
_exit(0);
break;
case SIGUSR1:
#ifdef PKG_MALLOC
cfg_update_no_cbs();
memlog=cfg_get(core, core_cfg, memlog);
if (memlog <= cfg_get(core, core_cfg, debug)){
if (cfg_get(core, core_cfg, mem_summary) & 1) {
LOG(memlog, "Memory status (pkg):\n");
pkg_status();
}
if (cfg_get(core, core_cfg, mem_summary) & 4) {
LOG(memlog, "Memory still-in-use summary (pkg):\n");
pkg_sums();
}
}
#endif
break;
/* ignored*/
case SIGUSR2:
case SIGHUP:
break;
case SIGCHLD:
#ifndef STOP_JIRIS_CHANGES
#ifdef SIG_DEBUG /* signal unsafe stuff follows */
LM_DBG("SIGCHLD received: "
"we do not worry about grand-children\n");
#endif
#else
_exit(0); /* terminate if one child died */
#endif
break;
}
}
}
/* install the signal handlers, returns 0 on success, -1 on error */
int install_sigs(void)
{
/* added by jku: add exit handler */
if (set_sig_h(SIGINT, sig_usr) == SIG_ERR ) {
ERR("no SIGINT signal handler can be installed\n");
goto error;
}
/* if we debug and write to a pipe, we want to exit nicely too */
if (set_sig_h(SIGPIPE, sig_usr) == SIG_ERR ) {
ERR("no SIGINT signal handler can be installed\n");
goto error;
}
if (set_sig_h(SIGUSR1, sig_usr) == SIG_ERR ) {
ERR("no SIGUSR1 signal handler can be installed\n");
goto error;
}
if (set_sig_h(SIGCHLD , sig_usr) == SIG_ERR ) {
ERR("no SIGCHLD signal handler can be installed\n");
goto error;
}
if (set_sig_h(SIGTERM , sig_usr) == SIG_ERR ) {
ERR("no SIGTERM signal handler can be installed\n");
goto error;
}
if (set_sig_h(SIGHUP , sig_usr) == SIG_ERR ) {
ERR("no SIGHUP signal handler can be installed\n");
goto error;
}
if (set_sig_h(SIGUSR2 , sig_usr) == SIG_ERR ) {
ERR("no SIGUSR2 signal handler can be installed\n");
goto error;
}
return 0;
error:
return -1;
}
/* returns -1 on error, 0 on success
* sets proto */
int parse_proto(unsigned char* s, long len, int* proto)
{
#define PROTO2UINT3(a, b, c) (( (((unsigned int)(a))<<16)+ \
(((unsigned int)(b))<<8)+ \
((unsigned int)(c)) ) | 0x20202020)
#define PROTO2UINT4(a, b ,c ,d) (( (((unsigned int)(a))<<24)+ \
(((unsigned int)(b))<<16)+ \
(((unsigned int)(c))<< 8)+ \
(((unsigned int)(d))) \
)| 0x20202020 )
unsigned int i;
if (likely(len==3)){
i=PROTO2UINT3(s[0], s[1], s[2]);
switch(i){
case PROTO2UINT3('u', 'd', 'p'):
*proto=PROTO_UDP;
break;
#ifdef USE_TCP
case PROTO2UINT3('t', 'c', 'p'):
if (tcp_disable) {
return -1;
}
*proto=PROTO_TCP;
break;
#ifdef USE_TLS
case PROTO2UINT3('t', 'l', 's'):
if (tcp_disable || tls_disable) {
return -1;
}
*proto=PROTO_TLS;
break;
#endif
#endif
default:
return -1;
}
}
#ifdef USE_SCTP
else if (likely(len==4)){
i=PROTO2UINT4(s[0], s[1], s[2], s[3]);
if (i==PROTO2UINT4('s', 'c', 't', 'p')) {
if (sctp_disable) {
return -1;
}
*proto=PROTO_SCTP;
} else {