-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.cpp
More file actions
6191 lines (5298 loc) · 189 KB
/
server.cpp
File metadata and controls
6191 lines (5298 loc) · 189 KB
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
#include "server.h"
int g_sock = -1;
int g_debug = 0;
char g_host[MAX_PASSWORD_SIZE];
int g_udp_port = DEFAULT_PORT;
char g_password[MAX_PASSWORD_SIZE];
#ifdef USE_SQLITE3
char g_log[256];
#endif
char g_talkgroup[256];
char g_banned[256];
int u_banned[MAX_BANNED_SIZE];
int g_housekeeping_minutes = DEFAULT_HOUSEKEEPING_MINUTES;
int g_keep_nodes_alive = 1;
int g_node_timeout = 1800;
int g_relax_ip_change = 1;
dword volatile g_tick;
dword volatile g_sec;
int g_scanner_tg = 777;
int g_parrot_tg = 9990;
int g_aprs_tg = 900999;
int g_worker_threads = 1;
dword radioid_old;
dword tg_old;
dword slotid_old;
dword nodeid_old;
static std::mutex g_state_lock;
static std::mutex g_sqlite_lock;
#ifdef USE_UPLINK
static std::mutex g_uplink_lock;
#else
static std::mutex g_obp_lock;
#endif
struct packet_send_target {
sockaddr_in addr;
bool slot2;
packet_send_target() : slot2(false) {
memset(&addr, 0, sizeof(addr));
}
};
struct rx_job {
sockaddr_in addr;
std::vector<byte> data;
};
struct rx_worker_ctx {
std::mutex m;
std::condition_variable cv;
std::deque<rx_job> q;
std::thread th;
bool stop;
rx_worker_ctx() : stop(false) {}
};
static std::vector<rx_worker_ctx*> g_rx_workers;
void handle_rx (sockaddr_in &addr, byte *pk, int pksize);
#ifdef HAVE_HTTPMODE
int g_monitor_enabled = 1;
int g_monitor_port = 8080;
char g_monitor_root[256] = "www";
static void trim_spaces(char* s);
struct talkgroup;
talkgroup * findgroup (dword tg, bool bCreateIfNecessary);
typedef struct {
int used;
int radio;
int tg;
int src;
int aprs;
int sms;
unsigned last_sec;
} MonMark;
#define MONMARK_N 1024
static MonMark g_marks[MONMARK_N];
#endif
int obp_local_port = 62000;
char ob_host[MAX_PASSWORD_SIZE];
int obp_remote_port = 62000;
std::vector<ob_peer> g_obp_peers;
#ifdef USE_UPLINK
std::vector<uplink_peer> g_uplinks;
#endif
#ifdef HAVE_APRS
aprs_client g_aprs = {0};
struct aprs_position_entry {
std::string key;
std::string callsign;
std::string comment;
char symbol_table;
char symbol_code;
double latitude;
double longitude;
dword last_sec;
dword dmrid;
aprs_position_entry()
: symbol_table('/'), symbol_code('>'), latitude(0.0), longitude(0.0), last_sec(0), dmrid(0) {
}
};
static std::map<dword, std::string> g_aprs_idmap;
static std::map<std::string, aprs_position_entry> g_aprs_positions;
static std::string g_aprs_rxbuf;
static void aprs_positions_lock();
static void aprs_positions_unlock();
static std::string aprs_trim_copy(const std::string& s) {
size_t b = 0;
while (b < s.size() && (s[b] == ' ' || s[b] == '\t' || s[b] == '\r' || s[b] == '\n')) ++b;
size_t e = s.size();
while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\r' || s[e - 1] == '\n')) --e;
return s.substr(b, e - b);
}
static std::string aprs_normalize_callsign(const std::string& raw) {
std::string s = aprs_trim_copy(raw);
std::string out;
out.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
unsigned char ch = (unsigned char)s[i];
if (ch == '>') break;
if (ch == ' ' || ch == '\t' || ch == ',' || ch == '\r' || ch == '\n') break;
out.push_back((char)toupper(ch));
}
return out;
}
static std::string aprs_callsign_base(const std::string& raw) {
std::string s = aprs_normalize_callsign(raw);
size_t dash = s.find('-');
if (dash != std::string::npos) s.erase(dash);
return s;
}
static dword aprs_lookup_dmrid_for_callsign(const std::string& callsign) {
std::string want = aprs_normalize_callsign(callsign);
std::string want_base = aprs_callsign_base(callsign);
if (want.empty()) return 0;
for (std::map<dword, std::string>::iterator it = g_aprs_idmap.begin(); it != g_aprs_idmap.end(); ++it) {
std::string have = aprs_normalize_callsign(it->second);
if (have == want) return it->first;
if (!want_base.empty() && aprs_callsign_base(have) == want_base) return it->first;
}
return 0;
}
static bool aprs_parse_coord_value(const char* src, int deg_digits, char hemi_pos, char hemi_neg, double* out_value) {
if (!src || !out_value) return false;
int deg = 0;
for (int i = 0; i < deg_digits; ++i) {
if (!isdigit((unsigned char)src[i])) return false;
deg = deg * 10 + (src[i] - '0');
}
if (!isdigit((unsigned char)src[deg_digits + 0]) || !isdigit((unsigned char)src[deg_digits + 1]))
return false;
int mins = (src[deg_digits + 0] - '0') * 10 + (src[deg_digits + 1] - '0');
if (mins < 0 || mins >= 60) return false;
double frac = 0.0;
double scale = 10.0;
int pos = deg_digits + 2;
if (src[pos] == '.') {
++pos;
while (isdigit((unsigned char)src[pos])) {
frac += (double)(src[pos] - '0') / scale;
scale *= 10.0;
++pos;
}
}
char hemi = src[pos];
if (hemi != hemi_pos && hemi != hemi_neg) return false;
double value = (double)deg + (((double)mins) + frac) / 60.0;
if (hemi == hemi_neg) value = -value;
*out_value = value;
return true;
}
static bool aprs_parse_position_payload(const std::string& payload, double* out_lat, double* out_lon, char* out_symtab, char* out_symcode, std::string* out_comment) {
if (out_lat) *out_lat = 0.0;
if (out_lon) *out_lon = 0.0;
if (out_symtab) *out_symtab = '/';
if (out_symcode) *out_symcode = '>';
if (out_comment) out_comment->clear();
if (payload.empty()) return false;
const char* p = payload.c_str();
if (*p == '!' || *p == '=') {
++p;
} else if (*p == '/' || *p == '@') {
if (payload.size() < 8) return false;
p += 8;
} else {
return false;
}
size_t remain = strlen(p);
if (remain < 19) return false;
double lat = 0.0;
double lon = 0.0;
if (!aprs_parse_coord_value(p, 2, 'N', 'S', &lat)) return false;
char symtab = p[8];
if (!aprs_parse_coord_value(p + 9, 3, 'E', 'W', &lon)) return false;
char symcode = p[18];
if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0) return false;
if (out_lat) *out_lat = lat;
if (out_lon) *out_lon = lon;
if (out_symtab) *out_symtab = symtab;
if (out_symcode) *out_symcode = symcode;
if (out_comment) *out_comment = aprs_trim_copy(std::string(p + 19));
return true;
}
static void aprs_store_position(const std::string& callsign, double latitude, double longitude, char symtab, char symcode, const std::string& comment) {
std::string key = aprs_normalize_callsign(callsign);
if (key.empty()) return;
aprs_position_entry entry;
entry.key = key;
entry.callsign = key;
entry.comment = aprs_trim_copy(comment);
entry.symbol_table = symtab ? symtab : '/';
entry.symbol_code = symcode ? symcode : '>';
entry.latitude = latitude;
entry.longitude = longitude;
entry.last_sec = g_sec ? g_sec : (dword)time(NULL);
entry.dmrid = aprs_lookup_dmrid_for_callsign(key);
aprs_positions_lock();
g_aprs_positions[key] = entry;
aprs_positions_unlock();
}
static void aprs_prune_positions() {
const dword now = g_sec ? g_sec : (dword)time(NULL);
const dword max_age = 86400;
aprs_positions_lock();
for (std::map<std::string, aprs_position_entry>::iterator it = g_aprs_positions.begin(); it != g_aprs_positions.end(); ) {
if (it->second.last_sec == 0 || now < it->second.last_sec || (now - it->second.last_sec) > max_age)
g_aprs_positions.erase(it++);
else
++it;
}
aprs_positions_unlock();
}
static void aprs_process_line(const std::string& raw_line) {
std::string line = aprs_trim_copy(raw_line);
if (line.empty() || line[0] == '#') return;
size_t gt = line.find('>');
size_t colon = line.find(':');
if (gt == std::string::npos || colon == std::string::npos || gt == 0 || colon <= gt) return;
std::string callsign = aprs_normalize_callsign(line.substr(0, gt));
std::string payload = line.substr(colon + 1);
double latitude = 0.0;
double longitude = 0.0;
char symtab = '/';
char symcode = '>';
std::string comment;
if (!aprs_parse_position_payload(payload, &latitude, &longitude, &symtab, &symcode, &comment))
return;
aprs_store_position(callsign, latitude, longitude, symtab, symcode, comment);
}
static const char* aprs_safe_callsign(dword id) {
static char buf[40];
const char* cs = aprs_lookup_callsign(id);
if (cs && *cs) return cs;
sprintf(buf, "DMR%u-9", (unsigned)id);
return buf;
}
static bool aprs_connected() {
return g_aprs.sock > 0;
}
static bool aprs_connect() {
if (!g_aprs.enabled) return false;
if (!g_aprs.server_host[0] || !g_aprs.callsign[0]) return false;
int s = socket(AF_INET, SOCK_STREAM, 0);
if (s == -1) return false;
sockaddr_in a; memset(&a,0,sizeof(a));
a.sin_family = AF_INET;
a.sin_port = htons(g_aprs.server_port);
#ifdef WIN32
unsigned long ip = inet_addr(g_aprs.server_host);
if (ip == INADDR_NONE) {
hostent* he = gethostbyname(g_aprs.server_host);
if (!he || he->h_addrtype != AF_INET) { CLOSESOCKET(s); return false; }
a.sin_addr.S_un.S_addr = *(u_long*)he->h_addr_list[0];
} else a.sin_addr.S_un.S_addr = ip;
#else
in_addr_t ip = inet_addr(g_aprs.server_host);
if (ip == INADDR_NONE) {
hostent* he = gethostbyname(g_aprs.server_host);
if (!he || he->h_addrtype != AF_INET) { CLOSESOCKET(s); return false; }
a.sin_addr.s_addr = *(in_addr_t*)he->h_addr_list[0];
} else a.sin_addr.s_addr = ip;
#endif
if (connect(s, (sockaddr*)&a, sizeof(a)) == -1) {
CLOSESOCKET(s);
return false;
}
g_aprs.sock = s;
g_aprs.last_io_sec = g_sec;
g_aprs_rxbuf.clear();
char line[512];
sprintf(line, "user %s pass %s vers DMRServer 0.30 filter %s\r\n",
g_aprs.callsign, g_aprs.passcode,
g_aprs.filter[0] ? g_aprs.filter : "m/0");
send(g_aprs.sock, line, (int)strlen(line), 0);
return true;
}
static void aprs_disconnect() {
if (g_aprs.sock > 0) {
CLOSESOCKET(g_aprs.sock);
g_aprs.sock = -1;
}
g_aprs_rxbuf.clear();
}
bool aprs_init_from_config() {
g_aprs.sock = -1;
g_aprs.last_io_sec = g_sec;
g_aprs.last_try_sec = 0;
g_aprs_rxbuf.clear();
if (!g_aprs.enabled) return false;
return aprs_connect();
}
static void aprs_send_line(const char* s) {
if (!aprs_connected()) return;
if (!s || !*s) return;
int n = (int)strlen(s);
send(g_aprs.sock, s, n, 0);
g_aprs.last_io_sec = g_sec;
}
void aprs_housekeeping() {
if (!g_aprs.enabled) return;
aprs_prune_positions();
if (aprs_connected() && g_aprs.keepalive_secs > 0 &&
g_sec - g_aprs.last_io_sec >= (dword)g_aprs.keepalive_secs) {
aprs_send_line("# keepalive\r\n");
}
if (!aprs_connected() && g_sec - g_aprs.last_try_sec >= (dword)g_aprs.reconnect_secs) {
g_aprs.last_try_sec = g_sec;
if (!aprs_connect()) {
}
}
if (aprs_connected() && select_rx(g_aprs.sock, 0)) {
char buf[1024];
int n = recv(g_aprs.sock, buf, sizeof(buf) - 1, 0);
if (n <= 0) {
aprs_disconnect();
return;
}
buf[n] = 0;
g_aprs.last_io_sec = g_sec;
g_aprs_rxbuf.append(buf, (size_t)n);
size_t pos = std::string::npos;
while ((pos = g_aprs_rxbuf.find('\n')) != std::string::npos) {
std::string line = g_aprs_rxbuf.substr(0, pos);
g_aprs_rxbuf.erase(0, pos + 1);
aprs_process_line(line);
}
if (g_aprs_rxbuf.size() > 4096)
g_aprs_rxbuf.erase(0, g_aprs_rxbuf.size() - 2048);
}
}
bool aprs_load_idmap(const char* path) {
FILE* f = fopen(path, "r");
if (!f) return false;
g_aprs_idmap.clear();
char line[256];
while (fgets(line, sizeof(line), f)) {
char* p = line;
while (*p==' '||*p=='\t') ++p;
if (*p=='#' || *p=='\r' || *p=='\n' || !*p) continue;
char* comma = strchr(p, ',');
if (!comma) continue;
*comma = 0;
dword id = (dword)atoi(p);
char* cs = comma + 1;
char* e = cs + strlen(cs);
while (e>cs && (e[-1]=='\r'||e[-1]=='\n'||e[-1]==' '||e[-1]=='\t')) *--e=0;
if (id) g_aprs_idmap[id] = cs;
}
fclose(f);
return true;
}
const char* aprs_lookup_callsign(dword dmrid) {
std::map<dword,std::string>::iterator it = g_aprs_idmap.find(dmrid);
if (it == g_aprs_idmap.end()) return NULL;
return (*it).second.c_str();
}
void aprs_send_heard(dword dmrid, dword tg, dword nodeid)
{
if (!g_aprs.enabled || !aprs_connected()) return;
const char* heard = aprs_safe_callsign(dmrid);
char line[512];
sprintf(line,
"%s>APDMR,TCPIP*:>Heard %s on TG %u via NODE %u (DMR APRS)\r\n",
g_aprs.callsign, heard, (unsigned)tg, (unsigned)nodeid);
aprs_send_line(line);
}
#endif
#ifdef HAVE_SMS
sms_settings g_sms = {0};
#endif
int g_auth_enabled = 0;
char g_auth_file[260] = {0};
char g_dmrids_file[260] = {0};
int g_auth_reload_secs = 0;
int g_auth_unknown_default = 0;
static std::map<dword, std::string> g_auth_map;
static std::mutex g_auth_lock;
static dword g_auth_last_load_sec = 0;
static std::string auth_lookup_pass_copy(dword dmrid);
struct WebSession {
dword dmrid;
unsigned expires;
};
static std::map<std::string, WebSession> g_web_sessions;
static const unsigned WEB_SESSION_TTL = 24u * 60u * 60u;
#ifdef USE_SQLITE3
sqlite3 *db;
char *zErrMsg = 0;
char sql[1024];
int rc;
static std::map<std::string,int> g_obp_timers;
struct sqlite_log_row_state {
int id;
int last_time_secs;
int last_connect;
dword last_seen_sec;
dword radio;
dword tg;
int slot;
dword node;
int src;
};
static int g_sqlite_log_max_rows = 20;
static int g_sqlite_active_api_limit = 5;
static int g_sqlite_active_timeout_secs = 8;
static dword g_sqlite_last_cleanup_sec = 0;
static std::map<std::string, sqlite_log_row_state> g_log_active_rows;
static sqlite3_stmt* g_log_insert_stmt = NULL;
static sqlite3_stmt* g_log_update_stmt = NULL;
static sqlite3_stmt* g_log_replace_stmt = NULL;
static long long g_log_seq = 0;
static int sqlite_log_prepare_stmt(sqlite3_stmt** st, const char* q)
{
if (!db) return SQLITE_MISUSE;
if (*st) return SQLITE_OK;
return sqlite3_prepare_v2(db, q, -1, st, NULL);
}
static void sqlite_log_reset_stmt(sqlite3_stmt* st)
{
if (!st) return;
sqlite3_reset(st);
sqlite3_clear_bindings(st);
}
static void sqlite_log_finalize_stmt(sqlite3_stmt** st)
{
if (*st) {
sqlite3_finalize(*st);
*st = NULL;
}
}
static void sqlite_log_shutdown()
{
sqlite_log_finalize_stmt(&g_log_insert_stmt);
sqlite_log_finalize_stmt(&g_log_update_stmt);
sqlite_log_finalize_stmt(&g_log_replace_stmt);
}
static long long sqlite_log_next_seq()
{
return ++g_log_seq;
}
static void sqlite_log_set_seq_seed_from_db()
{
if (!db) return;
sqlite3_stmt* st = NULL;
if (sqlite3_prepare_v2(db, "SELECT COALESCE(MAX(SEQ), 0) FROM LOG", -1, &st, NULL) != SQLITE_OK)
return;
if (sqlite3_step(st) == SQLITE_ROW)
g_log_seq = sqlite3_column_int64(st, 0);
sqlite3_finalize(st);
}
static int sqlite_log_row_count()
{
if (!db) return 0;
int count = 0;
sqlite3_stmt* st = NULL;
if (sqlite3_prepare_v2(db, "SELECT COUNT(*) FROM LOG", -1, &st, NULL) != SQLITE_OK)
return 0;
if (sqlite3_step(st) == SQLITE_ROW)
count = sqlite3_column_int(st, 0);
sqlite3_finalize(st);
return count;
}
static int sqlite_log_oldest_inactive_id()
{
if (!db) return 0;
int id = 0;
sqlite3_stmt* st = NULL;
if (sqlite3_prepare_v2(db, "SELECT ID FROM LOG WHERE ACTIVE=0 ORDER BY SEQ ASC, ID ASC LIMIT 1", -1, &st, NULL) != SQLITE_OK)
return 0;
if (sqlite3_step(st) == SQLITE_ROW)
id = sqlite3_column_int(st, 0);
sqlite3_finalize(st);
return id;
}
static void sqlite_log_prune_inactive_rows(int keep)
{
if (!db || keep <= 0) return;
int count = sqlite_log_row_count();
int excess = count - keep;
if (excess <= 0) return;
char query[512];
char* err = 0;
sprintf(query,
"DELETE FROM LOG WHERE ID IN ("
"SELECT ID FROM LOG WHERE ACTIVE=0 ORDER BY SEQ ASC, ID ASC LIMIT %d"
");", excess);
sqlite3_exec(db, query, 0, 0, &err);
if (err) sqlite3_free(err);
}
static int sqlite_log_insert_row(const char* date_now, dword radio, dword tg, int slot, dword node, int time_secs, int active, int connect, int src)
{
if (!db) return 0;
const char* q =
"INSERT INTO LOG (DATE,RADIO,TG,TIME,SLOT,NODE,ACTIVE,CONNECT,SRC,SEQ) VALUES (?,?,?,?,?,?,?,?,?,?)";
if (sqlite_log_prepare_stmt(&g_log_insert_stmt, q) != SQLITE_OK)
return 0;
sqlite_log_reset_stmt(g_log_insert_stmt);
sqlite3_bind_text(g_log_insert_stmt, 1, date_now, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(g_log_insert_stmt, 2, (int)radio);
sqlite3_bind_int(g_log_insert_stmt, 3, (int)tg);
sqlite3_bind_int(g_log_insert_stmt, 4, time_secs);
sqlite3_bind_int(g_log_insert_stmt, 5, slot);
sqlite3_bind_int(g_log_insert_stmt, 6, (int)node);
sqlite3_bind_int(g_log_insert_stmt, 7, active);
sqlite3_bind_int(g_log_insert_stmt, 8, connect);
sqlite3_bind_int(g_log_insert_stmt, 9, src);
sqlite3_bind_int64(g_log_insert_stmt, 10, sqlite_log_next_seq());
int id = 0;
if (sqlite3_step(g_log_insert_stmt) == SQLITE_DONE)
id = (int)sqlite3_last_insert_rowid(db);
sqlite_log_reset_stmt(g_log_insert_stmt);
return id;
}
static void sqlite_log_replace_row(int id, const char* date_now, dword radio, dword tg, int slot, dword node, int time_secs, int active, int connect, int src)
{
if (!db || id <= 0) return;
const char* q =
"UPDATE LOG SET DATE=?, RADIO=?, TG=?, TIME=?, SLOT=?, NODE=?, ACTIVE=?, CONNECT=?, SRC=?, SEQ=? WHERE ID=?";
if (sqlite_log_prepare_stmt(&g_log_replace_stmt, q) != SQLITE_OK)
return;
sqlite_log_reset_stmt(g_log_replace_stmt);
sqlite3_bind_text(g_log_replace_stmt, 1, date_now, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(g_log_replace_stmt, 2, (int)radio);
sqlite3_bind_int(g_log_replace_stmt, 3, (int)tg);
sqlite3_bind_int(g_log_replace_stmt, 4, time_secs);
sqlite3_bind_int(g_log_replace_stmt, 5, slot);
sqlite3_bind_int(g_log_replace_stmt, 6, (int)node);
sqlite3_bind_int(g_log_replace_stmt, 7, active);
sqlite3_bind_int(g_log_replace_stmt, 8, connect);
sqlite3_bind_int(g_log_replace_stmt, 9, src);
sqlite3_bind_int64(g_log_replace_stmt, 10, sqlite_log_next_seq());
sqlite3_bind_int(g_log_replace_stmt, 11, id);
sqlite3_step(g_log_replace_stmt);
sqlite_log_reset_stmt(g_log_replace_stmt);
}
static void sqlite_log_update_row(int id, const char* date_now, dword radio, dword tg, int slot, dword node, int time_secs, int active, int connect, int src)
{
if (!db || id <= 0) return;
const char* q =
"UPDATE LOG SET DATE=?, RADIO=?, TG=?, TIME=?, SLOT=?, NODE=?, ACTIVE=?, CONNECT=?, SRC=? WHERE ID=?";
if (sqlite_log_prepare_stmt(&g_log_update_stmt, q) != SQLITE_OK)
return;
sqlite_log_reset_stmt(g_log_update_stmt);
sqlite3_bind_text(g_log_update_stmt, 1, date_now, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(g_log_update_stmt, 2, (int)radio);
sqlite3_bind_int(g_log_update_stmt, 3, (int)tg);
sqlite3_bind_int(g_log_update_stmt, 4, time_secs);
sqlite3_bind_int(g_log_update_stmt, 5, slot);
sqlite3_bind_int(g_log_update_stmt, 6, (int)node);
sqlite3_bind_int(g_log_update_stmt, 7, active);
sqlite3_bind_int(g_log_update_stmt, 8, connect);
sqlite3_bind_int(g_log_update_stmt, 9, src);
sqlite3_bind_int(g_log_update_stmt, 10, id);
sqlite3_step(g_log_update_stmt);
sqlite_log_reset_stmt(g_log_update_stmt);
}
static void sqlite_log_make_now(char* date_now, size_t date_now_sz)
{
time_t now = time(0);
strftime(date_now, date_now_sz, "%d.%m.%Y / %H:%M:%S", localtime(&now));
}
static void sqlite_log_finish_state(std::map<std::string, sqlite_log_row_state>::iterator it, const char* date_now, int time_secs, int connect)
{
if (it == g_log_active_rows.end())
return;
sqlite_log_update_row(it->second.id, date_now, it->second.radio, it->second.tg, it->second.slot, it->second.node, time_secs, 0, connect, it->second.src);
g_obp_timers.erase(it->first);
g_log_active_rows.erase(it);
}
static void sqlite_log_finish_conflicts(const std::string& key, const char* date_now, dword node, int slot)
{
std::vector<std::string> conflicts;
for (std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.begin(); it != g_log_active_rows.end(); ++it) {
if (it->first == key)
continue;
if (it->second.node == node && it->second.slot == slot)
conflicts.push_back(it->first);
}
for (size_t i = 0; i < conflicts.size(); ++i) {
std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.find(conflicts[i]);
if (it != g_log_active_rows.end())
sqlite_log_finish_state(it, date_now, it->second.last_time_secs, it->second.last_connect);
}
}
static void sqlite_log_forget_node(dword node)
{
std::vector<std::string> doomed;
for (std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.begin(); it != g_log_active_rows.end(); ++it) {
if (it->second.node == node)
doomed.push_back(it->first);
}
for (size_t i = 0; i < doomed.size(); ++i) {
g_obp_timers.erase(doomed[i]);
g_log_active_rows.erase(doomed[i]);
}
}
static void sqlite_log_cleanup_stale_active(bool force_all = false)
{
if (!db)
return;
if (!force_all && g_sqlite_active_timeout_secs <= 0)
return;
dword now_sec = g_sec ? g_sec : (dword)time(NULL);
if (!force_all && g_sqlite_last_cleanup_sec == now_sec)
return;
g_sqlite_last_cleanup_sec = now_sec;
std::vector<std::string> expired;
for (std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.begin(); it != g_log_active_rows.end(); ++it) {
if (force_all || ((int)(now_sec - it->second.last_seen_sec) >= g_sqlite_active_timeout_secs))
expired.push_back(it->first);
}
if (expired.empty())
return;
char date_now[100];
sqlite_log_make_now(date_now, sizeof(date_now));
for (size_t i = 0; i < expired.size(); ++i) {
std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.find(expired[i]);
if (it != g_log_active_rows.end())
sqlite_log_finish_state(it, date_now, it->second.last_time_secs, it->second.last_connect);
}
sqlite_log_prune_inactive_rows(g_sqlite_log_max_rows);
}
static void sqlite_log_touch_active(const std::string& key, const char* date_now, dword radio, dword tg, int slot, dword node, int time_secs, int connect, int src)
{
sqlite_log_cleanup_stale_active();
std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.find(key);
if (it == g_log_active_rows.end()) {
sqlite_log_finish_conflicts(key, date_now, node, slot);
int id = 0;
if (sqlite_log_row_count() < g_sqlite_log_max_rows) {
id = sqlite_log_insert_row(date_now, radio, tg, slot, node, time_secs, 1, connect, src);
} else {
int reuse_id = sqlite_log_oldest_inactive_id();
if (reuse_id > 0) {
sqlite_log_replace_row(reuse_id, date_now, radio, tg, slot, node, time_secs, 1, connect, src);
id = reuse_id;
} else {
id = sqlite_log_insert_row(date_now, radio, tg, slot, node, time_secs, 1, connect, src);
}
}
if (id > 0) {
sqlite_log_row_state state;
state.id = id;
state.last_time_secs = time_secs;
state.last_connect = connect;
state.last_seen_sec = g_sec ? g_sec : (dword)time(NULL);
state.radio = radio;
state.tg = tg;
state.slot = slot;
state.node = node;
state.src = src;
g_log_active_rows[key] = state;
sqlite_log_prune_inactive_rows(g_sqlite_log_max_rows);
}
return;
}
int prev_time_secs = it->second.last_time_secs;
int prev_connect = it->second.last_connect;
int prev_src = it->second.src;
dword prev_radio = it->second.radio;
dword prev_tg = it->second.tg;
int prev_slot = it->second.slot;
dword prev_node = it->second.node;
if (time_secs < prev_time_secs)
time_secs = prev_time_secs;
it->second.last_seen_sec = g_sec ? g_sec : (dword)time(NULL);
it->second.last_time_secs = time_secs;
it->second.last_connect = connect;
it->second.radio = radio;
it->second.tg = tg;
it->second.slot = slot;
it->second.node = node;
it->second.src = src;
if (prev_time_secs == time_secs && prev_connect == connect &&
prev_src == src && prev_radio == radio && prev_tg == tg &&
prev_slot == slot && prev_node == node)
return;
sqlite_log_update_row(it->second.id, date_now, radio, tg, slot, node, time_secs, 1, connect, src);
}
static void sqlite_log_finish_active(const std::string& key, const char* date_now, int time_secs)
{
std::map<std::string, sqlite_log_row_state>::iterator it = g_log_active_rows.find(key);
if (it == g_log_active_rows.end())
return;
it->second.last_time_secs = time_secs;
sqlite_log_finish_state(it, date_now, time_secs, 1);
sqlite_log_prune_inactive_rows(g_sqlite_log_max_rows);
}
static dword obp_radioid_old = 0;
static dword obp_tg_old = 0;
static dword obp_slotid_old = 0;
static dword obp_nodeid_old = 0;
#endif
struct slot
{
struct node *node;
dword slotid;
dword tg;
slot *prev, *next;
dword parrotstart;
int parrotendcount;
memfile *parrot;
byte volatile parrotseq;
#ifdef HAVE_SMS
sms_buf sms;
#endif
slot() : node(NULL), slotid(0), tg(0), prev(NULL), next(NULL), parrotstart(0), parrotendcount(0), parrot(NULL), parrotseq(0) {
}
};
struct node
{
dword nodeid;
dword dmrid;
dword salt;
sockaddr_in addr;
dword hitsec;
slot slots[2];
bool bAuth;
dword timer;
bool has_location;
double latitude;
double longitude;
node() : nodeid(0), dmrid(0), salt(0), hitsec(0), bAuth(false), timer(0), has_location(false), latitude(0.0), longitude(0.0) {
memset(&addr, 0, sizeof(addr));
slots[0].node = this;
slots[1].node = this;
}
std::vector<dword> static_tgs_ts1;
std::vector<dword> static_tgs_ts2;
};
struct nodevector {
dword radioslot;
struct node *sub[100];
nodevector() {
memset (this, 0, sizeof(*this));
}
};
nodevector * g_node_index [HIGH_DMRID-LOW_DMRID];
struct parrot_exec
{
sockaddr_in addr;
memfile *file;
parrot_exec() {
file = NULL;
}
~parrot_exec() {
delete file;
file = NULL;
}
};
struct talkgroup
{
dword tg;
dword ownerslot;
dword tick;
slot *subscribers;
std::string country;
std::string name;
talkgroup() {
tg = 0;
ownerslot = 0;
tick = 0;
subscribers = NULL;
country.clear();
name.clear();
}
};
static std::map<dword, talkgroup*> g_talkgroups;
talkgroup *g_scanner;
static talkgroup* talkgroup_lookup(dword tg)
{
return findgroup(tg, false);
}
static void talkgroup_meta_snapshot(dword tg, std::string* name, std::string* country)
{
if (name) name->clear();
if (country) country->clear();
std::lock_guard<std::mutex> lk(g_state_lock);
talkgroup* g = talkgroup_lookup(tg);
if (!g)
return;
if (name) *name = g->name;
if (country) *country = g->country;
}
static std::string talkgroup_name_for(dword tg)
{
std::string name;
talkgroup_meta_snapshot(tg, &name, NULL);
return name;
}
static std::string talkgroup_country_for(dword tg)
{
std::string country;
talkgroup_meta_snapshot(tg, NULL, &country);
return country;
}
static void load_talkgroup_line(const char* raw)
{
if (!raw)
return;
char line[1024];
strncpy(line, raw, sizeof(line) - 1);
line[sizeof(line) - 1] = 0;
trim_spaces(line);
if (!line[0] || line[0] == '#')
return;
char* semi1 = strchr(line, ';');
if (!semi1) {
dword tg = (dword)atoi(line);
if (tg)
findgroup(tg, true);
return;
}
*semi1++ = 0;
trim_spaces(line);
trim_spaces(semi1);
dword tg = (dword)atoi(line);
if (!tg)
return;
std::string country;
std::string name;
char* semi2 = strchr(semi1, ';');
if (semi2) {