1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 /* sws.c: simple (silly?) web server
25 This code was originally graciously donated to the project by Juergen
26 Wilke. Thanks a bunch!
30 #define CURL_NO_OLDIES
32 #include "setup.h" /* portability help from the lib directory */
40 #ifdef HAVE_SYS_SOCKET_H
41 #include <sys/socket.h>
43 #ifdef HAVE_NETINET_IN_H
44 #include <netinet/in.h>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
52 #ifdef HAVE_NETINET_TCP_H
53 #include <netinet/tcp.h> /* for TCP_NODELAY */
56 #define ENABLE_CURLX_PRINTF
57 /* make the curlx header define all printf() functions to use the curlx_*
59 #include "curlx.h" /* from the private lib dir */
62 #include "server_sockaddr.h"
64 /* include memdebug.h last */
67 #if !defined(CURL_SWS_FORK_ENABLED) && defined(HAVE_FORK)
69 * The normal sws build for the plain standard curl test suite has no use for
70 * fork(), but if you feel wild and crazy and want to setup some more exotic
71 * tests. Define this and run...
73 #define CURL_SWS_FORK_ENABLED
77 static bool use_ipv6 = FALSE;
79 static bool use_gopher = FALSE;
80 static const char *ipv_inuse = "IPv4";
81 static int serverlogslocked = 0;
83 #define REQBUFSIZ 150000
84 #define REQBUFSIZ_TXT "149999"
86 static long prevtestno=-1; /* previous test number we served */
87 static long prevpartno=-1; /* previous part number we served */
88 static bool prevbounce=FALSE; /* instructs the server to increase the part
89 number for a test in case the identical
90 testno+partno request shows up again */
92 #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */
93 #define RCMD_IDLE 1 /* told to sit idle */
94 #define RCMD_STREAM 2 /* told to stream */
97 char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */
98 size_t checkindex; /* where to start checking of the request */
99 size_t offset; /* size of the incoming request */
100 long testno; /* test number found in the request */
101 long partno; /* part number found in the request */
102 bool open; /* keep connection open info, as found in the request */
103 bool auth_req; /* authentication required, don't wait for body unless
104 there's an Authorization header */
105 bool auth; /* Authorization header present in the incoming request */
106 size_t cl; /* Content-Length of the incoming request */
107 bool digest; /* Authorization digest header found */
108 bool ntlm; /* Authorization ntlm header found */
109 int writedelay; /* if non-zero, delay this number of seconds between
110 writes in the response */
111 int pipe; /* if non-zero, expect this many requests to do a "piped"
113 int skip; /* if non-zero, the server is instructed to not read this
114 many bytes from a PUT/POST request. Ie the client sends N
115 bytes said in Content-Length, but the server only reads N
117 int rcmd; /* doing a special command, see defines above */
118 int prot_version; /* HTTP version * 10 */
119 bool pipelining; /* true if request is pipelined */
122 static int ProcessRequest(struct httprequest *req);
123 static void storerequest(char *reqbuf, size_t totalsize);
125 #define DEFAULT_PORT 8999
127 #ifndef DEFAULT_LOGFILE
128 #define DEFAULT_LOGFILE "log/sws.log"
131 const char *serverlogfile = DEFAULT_LOGFILE;
133 #define SWSVERSION "cURL test suite HTTP server/0.1"
135 #define REQUEST_DUMP "log/server.input"
136 #define RESPONSE_DUMP "log/server.response"
138 /* very-big-path support */
139 #define MAXDOCNAMELEN 140000
140 #define MAXDOCNAMELEN_TXT "139999"
142 #define REQUEST_KEYWORD_SIZE 256
143 #define REQUEST_KEYWORD_SIZE_TXT "255"
145 #define CMD_AUTH_REQUIRED "auth_required"
147 /* 'idle' means that it will accept the request fine but never respond
148 any data. Just keep the connection alive. */
149 #define CMD_IDLE "idle"
151 /* 'stream' means to send a never-ending stream of data */
152 #define CMD_STREAM "stream"
154 #define END_OF_HEADERS "\r\n\r\n"
157 DOCNUMBER_NOTHING = -7,
159 DOCNUMBER_BADCONNECT = -5,
160 DOCNUMBER_INTERNAL= -4,
161 DOCNUMBER_CONNECT = -3,
162 DOCNUMBER_WERULEZ = -2,
166 static const char *end_of_headers = END_OF_HEADERS;
168 /* sent as reply to a QUIT */
169 static const char *docquit =
170 "HTTP/1.1 200 Goodbye" END_OF_HEADERS;
172 /* sent as reply to a CONNECT */
173 static const char *docconnect =
174 "HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS;
176 /* sent as reply to a "bad" CONNECT */
177 static const char *docbadconnect =
178 "HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS;
180 /* send back this on 404 file not found */
181 static const char *doc404 = "HTTP/1.1 404 Not Found\r\n"
182 "Server: " SWSVERSION "\r\n"
183 "Connection: close\r\n"
184 "Content-Type: text/html"
186 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
188 "<TITLE>404 Not Found</TITLE>\n"
190 "<H1>Not Found</H1>\n"
191 "The requested URL was not found on this server.\n"
192 "<P><HR><ADDRESS>" SWSVERSION "</ADDRESS>\n" "</BODY></HTML>\n";
194 /* do-nothing macro replacement for systems which lack siginterrupt() */
196 #ifndef HAVE_SIGINTERRUPT
197 #define siginterrupt(x,y) do {} while(0)
200 /* vars used to keep around previous signal handlers */
202 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
205 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
209 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
213 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
217 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
221 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
224 /* var which if set indicates that the program should finish execution */
226 SIG_ATOMIC_T got_exit_signal = 0;
228 /* if next is set indicates the first signal handled in exit_signal_handler */
230 static volatile int exit_signal = 0;
232 /* signal handler that will be triggered to indicate that the program
233 should finish its execution in a controlled manner as soon as possible.
234 The first time this is called it will set got_exit_signal to one and
235 store in exit_signal the signal that triggered its execution. */
237 static RETSIGTYPE exit_signal_handler(int signum)
239 int old_errno = ERRNO;
240 if(got_exit_signal == 0) {
242 exit_signal = signum;
244 (void)signal(signum, exit_signal_handler);
245 SET_ERRNO(old_errno);
248 static void install_signal_handlers(void)
251 /* ignore SIGHUP signal */
252 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
253 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
256 /* ignore SIGPIPE signal */
257 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
258 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
261 /* ignore SIGALRM signal */
262 if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
263 logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
266 /* handle SIGINT signal with our exit_signal_handler */
267 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
268 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
270 siginterrupt(SIGINT, 1);
273 /* handle SIGTERM signal with our exit_signal_handler */
274 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
275 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
277 siginterrupt(SIGTERM, 1);
281 static void restore_signal_handlers(void)
284 if(SIG_ERR != old_sighup_handler)
285 (void)signal(SIGHUP, old_sighup_handler);
288 if(SIG_ERR != old_sigpipe_handler)
289 (void)signal(SIGPIPE, old_sigpipe_handler);
292 if(SIG_ERR != old_sigalrm_handler)
293 (void)signal(SIGALRM, old_sigalrm_handler);
296 if(SIG_ERR != old_sigint_handler)
297 (void)signal(SIGINT, old_sigint_handler);
300 if(SIG_ERR != old_sigterm_handler)
301 (void)signal(SIGTERM, old_sigterm_handler);
305 static int ProcessRequest(struct httprequest *req)
307 char *line=&req->reqbuf[req->checkindex];
308 bool chunked = FALSE;
309 static char request[REQUEST_KEYWORD_SIZE];
310 static char doc[MAXDOCNAMELEN];
312 int prot_major, prot_minor;
315 end = strstr(line, end_of_headers);
317 logmsg("ProcessRequest() called");
319 /* try to figure out the request characteristics as soon as possible, but
323 (req->testno == DOCNUMBER_NOTHING) &&
324 !strncmp("/verifiedserver", line, 15)) {
325 logmsg("Are-we-friendly question received");
326 req->testno = DOCNUMBER_WERULEZ;
330 else if((req->testno == DOCNUMBER_NOTHING) &&
332 "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
339 req->prot_version = prot_major*10 + prot_minor;
341 /* find the last slash */
342 ptr = strrchr(doc, '/');
344 /* get the number after it */
349 if((strlen(doc) + strlen(request)) < 200)
350 sprintf(logbuf, "Got request: %s %s HTTP/%d.%d",
351 request, doc, prot_major, prot_minor);
353 sprintf(logbuf, "Got a *HUGE* request HTTP/%d.%d",
354 prot_major, prot_minor);
355 logmsg("%s", logbuf);
357 if(!strncmp("/verifiedserver", ptr, 15)) {
358 logmsg("Are-we-friendly question received");
359 req->testno = DOCNUMBER_WERULEZ;
363 if(!strncmp("/quit", ptr, 5)) {
364 logmsg("Request-to-quit received");
365 req->testno = DOCNUMBER_QUIT;
369 ptr++; /* skip the slash */
371 /* skip all non-numericals following the slash */
372 while(*ptr && !ISDIGIT(*ptr))
375 req->testno = strtol(ptr, &ptr, 10);
377 if(req->testno > 10000) {
378 req->partno = req->testno % 10000;
379 req->testno /= 10000;
384 sprintf(logbuf, "Requested test number %ld part %ld",
385 req->testno, req->partno);
386 logmsg("%s", logbuf);
388 filename = test2file(req->testno);
390 stream=fopen(filename, "rb");
393 logmsg("fopen() failed with error: %d %s", error, strerror(error));
394 logmsg("Error opening file: %s", filename);
395 logmsg("Couldn't open test file %ld", req->testno);
396 req->open = FALSE; /* closes connection */
404 /* get the custom server control "commands" */
405 error = getpart(&cmd, &cmdsize, "reply", "servercmd", stream);
408 logmsg("getpart() failed with error: %d", error);
409 req->open = FALSE; /* closes connection */
414 logmsg("Found a reply-servercmd section!");
416 if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) {
417 logmsg("instructed to require authorization header");
418 req->auth_req = TRUE;
420 else if(!strncmp(CMD_IDLE, cmd, strlen(CMD_IDLE))) {
421 logmsg("instructed to idle");
422 req->rcmd = RCMD_IDLE;
425 else if(!strncmp(CMD_STREAM, cmd, strlen(CMD_STREAM))) {
426 logmsg("instructed to stream");
427 req->rcmd = RCMD_STREAM;
429 else if(1 == sscanf(cmd, "pipe: %d", &num)) {
430 logmsg("instructed to allow a pipe size of %d", num);
432 logmsg("negative pipe size ignored");
434 req->pipe = num-1; /* decrease by one since we don't count the
435 first request in this number */
437 else if(1 == sscanf(cmd, "skip: %d", &num)) {
438 logmsg("instructed to skip this number of bytes %d", num);
441 else if(1 == sscanf(cmd, "writedelay: %d", &num)) {
442 logmsg("instructed to delay %d secs between packets", num);
443 req->writedelay = num;
446 logmsg("funny instruction found: %s", cmd);
454 if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
455 doc, &prot_major, &prot_minor) == 3) {
456 sprintf(logbuf, "Received a CONNECT %s HTTP/%d.%d request",
457 doc, prot_major, prot_minor);
458 logmsg("%s", logbuf);
460 if(req->prot_version == 10)
461 req->open = FALSE; /* HTTP 1.0 closes connection by default */
463 if(!strncmp(doc, "bad", 3))
464 /* if the host name starts with bad, we fake an error here */
465 req->testno = DOCNUMBER_BADCONNECT;
466 else if(!strncmp(doc, "test", 4)) {
467 /* if the host name starts with test, the port number used in the
468 CONNECT line will be used as test number! */
469 char *portp = strchr(doc, ':');
470 if(portp && (*(portp+1) != '\0') && ISDIGIT(*(portp+1)))
471 req->testno = strtol(portp+1, NULL, 10);
473 req->testno = DOCNUMBER_CONNECT;
476 req->testno = DOCNUMBER_CONNECT;
479 logmsg("Did not find test number in PATH");
480 req->testno = DOCNUMBER_404;
486 /* we don't have a complete request yet! */
487 logmsg("ProcessRequest returned without a complete request");
488 return 0; /* not complete yet */
490 logmsg("ProcessRequest found a complete request");
493 /* when using gopher we cannot check the request until the entire
494 thing has been received */
497 /* find the last slash in the line */
498 ptr = strrchr(line, '/');
501 ptr++; /* skip the slash */
503 /* skip all non-numericals following the slash */
504 while(*ptr && !ISDIGIT(*ptr))
507 req->testno = strtol(ptr, &ptr, 10);
509 if(req->testno > 10000) {
510 req->partno = req->testno % 10000;
511 req->testno /= 10000;
516 sprintf(logbuf, "Requested GOPHER test number %ld part %ld",
517 req->testno, req->partno);
518 logmsg("%s", logbuf);
523 /* we do have a full set, advance the checkindex to after the end of the
524 headers, for the pipelining case mostly */
525 req->checkindex += (end - line) + strlen(end_of_headers);
527 /* **** Persistence ****
529 * If the request is a HTTP/1.0 one, we close the connection unconditionally
532 * If the request is a HTTP/1.1 one, we MUST check for a "Connection:"
533 * header that might say "close". If it does, we close a connection when
534 * this request is processed. Otherwise, we keep the connection alive for X
542 if((req->cl==0) && curlx_strnequal("Content-Length:", line, 15)) {
543 /* If we don't ignore content-length, we read it and we read the whole
544 request including the body before we return. If we've been told to
545 ignore the content-length, we will return as soon as all headers
546 have been received */
548 char *ptr = line + 15;
549 unsigned long clen = 0;
550 while(*ptr && ISSPACE(*ptr))
554 clen = strtoul(ptr, &endptr, 10);
555 if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == ERRNO)) {
556 /* this assumes that a zero Content-Length is valid */
557 logmsg("Found invalid Content-Length: (%s) in the request", ptr);
558 req->open = FALSE; /* closes connection */
561 req->cl = clen - req->skip;
563 logmsg("Found Content-Length: %lu in the request", clen);
565 logmsg("... but will abort after %zu bytes", req->cl);
568 else if(curlx_strnequal("Transfer-Encoding: chunked", line,
569 strlen("Transfer-Encoding: chunked"))) {
570 /* chunked data coming in */
575 if(strstr(req->reqbuf, "\r\n0\r\n\r\n"))
576 /* end of chunks reached */
579 return 0; /* not done */
582 line = strchr(line, '\n');
588 if(!req->auth && strstr(req->reqbuf, "Authorization:")) {
589 req->auth = TRUE; /* Authorization: header present! */
591 logmsg("Authorization header found, as required");
594 if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) {
595 /* If the client is passing this Digest-header, we set the part number
596 to 1000. Not only to spice up the complexity of this, but to make
597 Digest stuff to work in the test suite. */
599 req->digest = TRUE; /* header found */
600 logmsg("Received Digest request, sending back data %ld", req->partno);
602 else if(!req->ntlm &&
603 strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) {
604 /* If the client is passing this type-3 NTLM header */
606 req->ntlm = TRUE; /* NTLM found */
607 logmsg("Received NTLM type-3, sending back data %ld", req->partno);
609 logmsg(" Expecting %zu POSTed bytes", req->cl);
612 else if(!req->ntlm &&
613 strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) {
614 /* If the client is passing this type-1 NTLM header */
616 req->ntlm = TRUE; /* NTLM found */
617 logmsg("Received NTLM type-1, sending back data %ld", req->partno);
619 else if((req->partno >= 1000) && strstr(req->reqbuf, "Authorization: Basic")) {
620 /* If the client is passing this Basic-header and the part number is already
621 >=1000, we add 1 to the part number. This allows simple Basic authentication
622 negotiation to work in the test suite. */
624 logmsg("Received Basic request, sending back data %ld", req->partno);
626 if(strstr(req->reqbuf, "Connection: close"))
627 req->open = FALSE; /* close connection after this request */
631 req->prot_version >= 11 &&
633 req->reqbuf + req->offset > end + strlen(end_of_headers) &&
634 (!strncmp(req->reqbuf, "GET", strlen("GET")) ||
635 !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) {
636 /* If we have a persistent connection, HTTP version >= 1.1
637 and GET/HEAD request, enable pipelining. */
638 req->checkindex = (end - req->reqbuf) + strlen(end_of_headers);
639 req->pipelining = TRUE;
645 /* scan for more header ends within this chunk */
646 line = &req->reqbuf[req->checkindex];
647 end = strstr(line, end_of_headers);
650 req->checkindex += (end - line) + strlen(end_of_headers);
654 /* If authentication is required and no auth was provided, end now. This
655 makes the server NOT wait for PUT/POST data and you can then make the
656 test case send a rejection before any such data has been sent. Test case
658 if(req->auth_req && !req->auth)
662 if(req->cl <= req->offset - (end - req->reqbuf) - strlen(end_of_headers))
665 return 0; /* not complete yet */
671 /* store the entire request in a file */
672 static void storerequest(char *reqbuf, size_t totalsize)
686 dump = fopen(REQUEST_DUMP, "ab");
687 } while ((dump == NULL) && ((error = ERRNO) == EINTR));
689 logmsg("Error opening file %s error: %d %s",
690 REQUEST_DUMP, error, strerror(error));
691 logmsg("Failed to write request input to " REQUEST_DUMP);
695 writeleft = totalsize;
697 written = fwrite(&reqbuf[totalsize-writeleft],
700 goto storerequest_cleanup;
702 writeleft -= written;
703 } while ((writeleft > 0) && ((error = ERRNO) == EINTR));
706 logmsg("Wrote request (%zu bytes) input to " REQUEST_DUMP, totalsize);
707 else if(writeleft > 0) {
708 logmsg("Error writing file %s error: %d %s",
709 REQUEST_DUMP, error, strerror(error));
710 logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s",
711 totalsize-writeleft, totalsize, REQUEST_DUMP);
714 storerequest_cleanup:
718 } while(res && ((error = ERRNO) == EINTR));
720 logmsg("Error closing file %s error: %d %s",
721 REQUEST_DUMP, error, strerror(error));
724 /* return 0 on success, non-zero on failure */
725 static int get_request(curl_socket_t sock, struct httprequest *req)
729 int done_processing = 0;
730 char *reqbuf = req->reqbuf;
733 char *pipereq = NULL;
734 size_t pipereq_length = 0;
736 if(req->pipelining) {
737 pipereq = reqbuf + req->checkindex;
738 pipereq_length = req->offset - req->checkindex;
741 /*** Init the httprequest structure properly for the upcoming request ***/
745 req->testno = DOCNUMBER_NOTHING;
748 req->auth_req = FALSE;
756 req->rcmd = RCMD_NORMALREQ;
757 req->prot_version = 0;
758 req->pipelining = FALSE;
760 /*** end of httprequest init ***/
762 while(!done_processing && (req->offset < REQBUFSIZ-1)) {
763 if(pipereq_length && pipereq) {
764 memmove(reqbuf, pipereq, pipereq_length);
765 got = curlx_uztosz(pipereq_length);
770 /* we are instructed to not read the entire thing, so we make sure to only
771 read what we're supposed to and NOT read the enire thing the client
773 got = sread(sock, reqbuf + req->offset, req->cl);
775 got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset);
780 logmsg("Connection closed by client");
785 logmsg("recv() returned error: (%d) %s", error, strerror(error));
789 /* dump the request received so far to the external file */
790 reqbuf[req->offset] = '\0';
791 storerequest(reqbuf, req->offset);
795 logmsg("Read %zd bytes", got);
797 req->offset += (size_t)got;
798 reqbuf[req->offset] = '\0';
800 done_processing = ProcessRequest(req);
803 if(done_processing && req->pipe) {
804 logmsg("Waiting for another piped request");
810 if((req->offset == REQBUFSIZ-1) && (got > 0)) {
811 logmsg("Request would overflow buffer, closing connection");
812 /* dump request received so far to external file anyway */
813 reqbuf[REQBUFSIZ-1] = '\0';
816 else if(req->offset > REQBUFSIZ-1) {
817 logmsg("Request buffer overflow, closing connection");
818 /* dump request received so far to external file anyway */
819 reqbuf[REQBUFSIZ-1] = '\0';
823 reqbuf[req->offset] = '\0';
825 /* dump the request to an external file */
826 storerequest(reqbuf, req->pipelining ? req->checkindex : req->offset);
830 return fail; /* return 0 on success */
833 /* returns -1 on failure */
834 static int send_doc(curl_socket_t sock, struct httprequest *req)
844 bool persistant = TRUE;
845 bool sendfailure = FALSE;
850 static char weare[256];
852 char partbuf[80]="data";
854 logmsg("Send response number %ld part %ld", req->testno, req->partno);
859 break; /* continue with business as usual */
861 #define STREAMTHIS "a string to stream 01234567890\n"
862 count = strlen(STREAMTHIS);
864 written = swrite(sock, STREAMTHIS, count);
867 if(written != (ssize_t)count) {
868 logmsg("Stopped streaming");
874 /* Do nothing. Sit idle. Pretend it rains. */
880 if(req->testno < 0) {
884 switch(req->testno) {
886 logmsg("Replying to QUIT");
889 case DOCNUMBER_WERULEZ:
890 /* we got a "friends?" question, reply back that we sure are */
891 logmsg("Identifying ourselves as friends");
892 sprintf(msgbuf, "WE ROOLZ: %ld\r\n", (long)getpid());
893 msglen = strlen(msgbuf);
895 sprintf(weare, "%s", msgbuf);
897 sprintf(weare, "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s",
901 case DOCNUMBER_INTERNAL:
902 logmsg("Bailing out due to internal error");
904 case DOCNUMBER_CONNECT:
905 logmsg("Replying to CONNECT");
908 case DOCNUMBER_BADCONNECT:
909 logmsg("Replying to a bad CONNECT");
910 buffer = docbadconnect;
914 logmsg("Replying to with a 404");
919 count = strlen(buffer);
922 char *filename = test2file(req->testno);
925 sprintf(partbuf, "data%ld", req->partno);
927 stream=fopen(filename, "rb");
930 logmsg("fopen() failed with error: %d %s", error, strerror(error));
931 logmsg("Error opening file: %s", filename);
932 logmsg("Couldn't open test file");
936 error = getpart(&ptr, &count, "reply", partbuf, stream);
939 logmsg("getpart() failed with error: %d", error);
945 if(got_exit_signal) {
951 /* re-open the same file again */
952 stream=fopen(filename, "rb");
955 logmsg("fopen() failed with error: %d %s", error, strerror(error));
956 logmsg("Error opening file: %s", filename);
957 logmsg("Couldn't open test file");
963 /* get the custom server control "commands" */
964 error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream);
967 logmsg("getpart() failed with error: %d", error);
975 if(got_exit_signal) {
983 /* If the word 'swsclose' is present anywhere in the reply chunk, the
984 connection will be closed after the data has been sent to the requesting
986 if(strstr(buffer, "swsclose") || !count) {
988 logmsg("connection close instruction \"swsclose\" found in response");
990 if(strstr(buffer, "swsbounce")) {
992 logmsg("enable \"swsbounce\" in the next request");
997 dump = fopen(RESPONSE_DUMP, "ab");
1000 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1001 logmsg("Error opening file: %s", RESPONSE_DUMP);
1002 logmsg("couldn't create logfile: " RESPONSE_DUMP);
1010 responsesize = count;
1012 /* Ok, we send no more than 200 bytes at a time, just to make sure that
1013 larger chunks are split up so that the client will need to do multiple
1014 recv() calls to get it and thus we exercise that code better */
1018 written = swrite(sock, buffer, num);
1024 logmsg("Sent off %zd bytes", written);
1026 if (req->writedelay) {
1027 logmsg("Pausing %d seconds", req->writedelay);
1028 sleep(req->writedelay);
1030 /* write to file as well */
1031 fwrite(buffer, 1, (size_t)written, dump);
1041 } while(res && ((error = ERRNO) == EINTR));
1043 logmsg("Error closing file %s error: %d %s",
1044 RESPONSE_DUMP, error, strerror(error));
1046 if(got_exit_signal) {
1055 logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) were sent",
1056 responsesize-count, responsesize);
1064 logmsg("Response sent (%zu bytes) and written to " RESPONSE_DUMP,
1076 if(2 == sscanf(ptr, "%31s %d", command, &num)) {
1077 if(!strcmp("wait", command)) {
1078 logmsg("Told to sleep for %d seconds", num);
1080 while(quarters > 0) {
1086 /* should not happen */
1088 logmsg("wait_ms() failed with error: (%d) %s",
1089 error, strerror(error));
1094 logmsg("Continuing after sleeping %d seconds", num);
1097 logmsg("Unknown command in reply command section");
1099 ptr = strchr(ptr, '\n');
1104 } while(ptr && *ptr);
1109 req->open = use_gopher?FALSE:persistant;
1111 prevtestno = req->testno;
1112 prevpartno = req->partno;
1118 int main(int argc, char *argv[])
1120 srvr_sockaddr_union_t me;
1121 curl_socket_t sock = CURL_SOCKET_BAD;
1122 curl_socket_t msgsock = CURL_SOCKET_BAD;
1123 int wrotepidfile = 0;
1125 unsigned short port = DEFAULT_PORT;
1126 char *pidname= (char *)".http.pid";
1127 struct httprequest req;
1132 #ifdef CURL_SWS_FORK_ENABLED
1133 bool use_fork = FALSE;
1137 if(!strcmp("--version", argv[arg])) {
1139 #ifdef CURL_SWS_FORK_ENABLED
1152 else if(!strcmp("--pidfile", argv[arg])) {
1155 pidname = argv[arg++];
1157 else if(!strcmp("--logfile", argv[arg])) {
1160 serverlogfile = argv[arg++];
1162 else if(!strcmp("--gopher", argv[arg])) {
1165 end_of_headers = "\r\n"; /* gopher style is much simpler */
1167 else if(!strcmp("--ipv4", argv[arg])) {
1174 else if(!strcmp("--ipv6", argv[arg])) {
1181 #ifdef CURL_SWS_FORK_ENABLED
1182 else if(!strcmp("--fork", argv[arg])) {
1187 else if(!strcmp("--port", argv[arg])) {
1191 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1192 if((endptr != argv[arg] + strlen(argv[arg])) ||
1193 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1194 fprintf(stderr, "sws: invalid --port argument (%s)\n",
1198 port = curlx_ultous(ulnum);
1202 else if(!strcmp("--srcdir", argv[arg])) {
1210 puts("Usage: sws [option]\n"
1212 " --logfile [file]\n"
1213 " --pidfile [file]\n"
1217 " --srcdir [path]\n"
1226 atexit(win32_cleanup);
1229 install_signal_handlers();
1231 pid = (long)getpid();
1236 sock = socket(AF_INET, SOCK_STREAM, 0);
1239 sock = socket(AF_INET6, SOCK_STREAM, 0);
1242 if(CURL_SOCKET_BAD == sock) {
1244 logmsg("Error creating socket: (%d) %s",
1245 error, strerror(error));
1250 if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1251 (void *)&flag, sizeof(flag))) {
1253 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1254 error, strerror(error));
1261 memset(&me.sa4, 0, sizeof(me.sa4));
1262 me.sa4.sin_family = AF_INET;
1263 me.sa4.sin_addr.s_addr = INADDR_ANY;
1264 me.sa4.sin_port = htons(port);
1265 rc = bind(sock, &me.sa, sizeof(me.sa4));
1269 memset(&me.sa6, 0, sizeof(me.sa6));
1270 me.sa6.sin6_family = AF_INET6;
1271 me.sa6.sin6_addr = in6addr_any;
1272 me.sa6.sin6_port = htons(port);
1273 rc = bind(sock, &me.sa, sizeof(me.sa6));
1275 #endif /* ENABLE_IPV6 */
1278 logmsg("Error binding socket on port %hu: (%d) %s",
1279 port, error, strerror(error));
1283 logmsg("Running %s %s version on port %d",
1284 use_gopher?"GOPHER":"HTTP", ipv_inuse, (int)port);
1286 /* start accepting connections */
1287 rc = listen(sock, 5);
1290 logmsg("listen() failed with error: (%d) %s",
1291 error, strerror(error));
1296 ** As soon as this server writes its pid file the test harness will
1297 ** attempt to connect to this server and initiate its verification.
1300 wrotepidfile = write_pidfile(pidname);
1305 msgsock = accept(sock, NULL, NULL);
1309 if (CURL_SOCKET_BAD == msgsock) {
1311 logmsg("MAJOR ERROR: accept() failed with error: (%d) %s",
1312 error, strerror(error));
1317 ** As soon as this server acepts a connection from the test harness it
1318 ** must set the server logs advisor read lock to indicate that server
1319 ** logs should not be read until this lock is removed by this server.
1322 set_advisor_read_lock(SERVERLOGS_LOCK);
1323 serverlogslocked = 1;
1325 #ifdef CURL_SWS_FORK_ENABLED
1327 /* The fork enabled version just forks off the child and don't care
1328 about it anymore, so don't assume otherwise. Beware and don't do
1332 printf("MAJOR ERROR: fork() failed!\n");
1337 /* not a fork, just set rc so the following proceeds nicely */
1339 /* 0 is returned to the child */
1342 logmsg("====> Client connect");
1346 * Disable the Nagle algorithm to make it easier to send out a large
1347 * response in many small segments to torture the clients more.
1350 if (setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
1351 (void *)&flag, sizeof(flag)) == -1) {
1352 logmsg("====> TCP_NODELAY failed");
1356 /* initialization of httprequest struct is done in get_request(), but due
1357 to pipelining treatment the pipelining struct field must be initialized
1358 previously to FALSE every time a new connection arrives. */
1360 req.pipelining = FALSE;
1366 if(get_request(msgsock, &req))
1367 /* non-zero means error, break out of loop */
1371 /* bounce treatment requested */
1372 if((req.testno == prevtestno) &&
1373 (req.partno == prevpartno)) {
1375 logmsg("BOUNCE part number to %ld", req.partno);
1384 send_doc(msgsock, &req);
1388 if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) {
1389 logmsg("special request received, no persistency");
1393 logmsg("instructed to close connection after server-reply");
1398 logmsg("=> persistant connection request ended, awaits new request");
1399 /* if we got a CONNECT, loop and get another request as well! */
1400 } while(req.open || (req.testno == DOCNUMBER_CONNECT));
1405 logmsg("====> Client disconnect");
1407 msgsock = CURL_SOCKET_BAD;
1409 if(serverlogslocked) {
1410 serverlogslocked = 0;
1411 clear_advisor_read_lock(SERVERLOGS_LOCK);
1414 if (req.testno == DOCNUMBER_QUIT)
1416 #ifdef CURL_SWS_FORK_ENABLED
1423 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1426 if(sock != CURL_SOCKET_BAD)
1430 logmsg("signalled to die");
1435 if(serverlogslocked) {
1436 serverlogslocked = 0;
1437 clear_advisor_read_lock(SERVERLOGS_LOCK);
1440 restore_signal_handlers();
1442 if(got_exit_signal) {
1443 logmsg("========> %s sws (port: %d pid: %ld) exits with signal (%d)",
1444 ipv_inuse, (int)port, pid, exit_signal);
1446 * To properly set the return status of the process we
1447 * must raise the same signal SIGINT or SIGTERM that we
1448 * caught and let the old handler take care of it.
1453 logmsg("========> sws quits");