forked from voipmonitor/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
voipmonitor.cpp
3736 lines (3423 loc) · 118 KB
/
voipmonitor.cpp
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
/* Martin Vit [email protected]
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2.
*/
#include <queue>
#include <climits>
// stevek - it could be smarter if sys/inotyfy.h available then use it otherwise use linux/inotify.h. I will do it later
#include "voipmonitor.h"
#ifndef FREEBSD
#include <sys/inotify.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
#include <signal.h>
#ifdef FREEBSD
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/ethernet.h>
#include <pthread.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/resource.h>
#include <semaphore.h>
#include <signal.h>
#include <execinfo.h>
#include <sstream>
#include <dirent.h>
#ifdef ISCURL
#include <curl/curl.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pcap.h>
#include "rtp.h"
#include "calltable.h"
#include "sniff.h"
#include "simpleini/SimpleIni.h"
#include "manager.h"
#include "filter_mysql.h"
#include "sql_db.h"
#include "tools.h"
#include "mirrorip.h"
#include "ipaccount.h"
#include "pcap_queue.h"
#include "generator.h"
#include "tcpreassembly.h"
#include "http.h"
#include "ip_frag.h"
#include "cleanspool.h"
#include "regcache.h"
#if defined(QUEUE_MUTEX) || defined(QUEUE_NONBLOCK)
extern "C" {
#include "liblfds.6/inc/liblfds.h"
}
#endif
#ifndef FREEBSD
#define BACKTRACE 1
#endif
#ifdef BACKTRACE
/* Since kernel version 2.2 the undocumented parameter to the signal handler has been declared
obsolete in adherence with POSIX.1b. A more correct way to retrieve additional information is
to use the SA_SIGINFO option when setting the handler */
#undef USE_SIGCONTEXT
#ifndef USE_SIGCONTEXT
/* get REG_EIP / REG_RIP from ucontext.h */
#include <ucontext.h>
#ifndef EIP
#define EIP 14
#endif
#if (defined (__x86_64__))
#ifndef REG_RIP
#define REG_RIP REG_INDEX(rip) /* seems to be 16 */
#endif
#endif
#endif
typedef struct { char name[10]; int id; char description[40]; } signal_def;
signal_def signal_data[] =
{
{ "SIGHUP", SIGHUP, "Hangup (POSIX)" },
{ "SIGINT", SIGINT, "Interrupt (ANSI)" },
{ "SIGQUIT", SIGQUIT, "Quit (POSIX)" },
{ "SIGILL", SIGILL, "Illegal instruction (ANSI)" },
{ "SIGTRAP", SIGTRAP, "Trace trap (POSIX)" },
{ "SIGABRT", SIGABRT, "Abort (ANSI)" },
{ "SIGIOT", SIGIOT, "IOT trap (4.2 BSD)" },
{ "SIGBUS", SIGBUS, "BUS error (4.2 BSD)" },
{ "SIGFPE", SIGFPE, "Floating-point exception (ANSI)" },
{ "SIGKILL", SIGKILL, "Kill, unblockable (POSIX)" },
{ "SIGUSR1", SIGUSR1, "User-defined signal 1 (POSIX)" },
{ "SIGSEGV", SIGSEGV, "Segmentation violation (ANSI)" },
{ "SIGUSR2", SIGUSR2, "User-defined signal 2 (POSIX)" },
{ "SIGPIPE", SIGPIPE, "Broken pipe (POSIX)" },
{ "SIGALRM", SIGALRM, "Alarm clock (POSIX)" },
{ "SIGTERM", SIGTERM, "Termination (ANSI)" },
{ "SIGSTKFLT", SIGSTKFLT, "Stack fault" },
{ "SIGCHLD", SIGCHLD, "Child status has changed (POSIX)" },
{ "SIGCLD", SIGCLD, "Same as SIGCHLD (System V)" },
{ "SIGCONT", SIGCONT, "Continue (POSIX)" },
{ "SIGSTOP", SIGSTOP, "Stop, unblockable (POSIX)" },
{ "SIGTSTP", SIGTSTP, "Keyboard stop (POSIX)" },
{ "SIGTTIN", SIGTTIN, "Background read from tty (POSIX)" },
{ "SIGTTOU", SIGTTOU, "Background write to tty (POSIX)" },
{ "SIGURG", SIGURG, "Urgent condition on socket (4.2 BSD)" },
{ "SIGXCPU", SIGXCPU, "CPU limit exceeded (4.2 BSD)" },
{ "SIGXFSZ", SIGXFSZ, "File size limit exceeded (4.2 BSD)" },
{ "SIGVTALRM", SIGVTALRM, "Virtual alarm clock (4.2 BSD)" },
{ "SIGPROF", SIGPROF, "Profiling alarm clock (4.2 BSD)" },
{ "SIGWINCH", SIGWINCH, "Window size change (4.3 BSD, Sun)" },
{ "SIGIO", SIGIO, "I/O now possible (4.2 BSD)" },
{ "SIGPOLL", SIGPOLL, "Pollable event occurred (System V)" },
{ "SIGPWR", SIGPWR, "Power failure restart (System V)" },
{ "SIGSYS", SIGSYS, "Bad system call" },
};
#endif
using namespace std;
int debugclean = 0;
/* global variables */
extern Calltable *calltable;
extern volatile int calls;
unsigned int opt_openfile_max = 65535;
int opt_packetbuffered = 0; // Make .pcap files writing ‘‘packet-buffered’’
// more slow method, but you can use partitialy
// writen file anytime, it will be consistent.
int opt_fork = 1; // fork or run foreground
int opt_saveSIP = 0; // save SIP packets to pcap file?
int opt_saveRTP = 0; // save RTP packets to pcap file?
int opt_onlyRTPheader = 0; // do not save RTP payload, only RTP header
int opt_saveRTCP = 0; // save RTCP packets to pcap file?
int opt_saveudptl = 0; // if = 1 all UDPTL packets will be saved (T.38 fax)
int opt_saveRAW = 0; // save RTP packets to pcap file?
int opt_saveWAV = 0; // save RTP packets to pcap file?
int opt_saveGRAPH = 0; // save GRAPH data to *.graph file?
int opt_gzipGRAPH = 0; // compress GRAPH data ?
int opt_saverfc2833 = 0;
int opt_dbdtmf = 0;
int opt_rtcp = 1; // pair RTP+1 port to RTCP and save it.
int opt_nocdr = 0; // do not save cdr?
int opt_gzipPCAP = 0; // compress PCAP data ?
int opt_mos_g729 = 0; // calculate MOS for G729 codec
int verbosity = 0; // debug level
int verbosityE = 0; // debug extended level
int opt_rtp_firstleg = 0; // if == 1 then save RTP stream only for first INVITE leg in case you are
// sniffing on SIP proxy where voipmonitor see both SIP leg.
int opt_jitterbuffer_f1 = 1; // turns off/on jitterbuffer simulator to compute MOS score mos_f1
int opt_jitterbuffer_f2 = 1; // turns off/on jitterbuffer simulator to compute MOS score mos_f2
int opt_jitterbuffer_adapt = 1; // turns off/on jitterbuffer simulator to compute MOS score mos_adapt
int opt_sip_register_active_nologbin = 1;
int opt_ringbuffer = 10; // ring buffer in MB
int opt_sip_register = 0; // if == 1 save REGISTER messages
int opt_audio_format = FORMAT_WAV; // define format for audio writing (if -W option)
int opt_manager_port = 5029; // manager api TCP port
char opt_manager_ip[32] = "127.0.0.1"; // manager api listen IP address
int opt_pcap_threaded = 0; // run reading packets from pcap in one thread and process packets in another thread via queue
int opt_norecord_header = 0; // if = 1 SIP call with X-VoipMonitor-norecord header will be not saved although global configuration says to record.
int opt_rtpnosip = 0; // if = 1 RTP stream will be saved into calls regardless on SIP signalizatoin (handy if you need extract RTP without SIP)
int opt_norecord_dtmf = 0; // if = 1 SIP call with dtmf == *0 sequence (in SIP INFO) will stop recording
int opt_savewav_force = 0; // if = 1 WAV will be generated no matter on filter rules
int opt_sipoverlap = 1;
int opt_id_sensor = -1;
int readend = 0;
int opt_dup_check = 0;
int opt_dup_check_ipheader = 1;
int rtptimeout = 300;
char opt_cdrurl[1024] = "";
int opt_destination_number_mode = 1;
int opt_cleanspool_interval = 0; // number of seconds between cleaning spool directory. 0 = disabled
int opt_cleanspool_sizeMB = 0; // number of MB to keep in spooldir
int opt_domainport = 0;
int request_iptelnum_reload = 0;
int opt_mirrorip = 0;
int opt_mirrorall = 0;
int opt_mirroronly = 0;
char opt_mirrorip_src[20];
char opt_mirrorip_dst[20];
int opt_printinsertid = 0;
int opt_ipaccount = 0;
int opt_ipacc_interval = 300;
bool opt_ipacc_sniffer_agregate = false;
bool opt_ipacc_agregate_only_customers_on_main_side = true;
bool opt_ipacc_agregate_only_customers_on_any_side = true;
bool opt_ipacc_multithread_save = true;
int opt_udpfrag = 1;
MirrorIP *mirrorip = NULL;
int opt_cdronlyanswered = 0;
int opt_cdronlyrtp = 0;
int opt_pcap_split = 1;
int opt_newdir = 1;
char opt_clientmanager[1024] = "";
int opt_clientmanagerport = 9999;
int opt_callslimit = 0;
char opt_silencedmtfseq[16] = "";
char opt_keycheck[1024] = "";
char opt_convert_char[64] = "";
int opt_skinny = 0;
int opt_read_from_file = 0;
char opt_pb_read_from_file[256] = "";
int opt_dscp = 0;
int opt_cdrproxy = 1;
int opt_enable_lua_tables = 0;
int opt_generator = 0;
int opt_generator_channels = 1;
int opt_skipdefault = 0;
int opt_filesclean = 1;
int opt_enable_tcpreassembly = 0;
int opt_tcpreassembly_pb_lock = 0;
int opt_tcpreassembly_thread = 1;
char opt_tcpreassembly_log[1024];
int opt_allow_zerossrc = 0;
int opt_convert_dlt_sll_to_en10 = 0;
int opt_mysqlcompress = 1;
int opt_cdr_ua_enable = 1;
unsigned long long cachedirtransfered = 0;
unsigned int opt_maxpcapsize_mb = 0;
int opt_mosmin_f2 = 1;
char opt_database_backup_from_date[20];
char opt_database_backup_from_mysql_host[256] = "";
char opt_database_backup_from_mysql_database[256] = "";
char opt_database_backup_from_mysql_user[256] = "";
char opt_database_backup_from_mysql_password[256] = "";
int opt_database_backup_pause = 300;
int opt_database_backup_insert_threads = 1;
int opt_database_backup_use_federated = 0;
string opt_mos_lqo_bin = "pesq";
string opt_mos_lqo_ref = "/usr/local/share/voipmonitor/audio/mos_lqe_original.wav";
string opt_mos_lqo_ref16 = "/usr/local/share/voipmonitor/audio/mos_lqe_original_16khz.wav";
regcache *regfailedcache;
int opt_onewaytimeout = 10;
int opt_saveaudio_reversestereo = 0;
unsigned int opt_maxpoolsize = 0;
unsigned int opt_maxpooldays = 0;
unsigned int opt_maxpoolsipsize = 0;
unsigned int opt_maxpoolsipdays = 0;
unsigned int opt_maxpoolrtpsize = 0;
unsigned int opt_maxpoolrtpdays = 0;
unsigned int opt_maxpoolgraphsize = 0;
unsigned int opt_maxpoolgraphdays = 0;
unsigned int opt_maxpoolaudiosize = 0;
unsigned int opt_maxpoolaudiodays = 0;
int opt_maxpool_clean_obsolete = 0;
char opt_php_path[1024];
struct pcap_stat pcapstat;
extern int opt_pcap_queue;
extern u_int opt_pcap_queue_block_max_time_ms;
extern size_t opt_pcap_queue_block_max_size;
extern u_int opt_pcap_queue_file_store_max_time_ms;
extern size_t opt_pcap_queue_file_store_max_size;
extern uint64_t opt_pcap_queue_store_queue_max_memory_size;
extern uint64_t opt_pcap_queue_store_queue_max_disk_size;
extern uint64_t opt_pcap_queue_bypass_max_size;
extern bool opt_pcap_queue_compress;
extern string opt_pcap_queue_disk_folder;
extern ip_port opt_pcap_queue_send_to_ip_port;
extern ip_port opt_pcap_queue_receive_from_ip_port;
extern int opt_pcap_queue_receive_dlt;
extern int opt_pcap_queue_iface_separate_threads;
extern int opt_pcap_queue_iface_dedup_separate_threads;
extern int opt_pcap_queue_iface_dedup_separate_threads_extend;
extern int sql_noerror;
int opt_cleandatabase_cdr = 0;
int opt_cleandatabase_register_state = 0;
int opt_cleandatabase_register_failed = 0;
unsigned int graph_delimiter = GRAPH_DELIMITER;
unsigned int graph_version = GRAPH_VERSION;
int opt_mos_lqo = 0;
bool opt_cdr_partition = 1;
bool opt_cdr_sipport = 0;
int opt_create_old_partitions = 0;
bool opt_disable_partition_operations = 0;
vector<dstring> opt_custom_headers_cdr;
vector<dstring> opt_custom_headers_message;
char configfile[1024] = ""; // config file name
string insert_funcname = "__insert";
char sql_driver[256] = "mysql";
char sql_cdr_table[256] = "cdr";
char sql_cdr_table_last30d[256] = "";
char sql_cdr_table_last7d[256] = "";
char sql_cdr_table_last1d[256] = "";
char sql_cdr_next_table[256] = "cdr_next";
char sql_cdr_ua_table[256] = "cdr_ua";
char sql_cdr_sip_response_table[256] = "cdr_sip_response";
char mysql_host[256] = "localhost";
char mysql_database[256] = "voipmonitor";
char mysql_table[256] = "cdr";
char mysql_user[256] = "root";
char mysql_password[256] = "";
int opt_mysql_port = 0; // 0 menas use standard port
int opt_skiprtpdata = 0;
char opt_match_header[128] = "";
char odbc_dsn[256] = "voipmonitor";
char odbc_user[256];
char odbc_password[256];
char odbc_driver[256];
char get_customer_by_ip_sql_driver[256] = "odbc";
char get_customer_by_ip_odbc_dsn[256];
char get_customer_by_ip_odbc_user[256];
char get_customer_by_ip_odbc_password[256];
char get_customer_by_ip_odbc_driver[256];
char get_customer_by_ip_query[1024];
char get_customers_ip_query[1024];
char get_customers_radius_name_query[1024];
char get_customer_by_pn_sql_driver[256] = "odbc";
char get_customer_by_pn_odbc_dsn[256];
char get_customer_by_pn_odbc_user[256];
char get_customer_by_pn_odbc_password[256];
char get_customer_by_pn_odbc_driver[256];
char get_customers_pn_query[1024];
vector<string> opt_national_prefix;
char get_radius_ip_driver[256];
char get_radius_ip_host[256];
char get_radius_ip_db[256];
char get_radius_ip_user[256];
char get_radius_ip_password[256];
char get_radius_ip_query[1024];
char get_radius_ip_query_where[1024];
int get_customer_by_ip_flush_period = 1;
char opt_pidfile[4098] = "/var/run/voipmonitor.pid";
char user_filter[2048] = "";
char ifname[1024]; // Specifies the name of the network device to use for
// the network lookup, for example, eth0
char opt_scanpcapdir[2048] = ""; // Specifies the name of the network device to use for
#ifndef FREEBSD
uint32_t opt_scanpcapmethod = IN_CLOSE_WRITE; // Specifies how to watch for new files in opt_scanpcapdir
#endif
int opt_promisc = 1; // put interface to promisc mode?
char pcapcommand[4092] = "";
char filtercommand[4092] = "";
int rtp_threaded = 0; // do not enable this until it will be reworked to be thread safe
int num_threads = 0; // this has to be 1 for now
unsigned int rtpthreadbuffer = 20; // default 20MB
unsigned int gthread_num = 0;
int opt_pcapdump = 0;
int opt_callend = 1; //if true, cdr.called is saved
char opt_chdir[1024];
char opt_cachedir[1024];
int opt_upgrade_try_http_if_https_fail = 0;
IPfilter *ipfilter = NULL; // IP filter based on MYSQL
IPfilter *ipfilter_reload = NULL; // IP filter based on MYSQL for reload purpose
int ipfilter_reload_do = 0; // for reload in main thread
TELNUMfilter *telnumfilter = NULL; // IP filter based on MYSQL
TELNUMfilter *telnumfilter_reload = NULL; // IP filter based on MYSQL for reload purpose
int telnumfilter_reload_do = 0; // for reload in main thread
pthread_t call_thread; // ID of worker storing CDR thread
pthread_t cdr_thread;
pthread_t sql_thread;
pthread_t readdump_libpcap_thread;
pthread_t manager_thread = 0; // ID of worker manager thread
pthread_t manager_client_thread; // ID of worker manager thread
pthread_t cachedir_thread; // ID of worker cachedir thread
pthread_t cleanspool_thread; // ID of worker clean thread
pthread_t database_backup_thread; // ID of worker backup thread
int terminating; // if set to 1, worker thread will terminate
int terminating2; // if set to 1, worker thread will terminate
char *sipportmatrix; // matrix of sip ports to monitor
char *httpportmatrix; // matrix of http ports to monitor
char *ipaccountportmatrix;
vector<u_int32_t> httpip;
vector<d_u_int32_t> httpnet;
uint8_t opt_sdp_reverse_ipport = 0;
queue<string> mysqlquery;
volatile unsigned int readit = 0;
volatile unsigned int writeit = 0;
int global_livesniffer = 0;
int global_livesniffer_all = 0;
unsigned int qringmax = 12500;
#if defined(QUEUE_MUTEX) || defined(QUEUE_NONBLOCK) || defined(QUEUE_NONBLOCK2)
pcap_packet *qring;
#endif
pcap_t *handle = NULL; // pcap handler
pcap_t *handle_dead_EN10MB = NULL;
read_thread *threads;
int manager_socket_server = 0;
pthread_mutex_t mysqlquery_lock;
pthread_mutex_t mysqlconnect_lock;
pthread_t pcap_read_thread;
#ifdef QUEUE_MUTEX
pthread_mutex_t readpacket_thread_queue_lock;
sem_t readpacket_thread_semaphore;
#endif
#ifdef QUEUE_NONBLOCK
struct queue_state *qs_readpacket_thread_queue = NULL;
#endif
nat_aliases_t nat_aliases; // net_aliases[local_ip] = extern_ip
MySqlStore *sqlStore = NULL;
char mac[32] = "";
PcapQueue *pcapQueueStatInterface;
TcpReassembly *tcpReassembly;
HttpData *httpData;
string storingCdrLastWriteAt;
string storingSqlLastWriteAt;
time_t startTime;
sem_t *globalSemaphore;
#define ENABLE_SEMAPHOR_FORK_MODE 0
#if ENABLE_SEMAPHOR_FORK_MODE
string SEMAPHOR_FORK_MODE_NAME() {
char forkModeName[1024] = "";
if(!forkModeName[0]) {
strcpy(forkModeName, configfile[0] ? configfile : "voipmonitor_fork_mode");
if(configfile[0]) {
char *point = forkModeName;
while(*point) {
if(!isdigit(*point) && !isalpha(*point)) {
*point = '_';
}
++point;
}
}
}
return(forkModeName);
}
#endif
void mysqlquerypush(string q) {
pthread_mutex_lock(&mysqlquery_lock);
mysqlquery.push(q);
pthread_mutex_unlock(&mysqlquery_lock);
}
void terminate2() {
terminating = 1;
}
#if ENABLE_SEMAPHOR_FORK_MODE
void exit_handler_fork_mode()
{
if(opt_fork) {
sem_unlink(SEMAPHOR_FORK_MODE_NAME().c_str());
if(globalSemaphore) {
sem_close(globalSemaphore);
}
}
}
#endif
/* handler for INTERRUPT signal */
void sigint_handler(int param)
{
syslog(LOG_ERR, "SIGINT received, terminating\n");
terminate2();
#if ENABLE_SEMAPHOR_FORK_MODE
exit_handler_fork_mode();
#endif
}
/* handler for TERMINATE signal */
void sigterm_handler(int param)
{
syslog(LOG_ERR, "SIGTERM received, terminating\n");
terminate2();
#if ENABLE_SEMAPHOR_FORK_MODE
exit_handler_fork_mode();
#endif
}
void find_and_replace( string &source, const string find, string replace ) {
size_t j;
for ( ; (j = source.find( find )) != string::npos ; ) {
source.replace( j, find.length(), replace );
}
}
void *clean_spooldir(void *dummy) {
if(debugclean) syslog(LOG_ERR, "run clean_spooldir()");
while(!terminating2) {
/* old code
char cmd[2048];
sprintf(cmd, "find \"%s/\" -type f -printf \"%%T@::%%p::%%s\\n\" | sort -rn | awk -v maxbytes=\"$((1024 * 1024 * %d))\" -F \"::\" 'BEGIN { curSize=0; } { curSize += $3; if (curSize > maxbytes) { print $2; } }'", opt_chdir, opt_cleanspool_sizeMB);
if(verbosity > 0) syslog(LOG_NOTICE, "cleaning spool: [%s]\n", cmd);
FILE* pipe = popen(cmd, "r");
if (!pipe) {
syslog(LOG_ERR, "cannot rum clean command: [%s] error:[%s]", cmd, strerror(errno));
continue;
}
while(!feof(pipe)) {
if(fgets(buffer, 4092, pipe) != NULL) {
// remove new line
buffer[strlen(buffer) - 1] = '\0';
unlink(buffer);
}
}
pclose(pipe);
sleep(opt_cleanspool_interval);
*/
/* obsolete
if(debugclean) syslog(LOG_ERR, "pthread_create(clean_spooldir_run)");
pthread_t tpid; // ID of worker clean thread
pthread_create(&tpid, NULL, clean_spooldir_run, NULL);
*/
if(debugclean) syslog(LOG_ERR, "run clean_spooldir_run");
clean_spooldir_run(NULL);
for(int i = 0; i < 300 && !terminating2; i++) {
sleep(1);
}
}
return NULL;
}
void *database_backup(void *dummy) {
if(!isSqlDriver("mysql")) {
syslog(LOG_ERR, "database_backup is only for mysql driver!");
return(NULL);
}
if(!opt_cdr_partition) {
syslog(LOG_ERR, "database_backup need enable partitions!");
return(NULL);
}
time_t createPartitionAt = 0;
time_t dropPartitionAt = 0;
SqlDb *sqlDb = createSqlObject();
if(!sqlDb->connect()) {
delete sqlDb;
return NULL;
}
SqlDb_mysql *sqlDb_mysql = dynamic_cast<SqlDb_mysql*>(sqlDb);
sqlStore = new MySqlStore(mysql_host, mysql_user, mysql_password, mysql_database);
for(int i = 1; i <= 10; i++) {
sqlStore->setIgnoreTerminating(i, true);
}
while(!terminating) {
syslog(LOG_NOTICE, "-- START BACKUP PROCESS");
time_t actTime = time(NULL);
if(actTime - createPartitionAt > 12 * 3600) {
createMysqlPartitionsCdr();
createPartitionAt = actTime;
}
if(actTime - dropPartitionAt > 12 * 3600) {
dropMysqlPartitionsCdr();
dropPartitionAt = actTime;
}
if(opt_database_backup_use_federated) {
sqlDb_mysql->dropFederatedTables();
sqlDb->createSchema(opt_database_backup_from_mysql_host,
opt_database_backup_from_mysql_database,
opt_database_backup_from_mysql_user,
opt_database_backup_from_mysql_password);
if(sqlDb_mysql->checkFederatedTables()) {
sqlDb_mysql->copyFromFederatedTables();
}
} else {
SqlDb *sqlDbSrc = new SqlDb_mysql();
sqlDbSrc->setConnectParameters(opt_database_backup_from_mysql_host,
opt_database_backup_from_mysql_user,
opt_database_backup_from_mysql_password,
opt_database_backup_from_mysql_database);
if(sqlDbSrc->connect()) {
SqlDb_mysql *sqlDbSrc_mysql = dynamic_cast<SqlDb_mysql*>(sqlDbSrc);
if(sqlDbSrc_mysql->checkSourceTables()) {
sqlDb_mysql->copyFromSourceTables(sqlDbSrc_mysql);
}
}
delete sqlDbSrc;
}
syslog(LOG_NOTICE, "-- END BACKUP PROCESS");
for(int i = 0; i < opt_database_backup_pause && !terminating; i++) {
sleep(1);
}
}
while(sqlStore->getSize()) {
syslog(LOG_NOTICE, "flush sqlStore");
sleep(1);
}
for(int i = 1; i <= 10; i++) {
sqlStore->setIgnoreTerminating(i, false);
}
delete sqlDb;
delete sqlStore;
return NULL;
}
/* cycle files_queue and move it to spool dir */
void *moving_cache( void *dummy ) {
string file;
char src_c[1024];
char dst_c[1024];
unsigned long long counter[2] = { 0, 0 };
while(1) {
u_int32_t mindatehour = 0;
int year, month, mday, hour;
while (1) {
calltable->lock_files_queue();
if(calltable->files_queue.size() == 0) {
calltable->unlock_files_queue();
break;
}
file = calltable->files_queue.front();
calltable->files_queue.pop();
calltable->unlock_files_queue();
sscanf(file.c_str(), "%d-%d-%d/%d", &year, &month, &mday, &hour);
u_int32_t datehour = year * 1000000 + month * 10000 + mday * 100 + hour;
if(!mindatehour || datehour < mindatehour) {
mindatehour = datehour;
}
string src;
src.append(opt_cachedir);
src.append("/");
src.append(file);
string dst;
dst.append(opt_chdir);
dst.append("/");
dst.append(file);
strncpy(src_c, (char*)src.c_str(), sizeof(src_c));
strncpy(dst_c, (char*)dst.c_str(), sizeof(dst_c));
if(verbosity > 2) syslog(LOG_ERR, "rename([%s] -> [%s])\n", src_c, dst_c);
cachedirtransfered += move_file(src_c, dst_c);
//TODO: error handling
//perror ("The following error occurred");
}
if(terminating2) {
break;
} else {
++counter[0];
if(mindatehour && counter[0] > counter[1] + 300) {
DIR* dp = opendir(opt_cachedir);
struct tm mindatehour_t;
memset(&mindatehour_t, 0, sizeof(mindatehour_t));
mindatehour_t.tm_year = mindatehour / 1000000 - 1900;
mindatehour_t.tm_mon = mindatehour / 10000 % 100 - 1;
mindatehour_t.tm_mday = mindatehour / 100 % 100;
mindatehour_t.tm_hour = mindatehour % 100;
if(dp) {
dirent* de;
while(true) {
de = readdir(dp);
if(de == NULL) break;
if(string(de->d_name) == ".." or string(de->d_name) == ".") continue;
if(de->d_type == DT_DIR && de->d_name[0] == '2') {
int year, month, mday;
sscanf(de->d_name, "%d-%d-%d", &year, &month, &mday);
bool moveHourDir = false;
for(int hour = 0; hour < 24; hour ++) {
struct tm dirdatehour_t;
memset(&dirdatehour_t, 0, sizeof(dirdatehour_t));
dirdatehour_t.tm_year = year - 1900;
dirdatehour_t.tm_mon = month - 1;
dirdatehour_t.tm_mday = mday;
dirdatehour_t.tm_hour = hour;
if(difftime(mktime(&mindatehour_t), mktime(&dirdatehour_t)) > 8 * 60 * 60) {
char hour_str[10];
sprintf(hour_str, "%02i", hour);
if(file_exists((char*)(string(opt_cachedir) + "/" + de->d_name + "/" + hour_str).c_str())) {
mkdir_r((string(opt_chdir) + "/" + de->d_name + "/" + hour_str).c_str(), 0777);
mv_r((string(opt_cachedir) + "/" + de->d_name + "/" + hour_str).c_str(), (string(opt_chdir) + "/" + de->d_name + "/" + hour_str).c_str());
rmdir((string(opt_cachedir) + "/" + de->d_name + "/" + hour_str).c_str());
moveHourDir = true;
}
}
}
if(moveHourDir) {
rmdir((string(opt_cachedir) + "/" + de->d_name).c_str());
}
}
}
closedir(dp);
}
counter[1] = counter[0];
}
}
sleep(1);
}
return NULL;
}
void *storing_sql( void *dummy ) {
SqlDb *sqlDb = createSqlObject();
if(!opt_nocdr) {
sqlDb->connect();
}
while(1) {
// process mysql query queue - concatenate queries to N messages
int size = 0;
int msgs = 50;
int _counterIpacc = 0;
string queryqueue = "";
int mysqlQuerySize = mysqlquery.size();
while(1) {
pthread_mutex_lock(&mysqlquery_lock);
if(mysqlquery.size() == 0) {
pthread_mutex_unlock(&mysqlquery_lock);
if(queryqueue != "") {
// send the rest
sqlDb->query("drop procedure if exists " + insert_funcname);
sqlDb->query("create procedure " + insert_funcname + "()\nbegin\n" + queryqueue + "\nend");
sqlDb->query("call " + insert_funcname + "();");
storingSqlLastWriteAt = getActDateTimeF();
//sqlDb->query(queryqueue);
queryqueue = "";
}
break;
}
string query = mysqlquery.front();
mysqlquery.pop();
--mysqlQuerySize;
pthread_mutex_unlock(&mysqlquery_lock);
queryqueue.append(query + "; ");
if(verbosity > 0) {
if(query.find("ipacc ") != string::npos) {
++_counterIpacc;
}
}
if(size < msgs) {
size++;
} else {
sqlDb->query("drop procedure if exists " + insert_funcname);
sqlDb->query("create procedure " + insert_funcname + "()\nbegin\n" + queryqueue + "\nend");
sqlDb->query("call " + insert_funcname + "();");
storingSqlLastWriteAt = getActDateTimeF();
//sqlDb->query(queryqueue);
queryqueue = "";
size = 0;
}
if(!opt_read_from_file &&
terminating && !sqlDb->connected()) {
break;
}
}
if(verbosity > 0 && _counterIpacc > 0) {
int _start = time(NULL);
int diffTime = time(NULL) - _start;
cout << "SAVE IPACC (" << sqlDateTimeString(time(NULL)) << "): " << _counterIpacc << " rec";
if(diffTime > 0) {
cout << " " << diffTime << " s " << (_counterIpacc/diffTime) << " rec/s";
}
cout << endl;
}
if(terminating) {
break;
}
sleep(1);
}
if(sqlDb) delete sqlDb;
return NULL;
}
/* cycle calls_queue and save it to MySQL */
void *storing_cdr( void *dummy ) {
Call *call;
time_t createPartitionAt = 0;
time_t dropPartitionAt = 0;
time_t createPartitionIpaccAt = 0;
while(1) {
if(!opt_nocdr and opt_cdr_partition and !opt_disable_partition_operations and isSqlDriver("mysql")) {
time_t actTime = time(NULL);
if(actTime - createPartitionAt > 12 * 3600) {
createMysqlPartitionsCdr();
createPartitionAt = actTime;
}
if(actTime - dropPartitionAt > 12 * 3600) {
dropMysqlPartitionsCdr();
dropPartitionAt = actTime;
}
}
if(opt_ipaccount and !opt_disable_partition_operations and isSqlDriver("mysql")) {
time_t actTime = time(NULL);
if(actTime - createPartitionIpaccAt > 12 * 3600) {
createMysqlPartitionsIpacc();
createPartitionIpaccAt = actTime;
}
}
if(request_iptelnum_reload == 1) { reload_capture_rules(); request_iptelnum_reload = 0;};
#ifdef ISCURL
string cdrtosend;
#endif
if(verbosity > 0 && !opt_pcap_queue) {
ostringstream outStr;
outStr << "calls[" << calls << "]";
if(opt_ipaccount) {
outStr << " ipacc_buffer[" << lengthIpaccBuffer() << "]";
}
#ifdef QUEUE_NONBLOCK2
if(!opt_pcap_queue) {
outStr << " qring[" << (writeit >= readit ? writeit - readit : writeit + qringmax - readit)
<< " (w" << writeit << ",r" << readit << ")]";
}
#endif
syslog(LOG_NOTICE, outStr.str().c_str());
}
while (1) {
if(request_iptelnum_reload == 1) { reload_capture_rules(); request_iptelnum_reload = 0;};
calltable->lock_calls_queue();
if(calltable->calls_queue.size() == 0) {
calltable->unlock_calls_queue();
break;
}
call = calltable->calls_queue.front();
calltable->calls_queue.pop_front();
calltable->unlock_calls_queue();
call->closeRawFiles();
if( (opt_savewav_force || (call->flags & FLAG_SAVEWAV)) && (call->type == INVITE || call->type == SKINNY_NEW)) {
if(verbosity > 0) printf("converting RAW file to WAV Queue[%d]\n", (int)calltable->calls_queue.size());
call->convertRawToWav();
}
regfailedcache->prunecheck(call->first_packet_time);
if(!opt_nocdr) {
if(call->type == INVITE or call->type == SKINNY_NEW) {
call->saveToDb(1);
} else if(call->type == REGISTER){
call->saveRegisterToDb();
} else if(call->type == MESSAGE){
call->saveMessageToDb();
}
}
#ifdef ISCURL
if(opt_cdrurl[0] != '\0') {
cdrtosend += call->getKeyValCDRtext();
cdrtosend += "##vmdelimiter###\n";
}
#endif
/* if pcapcommand is defined, execute command */
if(strlen(pcapcommand)) {
string source(pcapcommand);
string find1 = "%pcap%";
string find2 = "%basename%";
string find3 = "%dirname%";
string replace;
replace.append("\"");
replace.append(opt_chdir);
replace.append("/");
replace.append(call->dirname());
replace.append("/");
replace.append(call->fbasename);
replace.append(".pcap");
replace.append("\"");
find_and_replace(source, find1, replace);
find_and_replace(source, find2, call->fbasename);
find_and_replace(source, find3, call->dirname());
if(verbosity >= 2) printf("command: [%s]\n", source.c_str());
system(source.c_str());
};
if(call->flags & FLAG_RUNSCRIPT) {
string source(filtercommand);
string tmp = call->fbasename;
find_and_replace(source, string("%callid%"), escapeshellR(tmp));
tmp = call->dirname();
find_and_replace(source, string("%dirname%"), escapeshellR(tmp));
tmp = sqlDateTimeString(call->calltime());
find_and_replace(source, string("%calldate%"), escapeshellR(tmp));
tmp = call->caller;
find_and_replace(source, string("%caller%"), escapeshellR(tmp));
tmp = call->called;
find_and_replace(source, string("%called%"), escapeshellR(tmp));
if(verbosity >= 2) printf("command: [%s]\n", source.c_str());
system(source.c_str());
}
// Close SIP and SIP+RTP dump files ASAP to save file handles
call->getPcap()->close();
call->getPcapSip()->close();
/* if we delete call here directly, destructors and another cleaning functions can be
* called in the middle of working with call or another structures inside main thread
* so put it in deletequeue and delete it in the main thread. Another way can be locking
* call structure for every case in main thread but it can slow down thinks for each
* processing packet.
*/
calltable->lock_calls_deletequeue();
calltable->calls_deletequeue.push(call);
calltable->unlock_calls_deletequeue();
storingCdrLastWriteAt = getActDateTimeF();
}
#ifdef ISCURL
if(opt_cdrurl[0] != '\0' && cdrtosend.length() > 0) {
sendCDR(cdrtosend);
}
#endif
if(terminating) {
break;
}
sleep(1);
}
return NULL;
}
char daemonizeErrorTempFileName[L_tmpnam+1];
pthread_mutex_t daemonizeErrorTempFileLock;
static void daemonize(void)
{
tmpnam(daemonizeErrorTempFileName);
pthread_mutex_init(&daemonizeErrorTempFileLock, NULL);
pid_t pid;
pid = fork();
if (pid) {
// parent
sleep(5);
FILE *daemonizeErrorFile = fopen(daemonizeErrorTempFileName, "r");
if(daemonizeErrorFile) {
char buff[1024];
while(fgets(buff, sizeof(buff), daemonizeErrorFile)) {