forked from gvanem/Dump1090
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.c
2437 lines (2120 loc) · 61.7 KB
/
misc.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
/**\file misc.c
* \ingroup Misc
* \brief Various support functions.
*/
#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0602)
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0602 /* _WIN32_WINNT_WIN8 */
#endif
#include <stdint.h>
#include <sys/utime.h>
#include <inttypes.h>
#include <winsock2.h>
#include <windows.h>
#include <wininet.h>
#undef MOUSE_MOVED
#include <curses.h>
#include "aircraft.h"
#include "sqlite3.h"
#include "trace.h"
#include "misc.h"
#include "rtl-sdr/version.h"
#define TSIZE (int)(sizeof("HH:MM:SS.MMM: ") - 1)
/**
* Log a message to the `Modes.log` file with a timestamp.
* But no timestamp if `buf` starts with a `!`.
*/
void modeS_log (const char *buf)
{
const char *time = NULL;
char day_change [20] = "";
if (!Modes.log)
return;
if (*buf == '!')
buf++;
else
{
SYSTEMTIME now;
static WORD day = 0;
GetLocalTime (&now);
time = modeS_SYSTEMTIME_to_str (&now, false);
if (now.wDay != day) /* show the date once per day */
{
snprintf (day_change, sizeof(day_change), "%02u/%02u/%02u:\n", now.wYear, now.wMonth, now.wDay);
day = now.wDay;
}
}
if (*buf == '\n')
buf++;
if (time)
fprintf (Modes.log, "%s%s: %s", day_change, time, buf);
else fprintf (Modes.log, "%*.*s%s", TSIZE, TSIZE, "", buf);
}
/**
* A small log-buffer to catch errors from `externals/mongoose.c`.
*
* e.g. a `bind()` error is impossible to catch in the network event-handler.
* Use this to look for "bind: 10048" == `WSAEADDRINUSE` etc.
*/
static char _err_buf [200];
static int _err_idx = 0;
void modeS_err_set (bool on)
{
if (on)
_err_idx = 0;
else _err_idx = -1;
}
char *modeS_err_get (void)
{
return (_err_buf);
}
/**
* Print a character `c` to `Modes.log` or `stdout`.
* Used only if `(Modes.debug & DEBUG_MONGOOSE)` is enabled by `--debug m`.
*/
void modeS_logc (char c, void *param)
{
/* Since everything gets written in text-mode, we do not
* need an extra '\r'. We want plain '\n' line-endings.
*/
if (c != '\r')
{
if (param)
fputc (c, param); /* to 'stderr' */
else fputc (c, Modes.log ? Modes.log : stdout);
if (_err_idx >= 0 && _err_idx < (int)sizeof(_err_buf)-2)
{
_err_buf [_err_idx++] = c;
_err_buf [_err_idx] = '\0';
}
}
}
/**
* Print to `f` and optionally to `Modes.log`.
*/
void modeS_flogf (FILE *f, const char *fmt, ...)
{
char buf [1000];
char *p = buf;
va_list args;
va_start (args, fmt);
vsnprintf (buf, sizeof(buf), fmt, args);
va_end (args);
if (f && f != Modes.log) /* to `stdout` or `stderr` */
{
if (*p == '!')
p++;
fputs (p, f);
fflush (f);
}
if (Modes.log)
modeS_log (buf);
}
/**
* Disable, then enable Mongoose logging based on the `Modes.debug` bits.
*/
void modeS_set_log (void)
{
mg_log_set (0); /* By default, disable all logging from Mongoose */
if (Modes.debug & DEBUG_MONGOOSE)
{
mg_log_set_fn (modeS_logc, NULL);
mg_log_set (MG_LL_DEBUG);
}
else if (Modes.debug & DEBUG_MONGOOSE2)
{
mg_log_set_fn (modeS_logc, NULL);
mg_log_set (MG_LL_VERBOSE);
}
}
/**
* Format a `SYSTEMTIME` stucture into string. <br>
* Optionally show Year/Month/Day-of-Mounth first.
*/
static char *modeS_strftime (const SYSTEMTIME *st, bool show_YMD)
{
static char tbuf [50];
size_t left = sizeof(tbuf);
char *ptr = tbuf;
if (show_YMD)
{
int len = snprintf (ptr, left, "%02u/%02u/%02u, ",
st->wYear, st->wMonth, st->wDay);
ptr += len;
left -= len;
}
snprintf (ptr, left, "%02u:%02u:%02u.%03u",
st->wHour, st->wMinute, st->wSecond, st->wMilliseconds);
return (tbuf);
}
char *modeS_SYSTEMTIME_to_str (const SYSTEMTIME *st, bool show_YMD)
{
return modeS_strftime (st, show_YMD);
}
char *modeS_FILETIME_to_str (const FILETIME *ft, bool show_YMD)
{
SYSTEMTIME st;
FileTimeToSystemTime (ft, &st);
return modeS_strftime (&st, show_YMD);
}
char *modeS_FILETIME_to_loc_str (const FILETIME *ft, bool show_YMD)
{
static TIME_ZONE_INFORMATION tz_info;
static LONG timezone = 0; /* minutes */
static bool done = false;
ULONGLONG ul = *(ULONGLONG*) ft;
if (!done)
{
FILETIME ft2;
DWORD rc = GetTimeZoneInformation (&tz_info);
LONG dst_adjust = 0;
if (rc == TIME_ZONE_ID_UNKNOWN || rc == TIME_ZONE_ID_STANDARD || rc == TIME_ZONE_ID_DAYLIGHT)
{
timezone = tz_info.Bias + tz_info.StandardBias;
dst_adjust = tz_info.StandardBias - tz_info.DaylightBias;
}
done = true;
get_FILETIME_now (&ft2);
DEBUG (DEBUG_GENERAL, "rc: %ld, timezone: %ld min, dst_adjust: %ld min, now: %s\n",
rc, timezone, dst_adjust, modeS_FILETIME_to_loc_str(&ft2, true));
}
/* From minutes to 100 nsec units
*/
ul -= 600000000ULL * (ULONGLONG) timezone;
return modeS_FILETIME_to_str ((const FILETIME*)&ul, show_YMD);
}
/**
* Convert a "frequency string" with standard suffixes (k, M, G)
* to a `uint32_t` value.
*
* \param in Hertz a string to be parsed
* \retval the frequency as a `uint32_t` (max ~4.3 GHz)
* \note Taken from Osmo-SDR's `convenience.c` and modified.
*/
uint32_t ato_hertz (const char *Hertz)
{
char tmp [20], *end, last_ch;
int len;
double multiplier = 1.0;
uint32_t ret;
strcpy_s (tmp, sizeof(tmp), Hertz);
len = strlen (tmp);
last_ch = tmp [len-1];
tmp [len-1] = '\0';
switch (last_ch)
{
case 'g':
case 'G':
multiplier = 1E9;
break;
case 'm':
case 'M':
multiplier = 1E6;
break;
case 'k':
case 'K':
multiplier = 1E3;
break;
}
ret = (uint32_t) strtof (tmp, &end);
if (end == tmp || *end != '\0')
return (0);
return (uint32_t) (multiplier * ret);
}
/**
* Turn an hex digit into its 4 bit decimal value.
* Returns -1 if the digit is not in the 0-F range.
*/
int hex_digit_val (int c)
{
c = tolower (c);
if (c >= '0' && c <= '9')
return (c - '0');
if (c >= 'a' && c <= 'f')
return (c - 'a' + 10);
return (-1);
}
/*
* Check for `[\x80 ... \x9f]` escaped values.
*
* Based on `mg_json_unescape()`.
*/
static bool unescape (const char *from, size_t from_len, char *to, size_t to_len)
{
static const char hex_chars[] = "0123456789abcdef";
size_t from_idx, to_idx;
for (from_idx = 0, to_idx = 0; from_idx < from_len && to_idx < to_len; from_idx++)
{
if (from [from_idx] == '\\' && from [from_idx+1] == 'x' && from_idx + 3 < from_len)
{
int b2 = tolower (from [from_idx+2]);
int b3 = tolower (from [from_idx+3]);
int val;
if (b2 < '8' || b2 > '9' || b3 < '0' || b3 > 'f') /* Give up */
return (false);
val = (b2 - '0') << 4;
if (b3 <= '9')
val += (b3 - '0');
else val += (b3 - 'a') + 10;
((BYTE*)to) [to_idx++] = val;
from_idx += 3;
}
else
{
to [to_idx++] = from [from_idx];
}
}
if (to_idx >= to_len)
return (false);
if (to_len > 0)
to [to_idx] = '\0';
return (true);
}
/**
* Decode any `\\x80 ... \\x9f` sequence in `value`.
*/
const char *unescape_hex (const char *value)
{
static char buf [100];
if (unescape(value, strlen(value), buf, sizeof(buf)))
return (buf);
return (value);
}
/**
* Return true if string `s1` starts with `s2`.
*
* Ignore casing of both strings.
*/
bool str_startswith (const char *s1, const char *s2)
{
size_t s1_len, s2_len;
s1_len = strlen (s1);
s2_len = strlen (s2);
if (s2_len > s1_len)
return (false);
if (!strnicmp (s1, s2, s2_len))
return (true);
return (false);
}
/**
* Return true if string `s1` ends with `s2`.
*/
bool str_endswith (const char *s1, const char *s2)
{
const char *s1_end, *s2_end;
if (strlen(s2) > strlen(s1))
return (false);
s1_end = strchr (s1, '\0') - 1;
s2_end = strchr (s2, '\0') - 1;
while (s2_end >= s2)
{
if (*s1_end != *s2_end)
break;
s1_end--;
s2_end--;
}
return (s2_end == s2 - 1);
}
/**
* Trim leading blanks (space/tab) from a string.
*/
char *str_ltrim (char *s)
{
assert (s != NULL);
while (s[0] && s[1] && isspace ((int)s[0]))
s++;
return (s);
}
/**
* Trim trailing blanks (space/tab) from a string.
*/
char *str_rtrim (char *s)
{
size_t n;
assert (s != NULL);
n = strlen (s);
if (n == 0)
return (s);
n--;
while (n)
{
int ch = (int)s [n];
if (!isspace(ch))
break;
s [n--] = '\0';
}
return (s);
}
/**
* Trim leading and trailing blanks (space/tab) from a string.
*/
char *str_trim (char *s)
{
return str_rtrim (str_ltrim(s));
}
/**
* Strip drive-letter, directory and suffix from a filename.
*/
char *basename (const char *fname)
{
const char *base = fname;
if (fname && *fname)
{
if (fname[0] && fname[1] == ':')
{
fname += 2;
base = fname;
}
while (*fname)
{
if (IS_SLASH(*fname))
base = fname + 1;
fname++;
}
}
return (char*) base;
}
/**
* Return the directory part of a filename.
* A static buffer is returned so make a copy of this ASAP.
*/
char *dirname (const char *fname)
{
const char *p = fname;
const char *slash = NULL;
size_t dirlen;
static mg_file_path dir;
if (!fname)
return (NULL);
if (fname[0] && fname[1] == ':')
{
slash = fname + 1;
p += 2;
}
/* Find the rightmost slash.
*/
while (*p)
{
if (IS_SLASH(*p))
slash = p;
p++;
}
if (slash == NULL)
{
fname = ".";
dirlen = 1;
}
else
{
/* Remove any trailing slashes.
*/
while (slash > fname && (IS_SLASH(slash[-1])))
slash--;
/* How long is the directory we will return?
*/
dirlen = slash - fname + (slash == fname || slash[-1] == ':');
if (*slash == ':' && dirlen == 1)
dirlen += 2;
}
strncpy (dir, fname, dirlen);
if (slash && *slash == ':' && dirlen == 3)
dir[2] = '.'; /* for "x:foo" return "x:." */
if (IS_SLASH(dir[dirlen-1]))
dirlen--;
dir [dirlen] = '\0';
return (dir);
}
/**
* Return a filename on Unix form:
* All `\\` characters replaced with `/`.
*/
char *slashify (char *fname)
{
char *p = fname;
while (*p)
{
if (*p == '\\')
*p = '/';
p++;
}
return (fname);
}
/**
* Add or initialize a test `which` to the test-list at `*spec`.
*/
bool test_add (char **spec, const char *which)
{
char *s;
assert (spec);
assert (which);
if (!*spec)
s = mg_mprintf ("%s", which);
else s = mg_mprintf ("%s,%s", *spec, which);
free (*spec);
*spec = s;
return (s ? true : false);
}
/**
* Check if a test `which` is in the test-list at `spec`.
*/
bool test_contains (const char *spec, const char *which)
{
bool rc = false;
assert (which);
if (!spec) /* no test-spec disables all */
rc = false;
else if (!strcmp(spec, "*"))
{
rc = true; /* a '*' test-spec enables all */
printf ("spec='*', which='%s'\n", which);
}
else
{
mg_str s, k, v;
s = mg_str (spec);
while (mg_commalist(&s, &k, &v))
{
if (!strnicmp(which, k.ptr, k.len))
{
rc = true;
break;
}
}
}
return (rc);
}
/**
* Touch a file to current time.
*/
int touch_file (const char *file)
{
return _utime (file, NULL);
}
/**
* Open an existing file (or create) in share-mode but deny other
* processes to write to the file.
*/
FILE *fopen_excl (const char *file, const char *mode)
{
int fd, open_flags, share_flags;
switch (*mode)
{
case 'r':
open_flags = _O_RDONLY;
share_flags = S_IREAD;
break;
case 'w':
open_flags = _O_WRONLY;
share_flags = S_IWRITE;
break;
case 'a':
open_flags = _O_CREAT | _O_WRONLY | _O_APPEND;
share_flags = S_IWRITE;
break;
default:
return (NULL);
}
if (mode[1] == '+')
open_flags |= _O_CREAT | _O_TRUNC;
if (mode[strlen(mode)-1] == 'b')
open_flags |= O_BINARY;
fd = _sopen (file, open_flags | _O_SEQUENTIAL, SH_DENYWR, share_flags);
if (fd <= -1)
return (NULL);
return _fdopen (fd, mode);
}
#if MG_ENABLE_FILE
/*
* Internals of 'externals/mongoose.c':
*/
typedef struct dirent {
char d_name [MAX_PATH];
} dirent;
typedef struct win32_dir {
HANDLE handle;
WIN32_FIND_DATAW info;
dirent result;
} DIR;
extern DIR *opendir (const char *name);
extern int closedir (DIR *d);
extern dirent *readdir (DIR *d);
/**
* Touch all files in a directory to current time.
* Works on all sub-directories if `recurse == true`.
*/
int touch_dir (const char *directory, bool recurse)
{
dirent *d;
DIR *dir = opendir (directory);
int rc = 0;
if (!dir)
{
DEBUG (DEBUG_GENERAL, "GetLastError(): %lu\n", GetLastError());
return (0);
}
while ((d = readdir(dir)) != NULL)
{
char full_name [MAX_PATH];
DWORD attrs;
bool is_dir;
if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
continue;
snprintf (full_name, sizeof(full_name), "%s\\%s", directory, d->d_name);
attrs = GetFileAttributesA (full_name);
is_dir = (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY));
if (!is_dir && !recurse)
continue;
if (is_dir)
rc += touch_dir (full_name, true);
else rc += touch_file (full_name);
}
closedir (dir);
return (rc);
}
#endif /* MG_ENABLE_FILE */
/**
* \def DELTA_EPOCH_IN_USEC
*
* Number of micro-seconds between the beginning of the Windows epoch
* (Jan. 1, 1601) and the Unix epoch (Jan. 1, 1970).
*/
#define DELTA_EPOCH_IN_USEC 11644473600000000Ui64
static uint64_t FILETIME_to_unix_epoch (const FILETIME *ft)
{
uint64_t res = (uint64_t) ft->dwHighDateTime << 32;
res += ft->dwLowDateTime;
res /= 10; /* from 100 nano-sec periods to usec */
res -= DELTA_EPOCH_IN_USEC; /* from Win epoch to Unix epoch */
return (res);
}
int _gettimeofday (struct timeval *tv, void *timezone)
{
FILETIME ft;
uint64_t tim;
GetSystemTimePreciseAsFileTime (&ft);
tim = FILETIME_to_unix_epoch (&ft);
tv->tv_sec = (long) (tim / 1000000L);
tv->tv_usec = (long) (tim % 1000000L);
(void) timezone;
return (0);
}
int get_timespec_UTC (struct timespec *ts)
{
return timespec_get (ts, TIME_UTC);
}
/**
* Returns a `FILETIME *ft`.
*
* This is here since the above `#define _WIN32_WINNT 0x0602` (Win-8+)
* is *only* defined here.
*
* From: https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
* retrieves the current system date and time with the highest possible level of
* precision (<1us). The retrieved information is in
* Coordinated Universal Time (UTC) format.
*/
void get_FILETIME_now (FILETIME *ft)
{
GetSystemTimePreciseAsFileTime (ft);
}
/**
* Return micro-second time-stamp as a double.
*
* \note QueryPerformanceFrequency() is not related to the RDTSC instruction
* since it works poorly when power "management technologies" does it's
* tricks.
* \ref https://learn.microsoft.com/en-us/windows/win32/dxtecharts/game-timing-and-multicore-processors
* https://yakvi.github.io/handmade-hero-notes/html/day10.html
*/
double get_usec_now (void)
{
static uint64_t frequency = 0ULL;
LARGE_INTEGER ticks;
double usec;
if (frequency == 0ULL)
{
QueryPerformanceFrequency ((LARGE_INTEGER*)&frequency);
DEBUG (DEBUG_GENERAL, "QueryPerformanceFrequency(): %.3f MHz\n", (double)frequency / 1E6);
}
QueryPerformanceCounter (&ticks);
usec = 1E6 * ((double)ticks.QuadPart / (double)frequency);
return (usec);
}
/**
* Use 64-bit tick-time for Mongoose?
*/
#if MG_ENABLE_CUSTOM_MILLIS
uint64_t mg_millis (void)
{
return MSEC_TIME();
}
#endif
#if defined(_DEBUG)
/**
* Check for memory-leaks in `_DEBUG` mode.
*/
static _CrtMemState start_state;
void crtdbug_exit (void)
{
_CrtMemState end_state, diff_state;
_CrtMemCheckpoint (&end_state);
if (!_CrtMemDifference(&diff_state, &start_state, &end_state))
LOG_STDERR ("No mem-leaks detected.\n");
else
{
_CrtCheckMemory();
_CrtSetDbgFlag (0);
_CrtDumpMemoryLeaks();
}
}
void crtdbug_init (void)
{
_HFILE file = _CRTDBG_FILE_STDERR;
int mode = _CRTDBG_MODE_FILE;
int flags = _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_DELAY_FREE_MEM_DF;
_CrtSetReportFile (_CRT_ASSERT, file);
_CrtSetReportMode (_CRT_ASSERT, mode);
_CrtSetReportFile (_CRT_ERROR, file);
_CrtSetReportMode (_CRT_ERROR, mode);
_CrtSetReportFile (_CRT_WARN, file);
_CrtSetReportMode (_CRT_WARN, mode);
_CrtSetDbgFlag (flags | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
_CrtMemCheckpoint (&start_state);
}
#endif /* _DEBUG */
/**
* Return err-number and string for 'err'.
*/
const char *win_strerror (DWORD err)
{
static char buf [512+20];
char err_buf [512], *p;
HRESULT hr = 0;
if (HRESULT_SEVERITY(err))
hr = err;
if (err == ERROR_SUCCESS)
strcpy (err_buf, "No error");
else if (err == ERROR_BAD_EXE_FORMAT)
strcpy (err_buf, "Bad EXE format");
else if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
LANG_NEUTRAL, err_buf, sizeof(err_buf)-1, NULL))
strcpy (err_buf, "Unknown error");
if (hr)
snprintf (buf, sizeof(buf), "0x%08lX: %s", (u_long)hr, err_buf);
else snprintf (buf, sizeof(buf), "%lu: %s", (u_long)err, err_buf);
p = strrchr (buf, '\r');
if (p)
*p = '\0';
p = strrchr (buf, '.');
if (p && p[1] == '\0')
*p = '\0';
return (buf);
}
/**
* Return a string describing an error-code from RTLSDR.
*
* `rtlsdr_last_error()` always returns a positive value for WinUSB errors.
*
* While RTLSDR errors returned from all `rtlsdr_x()` functions are negative.
* And rather sparse:
* \li -1 if device handle is invalid
* \li -2 if EEPROM size is exceeded (depends on rtlsdr_x() function)
* \li -3 if no EEPROM was found (depends on rtlsdr_x() function)
*/
const char *get_rtlsdr_error (void)
{
uint32_t err = rtlsdr_last_error();
if (err == 0)
return ("No error.");
return trace_strerror (err);
}
/**
* Return a random integer in range `[a..b]`. \n
* Ref: http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range
*/
uint32_t random_range (uint32_t min, uint32_t max)
{
static bool done = false;
double scaled;
if (!done)
{
srand (time(NULL));
done = true;
}
scaled = (double) rand() / RAND_MAX;
return (uint32_t) ((max - min + 1) * scaled) + min;
}
int32_t random_range2 (int32_t min, int32_t max)
{
double scaled = (double) rand() / RAND_MAX;
return (int32_t) ((max - min + 1) * scaled) + min;
}
/**
* Return nicely formatted string `"xx,xxx,xxx"`
* with thousand separators (left adjusted).
*
* Use 8 buffers in round-robin.
*/
const char *qword_str (uint64_t val)
{
static char buf [8][30];
static int idx = 0;
char tmp[30];
char *rc = buf [idx++];
if (val < 1000ULL)
{
sprintf (rc, "%lu", (u_long)val);
}
else if (val < 1000000ULL) /* < 1E6 */
{
sprintf (rc, "%lu,%03lu", (u_long)(val/1000UL), (u_long)(val % 1000UL));
}
else if (val < 1000000000ULL) /* < 1E9 */
{
sprintf (tmp, "%9" PRIu64, val);
sprintf (rc, "%.3s,%.3s,%.3s", tmp, tmp+3, tmp+6);
}
else if (val < 1000000000000ULL) /* < 1E12 */
{
sprintf (tmp, "%12" PRIu64, val);
sprintf (rc, "%.3s,%.3s,%.3s,%.3s", tmp, tmp+3, tmp+6, tmp+9);
}
else /* >= 1E12 */
{
sprintf (tmp, "%15" PRIu64, val);
sprintf (rc, "%.3s,%.3s,%.3s,%.3s,%.3s", tmp, tmp+3, tmp+6, tmp+9, tmp+12);
}
idx &= 7;
return str_ltrim (rc);
}
const char *dword_str (DWORD val)
{
return qword_str ((uint64_t)val);
}
void *memdup (const void *from, size_t size)
{
void *ret = malloc (size);
if (ret)
return memcpy (ret, from, size);
return (NULL);
}
/**
* Print some details about the Sqlite3 package.
*/
static void print_sql_info (void)
{
const char *opt;
int i, sz = 0;
printf ("Sqlite3 ver: %s. Build options: ", sqlite3_libversion());
for (i = 0; (opt = sqlite3_compileoption_get(i)) != NULL; i++)
{
const char *opt_next = sqlite3_compileoption_get (i+1);
sz += printf ("SQLITE_%s%s", opt, opt_next ? ", " : "\n");
if (opt_next)
sz += sizeof(", SQLITE_") + strlen (opt_next);
if (sz >= 140)
{
fputs ("\n ", stdout);
sz = 0;
}
}
}
static void print_packed_web_info (void)
{
#if defined(USE_PACKED_DLL)
/**
* \todo
* Iterate over resources in `web-page.dll` and print
* all `mg_packed_spec_x()` descriptions.
*/
#endif
}
/**
* Return the compiler info the program was built with.
*/
static const char *compiler_info (void)
{
static char buf [50];
#if defined(__clang__)
snprintf (buf, sizeof(buf), "clang-cl %d.%d.%d",
__clang_major__, __clang_minor__, __clang_patchlevel__);
#elif defined(_MSC_FULL_VER)
snprintf (buf, sizeof(buf), "Microsoft cl %d.%d.%d",
_MSC_VER / 100, _MSC_VER % 100, _MSC_FULL_VER % 100000);
#else
snprintf (buf, sizeof(buf), "Microsoft cl %d.%d",
(_MSC_VER / 100), _MSC_VER % 100);
#endif
return (buf);
}
#if defined(MG_ENABLE_SELECT)
#define NETPOLLER "select()"
#elif defined(MG_ENABLE_EPOLL)
#define NETPOLLER "epoll"
#elif defined(MG_ENABLE_POLL)
#define NETPOLLER "WSAPoll()"
#else
#error "Cannot define 'NETPOLLER'?!"
#endif
static const char *build_features (void)
{
static char buf [150];
static const char *features[] = {
#if defined(_DEBUG)
"debug",
#else