-
Notifications
You must be signed in to change notification settings - Fork 1
/
velyrt.c
executable file
·3993 lines (3631 loc) · 153 KB
/
velyrt.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: EPL-2.0
// Copyright 2019 DaSoftver LLC. Written by Sergio Mijatovic.
// Licensed under Eclipse Public License - v 2.0. See LICENSE file.
// On the web https://vely.dev/ - this file is part of Vely framework.
//
// Main library used at VELY runtime. Most of the functions used
// within markups are implemented here. See also velyrtc.c which includes
// common functions shared between VELY runtime and VELY preprocessor.
//
#include "vely.h"
// functions (local)
size_t vely_write_url_response(void *ptr, size_t size, size_t nmemb, void *s);
void vely_init_output_buffer ();
num vely_validate_output ();
void vely_set_arg0 (char *program, char **arg0);
num vely_write_web (bool iserr, vely_config *pc, char *s, num nbyte);
void vely_gen_set_content_type(char *v);
void vely_gen_add_header (char *n, char *v);
void vely_gen_set_status (num st, char *line);
void vely_send_header(vely_input_req *iu);
num vely_gen_util_read (char *content, num len);
void vely_gen_set_content_length(char *v);
void vely_server_error ();
num vely_header_err(vely_config *pc);
void vely_cant_find_file ();
char *vely_gen_get_env(char *n);
num vely_gen_write (bool is_error, char *s, num nbyte);
void vely_flush_trace();
void vely_write_ereport(char *errtext, vely_config *pc);
void vely_read_child (int ofd, char **out_buf, num *out_len);
void vely_gen_header_end ();
void vely_check_set_cookie (char *name, char *val, char *secure, char *samesite, char *httponly, char *safety_clause, size_t safety_clause_len);
// write-string macros
#define VV_WRSTR_CUR (vely_get_config()->ctx.req->curr_write_to_string)
#define VV_WRSTR (vely_get_config()->ctx.req->write_string_arr[VV_WRSTR_CUR])
#define VV_WRSTR_LEN (VV_WRSTR.len)
#define VV_WRSTR_BUF (VV_WRSTR.string)
#define VV_WRSTR_POS (VV_WRSTR.buf_pos)
#define VV_WRSTR_ADD (VV_WRSTR.wlen)
#define VV_WRSTR_ADD_MIN 128 // min memory to add to write-string
#define VV_WRSTR_ADD_MAX 8192 // max memory to add to write-string
#define VV_WRSTR_ADJMEM(x) ((x) = ((x) < VV_WRSTR_ADD_MAX ? 2*(x):(x)))
#ifndef VV_COMMAND
#include "fcgi_config.h"
#include "fcgiapp.h"
static FCGX_Stream *vely_fcgi_in = NULL, *vely_fcgi_out = NULL, *vely_fcgi_err = NULL;
static FCGX_ParamArray vely_fcgi_envp;
#endif
static char finished_output = 0;
static num found_input_param = -1; // the id of found input param in vely_get_input_param (in ipars[]),
// we return char *, this set the id which is needed in set-input
extern num vely_end_program;
//
// Initialize vely_input_req structure for fetching input URL data
// req is URL structure used to hold input data.
// DO NOT USE vely_get_config() here as it's not available yet!
//
void vely_init_input_req (vely_input_req *req)
{
VV_TRACE("");
num i;
for (i=0; i < VV_MAX_NESTED_WRITE_STRING; i++)
{
req->write_string_arr[i].string = NULL;
req->write_string_arr[i].len = 0;
req->write_string_arr[i].buf_pos = 0;
req->write_string_arr[i].notrim = 0;
req->write_string_arr[i].wlen = VV_WRSTR_ADD_MIN;
}
req->curr_write_to_string = -1;// each write-to-string first increase it
req->disable_output = 0;
req->app = NULL;
req->if_none_match = NULL;
req->cookies = NULL;
req->num_of_cookies = 0;
req->ip.ipars = NULL;
req->ip.num_of_input_params = 0;
req->sent_header = 0;
req->data_was_output = 0;
req->silent = 0;
req->ec = 0;
req->is_shut = 0;
req->header=NULL; // no custom headers, set to non-NULL for custom headers
req->data = NULL; // user must assign request specific data structure
req->body = VV_EMPTY_STRING;
req->name = VV_EMPTY_STRING;
req->body_len = 0;
req->method = VV_OKAY;
req->task = -1; // meaning task not set
finished_output = 0; // reset finish-output indicator
vely_mem_os = false; // new request means memory garbage collector is on again, regardless
// of what it was at the end of the previous one
}
//
//Do not trim the last new line in write-string
//
void vely_write_to_string_notrim ()
{
VV_TRACE("");
assert (VV_WRSTR_CUR < VV_MAX_NESTED_WRITE_STRING); // see comment in vely_write_to_string_length ()
VV_WRSTR.notrim = 1;
}
//
// Returns length of current top-level write-string (or equivalent API which is
// vely_write_to_string()) string being written.
//
num vely_write_to_string_length ()
{
VV_TRACE ("");
vely_input_req *req = vely_get_config()->ctx.req;
assert (VV_WRSTR_CUR < VV_MAX_NESTED_WRITE_STRING); // overflow if asking within the last level
// because the level above it does not exist. We always show the length of previous write-string
// and that is one level up
return req->write_string_arr[req->curr_write_to_string+1].buf_pos;
}
//
// Write to string. str is either a VELY-allocated string into which to write
// or NULL, which signifies end of string writing.
// Once non-NULL string str is passed here, all future writing (such as print-noenc
// or print-web etc) goes to this string, until this function is called with NULL.
// Writing to string can be nested, so writing to string2 (while writing to string1)
// will write to string2 until NULL is passed, when it switches back to string1.
//
void vely_write_to_string (char **str)
{
VV_TRACE ("");
if (str == NULL)
{
// stop writing to string
if (VV_WRSTR_CUR<0)
{
vely_report_error ("Cannot stop writing to string if it was never initiated, or if stopped already");
}
if (VV_WRSTR_BUF == NULL)
{
vely_report_error ("Cannot find write-string data block");
}
if (VV_WRSTR.notrim == 0)
{
while (isspace(VV_WRSTR_BUF[VV_WRSTR_POS-1])) VV_WRSTR_POS--;
VV_WRSTR_BUF[VV_WRSTR_POS] = 0;
}
VV_WRSTR_BUF = vely_realloc (VV_WRSTR_BUF, VV_WRSTR_POS+1); // resize memory to just what's needed
*(VV_WRSTR.user_string) = VV_WRSTR_BUF;
// Do NOT set VV_WRSTR_POS = 0 because then function vely_write_to_string_length()
// couldn't possibly work
// restore notrim so all future write-strings are not 'notrim'
VV_WRSTR.notrim = 0;
// no more string to write
VV_WRSTR_BUF = NULL;
VV_WRSTR_CUR--;
}
else
{
// start writing to string
// Once curr_write_to_string is not -1 (i.e. 0 or more), there is a string writing in progress, even if
// nothing has been written to it yet. So the condition for "are we in string writing" is curr_write_to_string!=-1
VV_WRSTR_CUR++;
if (VV_WRSTR_CUR >= VV_MAX_NESTED_WRITE_STRING)
{
vely_report_error ("Too many nesting levels of writing to string in progress, maximum [%d] nesting levels", VV_MAX_NESTED_WRITE_STRING);
}
//
// assign an empty string to *str, in case it's used somehow within write-string (trying to do recursion,
// which is not allowed)
*str = VV_EMPTY_STRING;
VV_WRSTR.user_string = str;
// Use internal pointer and memory to build a string. Original user string remains empty until the end.
VV_WRSTR_ADD = VV_WRSTR_ADD_MIN; // start with min mem
VV_WRSTR_LEN = VV_WRSTR_ADD;
VV_WRSTR_BUF= (char*) vely_malloc (VV_WRSTR_LEN);
VV_WRSTR_POS = 0;
}
}
//
// Send html header out for a dynamically generated page. It is always no-caching.
// req is input request.
// If HTML output is disabled, NO header is sent.
//
void vely_output_http_header(vely_input_req *req)
{
VV_TRACE("");
if (req->sent_header == 1)
{
VV_TRACE("Header already sent, attempted to send it again");
return;
}
VV_TRACE ("sent header: [%lld]", req->sent_header);
if (vely_get_config()->ctx.req->disable_output == 1) return;
req->sent_header = 1;
// complain that header hasn't been sent yet! and cause fatal error at that.
vely_send_header(req);
}
void vely_check_set_cookie (char *name, char *val, char *secure, char *samesite, char *httponly, char *safety_clause, size_t safety_clause_len)
{
VV_TRACE("");
char *chk = name;
// Per rfc6265, cookie name must adhere to this and be present
while (*chk != 0)
{
if (*chk < 33 || *chk == 127 || // this excludes space, tab and control chars
*chk == '(' || *chk == ')' || *chk == '@' || *chk == ',' || *chk == ';' || *chk == ':' || *chk == '\\' ||
*chk == '"' || *chk == '/' || *chk == '[' || *chk == ']' || *chk == '?' || *chk == '=' ||
*chk == '{' || *chk == '}')
{
vely_report_error ("Cookie name [%s] is invalid at [%s]", name, chk);
}
chk ++;
}
if (name[0] == 0) vely_report_error ("Cookie name is empty");
// Per rfc6265, cookie value must adhere to this and be present
chk = val;
while (*chk != 0)
{
if (*chk < 33 || *chk == 127 || // this excludes space, tab and control chars
*chk == ',' || *chk == ';' || *chk == '\\' ||
(*chk == '"' && (chk != val && *(chk+1) != 0))) // quote is allowed only as first and last byte, not inside
{
vely_report_error ("Cookie value [%s] is invalid at [%s]", val, chk);
}
chk ++;
}
if (val[0] == 0) vely_report_error ("Cookie value is empty");
if (strcmp(secure, "Secure; ") && strcmp (secure, ""))
{
vely_report_error ("Cookie 'secure' can be only on or off, it is [%s]", secure);
}
if (strcmp(httponly, "HttpOnly; ") && strcmp (httponly, ""))
{
vely_report_error ("Cookie HttpOnly can be only on or off, it is [%s]", httponly);
}
if (samesite[0] != 0 && strcmp(samesite, "Strict") && strcmp (samesite, "Lax") && strcmp (samesite, "None"))
{
vely_report_error ("Cookie SameSite can be only empty, Strict, Lax or None");
}
if (samesite[0] != 0) snprintf (safety_clause, safety_clause_len, "; %s%sSameSite=%s", secure, httponly, samesite);
else snprintf (safety_clause, safety_clause_len, "; %s%s", secure, httponly);
}
//
// Sets cookie that's to be sent out when header is sent. req is input request, cookie_name is the name of the cookie,
// cookie_value is its value, path is the URL for which cookie is valid, expires is the date of exiration.
// SameSite is empty by default. Strict is to prevent cross-site request exploitations, for enhanced safety. Otherwise samesite can be
// Strict, Lax or None.
// httponly can be either "HttpOnly; " or empty string
// cookies[].is_set_by_program is set to 1 if this is the cookie we changed (i.e. not original in the web input).
//
void vely_set_cookie (vely_input_req *req, char *cookie_name, char *cookie_value, char *path, char *expires, char *samesite, char *httponly, char *secure)
{
VV_TRACE ("cookie path [%s] expires [%s]", path==NULL ? "NULL":path, expires==NULL ? "NULL":expires);
if (req->data_was_output == 1)
{
vely_report_error ("Cookie can only be set before any data is output, and either before or after header is output.");
}
char safety_clause[200];
vely_check_set_cookie (cookie_name, cookie_value, secure, samesite, httponly, safety_clause, sizeof(safety_clause));
num ind;
char *exp = NULL;
vely_find_cookie (req, cookie_name, &ind, NULL, &exp);
if (ind == -1)
{
if (req->num_of_cookies+1 >= VV_MAX_COOKIES)
{
vely_report_error ("Too many cookies [%lld]", req->num_of_cookies+1);
}
ind = req->num_of_cookies;
req->num_of_cookies++;
}
else
{
vely_free (req->cookies[ind].data);
}
char cookie_temp[VV_MAX_COOKIE_SIZE + 1];
if (expires == NULL || expires[0] == 0)
{
if (path == NULL || path[0] == 0)
{
snprintf (cookie_temp, sizeof(cookie_temp), "%s=%s%s", cookie_name, cookie_value, safety_clause);
VV_TRACE("cookie[1] is [%s]", cookie_temp);
}
else
{
snprintf (cookie_temp, sizeof(cookie_temp), "%s=%s; Path=%s%s", cookie_name, cookie_value, path, safety_clause);
VV_TRACE("cookie[2] is [%s]", cookie_temp);
}
}
else
{
if (path == NULL || path[0] == 0)
{
snprintf (cookie_temp, sizeof(cookie_temp), "%s=%s; Expires=%s%s", cookie_name, cookie_value, expires, safety_clause);
VV_TRACE("cookie[3] is [%s]", cookie_temp);
}
else
{
snprintf (cookie_temp, sizeof(cookie_temp), "%s=%s; Path=%s; Expires=%s%s", cookie_name, cookie_value, path, expires, safety_clause);
VV_TRACE("cookie[4] is [%s]", cookie_temp);
}
}
req->cookies[ind].data = vely_strdup (cookie_temp);
req->cookies[ind].is_set_by_program = 1;
VV_TRACE("cookie [%lld] is [%s]", ind,req->cookies[ind].data);
}
//
// Find cookie based on name cookie_name. req is input request. Output: ind is the index in the cookies[] array in
// req, path/exp is path and expiration of the cookie.
// When searching for a cookie, we search the cookie[] array, which we may have added to or deleted from, so it
// may not be the exact set of cookies from the web input.
// Returns cookie's value.
//
char *vely_find_cookie (vely_input_req *req, char *cookie_name, num *ind, char **path, char **exp)
{
VV_TRACE ("");
num ci;
num name_len = strlen (cookie_name);
for (ci = 0; ci < req->num_of_cookies; ci++)
{
VV_TRACE("Checking cookie [%s] against [%s]", req->cookies[ci].data, cookie_name);
// Cookie (trimmed) must start with name=value. After that, other options may be in any order
// But it is always ; Path= ; Expires= etc. - we set those in this exact format. We don't get any of
// those from the server - we set them, so we can search easily.
if (!strncmp (req->cookies[ci].data, cookie_name, name_len) && req->cookies[ci].data[name_len] == '=')
{
if (ind != NULL) *ind = ci;
char *val = req->cookies[ci].data+name_len+1;
char *semi = strchr (val, ';');
char *ret = NULL;
if (semi == NULL)
{
ret = vely_strdup (val);
}
else
{
*semi = 0;
ret = vely_strdup (val);
*semi = ';';
}
if (path != NULL)
{
char *p = strcasestr (val, "; Path=");
if (p != NULL)
{
semi = strchr (p + 7, ';');
if (semi != NULL) *semi = 0;
*path = vely_strdup (p + 7);
if (semi != NULL) *semi = ';';
}
else
{
*path = NULL;
}
}
if (exp != NULL)
{
char *p = strcasestr (val, "; Expires=");
if (p != NULL)
{
semi = strchr (p + 10, ';');
if (semi != NULL) *semi = 0;
*exp = vely_strdup (p + 10);
if (semi != NULL) *semi = ';';
}
else
{
*exp = NULL;
}
}
return ret;
}
}
if (ind != NULL) *ind = -1;
return VV_EMPTY_STRING;
}
//
// Delete cookie with name cookie_name. req is input request. "Deleting" means setting value to 'deleted' and
// expiration day to Epoch start. But the cookies is still there and will be sent out in header response, however
// it won't come back since browser will delete it (due to expiration date and not because of 'deleted').
// Returns index in cookies[] array of the cookie we just deleted.
// cookies[].is_set_by_program is set to 1 if this is the cookie we deleted (i.e. not original in the web input).
// If path is specified, we use it; if not, we assume it was the same default one (which generally works unless
// you mix different paths, such as via different reverse proxies
num vely_delete_cookie (vely_input_req *req, char *cookie_name, char *path, char *secure)
{
VV_TRACE ("");
num ci;
char *rpath = NULL;
char *exp = NULL;
vely_find_cookie (req, cookie_name, &ci, &rpath, &exp);
if (ci != -1)
{
vely_free (req->cookies[ci].data);
char del_cookie[300];
char safety_clause[200];
vely_check_set_cookie (cookie_name, "deleted", secure, "", "", safety_clause, sizeof(safety_clause));
if (path != NULL) rpath=path;
if (rpath != NULL)
{
snprintf (del_cookie, sizeof (del_cookie), "%s=deleted; Path=%s; Max-Age=0; Expires=Thu, 01 Jan 1970 01:01:01 GMT%s", cookie_name, rpath, safety_clause);
}
else
{
snprintf (del_cookie, sizeof (del_cookie), "%s=deleted; Max-Age=0; Expires=Thu, 01 Jan 1970 01:01:01 GMT%s", cookie_name, safety_clause);
}
req->cookies[ci].data = vely_strdup (del_cookie);
req->cookies[ci].is_set_by_program = 1;
return ci;
}
return -1;
}
//
// Send header out. This does it only for web output, i.e. nothing happens for command line program.
// Only changed cookies are sent back (since unchanged ones are already in the browser). Cache is no-cache
// because the html output is ALWAYS generated. Cookies are secure if this is over https connection.
// Charset is always UTF-8.
//
// req can be NULL here, if called from oops page, or req may have very little data in it
// We send header out ONLY:
// 1. if explicitly called via vely_send_header or vely_output_http_header
// 2. it is an error
// 3. we send out a file
// This is important because we do NOT want to send header out just because some text is going
// out - this would break a lot of functionality, such as sending custom headers.
// HEADER MUST BE EXPLICITLY SENT OUT.
// If req->header is not-NULL (ctype, cache_control, status_id, status_text or control/value), then
// custom headers are sent out. This way any kind of header can be sent.
//
void vely_send_header(vely_input_req *req)
{
VV_TRACE("");
vely_header *header = req->header;
if (header!=NULL && header->ctype != NULL)
{
//
// Set custom content type if available
//
VV_TRACE("Setting custom content type for HTTP header (%s)", header->ctype);
vely_gen_set_content_type(header->ctype);
}
else
{
vely_gen_set_content_type("text/html;charset=utf-8");
}
if (header!=NULL && header->cache_control != NULL)
{
//
// Set custom cache control if available
//
VV_TRACE("Setting custom cache for HTTP header (%s)", header->cache_control);
vely_gen_add_header ("Cache-Control", header->cache_control);
}
else
{
// this is for output from VELY files only! for files, we cache-forever by default
vely_gen_add_header ("Cache-Control", "max-age=0, no-cache");
vely_gen_add_header ("Pragma", "no-cache");
VV_TRACE("Setting no cache for HTTP header (1)");
// the moment first actual data is sent, this is immediately flushed by fcgi?
}
//
// Set status if available
//
if (header!=NULL && header->status_id != 0 && header->status_text != NULL)
{
vely_gen_set_status (header->status_id, header->status_text);
} else vely_gen_set_status (200, "OK");
//
// Set any custom headers if available
//
if (header!=NULL)
{
// add any headers set from the caller
num i;
for (i = 0; i<VV_MAX_HTTP_HEADER; i++)
{
if (header->control[i]!=NULL && header->value[i]!=NULL)
{
// we use add_header because it allows multiple directives of the same kind
// but must not make duplicates of what's already there, except for Set-Cookie
vely_gen_add_header (header->control[i], header->value[i]);
}
else break;
}
}
}
//
// Flush trace.
//
void vely_flush_trace()
{
//
// Do Not Trace this call, as it's trace internal workings
//
//
// Make sure tracing is copied over to system buffers, such as before proceeding with error handling,
// just in case things go bad
//
vely_config *pc = vely_get_config();
if (pc != NULL && pc->trace.f != NULL)
{
fflush (pc->trace.f);
}
}
//
// Write error report when fatal error happens. errtext is the error text.
// Guard agains request being NULL. pc must NOT be NULL (the exec context)
//
void vely_write_ereport(char *errtext, vely_config *pc)
{
//
//
// !!
// req can be NULL here so must guard for it
// !!
// This is to display the request itself that is associated with the error
//
//
vely_input_req *req = pc->ctx.req;
// Static variables are fine (for keeping the stack reserved), but
// ONLY if they do not initialize! If they do, next time around (for
// the next request in fastcgi), they will NOT initialize, and they should.
static char log_file[300];
static char time[VV_TIME_LEN + 1];
static FILE *fout;
// End of OK static
vely_current_time (time, sizeof(time)-1);
snprintf (log_file, sizeof (log_file), "%s/backtrace", pc->app.trace_dir);
VV_TRACE ("Error has occurred, trying to open backtrace log [%s]", log_file);
fout = vely_fopen (log_file, "a+");
if (fout == NULL)
{
fout = vely_fopen (log_file, "w+");
if (fout == NULL)
{
VV_TRACE ("Cannot open report file, error [%s]", strerror(errno));
VV_FATAL ("Cannot open report file, error [%m]");
}
}
VV_TRACE ("Writing to backtrace log");
fseek (fout, 0, SEEK_END);
fprintf (fout, "%lld: %s: -------- BEGIN REPORT -------- \n", vely_getpid(), time);
VV_TRACE ("Writing PID");
fprintf (fout, "%lld: %s: URL: [%s][%s][%s]\n", vely_getpid(), time, vely_getenv("SCRIPT_NAME"), vely_getenv("PATH_INFO"), vely_getenv("QUERY_STRING"));
num i;
if (req != NULL && req->ip.ipars != NULL)
{
VV_TRACE ("Writing input params");
for (i = 0; i < req->ip.num_of_input_params; i++)
{
fprintf (fout, "%lld: %s: Param #%lld, [%s]: [%s]\n", vely_getpid(), time, i,
req->ip.ipars[i].name == NULL ? "NULL" : req->ip.ipars[i].name,
req->ip.ipars[i].value == NULL ? "NULL" : req->ip.ipars[i].value);
}
}
VV_TRACE ("Writing error information");
fprintf (fout, "%lld: %s: The trace of where the problem occurred:\n", vely_getpid(), time);
fclose (fout); // close because we will be writing to backtrace (which is fout) in vely_get_stack
VV_TRACE ("Getting stack");
vely_get_stack (log_file);
VV_TRACE ("Opening report file");
fout = vely_fopen (log_file, "a+"); // continue to write to backtrace
if (fout == NULL)
{
VV_TRACE ("Cannot open report file, error [%s]", strerror(errno));
VV_FATAL ("Cannot open report file, error [%m]");
}
fprintf (fout, "PID [%lld] TIME [%s] TRACE FILE [%s] ERROR: ***** %s *****\n", vely_getpid(), time, vely_get_config()->trace.fname, errtext);
fprintf (fout, "%lld: %s: -------- END REPORT -------- \n", vely_getpid(), time);
fclose (fout);
VV_TRACE ("Before skipping request");
vely_flush_trace();
}
//
// This is called when fatal error happens in program. Catches all errors, from program's report-error to SIGSEGV.
// Report an error in program. printf-like function that outputs error to trace file
// (if enabled). Backtrace files is also written. Exit code (for command line) is set to 99.
// After this, we don't exit, we jump to the end of request, so it will process the next request for FCGI
//
void _vely_report_error (char *format, ...)
{
VV_TRACE("");
vely_mem_os = false; // switch to managed memory though no new heap should be alloc'd
// THIS FUNCTION MUST NOT USE VV_MALLOC NOR MALLOC
// as it can be used to report out of memory errors
// get error message passed, format it into a single string
// This has no dependencies on pc or anything really
static char errtext[VV_MAX_ERR_LEN + 1];
va_list args;
va_start (args, format);
num err_len = vsnprintf (errtext, sizeof(errtext), format, args);
va_end (args);
vely_config *pc = vely_get_config();
if (pc == NULL)
{
VV_FATAL ("Program context is empty, error [%s]", errtext);
}
// when reporting error, any information traced here must go to the trace file, regardless
// of whether we trace or not. We reset tracelevel at the beginning of each request so it doesn't stay in tracing.
// trace the message - never needs to trace message just before report-error
pc->debug.trace_level = 1;
VV_TRACE ("Error: %s", errtext);
vely_flush_trace(); // flush because if things go bad, no trace (literally) is left to examine (same for below calls)
// Never error out more than once, if we do, say we did and move on to the next request
// UnLikely to happen but still
if (pc->ctx.vely_report_error_is_in_report == 1)
{
VV_TRACE ("Leaving error handling because an error happened during error handling [%s]", errtext);
vely_flush_trace();
// Reason for exiting: if rollback fails (in vely_check_transaction below)
// , then we would proceed to next request, and this can continue
// previous request's transaction, leading to corrupt data
VV_FATAL ("Fatal error during error reporting, error [%s]", errtext);
return; // should never happen
}
pc->ctx.vely_report_error_is_in_report = 1;
// Rollback any open transactions. Error can happen in there too, but if it dies, we exit the process (see above)
// rather than risk complications
vely_check_transaction (1);
vely_write_ereport (errtext, pc);
vely_flush_trace();
// send to stderr (for web client, goes to web server error log, for standalone to stderr)
// we will try to make 500 Server Error here, but if the header has already been output, it won't come out
// for example vely_bad_request() may have been done prior to this, or just out-header
vely_server_error();
// write to stderror (server log)
vely_gen_write (true, errtext, err_len);
vely_gen_write (true, "\n", 1);
//
//
// if this report-error happens anywhere outside a request, we will just start a new one
// Otherwise, close this request, release resources and process the next one (for FCGI).
//
//
vely_error_request(1);// go to process the next request
}
//
// Decode string encoded previously (web or url encoding). enc_type is VV_WEB or
// VV_URL. String v (which is encoded at the entry) holds decoded value on return.
// inlen is the number of bytes to decode, negative if all until null-char (strlen)
// Return value is the length of decoded string.
//
num vely_decode (num enc_type, char *v, num inlen)
{
VV_TRACE("");
if (inlen < 0) inlen = strlen (v);
num i;
num j = 0;
if (enc_type == VV_WEB)
{
for (i = 0; i < inlen; i ++)
{
if (v[i] == '&')
{
if (!strncmp (v+i+1, "amp;", 4))
{
v[j++] = '&';
i += 4;
}
else if (!strncmp (v+i+1, "quot;", 5))
{
v[j++] = '"';
i += 5;
}
else if (!strncmp (v+i+1, "apos;", 5))
{
v[j++] = '\'';
i += 5;
}
else if (!strncmp (v+i+1, "lt;", 3))
{
v[j++] = '<';
i += 3;
}
else if (!strncmp (v+i+1, "gt;", 3))
{
v[j++] = '>';
i += 3;
}
else v[j++] = v[i];
}
else
{
v[j++] = v[i];
}
}
v[j] = 0;
}
else if (enc_type == VV_URL)
{
// check if each examined hex digit is valid, and if not break and finish by setting 0 at the end
// this covers %X<null> pr %XY where X or Y are invalid of %<null> and such
// this macro is specific to the following loop only
#define URLDIG(x,r) if ((x) >='A' && (x) <= 'F') (r)=((x)-'A')+10;\
else if ((x) >='a' && (x) <= 'f') (r)=((x)-'a')+10;\
else if ((x) >='0' && (x) <= '9') (r)=(x)-'0';\
else break;
for (i = 0; i < inlen; i ++)
{
if (v[i] == '%')
{
int h;
int l;
URLDIG(v[i+1],h);
URLDIG(v[i+2],l);
v[j++] = h*16+l;
i+=2;
} else if (v[i] == '+')
{
v[j++] = ' ';
}
else
{
v[j++] = v[i];
}
}
v[j] = 0;
}
else
{
assert (1==2);
}
return j;
}
//
// Lock a file. filepath is the file. lock_fd is the file descriptor of the locked
// open file. Returns VV_OKAY if locked and other error codes if not.
// This is used for locking resources between various processes. Once a process exits,
// the lock is released - meaning if you fork() a process and then exit, the forked process
// will NOT have the lock.
//
num vely_lockfile(char *filepath, num *lock_fd)
{
VV_TRACE ("");
struct flock lock;
num fd;
/* Invalid path? */
if (filepath == NULL || *filepath == '\0')
{
VELY_ERR0;
return VV_ERR_INVALID;
}
/* Open the file. No checking for EINTR, as it is fatal in chandle.c */
fd = open(filepath, O_RDWR | O_CREAT, 0600);
if (fd == -1)
{
VELY_ERR;
return VV_ERR_CREATE;
}
/* Application must NOT close input/output/error, or those may get occupied*/
/* Exclusive lock, cover the entire file (regardless of size). */
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) == -1)
{
VELY_ERR;
/* Lock failed. Close file and report locking failure. */
close(fd);
return VV_ERR_FAILED;
}
if (lock_fd != NULL) *lock_fd = fd;
// success, the file is open and locked, and will remain locked until the process ends
// or until the caller does close (*lock_fd);
return VV_OKAY;
}
//
// Get input parameters from web input in the form of
// name/value pairs, meaning from a GET, POST, PUT, PATCH or DELETE (with OPTIONS to support for CORS).
// req is an input request
// If 'method' if NULL, environment REQUEST_METHOD is read, otherwise 'input' must be specified as input for query string.
// this is useful for passing URL from command line.
// For any method we read both body and query string. For some like GET, body is unusual but not forbidden.
// query string is based on environment variable QUERY_STRING
// Returns 1 if ok, 0 if not ok but handled (such as Forbidden), otherwise Errors out.
// Other information is obtained too such as HTTP_REFERRED that could be used to disallow
// viewing images unless referred to by this site (not a functionality here, it
// can be implemented in vely application).
// ETag/If-non-match is obtained for cache management. Cookies are obtained from the client
// ONLY the first time this is called in a request - we may alter cookies later, so if vely_get_input()
// is called again in the same request, cookies are NOT obtained again.
// Input parameters are stored in req variable, where they can be obtained from
// by the program. Files are uploaded automatically and are parameterized in the form of xxx_location, xxx_filename,
// xxx_ext, xxx_size, xxx_id. So if input parameter was myparam, it would be
// myparam_location, myparam_filename etc. _location is the local file path where file is
// stored. _filename is the actual HTML filename parameter. _ext is extension (with . in
// front of it, lower cased). _size is the size of the file. _id is the id produced by
// vely_get_document_id() and also id is what _location is based on. If file was empty, then
// all params but _filename are empty.
// If 'input' is specified, it overrides what's from QUERY_STRING. This is only if 'method' present.
//
num vely_get_input(vely_input_req *req, char *method, char *input)
{
VV_TRACE("");
req->ip.num_of_input_params = 0;
req->ip.ipars = NULL;
vely_config *pc = vely_get_config();
char *req_method = NULL;
char *qry = NULL;
char *cont_type = NULL;
char *cont_len = NULL;
num cont_len_byte = 0; // default zero if content-length not specified
char *content = NULL;
char *cookie = NULL;
req->ip.num_of_input_params = 0;
// some env vars are obtained right away, other are rarely used
// and are obtaineable from $$ variables
VV_STRDUP (req->referring_url, vely_getenv ("HTTP_REFERER"));
VV_TRACE ("Referer is [%s]", req->referring_url);
// when there is a redirection to home page, referring url is empty
char *sil = vely_getenv ("VV_SILENT_HEADER");
if (!strcmp (sil, "yes"))
{
req->silent = 1;
}
char *nm = vely_getenv ("HTTP_IF_NONE_MATCH");
if (nm[0] != 0)
{
VV_STRDUP (req->if_none_match, nm);
VV_TRACE("IfNoneMatch received [%s]", nm);
}
// this function is often called in "simulation" of a request. ONLY the first request gets cookies
// from the client (which is HTTP_COOKIE). After this first request, we may alter cookies in memory,
// and so we do NOT get cookies again from the client.
if (req->cookies == NULL)
{
// make a copy of cookies since we're going to change the string!
cookie = vely_strdup (vely_getenv ("HTTP_COOKIE"));
req->cookies = vely_calloc (VV_MAX_COOKIES, sizeof (vely_cookies)); // regardless of whether there are cookies in input or not
// since we can set them. This also SETS TO ZERO is_set_by_program which is a MUST, so HAVE to use vely_calloc.
if (cookie[0] != 0)
{
VV_TRACE ("Cookie [%s]", cookie);
num tot_cookies = 0;
while (1)
{
if (tot_cookies >= VV_MAX_COOKIES)
{
vely_bad_request();
vely_report_error("Too many cookies [%lld]", tot_cookies);
}
char *ew = strchr (cookie, ';');
if (ew != NULL)
{
*ew = 0;
ew++;
while (isspace(*ew)) ew++;
}
req->cookies[tot_cookies].data = vely_strdup (cookie);
VV_TRACE("Cookie [%s]",req->cookies[tot_cookies].data);
tot_cookies++;
if (ew == NULL) break;
cookie = ew;
}
req->num_of_cookies = tot_cookies;
}
else
{
req->num_of_cookies = 0;
}
}
// request method, GET or POST
// method, input override environment
// if method, 'input' will overrde QUERY_STRING
if (method != NULL)
{
req_method = method;
}
else
{
req_method = vely_getenv ("REQUEST_METHOD");
}
if (req_method[0] == 0)
{
vely_bad_request();
vely_report_error ("REQUEST_METHOD environment variable is not found");
}
num is_multipart = 0;
VV_TRACE ("Request Method: %s", req_method);
char *new_cont = (char*)vely_malloc (VV_MAX_SIZE_OF_URL + 1);
num new_cont_ptr = 0;
num would_write;
bool is_post = false;
bool is_patch = false;
bool is_get = false;
bool is_delete = false;
bool is_put = false;
bool is_other = false;
bool is_query_string = false; // is the body x-www-form-urlencoded
if (!strcasecmp(req_method, "POST")) {is_post=true;req->method=VV_POST;}
else if (!strcasecmp(req_method, "GET")) {is_get=true;req->method=VV_GET;}
else if (!strcasecmp(req_method, "PATCH")) {is_patch=true;req->method=VV_PATCH;}
else if (!strcasecmp(req_method, "PUT")) {is_put=true;req->method=VV_PUT;}
else if (!strcasecmp(req_method, "DELETE")) {is_delete=true;req->method=VV_DELETE;}
else {is_other=true;req->method=VV_OTHER;}
// content type is generally not specified for GET or DELETE, but it may be
// so this is generic processing with a few constraints
cont_type = vely_getenv ("CONTENT_TYPE");
// size of input data
cont_len = vely_getenv ("CONTENT_LENGTH");
if (cont_type[0] != 0)
{
// handle POST request, first check content type
// x-www-form-urlencoded and multipart/form-data are two content mime types that all clients
// must support. urlencode is for non-binary and multipart is when files are involved. It is
// one or the other. Per https://datatracker.ietf.org/doc/html/rfc7578, multipart/mixed is
// deprecated and is not implemented here.
char *mult = "multipart/form-data;";
char *mform = NULL;
if ((mform = strcasestr (cont_type, mult)) != NULL)
{
if (mform == cont_type || *(mform - 1) == ';' || isspace (*(mform - 1)))
{
is_multipart = 1;
}
}
if (!strcasecmp (cont_type, "application/x-www-form-urlencoded")) is_query_string = true;