-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgolfrtc.c
executable file
·1573 lines (1410 loc) · 47.6 KB
/
golfrtc.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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2019 Gliim LLC.
// Licensed under Apache License v2. See LICENSE file.
// On the web http://golf-lang.com/ - this file is part of Golf framework.
//
// Library used both by GOLF utility and GOLF run-time
// trailing 'c' in the name of this file refers to 'common'
// code.
//
#include "golf.h"
int gg_errno=0;
bool gg_optmem=false;
// Function prototypes
gg_num gg_core_write_file(FILE *f, gg_num content_len, char *content, char ispos, gg_num pos);
//
// Close trace file
// Returns GG_ERR_CLOSE if there is no context or not open, or the same
// as gg_fclose() if it's open
//
gg_num gg_close_trace ()
{
gg_config *pc = gg_get_config();
if (pc == NULL) return GG_ERR_CLOSE;
// open trace file, for fcgi, it will not be NULL (from previous request)
if (pc->trace.f != NULL)
{
return gg_fclose(pc->trace.f);
} else return GG_ERR_CLOSE;
}
//
// Open trace file and write begin-trace message
// Returns 0 if opened, -1 if not
// Any memory alloc here MUST be malloc since it survives fcgi requests and continues
// over many such requests.
//
gg_num gg_open_trace ()
{
gg_config *pc = gg_get_config();
if (pc == NULL) return -1;
// open trace file, for fcgi, it will not be NULL (from previous request)
if (pc->trace.f != NULL)
{
return 0; // reuse tracing for the same process
}
if (pc->debug.trace_level > 0)
{
// timestamp, as PIDs can recycle
gg_current_time (pc->trace.time, sizeof(pc->trace.time)-1);
// append if file exists, otherwise open anew
snprintf(pc->trace.fname, sizeof(pc->trace.fname), "%s/trace-%ld-%s", pc->app.trace_dir, gg_getpid(), pc->trace.time);
pc->trace.f = gg_fopen (pc->trace.fname, "a+");
if (pc->trace.f == NULL)
{
pc->trace.f = gg_fopen (pc->trace.fname, "w+");
if (pc->trace.f == NULL)
{
return -1;
}
}
}
return 0;
}
//
// Trace execution. This is called from GG_TRACE.
// 'trace_level' is currently always 1. It is compared with the trace parameter in debug file, which is currently
// 0 or 1 (no tracing for 0 and tracing for 1). In the future, there may be more trace levels, with trace level 1
// including all tracing, trace level 2 including levels 2,3.. in trace file, etc.
// 'from_file' is the file name this trace is coming from.
// 'from_line' is the source line number, 'from_fun' is the function name.
// The rest (format,...) is printf-like data, the actual trace content.
// The trace also includes current time and PID.
//
// Trace can be called from memory function like gg_realloc.
// If trace is called from anywhere else other than gg_* functions, it will work the same way except there is no double calling of gg_check_memory.
//
void _gg_trace(gg_num trace_level, const char *from_file, gg_num from_line, const char *from_fun, char *format, ...)
{
gg_config *pc = gg_get_config();
if (pc == NULL) return; // do nothing if no config
// THIS FUNCTON MUST NEVER USE ANY FORM OF MALLOC OR GG_MALLOC
// or it may fail when memory is out or not available (such as in gg_malloc)
// control which tracing will be done
if (pc->debug.trace_level < trace_level) return;
char trc[GG_TRACE_LEN + 1];
// if this tracing came from this very function, ignore
if (pc->trace.in_trace == 1) return;
pc->trace.in_trace = 1;
if (pc->trace.f == NULL)
{
gg_open_trace(); // trace gets opened during fatal error, so open if not enabled
if (pc->trace.f == NULL) // if couldn't open, do not trace
{
pc->trace.in_trace = 0;
return;
}
}
va_list args;
va_start (args, format);
vsnprintf (trc, sizeof(trc) , format, args);
va_end (args);
// write time, code and message out
// do NOT use pc->trace.time - this MUST stay constant during the request because it is
// used in save_HTML to make sure name generated from this value is the same even if this name
// is generated multiple times.
// We do not specify PID as it is embedded in file name.
char curr_time[200];
gg_current_time (curr_time, sizeof(curr_time)-1);
fprintf (pc->trace.f, "%s (%s:%ld)| %s %s\n", curr_time, from_file, from_line, from_fun, trc);
//
// We do not fflush() here - this is done either at the end of request (gg_shut()) or
// when program crashes (gg_report_error())
//
pc->trace.in_trace = 0;
}
//
// Get PID
//
gg_num gg_getpid ()
{
GG_TRACE ("");
return (gg_num) getpid();
}
//
// Get current time
// Output: outstr is the time string.
// out_str_len is time string buffer size
// If can't get time, output is empty string.
//
void gg_current_time (char *outstr, gg_num out_str_len)
{
GG_TRACE("");
time_t t;
struct tm *tmp;
// get current time zone - may be set by customer program!
char *curr_time_zone = getenv("TZ");
#define restore_curr_time_zone if (curr_time_zone!=NULL && curr_time_zone[0]!=0) { putenv(curr_time_zone); tzset(); }
// set time zone to local - we did this in main() first thing before customer code. We cast gg_get_tz()
// into mutable char * because putenv does NOT modify its string. The result of gg_get_tz must NOT change by
// callers.
putenv((char*)gg_get_tz());
tzset();
t = time(NULL);
tmp = localtime(&t);
if (tmp == NULL)
{
// return to customer TZ
restore_curr_time_zone
outstr[0] = 0;
return;
}
if (strftime(outstr, out_str_len, "%F-%H-%M-%S", tmp) == 0)
{
outstr[0] = 0;
}
// return to customer TZ
restore_curr_time_zone
}
//
// Both configuration and run-time information (context, debug, trace, etc.)
// This is really a program context.
// EVERYTHING IN GG_CONFIG MUST BE MALLOC (NOT GG_MALLOC) AS IT IS USED ACROSS REQUESTS
//
gg_config *gg_pc;
//
// Get config and context data
//
gg_config *gg_alloc_config()
{
// start /var/log/syslog so that fatal message have a place to go to
openlog(gg_app_name, LOG_PERROR | LOG_PID, LOG_USER);
// all of golf config (sub)structures must be zeroed-out - we rely on this when setting directories, user id and such
gg_pc = (gg_config*)calloc (1, sizeof(gg_config));
if (gg_pc == NULL)
{
GG_FATAL ("Cannot allocate program context");
}
gg_init_config (gg_pc);
return gg_pc;
}
//
// Initialize program context. This is called only once for the
// life of the process. pc is program context.
//
void gg_init_config(gg_config *pc)
{
assert (pc);
// pc->* are set to 0 or NULL - set here only what's not zero
pc->app.max_upload_size = 5000000;
gg_reset_config (pc);
}
//
// Reset program context. This is called for each new web request
//
void gg_reset_config(gg_config *pc)
{
assert (pc);
// these need to reset with each request
// DO NOT RESET debug structure - should stay as it is for all request during the life of process!
pc->ctx.req = NULL;
pc->ctx.gg_report_error_is_in_report = 0;
pc->debug.trace_level = gg_is_trace; // reset tracing, as it is set to 1 during report-error
}
//
// UP TO HERE THERE CAN BE NO GG_MALLOC
//
//
// Find number of occurances in string 'str' of a substring 'find'
// If len_find isn't 0, then it's length of find.
// If case_sensitive is 1, then it's case sensitive, if 0 then not.
//
// Returns number of occurances of find in str
//
gg_num gg_count_substring (char *str, char *find, gg_num len_find, gg_num case_sensitive)
{
GG_TRACE("");
gg_num count = 0;
if (find == NULL || find[0] == 0) return 0;
// here not empty or NULL
gg_num len;
if (len_find != 0) len = len_find; else len = gg_mem_get_len(gg_mem_get_id(find));
char *tmp = str;
while((tmp = (case_sensitive == 1 ? strstr(tmp, find) : strcasestr(tmp, find))) != NULL)
{
count++;
tmp += len;
}
return count;
}
//
// Replace string 'find' with string 'subst' in string 'str', which is of size 'strsize' (total size in bytes of buffer
// that is available). 'all' is 1 if all occurrance of 'find' are to be replaced.
// Output 'last' is the last byte position from which 'find' was searched for, but was not found (i.e.
// last byte position after which there is no more 'find' strings found).
// If case_sensitive is 1 then it's case sensitive, and 0 otherwise.
// Returns length of subst string, or -1 if not enough memory. If -1, whatever substitutions could have been
// made, were made, in which case use 'last' to know where we stopped.
//
gg_num gg_replace_string (char *str, gg_num strsize, char *find, char *subst, gg_num all, char **last, gg_num case_sensitive)
{
GG_TRACE("");
assert (str);
assert (find);
assert (subst);
gg_num len = strlen (str);
gg_num lenf = strlen (find);
gg_num lens = strlen (subst);
gg_num occ = 0;
gg_num currsize = len + 1;
char *curr = str;
if (last != NULL) *last = NULL;
while (1)
{
// find a string and move memory to kill the found
// string and install new one - minimal memmove
// based on diff
char *f = (case_sensitive==1 ? strstr (curr, find) : strcasestr (curr,find));
if (f == NULL) break;
currsize -= lenf;
currsize += lens;
if (currsize > strsize)
{
return -1;
}
memmove (f + lens, f + lenf, len - (f - str + lenf) + 1);
memcpy (f, subst, lens);
// update length
len = len - lenf + lens;
curr = f + lens; // next pos to look from
if (last != NULL) *last = curr;
// for caller, where to look next, if in
// external loop, for 'all==0' only
occ++;
if (all == 0) break;
}
return len;
}
//
// Trim string on both left and right and place string back
// into the original buffer. Trims spaces, tabs, newlines.
// str is the string to be gg_trimmed.
// len is the length of string on the input, and it has new length
// on the output. 'len' MUST be the strlen(str) on input!
// if alloc is true, then str is alloc'd mem
// MUST NOT realloc as that would invalidate other references to this string
//
void gg_trim (char *str, gg_num *len, bool alloc)
{
GG_TRACE("");
assert (str);
assert (len);
gg_num i = 0;
// clear leading spaces
while (isspace (str[i])) i++;
// move string back, overriding leading spaces
if (i) memmove (str, str + i, *len - i + 1);
// update length
*len = *len -i;
// start from the end
i = *len - 1;
// find the last non-space char
while (i>=0 && isspace (str[i])) i--;
// make the end of string there
str[i + 1] = 0;
// update length of string
*len = i + 1;
if (alloc) gg_mem_set_len (gg_mem_get_id(str), *len+1);
}
//
// Trim string on both left and right and return pointer to trimmed string- no movement of string
// Trims spaces, tabs, newlines.
// str is the string to be trimmed
// len is the length of string on the input, and it has new length
// on the output. 'len' MUST be the strlen(str) on input!
//
char *gg_trim_ptr (char *str, gg_num *len)
{
GG_TRACE("");
assert (str);
assert (len);
char *res = str;
gg_num s = 0;
// clear leading spaces
while (isspace (str[s])) s++;
res = str + s;
// start from the end
gg_num e = *len - 1;
// update length
*len = *len -s;
// find the last non-space char
gg_num j = 0;
while (e>=s && isspace (str[e])) { e--; j++;}
// make the end of string there
str[e + 1] = 0;
// update length of string
*len = *len - j;
return res;
}
//
// Returns GG_DIR if 'dir' is a directory,
// GG_FILE if it's file, GG_ERR_FAILED if can't stat
//
gg_num gg_file_type (char *dir)
{
GG_TRACE("");
struct stat sb;
if (stat(dir, &sb) == 0)
{
if (S_ISDIR(sb.st_mode)) return GG_DIR; else return GG_FILE;
}
else
{
GG_ERR;
return GG_ERR_FAILED;
}
}
//
// Get Position from file FILE* f
// Returns GG_OKAY if okay, GG_ERR_POSITION if cannot do it
//
gg_num gg_get_file_pos(FILE *f, gg_num *pos)
{
GG_TRACE("");
long p = ftell (f);
if (p == -1) {
GG_ERR;
GG_TRACE("Cannot get position in file, errno [%d]", errno);
return GG_ERR_POSITION;
}
*pos = p;
return GG_OKAY;
}
//
// Position file FILE* f to pos
// Returns GG_OKAY if okay, GG_ERR_POSITION if cannot do it
// GG_ERR_OPEN if file not opened
//
gg_num gg_set_file_pos(FILE *f, gg_num pos)
{
GG_TRACE("");
if (f==NULL)
{
GG_ERR;
return GG_ERR_OPEN;
}
if (fseek (f,pos,SEEK_SET) != 0) {
GG_ERR;
GG_TRACE("Cannot position in file to [%ld], errno [%d]", pos, errno);
return GG_ERR_POSITION;
}
return GG_OKAY;
}
//
// Get size of file from open FILE*
// f is FILE *
// Returns size of the file
//
gg_num gg_get_open_file_size(FILE *f)
{
GG_TRACE("");
long ppos = ftell(f);
fseek(f, 0L, SEEK_END);
long size=ftell(f);
fseek(f, ppos, SEEK_SET); // position to where we were before
return (gg_num)size;
}
//
// Get size of file
// fn is file name.
// Returns size of the file, or -1 if file cannot be stat'
//
gg_num gg_get_file_size(char *fn)
{
GG_TRACE("");
struct stat st;
if (stat(fn, &st) != 0)
{
GG_ERR;
return GG_ERR_FAILED;
}
return (gg_num)(st.st_size);
}
//
// Checks if input parameter name (in URL) is valid for golf.
// Valid names are considered to have only alphanumeric characters and
// underscores/hyphens, and must start with an alphabet character.
// If hyphen is true, then it's allowed, otherwise it's not. If hyphen is allowed and conv_hyphen is true, then each hyphen
// is converted to underscore.
// Returns 1 if name is valid, 0 if not.
//
gg_num gg_is_valid_param_name (char *name, bool hyphen, bool conv_hyphen)
{
GG_TRACE ("");
assert (name);
gg_num i = 1; // we already check the first byte before entering while loop
if (!isalpha(name[0])) return 0;
while (name[i] != 0)
{
if (isalnum(name[i])) { i++; continue;}
if (name[i] == '_') { i++; continue;}
if (name[i] == '-' && hyphen)
{
if (conv_hyphen) name[i] = '_';
i++;
continue;
}
return 0;
}
return 1;
}
//
// Initialize sequential list storage data
// fdata is storage data variable.
// Data can be stored in order and retrieved in the same order and rewound
// any number of times. Once used, must be purged.
//
void gg_store_init (gg_fifo **fdata_ptr)
{
GG_TRACE ("");
*fdata_ptr = (gg_fifo*)gg_malloc (sizeof(gg_fifo));
gg_fifo *fdata = *fdata_ptr;
fdata->num_of = 0;
fdata->last_ptr = NULL;
fdata->retrieve_ptr = NULL;
fdata->first_ptr = NULL;
}
//
// Store name/value pair, with 'name' being the name and 'data' being the value
// in storage data 'fdata'. Both strings are stored in the list as pointers.
// This is for lifo variety.
//
void gg_store_l (gg_fifo *fdata, char *name, void *data)
{
GG_TRACE ("");
gg_fifo_item *np = gg_malloc (sizeof (gg_fifo_item));
// No need to check if np->name/data equal to name/data because np is just created here, has nothing to begin with
//
if (gg_optmem) gg_mem_add_ref (1, NULL, data);
gg_mem_set_process (data, false);
np->data = data;
//
if (gg_optmem) gg_mem_add_ref (1, NULL, name);
gg_mem_set_process (name, false);
np->name = name;
//
np->next = NULL;
if (fdata->num_of == 0)
{
fdata->first_ptr = np;
fdata->last_ptr = np;
}
else
{
np->next = fdata->first_ptr;
fdata->first_ptr = np;
}
fdata->retrieve_ptr = np;
fdata->num_of++;
}
//
//
// Store name/value pair, with 'name' being the name and 'data' being the value
// in storage data 'fdata'. Both strings are stored in the list as pointers.
// This is for fifo variety.
//
void gg_store (gg_fifo *fdata, char *name, void *data)
{
GG_TRACE ("");
gg_fifo_item *np = gg_malloc (sizeof (gg_fifo_item));
// No need to check if np->name/data equal to name/data because np is just created here, has nothing to begin with
//
if (gg_optmem) gg_mem_add_ref(1, NULL, data);
gg_mem_set_process (data, false);
np->data = data;
//
if (gg_optmem) gg_mem_add_ref(1, NULL, name);
gg_mem_set_process (name, false);
np->name = name;
//
np->next = NULL;
if (fdata->num_of == 0)
{
fdata->first_ptr = np;
fdata->last_ptr = np;
fdata->retrieve_ptr = np;
}
else
{
fdata->last_ptr->next = np;
fdata->last_ptr = np;
}
fdata->num_of++;
}
//
// Retrieve name/value pair from storage data 'fdata', with 'name' being the
// name and 'data' being the value. The name/data are simply assigned pointer
// values. Initially, this starts with fist name/value pair put in.
//
gg_num gg_retrieve (gg_fifo *fdata, gg_num is_def_n, char **name, gg_num is_def_d, void **data)
{
GG_TRACE ("");
assert (fdata != NULL);
if (fdata->retrieve_ptr == NULL)
{
return GG_ERR_EXIST;
}
if (data != NULL)
{
if (gg_optmem)
{
if (*data != fdata->retrieve_ptr->data)
{
gg_mem_add_ref(is_def_d, *data, fdata->retrieve_ptr->data);
*data = fdata->retrieve_ptr->data;
}
}
else
{
*data = fdata->retrieve_ptr->data;
}
}
if (name != NULL)
{
if (gg_optmem)
{
if (*name != fdata->retrieve_ptr->name)
{
gg_mem_add_ref(is_def_n, *name, fdata->retrieve_ptr->name);
*name = fdata->retrieve_ptr->name;
}
}
else
{
*name = fdata->retrieve_ptr->name;
}
}
fdata->retrieve_ptr = fdata->retrieve_ptr->next;
return GG_OKAY;
}
//
// Rewind name/value pair in storage 'fdata', so that next gg_retrieve()
// starts from the items first put in.
void gg_rewind (gg_fifo *fdata)
{
GG_TRACE ("");
assert (fdata != NULL);
fdata->retrieve_ptr = fdata->first_ptr;
}
//
// Delete the very first name/value pair in fifo 'fdata', all the way up to the current
// element (which is one after last read, or NULL if already retrieved the last one), excluding.
//
void gg_fifo_delete (gg_fifo *fdata)
{
GG_TRACE ("");
if (fdata->first_ptr == NULL) return;
while (fdata->first_ptr != fdata->retrieve_ptr)
{
gg_fifo_item *temp = fdata->first_ptr;
if (temp == fdata->last_ptr) fdata->last_ptr = fdata->first_ptr = fdata->retrieve_ptr = NULL;
else fdata->first_ptr = temp->next;
gg_free (temp->data);
gg_free (temp->name);
gg_free (temp);
fdata->num_of--;
}
}
//
// Purge all data from storage 'fdata' and initialize for another use.
//
void gg_purge (gg_fifo **fdata_p)
{
GG_TRACE ("");
gg_fifo *fdata = *fdata_p;
fdata->retrieve_ptr = NULL; // delete up to the end, i.e. all of them
gg_fifo_delete (fdata);
gg_free(fdata);
gg_store_init (fdata_p); // okay fdata_p since fdata_p!=NULL
}
//
// Initialize linked list storage data
// fdata is storage data variable.
// process is true if this list is process-scoped
//
void gg_list_init (gg_list **fdata_ptr, bool process)
{
GG_TRACE ("");
*fdata_ptr = (gg_list*)gg_malloc (sizeof(gg_list));
gg_list *fdata = *fdata_ptr;
fdata->num_of = 0;
fdata->last = NULL;
fdata->curr = NULL;
fdata->first = NULL;
fdata->process = process;
}
//
// Store name/value pair, with 'name' being the name and 'data' being the value
// in linked list storage data 'fdata'. Both strings are stored in the list as pointers.
// New element stored at current position (at the very end if current is NULL)
//
void gg_list_store (gg_list *fdata, char *name, void *data, bool append)
{
GG_TRACE ("");
gg_list_item *np = gg_malloc (sizeof (gg_list_item));
// No need to check if np->name/data equal to name/data because np is just created here, has nothing to begin with
//
if (gg_optmem) gg_mem_add_ref(1, NULL, data);
gg_mem_set_process (data, false);
np->data = data;
//
if (gg_optmem) gg_mem_add_ref(1, NULL, name);
gg_mem_set_process (name, false);
np->name = name;
//
np->next = NULL;
np->prev = NULL;
if (fdata->num_of == 0)
{
fdata->first = np;
fdata->last = np;
fdata->curr = np;
}
else
{
if (append) fdata->curr = NULL;
if (fdata->curr == NULL)
{
fdata->last->next = np;
np->prev = fdata->last;
fdata->last = np;
fdata->curr = np;
}
else if (fdata->curr == fdata->first)
{
np->next = fdata->first;
fdata->first->prev = np;
fdata->first = np;
fdata->curr = np;
}
else
{
fdata->curr->prev->next = np;
np->prev = fdata->curr->prev;
np->next = fdata->curr;
fdata->curr->prev = np;
fdata->curr = np;
}
}
fdata->num_of++;
}
//
// Retrieve name/value pair from linked list data 'fdata', with 'name' being the
// name and 'data' being the value. The name/data are simply assigned pointer
// values. Element retrieved is the current one.
//
void gg_list_retrieve (gg_list *fdata, char **name, void **data)
{
GG_TRACE ("");
if (fdata->curr == NULL)
{
return;
}
if (data != NULL) *data = fdata->curr->data;
if (name != NULL) *name = fdata->curr->name;
}
//
// Delete current element in linked list 'fdata'
// Inline so purge doesn't waste time
//
inline gg_num gg_list_delete (gg_list *fdata)
{
GG_TRACE ("");
gg_list_item *temp = fdata->curr;
if (temp == NULL) return GG_ERR_EXIST;
gg_free (temp->data);
gg_free (temp->name);
if (temp->next != NULL) {
temp->next->prev = temp->prev;
fdata->curr = temp->next;
}
else
{
fdata->last = temp->prev;
fdata->curr = temp->prev;
}
if (temp->prev != NULL) temp->prev->next = temp->next; else
{
fdata->first = temp->next;
fdata->curr = temp->next;
}
gg_free (temp);
fdata->num_of--;
return GG_OKAY;
}
//
// Purge all data from linked list 'fdata_p' and initialize for another use.
//
void gg_list_purge (gg_list **fdata_p)
{
GG_TRACE ("");
gg_list *fdata = *fdata_p;
bool p = (*fdata_p)->process;
while (fdata->num_of > 0)
{
fdata->curr = fdata->first;
gg_list_delete (fdata);
}
gg_free(fdata);
gg_list_init (fdata_p, p); // okay fdata_p since fdata_p!=NULL
}
//
// The same as strncpy() except that zero byte is placed at the end and it returns
// the length of the dest string.
//
gg_num gg_strncpy(char *dest, char *src, gg_num max_len)
{
GG_TRACE("");
gg_num len = strlen (src);
if (len < max_len)
{
memcpy (dest, src, len+1 );
return len;
}
else
{
memcpy (dest, src, max_len-1 );
dest[max_len - 1] = 0;
return max_len - 1;
}
}
//
// Initialize a string that is allocated on the heap, like malloc with value of string s
//
char *gg_init_string(char *s)
{
GG_TRACE("");
if (s == NULL) return NULL;
gg_num l = strlen (s);
char *res = gg_malloc (l+1);
memcpy (res, s, l+1);
return res;
}
//
// Get timezone that's local to this server.
// Returns string in the format TZ=<timezone>, eg. TZ=MST
//
char * gg_get_tz ()
{
//
// This static usage is okay because the timezone is the SAME for all modules that could
// run in this process. We can set timezone once for any of the modules, and the rest can
// use the timezone just fine.
//
static gg_num is_tz = 0;
static char tz[200];
// TZ variable isn't set by default, so we cannot count on it. Functions
// that operate on time do CHECK if it's set, but unless we set it, it
// WONT be set
if (is_tz == 0)
{
is_tz = 1;
// get localtime zone
time_t t = time(NULL);
struct tm *tm = localtime(&t);
snprintf (tz, sizeof(tz), "TZ=%s", tm->tm_zone);
}
return tz;
}
//
// Read entire file with path 'name' and store file contents in output 'data', unless
// pos/len is specified (len is <>0 or pos<>0), in which case read len (default is 0, the rest of the file) bytes
// from position pos (default is 0, the beginning). Returns -1 if cannot open file, -2 if cannot read,
// -3 cannot position, -4 if nothing to read (pos/len bad), or size of data read.
// Note: zero byte is place after the end, so if return value is 10, it means
// there are 11 bytes, with zero at the end, regardless of whether the data is a
// string or not.
// If there is not enough memory, gg_malloc will error out.
//
gg_num gg_read_file (char *name, char **data, gg_num pos, gg_num len)
{
GG_TRACE ("");
if (pos < 0) {GG_ERR0; return GG_ERR_POSITION;} // len is negative
if (len < 0) {GG_ERR0; return GG_ERR_READ;} // pos is negative
FILE *f = gg_fopen (name, "r");
if (f == NULL)
{
//gg_fopen sets GG_ERR
return GG_ERR_OPEN;
}
gg_num sz;
if (len > 0) sz = len; else sz = gg_get_open_file_size(f) - pos;
if (sz < 0) { GG_ERR0; return GG_ERR_POSITION;} // pos is beyond size
if (sz == 0)
{
*data = GG_EMPTY_STRING;
return 0; // nothing to read just an empty string
}
if (pos > 0)
{
if (fseek (f,pos,SEEK_SET) != 0) {
GG_ERR;
GG_TRACE("File [%s], cannot position to [%ld], errno [%d]", name, pos, errno);
fclose (f);
*data = GG_EMPTY_STRING;
return GG_ERR_POSITION;
}
}
*data = gg_malloc (sz + 1);
gg_num id = gg_mem_get_id (*data);
gg_num rd;
rd = fread (*data, 1, sz, f);
if (ferror (f))
{
GG_ERR;
gg_free (*data);
fclose(f);
*data = GG_EMPTY_STRING;
return GG_ERR_READ;
}
(*data)[rd] = 0;
gg_mem_set_len (id, rd+1);
fclose(f);
return rd;
}
//
// Read file with FILE* f and store file contents in output 'data'
// len (default is 0, the rest of the file) is the number of bytes to read
// from position pos, if not specified then from current position . Returns -1 if cannot open file, -2 if cannot read,
// -3 cannot position, -4 if nothing to read (pos/len bad), or size of data read.
// Note: zero byte is place after the end, so if return value is 10, it means
// there are 11 bytes, with zero at the end, regardless of whether the data is a
// string or not.
// If there is not enough memory, gg_malloc will error out.
// ispos is true if position is given
//
gg_num gg_read_file_id (FILE *f, char **data, gg_num pos, gg_num len, bool ispos)
{
GG_TRACE ("");
if (ispos && pos < 0) {GG_ERR0; return GG_ERR_POSITION;} // len is negative
if (len < 0) {GG_ERR0; return GG_ERR_READ;} // len is negative
if (f == NULL)
{
GG_ERR;
return GG_ERR_OPEN;
}
gg_num sz;
if (len > 0) sz = len; else
{
// If position not specified, find the current position, so that "reading to the
// end of the file" is correct exactly.
if (!ispos) {
if (gg_get_file_pos (f, &pos) != GG_OKAY) { return GG_ERR_POSITION;}