forked from allinurl/goaccess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
1160 lines (995 loc) · 26.8 KB
/
util.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
/**
* util.c -- a set of handy functions to help parsing
* ______ ___
* / ____/___ / | _____________ __________
* / / __/ __ \/ /| |/ ___/ ___/ _ \/ ___/ ___/
* / /_/ / /_/ / ___ / /__/ /__/ __(__ |__ )
* \____/\____/_/ |_\___/\___/\___/____/____/
*
* The MIT License (MIT)
* Copyright (c) 2009-2023 Gerardo Orellana <hello @ goaccess.io>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#define _GNU_SOURCE
#define _DEFAULT_SOURCE
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <inttypes.h>
#include <regex.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include "util.h"
#include "error.h"
#include "labels.h"
#include "xmalloc.h"
/* HTTP status codes categories */
static const char *code_type[][2] = {
{"1", STATUS_CODE_1XX},
{"2", STATUS_CODE_2XX},
{"3", STATUS_CODE_3XX},
{"4", STATUS_CODE_4XX},
{"5", STATUS_CODE_5XX},
};
/* HTTP status codes */
static const char *codes[][2] = {
{"100", STATUS_CODE_100},
{"101", STATUS_CODE_101},
{"200", STATUS_CODE_200},
{"201", STATUS_CODE_201},
{"202", STATUS_CODE_202},
{"203", STATUS_CODE_203},
{"204", STATUS_CODE_204},
{"205", STATUS_CODE_205},
{"206", STATUS_CODE_206},
{"207", STATUS_CODE_207},
{"208", STATUS_CODE_208},
{"300", STATUS_CODE_300},
{"301", STATUS_CODE_301},
{"302", STATUS_CODE_302},
{"303", STATUS_CODE_303},
{"304", STATUS_CODE_304},
{"305", STATUS_CODE_305},
{"307", STATUS_CODE_307},
{"308", STATUS_CODE_308},
{"400", STATUS_CODE_400},
{"401", STATUS_CODE_401},
{"402", STATUS_CODE_402},
{"403", STATUS_CODE_403},
{"404", STATUS_CODE_404},
{"405", STATUS_CODE_405},
{"406", STATUS_CODE_406},
{"407", STATUS_CODE_407},
{"408", STATUS_CODE_408},
{"409", STATUS_CODE_409},
{"410", STATUS_CODE_410},
{"411", STATUS_CODE_411},
{"412", STATUS_CODE_412},
{"413", STATUS_CODE_413},
{"414", STATUS_CODE_414},
{"415", STATUS_CODE_415},
{"416", STATUS_CODE_416},
{"417", STATUS_CODE_417},
{"418", STATUS_CODE_418},
{"421", STATUS_CODE_421},
{"422", STATUS_CODE_422},
{"423", STATUS_CODE_423},
{"424", STATUS_CODE_424},
{"426", STATUS_CODE_426},
{"428", STATUS_CODE_428},
{"429", STATUS_CODE_429},
{"431", STATUS_CODE_431},
{"444", STATUS_CODE_444},
{"451", STATUS_CODE_451},
{"494", STATUS_CODE_494},
{"495", STATUS_CODE_495},
{"496", STATUS_CODE_496},
{"497", STATUS_CODE_497},
{"499", STATUS_CODE_499},
{"500", STATUS_CODE_500},
{"501", STATUS_CODE_501},
{"502", STATUS_CODE_502},
{"503", STATUS_CODE_503},
{"504", STATUS_CODE_504},
{"505", STATUS_CODE_505},
{"520", STATUS_CODE_520},
{"521", STATUS_CODE_521},
{"522", STATUS_CODE_522},
{"523", STATUS_CODE_523},
{"524", STATUS_CODE_524}
};
/* Return part of a string
*
* On error NULL is returned.
* On success the extracted part of string is returned */
char *
substring (const char *str, int begin, int len) {
char *buffer;
if (str == NULL)
return NULL;
if (begin < 0)
begin = strlen (str) + begin;
if (begin < 0)
begin = 0;
if (len < 0)
len = 0;
if (((size_t) begin) > strlen (str))
begin = strlen (str);
if (((size_t) len) > strlen (&str[begin]))
len = strlen (&str[begin]);
if ((buffer = xmalloc (len + 1)) == NULL)
return NULL;
memcpy (buffer, &(str[begin]), len);
buffer[len] = '\0';
return buffer;
}
/* A pointer to the allocated memory of the new string
*
* On success, a pointer to a new string is returned */
char *
alloc_string (const char *str) {
char *new = xmalloc (strlen (str) + 1);
strcpy (new, str);
return new;
}
/* A wrapper function to copy the first num characters of source to
* destination. */
void
xstrncpy (char *dest, const char *source, const size_t dest_size) {
strncpy (dest, source, dest_size);
if (dest_size > 0) {
dest[dest_size - 1] = '\0';
} else {
dest[0] = '\0';
}
}
/* A random string generator. */
void
genstr (char *dest, size_t len) {
char set[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (; len > 0; --len)
*dest++ = set[rand () % (sizeof (set) - 1)];
*dest = '\0';
}
/* Count the number of matches on the string `s1` given a character `c`
*
* If the character is not found, 0 is returned
* On success, the number of characters found */
int
count_matches (const char *s1, char c) {
const char *ptr = s1;
int n = 0;
do {
if (*ptr == c)
n++;
} while (*(ptr++));
return n;
}
/* Simple but efficient uint32_t hashing. */
#if defined(__clang__) && defined(__clang_major__) && (__clang_major__ >= 4)
__attribute__((no_sanitize ("unsigned-integer-overflow")))
#if (__clang_major__ >= 12)
__attribute__((no_sanitize ("unsigned-shift-base")))
#endif
#endif
uint32_t
djb2 (const unsigned char *str) {
uint32_t hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
/* String matching where one string contains wildcard characters.
*
* If no match found, 1 is returned.
* If match found, 0 is returned. */
static int
wc_match (const char *wc, char *str) {
while (*wc && *str) {
if (*wc == '*') {
while (*wc && *wc == '*')
wc++;
if (!*wc)
return 1;
while (*str && *str != *wc)
str++;
} else if (*wc == '?' || *wc == *str) {
wc++;
str++;
} else {
break;
}
}
if (!*wc && !*str)
return 1;
return 0;
}
/* Generic routine to extract all groups from a string given a POSIX regex.
*
* If no match found or error, NULL is returned.
* If match found, a string is returned. */
char *
regex_extract_string (const char *str, const char *regex, int max_groups, char const **err) {
char *copy = NULL, *dest = NULL;
int i, ret = 0;
regex_t re;
regmatch_t groups[max_groups];
if (str == NULL || *str == '\0') {
*err = "Invalid string.";
return NULL;
}
if (regcomp (&re, regex, REG_EXTENDED)) {
*err = "Unable to compile regular expression upon extraction";
return NULL;
}
ret = regexec (&re, str, max_groups, groups, 0);
if (ret == REG_NOMATCH) {
*err = "Unable to match regular expression extraction.";
goto out;
}
if (ret != 0) {
*err = "Error while matching regular expression extraction.";
goto out;
}
dest = xstrdup ("");
for (i = 0; i < max_groups; ++i) {
if (groups[i].rm_so == -1)
break;
copy = xstrdup (str);
copy[groups[i].rm_eo] = 0;
append_str (&dest, copy + groups[i].rm_so);
free (copy);
}
out:
regfree (&re);
return ret == 0 ? dest : NULL;
}
/* Determine if the given host needs to be ignored given the list of
* referrers to ignore.
*
* On error, or the referrer is not found, 0 is returned
* On success, or if the host needs to be ignored, 1 is returned */
int
ignore_referer (const char *host) {
char *needle = NULL;
int i, ignore = 0;
if (conf.ignore_referer_idx == 0)
return 0;
if (host == NULL || *host == '\0')
return 0;
needle = xstrdup (host);
for (i = 0; i < conf.ignore_referer_idx; ++i) {
if (conf.ignore_referers[i] == NULL || *conf.ignore_referers[i] == '\0')
continue;
if (wc_match (conf.ignore_referers[i], needle)) {
ignore = 1;
goto out;
}
}
out:
free (needle);
return ignore;
}
/* Determine if the given host needs to be hidden given the list of
* referrers to hide.
*
* On error, or the referrer is not found, 0 is returned
* On success, or if the host needs to be ignored, 1 is returned */
int
hide_referer (const char *host) {
char *needle = NULL;
int i, ignore = 0;
if (conf.hide_referer_idx == 0)
return 0;
if (host == NULL || *host == '\0')
return 0;
needle = xstrdup (host);
for (i = 0; i < conf.hide_referer_idx; ++i) {
if (conf.hide_referers[i] == NULL || *conf.hide_referers[i] == '\0')
continue;
if (wc_match (conf.hide_referers[i], needle)) {
ignore = 1;
goto out;
}
}
out:
free (needle);
return ignore;
}
/* Determine if the given ip is within a range of IPs.
*
* On error, or not within the range, 0 is returned
* On success, or if within the range, 1 is returned */
static int
within_range (const char *ip, const char *start, const char *end) {
struct in6_addr addr6, start6, end6;
struct in_addr addr4, start4, end4;
if (start == NULL || *start == '\0')
return 0;
if (end == NULL || *end == '\0')
return 0;
if (ip == NULL || *ip == '\0')
return 0;
/* IPv4 */
if (1 == inet_pton (AF_INET, ip, &addr4)) {
if (1 != inet_pton (AF_INET, start, &start4))
return 0;
if (1 != inet_pton (AF_INET, end, &end4))
return 0;
if (memcmp (&addr4, &start4, sizeof (addr4)) >= 0 &&
memcmp (&addr4, &end4, sizeof (addr4)) <= 0)
return 1;
}
/* IPv6 */
else if (1 == inet_pton (AF_INET6, ip, &addr6)) {
if (1 != inet_pton (AF_INET6, start, &start6))
return 0;
if (1 != inet_pton (AF_INET6, end, &end6))
return 0;
if (memcmp (&addr6, &start6, sizeof (addr6)) >= 0 &&
memcmp (&addr6, &end6, sizeof (addr6)) <= 0)
return 1;
}
return 0;
}
/* Determine if the given IP needs to be ignored given the list of IPs
* to ignore.
*
* On error, or not within the range, 0 is returned
* On success, or if within the range, 1 is returned */
int
ip_in_range (const char *ip) {
char *start, *end, *dash;
int i;
for (i = 0; i < conf.ignore_ip_idx; ++i) {
end = NULL;
if (conf.ignore_ips[i] == NULL || *conf.ignore_ips[i] == '\0')
continue;
start = xstrdup (conf.ignore_ips[i]);
/* split range */
if ((dash = strchr (start, '-')) != NULL) {
*dash = '\0';
end = dash + 1;
}
/* matches single IP */
if (end == NULL) {
if (strcmp (ip, start) == 0) {
free (start);
return 1;
}
}
/* within range */
else {
if (within_range (ip, start, end)) {
free (start);
return 1;
}
}
free (start);
}
return 0;
}
/* Searches the array of output formats for the given extension value.
*
* If not found, 1 is returned.
* On success, the given filename is malloc'd and assigned and 0 is
* returned. */
int
find_output_type (char **filename, const char *ext, int alloc) {
int i;
const char *dot = NULL;
for (i = 0; i < conf.output_format_idx; ++i) {
/* for backwards compatibility. i.e., -o json */
if (strcmp (conf.output_formats[i], ext) == 0)
return 0;
if ((dot = strrchr (conf.output_formats[i], '.')) != NULL && strcmp (dot + 1, ext) == 0) {
if (alloc)
*filename = xstrdup (conf.output_formats[i]);
return 0;
}
}
return 1;
}
/* Validates the '-o' filename extension for any of:
* 1) .csv
* 2) .json
* 3) .html
*
* Return Value
* 1: valid
* 0: invalid
* -1: non-existent extension
*/
int
valid_output_type (const char *filename) {
const char *ext = NULL;
size_t sl;
if ((ext = strrchr (filename, '.')) == NULL)
return -1;
ext++;
/* Is extension 3<=len<=4? */
sl = strlen (ext);
if (sl < 3 || sl > 4)
return 0;
if (strcmp ("html", ext) == 0)
return 1;
if (strcmp ("json", ext) == 0)
return 1;
if (strcmp ("csv", ext) == 0)
return 1;
return 0;
}
/* Get the path to the user config file (ie. HOME/.goaccessrc).
*
* On error, it returns NULL.
* On success, the path of the user config file is returned. */
char *
get_user_config (void) {
char *user_home = NULL, *path = NULL;
size_t len;
user_home = getenv ("HOME");
if (user_home == NULL)
return NULL;
len = snprintf (NULL, 0, "%s/.goaccessrc", user_home) + 1;
path = xmalloc (len);
snprintf (path, len, "%s/.goaccessrc", user_home);
return path;
}
/* Get the path to the global config file.
*
* On success, the path of the global config file is returned. */
char *
get_global_config (void) {
char *path = NULL;
size_t len;
len = snprintf (NULL, 0, "%s/goaccess/goaccess.conf", SYSCONFDIR) + 1;
path = xmalloc (len);
snprintf (path, len, "%s/goaccess/goaccess.conf", SYSCONFDIR);
return path;
}
/* A self-checking wrapper to convert_date().
*
* On error, a newly malloc'd '---' string is returned.
* On success, a malloc'd 'Ymd' date is returned. */
char *
get_visitors_date (const char *odate, const char *from, const char *to) {
char date[DATE_TIME] = ""; /* Ymd */
memset (date, 0, sizeof *date);
/* verify we have a valid date conversion */
if (convert_date (date, odate, from, to, DATE_TIME) == 0)
return xstrdup (date);
LOG_DEBUG (("invalid date: %s", odate));
return xstrdup ("---");
}
static time_t
tm2time (const struct tm *src) {
struct tm tmp;
tmp = *src;
return timegm (&tmp) - src->tm_gmtoff;
}
void
set_tz (void) {
char tz[TZ_NAME_LEN] = { 0 };
if (!conf.tz_name)
return;
snprintf (tz, TZ_NAME_LEN, "TZ=%s", conf.tz_name);
if ((putenv (tz)) != 0) {
LOG_DEBUG (("Can't set TZ env variable %s: %s\n", tz, strerror (errno)));
return;
}
tzset ();
}
/* Format the given date/time according the given format.
*
* On error, 1 is returned.
* On success, 0 is returned. */
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
int
str_to_time (const char *str, const char *fmt, struct tm *tm, int tz) {
time_t t;
char *end = NULL, *sEnd = NULL;
unsigned long long ts = 0;
int us, ms;
#if !defined(__GLIBC__)
int se;
#endif
time_t seconds = 0;
if (str == NULL || *str == '\0' || fmt == NULL || *fmt == '\0')
return 1;
us = strcmp ("%f", fmt) == 0;
ms = strcmp ("%*", fmt) == 0;
#if !defined(__GLIBC__)
se = strcmp ("%s", fmt) == 0;
#endif
/* check if char string needs to be converted from milli/micro seconds */
/* note that MUSL doesn't have %s under strptime(3) */
#if !defined(__GLIBC__)
if (se || us || ms) {
#else
if (us || ms) {
#endif
errno = 0;
ts = strtoull (str, &sEnd, 10);
if (str == sEnd || *sEnd != '\0' || errno == ERANGE)
return 1;
seconds = (us) ? ts / SECS : ((ms) ? ts / MILS : ts);
if (conf.tz_name && tz)
set_tz ();
/* if GMT needed, gmtime_r instead of localtime_r. */
localtime_r (&seconds, tm);
return 0;
}
end = strptime (str, fmt, tm);
if (end == NULL || *end != '\0')
return 1;
if (!tz || !conf.tz_name)
return 0;
if ((t = tm2time (tm)) == -1) {
LOG_DEBUG (("Can't set time via tm2time() %s: %s\n", str, strerror (errno)));
return 0;
}
set_tz ();
localtime_r (&t, tm);
return 0;
}
/* Convert a date from one format to another and store in the given buffer.
*
* On error, 1 is returned.
* On success, 0 is returned. */
int
convert_date (char *res, const char *data, const char *from, const char *to, int size) {
struct tm tm;
memset (&tm, 0, sizeof (tm));
timestamp = time (NULL);
localtime_r (×tamp, &now_tm);
/* This assumes that the the given date is already in the correct timezone. */
if (str_to_time (data, from, &tm, 0) != 0)
return 1;
/* if not a timestamp, use current year if not passed */
if (!has_timestamp (from) && strpbrk (from, "Yy") == NULL)
tm.tm_year = now_tm.tm_year;
if (strftime (res, size, to, &tm) <= 0)
return 1;
return 0;
}
#pragma GCC diagnostic warning "-Wformat-nonliteral"
/* Determine if the given IP is a valid IPv4/IPv6 address.
*
* On error, 1 is returned.
* On success, 0 is returned. */
int
invalid_ipaddr (char *str, int *ipvx) {
union {
struct sockaddr addr;
struct sockaddr_in6 addr6;
struct sockaddr_in addr4;
} a;
(*ipvx) = TYPE_IPINV;
if (str == NULL || *str == '\0')
return 1;
memset (&a, 0, sizeof (a));
if (1 == inet_pton (AF_INET, str, &a.addr4.sin_addr)) {
(*ipvx) = TYPE_IPV4;
return 0;
} else if (1 == inet_pton (AF_INET6, str, &a.addr6.sin6_addr)) {
(*ipvx) = TYPE_IPV6;
return 0;
}
return 1;
}
/* Encode a data key and a unique visitor's key to a new uint64_t key
*
* ###NOTE: THIS LIMITS THE MAX VALUE OF A DATA TABLE TO uint32_t
* WILL NEED TO CHANGE THIS IF WE GO OVER uint32_t
*/
uint64_t
u64encode (uint32_t x, uint32_t y) {
return x > y ? (uint32_t) y | ((uint64_t) x << 32) : (uint32_t) x | ((uint64_t) y << 32);
}
/* Decode a uint64_t number into the original two uint32_t */
void
u64decode (uint64_t n, uint32_t *x, uint32_t *y) {
*x = (uint64_t) n >> 32;
*y = (uint64_t) n & 0xFFFFFFFF;
}
/* Get information about the filename.
*
* On error, -1 is returned.
* On success, the file size of the given filename. */
off_t
file_size (const char *filename) {
struct stat st;
if (stat (filename, &st) == 0)
return st.st_size;
LOG_DEBUG (("Can't determine size of %s: %s\n", filename, strerror (errno)));
return -1;
}
/* Determine if the given status code is within the list of status
* codes and find out the status type/category.
*
* If not found, "Unknown" is returned.
* On success, the status code type/category is returned. */
const char *
verify_status_code_type (const char *str) {
size_t i;
for (i = 0; i < ARRAY_SIZE (code_type); i++)
if (strchr (code_type[i][0], str[0]) != NULL)
return _(code_type[i][1]);
return "Unknown";
}
/* Determine if the given status code is within the list of status
* codes.
*
* If not found, "Unknown" is returned.
* On success, the status code is returned. */
const char *
verify_status_code (char *str) {
size_t i;
for (i = 0; i < ARRAY_SIZE (codes); i++)
if (strstr (str, codes[i][0]) != NULL)
return _(codes[i][1]);
return "Unknown";
}
/* Checks if the given string is within the given array.
*
* If not found, -1 is returned.
* If found, the key for needle in the array is returned. */
int
str_inarray (const char *s, const char *arr[], int size) {
int i;
for (i = 0; i < size; i++) {
if (strcmp (arr[i], s) == 0)
return i;
}
return -1;
}
/* Strip whitespace from the beginning of a string.
*
* On success, a string with whitespace stripped from the beginning of
* the string is returned. */
char *
ltrim (char *s) {
char *begin = s;
while (isspace (*begin))
++begin;
memmove (s, begin, strlen (begin) + 1);
return s;
}
/* Strip whitespace from the end of a string.
*
* On success, a string with whitespace stripped from the end of the
* string is returned. */
char *
rtrim (char *s) {
char *end = s + strlen (s);
while ((end != s) && isspace (*(end - 1)))
--end;
*end = '\0';
return s;
}
/* Strip whitespace from the beginning and end of the string.
*
* On success, the trimmed string is returned. */
char *
trim_str (char *str) {
return rtrim (ltrim (str));
}
/* Convert the file size in bytes to a human readable format.
*
* On error, the original size of the string in bytes is returned.
* On success, the file size in a human readable format is returned. */
char *
filesize_str (unsigned long long log_size) {
char *size = xmalloc (sizeof (char) * 12);
if (log_size >= (1ULL << 50))
snprintf (size, 12, "%.2f PiB", (double) (log_size) / PIB (1ULL));
else if (log_size >= (1ULL << 40))
snprintf (size, 12, "%.2f TiB", (double) (log_size) / TIB (1ULL));
else if (log_size >= (1ULL << 30))
snprintf (size, 12, "%.2f GiB", (double) (log_size) / GIB (1ULL));
else if (log_size >= (1ULL << 20))
snprintf (size, 12, "%.2f MiB", (double) (log_size) / MIB (1ULL));
else if (log_size >= (1ULL << 10))
snprintf (size, 12, "%.2f KiB", (double) (log_size) / KIB (1ULL));
else
snprintf (size, 12, "%.1f B", (double) (log_size));
return size;
}
/* Convert microseconds to a human readable format.
*
* On error, a malloc'd string in microseconds is returned.
* On success, the time in a human readable format is returned. */
char *
usecs_to_str (unsigned long long usec) {
char *size = xmalloc (sizeof (char) * 11);
if (usec >= DAY)
snprintf (size, 11, "%.2f d", (double) (usec) / DAY);
else if (usec >= HOUR)
snprintf (size, 11, "%.2f hr", (double) (usec) / HOUR);
else if (usec >= MINS)
snprintf (size, 11, "%.2f mn", (double) (usec) / MINS);
else if (usec >= SECS)
snprintf (size, 11, "%.2f s", (double) (usec) / SECS);
else if (usec >= MILS)
snprintf (size, 11, "%.2f ms", (double) (usec) / MILS);
else
snprintf (size, 11, "%.2f us", (double) (usec));
return size;
}
/* Convert the given int to a string with the ability to add some
* padding.
*
* On success, the given number as a string is returned. */
char *
int2str (int d, int width) {
char *s = xmalloc (snprintf (NULL, 0, "%*d", width, d) + 1);
sprintf (s, "%*d", width, d);
return s;
}
/* Convert the given uint32_t to a string with the ability to add some
* padding.
*
* On success, the given number as a string is returned. */
char *
u322str (uint32_t d, int width) {
char *s = xmalloc (snprintf (NULL, 0, "%*u", width, d) + 1);
sprintf (s, "%*u", width, d);
return s;
}
/* Convert the given uint64_t to a string with the ability to add some
* padding.
*
* On success, the given number as a string is returned. */
char *
u642str (uint64_t d, int width) {
char *s = xmalloc (snprintf (NULL, 0, "%*" PRIu64, width, d) + 1);
sprintf (s, "%*" PRIu64, width, d);
return s;
}
/* Convert the given float to a string with the ability to add some
* padding.
*
* On success, the given number as a string is returned. */
char *
float2str (float d, int width) {
char *s = xmalloc (snprintf (NULL, 0, "%*.2f", width, d) + 1);
sprintf (s, "%*.2f", width, d);
return s;
}
int
ptr2int (char *ptr) {
char *sEnd = NULL;
int value = -1;
value = strtol (ptr, &sEnd, 10);
if (ptr == sEnd || *sEnd != '\0' || errno == ERANGE) {
LOG_DEBUG (("Invalid parse of integer value from pointer. \n"));
return -1;
}
return value;
}
int
str2int (const char *date) {
char *sEnd = NULL;
int d = strtol (date, &sEnd, 10);
if (date == sEnd || *sEnd != '\0' || errno == ERANGE)
return -1;
return d;
}
/* Determine the length of an integer (number of digits).
*
* On success, the length of the number is returned. */
int
intlen (uint64_t num) {
int l = 1;
while (num > 9) {
l++;
num /= 10;
}
return l;
}
/* Allocate a new string and fill it with the given character.
*
* On success, the newly allocated string is returned. */
char *
char_repeat (int n, char c) {
char *dest = xmalloc (n + 1);
memset (dest, c, n);
dest[n] = '\0';
return dest;
}
/* Replace all occurrences of the given char with the replacement
* char.
*
* On error the original string is returned.
* On success, a string with the replaced values is returned. */
char *
char_replace (char *str, char o, char n) {
char *p = str;
if (str == NULL || *str == '\0')
return str;
while ((p = strchr (p, o)) != NULL)
*p++ = n;
return str;
}
/* Remove all occurrences of a new line.
*
* On success, a string with the replaced new lines is returned. */
void
strip_newlines (char *str) {
char *src, *dst;
for (src = dst = str; *src != '\0'; src++) {
*dst = *src;
if (*dst != '\r' && *dst != '\n')
dst++;
}
*dst = '\0';