-
Notifications
You must be signed in to change notification settings - Fork 0
/
webs.c
executable file
·3178 lines (2740 loc) · 71.6 KB
/
webs.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
/*
* webs.c -- GoAhead Embedded HTTP webs server
*
* Copyright (c) GoAhead Software Inc., 1995-2010. All Rights Reserved.
*
* See the file "license.txt" for usage and redistribution license requirements
*
*/
/******************************** Description *********************************/
/*
* This module implements an embedded HTTP/1.1 web server. It supports
* loadable URL handlers that define the nature of URL processing performed.
*/
/********************************* Includes ***********************************/
#include "wsIntrn.h"
#ifdef DIGEST_ACCESS_SUPPORT
#include "websda.h"
#endif
extern socket_t **socketList; /* List of open sockets */
/******************************** Global Data *********************************/
websStatsType websStats; /* Web access stats */
webs_t *webs; /* Open connection list head */
sym_fd_t websMime; /* Set of mime types */
int websMax; /* List size */
int websPort; /* Listen port for server */
char_t websHost[64]; /* Host name for the server */
char_t websIpaddr[64]; /* IP address for the server */
char_t *websHostUrl = NULL; /* URL to access server */
char_t *websIpaddrUrl = NULL; /* URL to access server */
/*********************************** Locals ***********************************/
/*
* Standard HTTP error codes
*/
websErrorType websErrors[] = {
{ 200, T("Data follows") },
{ 204, T("No Content") },
{ 301, T("Redirect") },
{ 302, T("Redirect") },
{ 304, T("Use local copy") },
{ 400, T("Page not found") },
{ 401, T("Unauthorized") },
{ 403, T("Forbidden") },
{ 404, T("Site or Page Not Found") },
{ 405, T("Access Denied") },
{ 500, T("Web Error") },
{ 501, T("Not Implemented") },
{ 503, T("Site Temporarily Unavailable. Try again.") },
{ 0, NULL }
};
#ifdef WEBS_LOG_SUPPORT
static char_t websLogname[64] = T("log.txt"); /* Log filename */
static int websLogFd; /* Log file handle */
#endif
#ifdef WEBS_TRACE_SUPPORT
static char_t websTracename[64] = T("trace.txt"); /* Log filename */
static int websTraceFd; /* Log file handle */
#endif
static int websListenSock; /* Listen socket */
static char_t websRealm[64] = T("GoAhead"); /* Realm name */
static int websOpenCount = 0; /* count of apps using this module */
/**************************** Forward Declarations ****************************/
/*static char_t *websErrorMsg(int code);*/
static int websGetInput(webs_t wp, char_t **ptext, int *nbytes);
static int websParseFirst(webs_t wp, char_t *text);
static void websParseRequest(webs_t wp);
static void websSocketEvent(int sid, int mask, void* data);
static int websGetTimeSinceMark(webs_t wp);
#ifdef WEBS_LOG_SUPPORT
static void websLog(webs_t wp, int code);
#endif
#ifdef WEBS_TRACE_SUPPORT
static void traceHandler(int level, char_t *buf);
#endif
#ifdef WEBS_IF_MODIFIED_SUPPORT
static time_t dateParse(time_t tip, char_t *cmd);
#endif
/*********************************** Code *************************************/
/*
* Open the GoAhead WebServer
*/
int websOpenServer(int port, int retries)
{
websMimeType *mt;
if (++websOpenCount != 1) {
return websPort;
}
a_assert(port > 0);
a_assert(retries >= 0);
websDefaultOpen();
#ifdef WEBS_PAGE_ROM
websRomOpen();
#endif
webs = NULL;
websMax = 0;
/*
* Create a mime type lookup table for quickly determining the content type
*/
websMime = symOpen(WEBS_SYM_INIT * 4);
a_assert(websMime >= 0);
for (mt = websMimeList; mt->type; mt++) {
symEnter(websMime, mt->ext, valueString(mt->type, 0), 0);
}
/*
* Open the URL handler module. The caller should create the required
* URL handlers after calling this function.
*/
if (websUrlHandlerOpen() < 0) {
return -1;
}
websFormOpen();
#ifdef WEBS_LOG_SUPPORT
/*
* Optional request log support
*/
#ifndef VXWORKS
websLogFd = gopen(websLogname, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY,
0666);
#else
websLogFd = gopen(websLogname, O_CREAT | O_TRUNC | O_WRONLY, 0666);
lseek(fd, 0, SEEK_END);
#endif /* VXWORKS */
a_assert(websLogFd >= 0);
#endif
#ifdef WEBS_TRACE_SUPPORT
/*
* Optional trace support
*/
#ifndef VXWORKS
websTraceFd = gopen(websTracename, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY,
0666);
#else
websTraceFd = gopen(websTracename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
lseek(fd, 0, SEEK_END);
#endif /* VXWORKS */
a_assert(websTraceFd >= 0);
traceSetHandler(traceHandler);
#endif
return websOpenListen(port, retries);
}
/******************************************************************************/
/*
* Close the GoAhead WebServer
*/
void websCloseServer()
{
webs_t wp;
int wid;
if (--websOpenCount > 0) {
return;
}
/*
* Close the listen handle first then all open connections.
*/
websCloseListen();
/*
* Close each open browser connection and free all resources
*/
for (wid = websMax; webs && wid >= 0; wid--) {
if ((wp = webs[wid]) == NULL) {
continue;
}
socketCloseConnection(wp->sid);
websFree(wp);
}
#ifdef WEBS_LOG_SUPPORT
if (websLogFd >= 0) {
close(websLogFd);
websLogFd = -1;
}
#endif
#ifdef WEBS_TRACE_SUPPORT
if (websTraceFd >= 0) {
close(websTraceFd);
websTraceFd = -1;
}
#endif
#ifdef WEBS_PAGE_ROM
websRomClose();
#endif
websDefaultClose();
symClose(websMime);
websFormClose();
websUrlHandlerClose();
}
/******************************************************************************/
/*
* Open the GoAhead WebServer listen port
*/
int websOpenListen(int port, int retries)
{
int i, orig;
a_assert(port > 0);
a_assert(retries >= 0);
orig = port;
/*
* Open the webs webs listen port. If we fail, try the next port.
*/
for (i = 0; i <= retries; i++) {
websListenSock = socketOpenConnection(NULL, port, websAccept, 0);
if (websListenSock >= 0) {
break;
}
port++;
}
if (i > retries) {
error(E_L, E_USER, T("Couldn't open a socket on ports %d - %d"),
orig, port - 1);
return -1;
}
/*
* Determine the full URL address to access the home page for this web server
*/
websPort = port;
bfreeSafe(B_L, websHostUrl);
bfreeSafe(B_L, websIpaddrUrl);
websIpaddrUrl = websHostUrl = NULL;
if (port == 80) {
websHostUrl = bstrdup(B_L, websHost);
websIpaddrUrl = bstrdup(B_L, websIpaddr);
} else {
fmtAlloc(&websHostUrl, WEBS_MAX_URL + 80, T("%s:%d"), websHost, port);
fmtAlloc(&websIpaddrUrl, WEBS_MAX_URL + 80, T("%s:%d"),
websIpaddr, port);
}
trace(0, T("webs: Listening for HTTP requests at address %s\n"),
websIpaddrUrl);
return port;
}
/******************************************************************************/
/*
* Close webs listen port
*/
void websCloseListen()
{
if (websListenSock >= 0) {
socketCloseConnection(websListenSock);
websListenSock = -1;
}
bfreeSafe(B_L, websHostUrl);
bfreeSafe(B_L, websIpaddrUrl);
websIpaddrUrl = websHostUrl = NULL;
}
/******************************************************************************/
/*
* Accept a connection
*/
int websAccept(int sid, char *ipaddr, int port, int listenSid)
{
webs_t wp;
int wid;
struct sockaddr_in ifAddr;
int len;
char *pString;
a_assert(ipaddr && *ipaddr);
a_assert(sid >= 0);
a_assert(port >= 0);
/*
* Allocate a new handle for this accepted connection. This will allocate
* a webs_t structure in the webs[] list
*/
if ((wid = websAlloc(sid)) < 0) {
return -1;
}
wp = webs[wid];
a_assert(wp);
wp->listenSid = listenSid;
ascToUni(wp->ipaddr, ipaddr, min(sizeof(wp->ipaddr), strlen(ipaddr) + 1));
/*
* Get the ip address of the interface that acept the connection.
*/
len = sizeof(struct sockaddr_in);
if (getsockname(socketList[sid]->sock, (struct sockaddr *)&ifAddr, (socklen_t *) &len) < 0)
return -1;
pString = inet_ntoa(ifAddr.sin_addr);
gstrncpy(wp->ifaddr, pString, gstrlen(pString));
/*
* Check if this is a request from a browser on this system. This is useful
* to know for permitting administrative operations only for local access
*/
if (gstrcmp(wp->ipaddr, T("127.0.0.1")) == 0 ||
gstrcmp(wp->ipaddr, websIpaddr) == 0 ||
gstrcmp(wp->ipaddr, websHost) == 0) {
wp->flags |= WEBS_LOCAL_REQUEST;
}
/*
* Arrange for websSocketEvent to be called when read data is available
*/
socketCreateHandler(sid, SOCKET_READABLE, websSocketEvent, wp);
/*
* Arrange for a timeout to kill hung requests
*/
wp->timeout = emfSchedCallback(WEBS_TIMEOUT, websTimeout, (void *) wp);
trace(8, T("webs: accept request\n"));
return 0;
}
/******************************************************************************/
/*
* The webs socket handler. Called in response to I/O. We just pass control
* to the relevant read or write handler. A pointer to the webs structure
* is passed as a (void*) in iwp.
*/
static void websSocketEvent(int sid, int mask, void* iwp)
{
webs_t wp;
wp = (webs_t) iwp;
a_assert(wp);
if (! websValid(wp)) {
return;
}
if (mask & SOCKET_READABLE) {
websReadEvent(wp);
}
if (mask & SOCKET_WRITABLE) {
if (websValid(wp) && wp->writeSocket) {
(*wp->writeSocket)(wp);
}
}
}
/******************************************************************************/
/*
* The webs read handler. This is the primary read event loop. It uses a
* state machine to track progress while parsing the HTTP request.
* Note: we never block as the socket is always in non-blocking mode.
*/
void websReadEvent(webs_t wp)
{
char_t *text;
int rc, nbytes, len, done, fd, size;
a_assert(wp);
a_assert(websValid(wp));
websSetTimeMark(wp);
/*
* Read as many lines as possible. socketGets is called to read the header
* and socketRead is called to read posted data.
*/
text = NULL;
fd = -1;
for (done = 0; !done; ) {
if (text) {
bfree(B_L, text);
text = NULL;
}
/*
* Get more input into "text". Returns 0, if more data is needed
* to continue, -1 if finished with the request, or 1 if all
* required data is available for current state.
*/
while ((rc = websGetInput(wp, &text, &nbytes)) == 0) {
;
}
/*
* websGetInput returns -1 if it finishes with the request
*/
if (rc < 0) {
break;
}
/*
* This is the state machine for the web server.
*/
switch(wp->state) {
case WEBS_BEGIN:
/*
* Parse the first line of the Http header
*/
if (websParseFirst(wp, text) < 0) {
done++;
break;
}
wp->state = WEBS_HEADER;
break;
case WEBS_HEADER:
/*
* Store more of the HTTP header. As we are doing line reads, we
* need to separate the lines with '\n'
*/
if (ringqLen(&wp->header) > 0) {
ringqPutStr(&wp->header, T("\n"));
}
ringqPutStr(&wp->header, text);
break;
case WEBS_POST_CLEN:
/*
* POST request with content specified by a content length.
* If this is a CGI request, write the data to the cgi stdin.
* socketGets was used to get the data and it strips \n's so
* add them back in here.
*/
#ifndef __NO_CGI_BIN
if (wp->flags & WEBS_CGI_REQUEST) {
if (fd == -1) {
#if !defined(WIN32)
fd = gopen(wp->cgiStdin, O_CREAT | O_WRONLY | O_BINARY,
0666);
#else
_sopen_s(&fd, wp->cgiStdin, O_CREAT | O_WRONLY | O_BINARY, _SH_DENYNO, 0666);
#endif
}
gwrite(fd, text, nbytes);
/*
* NOTE that the above comment is wrong -- if the content length
* is set, websGetInput() does NOT use socketGets(), it uses
* socketRead(), so the line below that adds an additional newline
* is destructive.
*/
/*gwrite(fd, T("\n"), sizeof(char_t));*/
/*
* Line removed as per BUG02488
*
nbytes += 1;
*/
} else
#endif
if (wp->query) {
if (wp->query[0] && !(wp->flags & WEBS_POST_DATA)) {
/*
* Special case where the POST request also had query data
* specified in the URL, ie. url?query_data. In this case
* the URL query data is separated by a '&' from the posted
* query data.
*/
len = gstrlen(wp->query);
if (text) {
size = (len + gstrlen(text) + 2) * sizeof(char_t);
wp->query = brealloc(B_L, wp->query,
size);
wp->query[len++] = '&';
#if !defined(WIN32)
strcpy(&wp->query[len], text);
#else
strcpy_s(&wp->query[len], size - len, text);
#endif
}
} else {
/*
* The existing query data came from the POST request so just
* append it.
*/
if (text != NULL)
{
len = gstrlen(wp->query);
size = (len + gstrlen(text) + 1) * sizeof(char_t);
wp->query = brealloc(B_L, wp->query, size);
if (wp->query) {
#if !defined(WIN32)
gstrcpy(&wp->query[len], text);
#else
strcpy_s(&wp->query[len], size - len, text);
#endif
}
}
}
} else {
wp->query = bstrdup(B_L, text);
}
/*
* Calculate how much more post data is to be read.
*/
wp->flags |= WEBS_POST_DATA;
wp->clen -= nbytes;
if (wp->clen > 0) {
if (nbytes > 0) {
break;
}
done++;
break;
}
/*
* No more data so process the request, (but be sure to close
* the input file first!).
*/
if (fd != -1) {
gclose (fd);
fd = -1;
}
websUrlHandlerRequest(wp);
done++;
break;
case WEBS_POST:
/*
* POST without content-length specification
* If this is a CGI request, write the data to the cgi stdin.
* socketGets was used to get the data and it strips \n's so
* add them back in here.
*/
#ifndef __NO_CGI_BIN
if (wp->flags & WEBS_CGI_REQUEST) {
if (fd == -1) {
#if !defined(WIN32)
fd = gopen(wp->cgiStdin, O_CREAT | O_WRONLY | O_BINARY,
0666);
#else
_sopen_s(&fd, wp->cgiStdin, O_CREAT | O_WRONLY | O_BINARY,
_SH_DENYNO, 0666);
#endif
}
gwrite(fd, text, nbytes);
gwrite(fd, T("\n"), sizeof(char_t));
} else
#endif
if (wp->query && *wp->query && !(wp->flags & WEBS_POST_DATA)) {
len = gstrlen(wp->query);
size = (len + gstrlen(text) + 2) * sizeof(char_t);
wp->query = brealloc(B_L, wp->query, size);
if (wp->query) {
wp->query[len++] = '&';
#if !defined(WIN32)
gstrcpy(&wp->query[len], text);
#else
strcpy_s(&wp->query[len], size - len, text);
#endif
}
} else {
wp->query = bstrdup(B_L, text);
}
wp->flags |= WEBS_POST_DATA;
done++;
break;
default:
websError(wp, 404, T("Bad state"));
done++;
break;
}
}
if (fd != -1) {
fd = gclose (fd);
}
if (text) {
bfree(B_L, text);
}
}
/******************************************************************************/
/*
* Get input from the browser. Return TRUE (!0) if the request has been
* handled. Return -1 on errors or if the request has been processed,
* 1 if input read, and 0 to instruct the caller to call again for more input.
*
* Note: socketRead will Return the number of bytes read if successful. This
* may be less than the requested "bufsize" and may be zero. It returns -1 for
* errors. It returns 0 for EOF. Otherwise it returns the number of bytes
* read. Since this may be zero, callers should use socketEof() to
* distinguish between this and EOF.
*/
static int websGetInput(webs_t wp, char_t **ptext, int *pnbytes)
{
char_t *text;
char buf[WEBS_SOCKET_BUFSIZ+1];
int nbytes, len, clen;
a_assert(websValid(wp));
a_assert(ptext);
a_assert(pnbytes);
*ptext = text = NULL;
*pnbytes = 0;
/*
* If this request is a POST with a content length, we know the number
* of bytes to read so we use socketRead().
*/
if (wp->state == WEBS_POST_CLEN) {
len = (wp->clen > WEBS_SOCKET_BUFSIZ) ? WEBS_SOCKET_BUFSIZ : wp->clen;
} else {
len = 0;
}
if (len > 0) {
#ifdef WEBS_SSL_SUPPORT
if (wp->flags & WEBS_SECURE) {
nbytes = websSSLRead(wp->wsp, buf, len);
} else {
nbytes = socketRead(wp->sid, buf, len);
}
#else
nbytes = socketRead(wp->sid, buf, len);
#endif
if (nbytes < 0) { /* Error */
websDone(wp, 0);
return -1;
} else if (nbytes == 0) { /* EOF or No data available */
/*
* Infinite CPU usage if not all post data is sent.
* This is a side-effect of socketRead whose return value does not
* distinguish between EOF and no-data and we have to explicitly use
* the socketEof() to test for it.
*/
if (socketEof(wp->sid)) {
websDone(wp, 0);
}
return -1;
} else { /* Valid data */
/*
* Convert to UNICODE if necessary. First be sure the string
* is NULL terminated.
*/
buf[nbytes] = '\0';
if ((text = ballocAscToUni(buf, nbytes)) == NULL) {
websError(wp, 503, T("Insufficient memory"));
return -1;
}
}
} else {
#ifdef WEBS_SSL_SUPPORT
if (wp->flags & WEBS_SECURE) {
nbytes = websSSLGets(wp->wsp, &text);
} else {
nbytes = socketGets(wp->sid, &text);
}
#else
nbytes = socketGets(wp->sid, &text);
#endif
if (nbytes < 0) {
int eof;
/*
* Error, EOF or incomplete
*/
#ifdef WEBS_SSL_SUPPORT
if (wp->flags & WEBS_SECURE) {
/*
* If state is WEBS_BEGIN and the request is secure, a -1 will
* usually indicate SSL negotiation
*/
if (wp->state == WEBS_BEGIN) {
eof = 1;
} else {
eof = websSSLEof(wp->wsp);
}
} else {
eof = socketEof(wp->sid);
}
#else
eof = socketEof(wp->sid);
#endif
if (eof) {
/*
* If this is a post request without content length, process
* the request as we now have all the data. Otherwise just
* close the connection.
*/
if (wp->state == WEBS_POST) {
websUrlHandlerRequest(wp);
} else {
websDone(wp, 0);
}
} else {
/*
* If an error occurred and it wasn't an eof, close the connection
*/
#ifdef HP_FIX
websDone(wp, 0);
#endif /*HP_FIX*/
}
/*
* If state is WEBS_HEADER and the ringq is empty, then this is a
* simple request with no additional header fields to process and
* no empty line terminator.
*/
/*
* NOTE: this fix for earlier versions of browsers is troublesome
* because if we don't receive the entire header in the first pass
* this code assumes we were only expecting a one line header, which
* is not necessarily the case. So we weren't processing the whole
* header and weren't fufilling requests properly.
*/
return -1;
} else if (nbytes == 0) {
if (wp->state == WEBS_HEADER) {
/*
* Valid empty line, now finished with header
*/
websParseRequest(wp);
if (wp->flags & WEBS_POST_REQUEST) {
if (wp->flags & WEBS_CLEN) {
wp->state = WEBS_POST_CLEN;
clen = wp->clen;
} else {
wp->state = WEBS_POST;
clen = 1;
}
if (clen > 0) {
/*
* Return 0 to get more data.
*/
return 0;
}
return 1;
}
/*
* We've read the header so go and handle the request
*/
websUrlHandlerRequest(wp);
}
return -1;
}
}
a_assert(text);
a_assert(nbytes > 0);
*ptext = text;
*pnbytes = nbytes;
return 1;
}
/******************************************************************************/
/*
* Parse the first line of a HTTP request
*/
static int websParseFirst(webs_t wp, char_t *text)
{
char_t *op, *proto, *protoVer, *url, *host, *query, *path, *port, *ext;
char_t *buf;
int testPort;
a_assert(websValid(wp));
a_assert(text && *text);
/*
* Determine the request type: GET, HEAD or POST
*/
op = gstrtok(text, T(" \t"));
if (op == NULL || *op == '\0') {
websError(wp, 400, T("Bad HTTP request"));
return -1;
}
if (gstrcmp(op, T("GET")) != 0) {
if (gstrcmp(op, T("POST")) == 0) {
wp->flags |= WEBS_POST_REQUEST;
} else if (gstrcmp(op, T("HEAD")) == 0) {
wp->flags |= WEBS_HEAD_REQUEST;
} else {
websError(wp, 400, T("Bad request type"));
return -1;
}
}
/*
* Store result in the form (CGI) variable store
*/
websSetVar(wp, T("REQUEST_METHOD"), op);
url = gstrtok(NULL, T(" \t\n"));
if (url == NULL || *url == '\0') {
websError(wp, 400, T("Bad HTTP request"));
return -1;
}
protoVer = gstrtok(NULL, T(" \t\n"));
/*
* Parse the URL and store all the various URL components. websUrlParse
* returns an allocated buffer in buf which we must free. We support both
* proxied and non-proxied requests. Proxied requests will have http://host/
* at the start of the URL. Non-proxied will just be local path names.
*/
host = path = port = proto = query = ext = NULL;
if (websUrlParse(url, &buf, &host, &path, &port, &query, &proto,
NULL, &ext) < 0) {
websError(wp, 400, T("Bad URL format"));
return -1;
}
wp->url = bstrdup(B_L, url);
#ifndef __NO_CGI_BIN
if (gstrstr(url, CGI_BIN) != NULL) {
wp->flags |= WEBS_CGI_REQUEST;
if (wp->flags & WEBS_POST_REQUEST) {
wp->cgiStdin = websGetCgiCommName();
}
}
#endif
wp->query = bstrdup(B_L, query);
wp->host = bstrdup(B_L, host);
wp->path = bstrdup(B_L, path);
wp->protocol = bstrdup(B_L, proto);
wp->protoVersion = bstrdup(B_L, protoVer);
if ((testPort = socketGetPort(wp->listenSid)) >= 0) {
wp->port = testPort;
} else {
wp->port = gatoi(port);
}
if (gstrcmp(ext, T(".asp")) == 0) {
wp->flags |= WEBS_ASP;
}
bfree(B_L, buf);
websUrlType(url, wp->type, TSZ(wp->type));
#ifdef WEBS_PROXY_SUPPORT
/*
* Determine if this is a request for local webs data. If it is not a proxied
* request from the browser, we won't see the "http://" or the system name, so
* we assume it must be talking to us directly for local webs data.
* Note: not fully implemented yet.
*/
if (gstrstr(wp->url, T("http://")) == NULL ||
((gstrcmp(wp->host, T("localhost")) == 0 ||
gstrcmp(wp->host, websHost) == 0) && (wp->port == websPort))) {
wp->flags |= WEBS_LOCAL_PAGE;
if (gstrcmp(wp->path, T("/")) == 0) {
wp->flags |= WEBS_HOME_PAGE;
}
}
#endif
ringqFlush(&wp->header);
return 0;
}
/******************************************************************************/
/*
* Parse a full request
*/
#define isgoodchar(s) (gisalnum((s)) || ((s) == '/') || ((s) == '_') || \
((s) == '.') || ((s) == '-') )
static void websParseRequest(webs_t wp)
{
char_t *authType, *upperKey, *cp, *browser, *lp, *key, *value;
a_assert(websValid(wp));
/*
* Define default CGI values
*/
websSetVar(wp, T("HTTP_AUTHORIZATION"), T(""));
/*
* Parse the header and create the Http header keyword variables
* We rewrite the header as we go for non-local requests. NOTE: this
* modifies the header string directly and tokenizes each line with '\0'.
*/
browser = NULL;
for (lp = (char_t*) wp->header.servp; lp && *lp; ) {
cp = lp;
if ((lp = gstrchr(lp, '\n')) != NULL) {
lp++;
}
if ((key = gstrtok(cp, T(": \t\n"))) == NULL) {
continue;
}
if ((value = gstrtok(NULL, T("\n"))) == NULL) {
value = T("");
}
while (gisspace(*value)) {
value++;
}
strlower(key);
/*
* Create a variable (CGI) for each line in the header
*/
fmtAlloc(&upperKey, (gstrlen(key) + 6), T("HTTP_%s"), key);
for (cp = upperKey; *cp; cp++) {
if (*cp == '-')
*cp = '_';
}
strupper(upperKey);
websSetVar(wp, upperKey, value);
bfree(B_L, upperKey);
/*
* Track the requesting agent (browser) type
*/
if (gstrcmp(key, T("user-agent")) == 0) {
wp->userAgent = bstrdup(B_L, value);
/*
* Parse the user authorization. ie. password
*/
} else if (gstricmp(key, T("authorization")) == 0) {
/*
* Determine the type of Authorization Request
*/
authType = bstrdup (B_L, value);
a_assert (authType);
/*
* Truncate authType at the next non-alpha character
*/
cp = authType;
while (gisalpha(*cp)) {
cp++;
}
*cp = '\0';
wp->authType = bstrdup(B_L, authType);
bfree(B_L, authType);
if (gstricmp(wp->authType, T("basic")) == 0) {
char_t userAuth[FNAMESIZE];
/*
* The incoming value is username:password (Basic authentication)
*/
if ((cp = gstrchr(value, ' ')) != NULL) {
*cp = '\0';
/*
* bugfix 5/24/02 -- we were leaking the memory pointed to by
* wp->authType that was allocated just before the if()
* statement that we are currently in. Thanks to Simon Byholm.
*/
bfree(B_L, wp->authType);
wp->authType = bstrdup(B_L, value);
websDecode64(userAuth, ++cp, sizeof(userAuth));
} else {
websDecode64(userAuth, value, sizeof(userAuth));
}
/*
* Split userAuth into userid and password
*/
if ((cp = gstrchr(userAuth, ':')) != NULL) {