Debian Codegraph @

deps/curl/tests/server/sws.c

raw
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
9 *
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 https://curl.haxx.se/docs/copyright.html.
13 *
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.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ***************************************************************************/
22 #include "server_setup.h"
23
24 /* sws.c: simple (silly?) web server
25
26 This code was originally graciously donated to the project by Juergen
27 Wilke. Thanks a bunch!
28
29 */
30
31 #ifdef HAVE_SIGNAL_H
32 #include <signal.h>
33 #endif
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37 #ifdef HAVE_NETINET_IN6_H
38 #include <netinet/in6.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
42 #endif
43 #ifdef HAVE_NETDB_H
44 #include <netdb.h>
45 #endif
46 #ifdef HAVE_NETINET_TCP_H
47 #include <netinet/tcp.h> /* for TCP_NODELAY */
48 #endif
49
50 #define ENABLE_CURLX_PRINTF
51 /* make the curlx header define all printf() functions to use the curlx_*
52 versions instead */
53 #include "curlx.h" /* from the private lib dir */
54 #include "getpart.h"
55 #include "inet_pton.h"
56 #include "util.h"
57 #include "server_sockaddr.h"
58
59 /* include memdebug.h last */
60 #include "memdebug.h"
61
62 #ifdef USE_WINSOCK
63 #undef EINTR
64 #define EINTR 4 /* errno.h value */
65 #undef EAGAIN
66 #define EAGAIN 11 /* errno.h value */
67 #undef ERANGE
68 #define ERANGE 34 /* errno.h value */
69 #endif
70
71 static enum {
72 socket_domain_inet = AF_INET
73 #ifdef ENABLE_IPV6
74 , socket_domain_inet6 = AF_INET6
75 #endif
76 #ifdef USE_UNIX_SOCKETS
77 , socket_domain_unix = AF_UNIX
78 #endif
79 } socket_domain = AF_INET;
80 static bool use_gopher = FALSE;
81 static int serverlogslocked = 0;
82 static bool is_proxy = FALSE;
83
84 #define REQBUFSIZ 150000
85 #define REQBUFSIZ_TXT "149999"
86
87 static long prevtestno = -1; /* previous test number we served */
88 static long prevpartno = -1; /* previous part number we served */
89 static bool prevbounce = FALSE; /* instructs the server to increase the part
90 number for a test in case the identical
91 testno+partno request shows up again */
92
93 #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */
94 #define RCMD_IDLE 1 /* told to sit idle */
95 #define RCMD_STREAM 2 /* told to stream */
96
97 struct httprequest {
98 char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */
99 bool connect_request; /* if a CONNECT */
100 unsigned short connect_port; /* the port number CONNECT used */
101 size_t checkindex; /* where to start checking of the request */
102 size_t offset; /* size of the incoming request */
103 long testno; /* test number found in the request */
104 long partno; /* part number found in the request */
105 bool open; /* keep connection open info, as found in the request */
106 bool auth_req; /* authentication required, don't wait for body unless
107 there's an Authorization header */
108 bool auth; /* Authorization header present in the incoming request */
109 size_t cl; /* Content-Length of the incoming request */
110 bool digest; /* Authorization digest header found */
111 bool ntlm; /* Authorization ntlm header found */
112 int writedelay; /* if non-zero, delay this number of seconds between
113 writes in the response */
114 int skip; /* if non-zero, the server is instructed to not read this
115 many bytes from a PUT/POST request. Ie the client sends N
116 bytes said in Content-Length, but the server only reads N
117 - skip bytes. */
118 int rcmd; /* doing a special command, see defines above */
119 int prot_version; /* HTTP version * 10 */
120 int callcount; /* times ProcessRequest() gets called */
121 bool skipall; /* skip all incoming data */
122 bool noexpect; /* refuse Expect: (don't read the body) */
123 bool connmon; /* monitor the state of the connection, log disconnects */
124 bool upgrade; /* test case allows upgrade to http2 */
125 bool upgrade_request; /* upgrade request found and allowed */
126 bool close; /* similar to swsclose in response: close connection after
127 response is sent */
128 int done_processing;
129 };
130
131 #define MAX_SOCKETS 1024
132
133 static curl_socket_t all_sockets[MAX_SOCKETS];
134 static size_t num_sockets = 0;
135
136 static int ProcessRequest(struct httprequest *req);
137 static void storerequest(const char *reqbuf, size_t totalsize);
138
139 #define DEFAULT_PORT 8999
140
141 #ifndef DEFAULT_LOGFILE
142 #define DEFAULT_LOGFILE "log/sws.log"
143 #endif
144
145 const char *serverlogfile = DEFAULT_LOGFILE;
146
147 #define SWSVERSION "curl test suite HTTP server/0.1"
148
149 #define REQUEST_DUMP "log/server.input"
150 #define RESPONSE_DUMP "log/server.response"
151
152 /* when told to run as proxy, we store the logs in different files so that
153 they can co-exist with the same program running as a "server" */
154 #define REQUEST_PROXY_DUMP "log/proxy.input"
155 #define RESPONSE_PROXY_DUMP "log/proxy.response"
156
157 /* very-big-path support */
158 #define MAXDOCNAMELEN 140000
159 #define MAXDOCNAMELEN_TXT "139999"
160
161 #define REQUEST_KEYWORD_SIZE 256
162 #define REQUEST_KEYWORD_SIZE_TXT "255"
163
164 #define CMD_AUTH_REQUIRED "auth_required"
165
166 /* 'idle' means that it will accept the request fine but never respond
167 any data. Just keep the connection alive. */
168 #define CMD_IDLE "idle"
169
170 /* 'stream' means to send a never-ending stream of data */
171 #define CMD_STREAM "stream"
172
173 /* 'connection-monitor' will output when a server/proxy connection gets
174 disconnected as for some cases it is important that it gets done at the
175 proper point - like with NTLM */
176 #define CMD_CONNECTIONMONITOR "connection-monitor"
177
178 /* upgrade to http2 */
179 #define CMD_UPGRADE "upgrade"
180
181 /* close connection */
182 #define CMD_SWSCLOSE "swsclose"
183
184 /* deny Expect: requests */
185 #define CMD_NOEXPECT "no-expect"
186
187 #define END_OF_HEADERS "\r\n\r\n"
188
189 enum {
190 DOCNUMBER_NOTHING = -4,
191 DOCNUMBER_QUIT = -3,
192 DOCNUMBER_WERULEZ = -2,
193 DOCNUMBER_404 = -1
194 };
195
196 static const char *end_of_headers = END_OF_HEADERS;
197
198 /* sent as reply to a QUIT */
199 static const char *docquit =
200 "HTTP/1.1 200 Goodbye" END_OF_HEADERS;
201
202 /* send back this on 404 file not found */
203 static const char *doc404 = "HTTP/1.1 404 Not Found\r\n"
204 "Server: " SWSVERSION "\r\n"
205 "Connection: close\r\n"
206 "Content-Type: text/html"
207 END_OF_HEADERS
208 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
209 "<HTML><HEAD>\n"
210 "<TITLE>404 Not Found</TITLE>\n"
211 "</HEAD><BODY>\n"
212 "<H1>Not Found</H1>\n"
213 "The requested URL was not found on this server.\n"
214 "<P><HR><ADDRESS>" SWSVERSION "</ADDRESS>\n" "</BODY></HTML>\n";
215
216 /* do-nothing macro replacement for systems which lack siginterrupt() */
217
218 #ifndef HAVE_SIGINTERRUPT
219 #define siginterrupt(x,y) do {} while(0)
220 #endif
221
222 /* vars used to keep around previous signal handlers */
223
224 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
225
226 #ifdef SIGHUP
227 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
228 #endif
229
230 #ifdef SIGPIPE
231 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
232 #endif
233
234 #ifdef SIGALRM
235 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
236 #endif
237
238 #ifdef SIGINT
239 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
240 #endif
241
242 #ifdef SIGTERM
243 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
244 #endif
245
246 #if defined(SIGBREAK) && defined(WIN32)
247 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
248 #endif
249
250 /* var which if set indicates that the program should finish execution */
251
252 SIG_ATOMIC_T got_exit_signal = 0;
253
254 /* if next is set indicates the first signal handled in exit_signal_handler */
255
256 static volatile int exit_signal = 0;
257
258 /* work around for handling trailing headers */
259 static int already_recv_zeroed_chunk = FALSE;
260
261 /* signal handler that will be triggered to indicate that the program
262 should finish its execution in a controlled manner as soon as possible.
263 The first time this is called it will set got_exit_signal to one and
264 store in exit_signal the signal that triggered its execution. */
265
266 static RETSIGTYPE exit_signal_handler(int signum)
267 {
268 int old_errno = errno;
269 if(got_exit_signal == 0) {
270 got_exit_signal = 1;
271 exit_signal = signum;
272 }
273 (void)signal(signum, exit_signal_handler);
274 errno = old_errno;
275 }
276
277 static void install_signal_handlers(void)
278 {
279 #ifdef SIGHUP
280 /* ignore SIGHUP signal */
281 old_sighup_handler = signal(SIGHUP, SIG_IGN);
282 if(old_sighup_handler == SIG_ERR)
283 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
284 #endif
285 #ifdef SIGPIPE
286 /* ignore SIGPIPE signal */
287 old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
288 if(old_sigpipe_handler == SIG_ERR)
289 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
290 #endif
291 #ifdef SIGALRM
292 /* ignore SIGALRM signal */
293 old_sigalrm_handler = signal(SIGALRM, SIG_IGN);
294 if(old_sigalrm_handler == SIG_ERR)
295 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
296 #endif
297 #ifdef SIGINT
298 /* handle SIGINT signal with our exit_signal_handler */
299 old_sigint_handler = signal(SIGINT, exit_signal_handler);
300 if(old_sigint_handler == SIG_ERR)
301 logmsg("cannot install SIGINT handler: %s", strerror(errno));
302 else
303 siginterrupt(SIGINT, 1);
304 #endif
305 #ifdef SIGTERM
306 /* handle SIGTERM signal with our exit_signal_handler */
307 old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
308 if(old_sigterm_handler == SIG_ERR)
309 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
310 else
311 siginterrupt(SIGTERM, 1);
312 #endif
313 #if defined(SIGBREAK) && defined(WIN32)
314 /* handle SIGBREAK signal with our exit_signal_handler */
315 old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
316 if(old_sigbreak_handler == SIG_ERR)
317 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
318 else
319 siginterrupt(SIGBREAK, 1);
320 #endif
321 }
322
323 static void restore_signal_handlers(void)
324 {
325 #ifdef SIGHUP
326 if(SIG_ERR != old_sighup_handler)
327 (void)signal(SIGHUP, old_sighup_handler);
328 #endif
329 #ifdef SIGPIPE
330 if(SIG_ERR != old_sigpipe_handler)
331 (void)signal(SIGPIPE, old_sigpipe_handler);
332 #endif
333 #ifdef SIGALRM
334 if(SIG_ERR != old_sigalrm_handler)
335 (void)signal(SIGALRM, old_sigalrm_handler);
336 #endif
337 #ifdef SIGINT
338 if(SIG_ERR != old_sigint_handler)
339 (void)signal(SIGINT, old_sigint_handler);
340 #endif
341 #ifdef SIGTERM
342 if(SIG_ERR != old_sigterm_handler)
343 (void)signal(SIGTERM, old_sigterm_handler);
344 #endif
345 #if defined(SIGBREAK) && defined(WIN32)
346 if(SIG_ERR != old_sigbreak_handler)
347 (void)signal(SIGBREAK, old_sigbreak_handler);
348 #endif
349 }
350
351 /* returns true if the current socket is an IP one */
352 static bool socket_domain_is_ip(void)
353 {
354 switch(socket_domain) {
355 case AF_INET:
356 #ifdef ENABLE_IPV6
357 case AF_INET6:
358 #endif
359 return true;
360 default:
361 /* case AF_UNIX: */
362 return false;
363 }
364 }
365
366 /* based on the testno, parse the correct server commands */
367 static int parse_servercmd(struct httprequest *req)
368 {
369 FILE *stream;
370 char *filename;
371 int error;
372
373 filename = test2file(req->testno);
374 req->close = FALSE;
375 req->connmon = FALSE;
376
377 stream = fopen(filename, "rb");
378 if(!stream) {
379 error = errno;
380 logmsg("fopen() failed with error: %d %s", error, strerror(error));
381 logmsg(" [1] Error opening file: %s", filename);
382 logmsg(" Couldn't open test file %ld", req->testno);
383 req->open = FALSE; /* closes connection */
384 return 1; /* done */
385 }
386 else {
387 char *orgcmd = NULL;
388 char *cmd = NULL;
389 size_t cmdsize = 0;
390 int num = 0;
391
392 /* get the custom server control "commands" */
393 error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
394 fclose(stream);
395 if(error) {
396 logmsg("getpart() failed with error: %d", error);
397 req->open = FALSE; /* closes connection */
398 return 1; /* done */
399 }
400
401 cmd = orgcmd;
402 while(cmd && cmdsize) {
403 char *check;
404
405 if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) {
406 logmsg("instructed to require authorization header");
407 req->auth_req = TRUE;
408 }
409 else if(!strncmp(CMD_IDLE, cmd, strlen(CMD_IDLE))) {
410 logmsg("instructed to idle");
411 req->rcmd = RCMD_IDLE;
412 req->open = TRUE;
413 }
414 else if(!strncmp(CMD_STREAM, cmd, strlen(CMD_STREAM))) {
415 logmsg("instructed to stream");
416 req->rcmd = RCMD_STREAM;
417 }
418 else if(!strncmp(CMD_CONNECTIONMONITOR, cmd,
419 strlen(CMD_CONNECTIONMONITOR))) {
420 logmsg("enabled connection monitoring");
421 req->connmon = TRUE;
422 }
423 else if(!strncmp(CMD_UPGRADE, cmd, strlen(CMD_UPGRADE))) {
424 logmsg("enabled upgrade to http2");
425 req->upgrade = TRUE;
426 }
427 else if(!strncmp(CMD_SWSCLOSE, cmd, strlen(CMD_SWSCLOSE))) {
428 logmsg("swsclose: close this connection after response");
429 req->close = TRUE;
430 }
431 else if(1 == sscanf(cmd, "skip: %d", &num)) {
432 logmsg("instructed to skip this number of bytes %d", num);
433 req->skip = num;
434 }
435 else if(!strncmp(CMD_NOEXPECT, cmd, strlen(CMD_NOEXPECT))) {
436 logmsg("instructed to reject Expect: 100-continue");
437 req->noexpect = TRUE;
438 }
439 else if(1 == sscanf(cmd, "writedelay: %d", &num)) {
440 logmsg("instructed to delay %d secs between packets", num);
441 req->writedelay = num;
442 }
443 else {
444 logmsg("Unknown <servercmd> instruction found: %s", cmd);
445 }
446 /* try to deal with CRLF or just LF */
447 check = strchr(cmd, '\r');
448 if(!check)
449 check = strchr(cmd, '\n');
450
451 if(check) {
452 /* get to the letter following the newline */
453 while((*check == '\r') || (*check == '\n'))
454 check++;
455
456 if(!*check)
457 /* if we reached a zero, get out */
458 break;
459 cmd = check;
460 }
461 else
462 break;
463 }
464 free(orgcmd);
465 }
466
467 return 0; /* OK! */
468 }
469
470 static int ProcessRequest(struct httprequest *req)
471 {
472 char *line = &req->reqbuf[req->checkindex];
473 bool chunked = FALSE;
474 static char request[REQUEST_KEYWORD_SIZE];
475 static char doc[MAXDOCNAMELEN];
476 char logbuf[456];
477 int prot_major, prot_minor;
478 char *end = strstr(line, end_of_headers);
479
480 req->callcount++;
481
482 logmsg("Process %d bytes request%s", req->offset,
483 req->callcount > 1?" [CONTINUED]":"");
484
485 /* try to figure out the request characteristics as soon as possible, but
486 only once! */
487
488 if(use_gopher &&
489 (req->testno == DOCNUMBER_NOTHING) &&
490 !strncmp("/verifiedserver", line, 15)) {
491 logmsg("Are-we-friendly question received");
492 req->testno = DOCNUMBER_WERULEZ;
493 return 1; /* done */
494 }
495
496 else if((req->testno == DOCNUMBER_NOTHING) &&
497 sscanf(line,
498 "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
499 request,
500 doc,
501 &prot_major,
502 &prot_minor) == 4) {
503 char *ptr;
504
505 req->prot_version = prot_major*10 + prot_minor;
506
507 /* find the last slash */
508 ptr = strrchr(doc, '/');
509
510 /* get the number after it */
511 if(ptr) {
512 if((strlen(doc) + strlen(request)) < 400)
513 msnprintf(logbuf, sizeof(logbuf), "Got request: %s %s HTTP/%d.%d",
514 request, doc, prot_major, prot_minor);
515 else
516 msnprintf(logbuf, sizeof(logbuf), "Got a *HUGE* request HTTP/%d.%d",
517 prot_major, prot_minor);
518 logmsg("%s", logbuf);
519
520 if(!strncmp("/verifiedserver", ptr, 15)) {
521 logmsg("Are-we-friendly question received");
522 req->testno = DOCNUMBER_WERULEZ;
523 return 1; /* done */
524 }
525
526 if(!strncmp("/quit", ptr, 5)) {
527 logmsg("Request-to-quit received");
528 req->testno = DOCNUMBER_QUIT;
529 return 1; /* done */
530 }
531
532 ptr++; /* skip the slash */
533
534 /* skip all non-numericals following the slash */
535 while(*ptr && !ISDIGIT(*ptr))
536 ptr++;
537
538 req->testno = strtol(ptr, &ptr, 10);
539
540 if(req->testno > 10000) {
541 req->partno = req->testno % 10000;
542 req->testno /= 10000;
543 }
544 else
545 req->partno = 0;
546
547 if(req->testno) {
548
549 msnprintf(logbuf, sizeof(logbuf), "Requested test number %ld part %ld",
550 req->testno, req->partno);
551 logmsg("%s", logbuf);
552 }
553 else {
554 logmsg("No test number");
555 req->testno = DOCNUMBER_NOTHING;
556 }
557
558 }
559
560 if(req->testno == DOCNUMBER_NOTHING) {
561 /* didn't find any in the first scan, try alternative test case
562 number placements */
563
564 if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
565 doc, &prot_major, &prot_minor) == 3) {
566 char *portp = NULL;
567
568 msnprintf(logbuf, sizeof(logbuf),
569 "Received a CONNECT %s HTTP/%d.%d request",
570 doc, prot_major, prot_minor);
571 logmsg("%s", logbuf);
572
573 req->connect_request = TRUE;
574
575 if(req->prot_version == 10)
576 req->open = FALSE; /* HTTP 1.0 closes connection by default */
577
578 if(doc[0] == '[') {
579 char *p = &doc[1];
580 unsigned long part = 0;
581 /* scan through the hexgroups and store the value of the last group
582 in the 'part' variable and use as test case number!! */
583 while(*p && (ISXDIGIT(*p) || (*p == ':') || (*p == '.'))) {
584 char *endp;
585 part = strtoul(p, &endp, 16);
586 if(ISXDIGIT(*p))
587 p = endp;
588 else
589 p++;
590 }
591 if(*p != ']')
592 logmsg("Invalid CONNECT IPv6 address format");
593 else if(*(p + 1) != ':')
594 logmsg("Invalid CONNECT IPv6 port format");
595 else
596 portp = p + 1;
597
598 req->testno = part;
599 }
600 else
601 portp = strchr(doc, ':');
602
603 if(portp && (*(portp + 1) != '\0') && ISDIGIT(*(portp + 1))) {
604 unsigned long ulnum = strtoul(portp + 1, NULL, 10);
605 if(!ulnum || (ulnum > 65535UL))
606 logmsg("Invalid CONNECT port received");
607 else
608 req->connect_port = curlx_ultous(ulnum);
609
610 }
611 logmsg("Port number: %d, test case number: %ld",
612 req->connect_port, req->testno);
613 }
614 }
615
616 if(req->testno == DOCNUMBER_NOTHING) {
617 /* Still no test case number. Try to get the number off the last dot
618 instead, IE we consider the TLD to be the test number. Test 123 can
619 then be written as "example.com.123". */
620
621 /* find the last dot */
622 ptr = strrchr(doc, '.');
623
624 /* get the number after it */
625 if(ptr) {
626 ptr++; /* skip the dot */
627
628 req->testno = strtol(ptr, &ptr, 10);
629
630 if(req->testno > 10000) {
631 req->partno = req->testno % 10000;
632 req->testno /= 10000;
633
634 logmsg("found test %d in requested host name", req->testno);
635
636 }
637 else
638 req->partno = 0;
639
640 msnprintf(logbuf, sizeof(logbuf),
641 "Requested test number %ld part %ld (from host name)",
642 req->testno, req->partno);
643 logmsg("%s", logbuf);
644
645 }
646
647 if(!req->testno) {
648 logmsg("Did not find test number in PATH");
649 req->testno = DOCNUMBER_404;
650 }
651 else
652 parse_servercmd(req);
653 }
654 }
655 else if((req->offset >= 3) && (req->testno == DOCNUMBER_NOTHING)) {
656 logmsg("** Unusual request. Starts with %02x %02x %02x (%c%c%c)",
657 line[0], line[1], line[2], line[0], line[1], line[2]);
658 }
659
660 if(!end) {
661 /* we don't have a complete request yet! */
662 logmsg("request not complete yet");
663 return 0; /* not complete yet */
664 }
665 logmsg("- request found to be complete (%d)", req->testno);
666
667 if(req->testno == DOCNUMBER_NOTHING) {
668 /* check for a Testno: header with the test case number */
669 char *testno = strstr(line, "\nTestno: ");
670 if(testno) {
671 req->testno = strtol(&testno[9], NULL, 10);
672 logmsg("Found test number %d in Testno: header!", req->testno);
673 }
674 else {
675 logmsg("No Testno: header");
676 }
677 }
678
679 /* find and parse <servercmd> for this test */
680 parse_servercmd(req);
681
682 if(use_gopher) {
683 /* when using gopher we cannot check the request until the entire
684 thing has been received */
685 char *ptr;
686
687 /* find the last slash in the line */
688 ptr = strrchr(line, '/');
689
690 if(ptr) {
691 ptr++; /* skip the slash */
692
693 /* skip all non-numericals following the slash */
694 while(*ptr && !ISDIGIT(*ptr))
695 ptr++;
696
697 req->testno = strtol(ptr, &ptr, 10);
698
699 if(req->testno > 10000) {
700 req->partno = req->testno % 10000;
701 req->testno /= 10000;
702 }
703 else
704 req->partno = 0;
705
706 msnprintf(logbuf, sizeof(logbuf),
707 "Requested GOPHER test number %ld part %ld",
708 req->testno, req->partno);
709 logmsg("%s", logbuf);
710 }
711 }
712
713 /* **** Persistence ****
714 *
715 * If the request is a HTTP/1.0 one, we close the connection unconditionally
716 * when we're done.
717 *
718 * If the request is a HTTP/1.1 one, we MUST check for a "Connection:"
719 * header that might say "close". If it does, we close a connection when
720 * this request is processed. Otherwise, we keep the connection alive for X
721 * seconds.
722 */
723
724 do {
725 if(got_exit_signal)
726 return 1; /* done */
727
728 if((req->cl == 0) && strncasecompare("Content-Length:", line, 15)) {
729 /* If we don't ignore content-length, we read it and we read the whole
730 request including the body before we return. If we've been told to
731 ignore the content-length, we will return as soon as all headers
732 have been received */
733 char *endptr;
734 char *ptr = line + 15;
735 unsigned long clen = 0;
736 while(*ptr && ISSPACE(*ptr))
737 ptr++;
738 endptr = ptr;
739 errno = 0;
740 clen = strtoul(ptr, &endptr, 10);
741 if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == errno)) {
742 /* this assumes that a zero Content-Length is valid */
743 logmsg("Found invalid Content-Length: (%s) in the request", ptr);
744 req->open = FALSE; /* closes connection */
745 return 1; /* done */
746 }
747 if(req->skipall)
748 req->cl = 0;
749 else
750 req->cl = clen - req->skip;
751
752 logmsg("Found Content-Length: %lu in the request", clen);
753 if(req->skip)
754 logmsg("... but will abort after %zu bytes", req->cl);
755 }
756 else if(strncasecompare("Transfer-Encoding: chunked", line,
757 strlen("Transfer-Encoding: chunked"))) {
758 /* chunked data coming in */
759 chunked = TRUE;
760 }
761 else if(req->noexpect &&
762 strncasecompare("Expect: 100-continue", line,
763 strlen("Expect: 100-continue"))) {
764 if(req->cl)
765 req->cl = 0;
766 req->skipall = TRUE;
767 logmsg("Found Expect: 100-continue, ignore body");
768 }
769
770 if(chunked) {
771 if(strstr(req->reqbuf, "\r\n0\r\n\r\n")) {
772 /* end of chunks reached */
773 return 1; /* done */
774 }
775 else if(strstr(req->reqbuf, "\r\n0\r\n")) {
776 char *last_crlf_char = strstr(req->reqbuf, "\r\n\r\n");
777 while(TRUE) {
778 if(!strstr(last_crlf_char + 4, "\r\n\r\n"))
779 break;
780 last_crlf_char = strstr(last_crlf_char + 4, "\r\n\r\n");
781 }
782 if(last_crlf_char &&
783 last_crlf_char > strstr(req->reqbuf, "\r\n0\r\n"))
784 return 1;
785 already_recv_zeroed_chunk = TRUE;
786 return 0;
787 }
788 else if(already_recv_zeroed_chunk && strstr(req->reqbuf, "\r\n\r\n"))
789 return 1;
790 else
791 return 0; /* not done */
792 }
793
794 line = strchr(line, '\n');
795 if(line)
796 line++;
797
798 } while(line);
799
800 if(!req->auth && strstr(req->reqbuf, "Authorization:")) {
801 req->auth = TRUE; /* Authorization: header present! */
802 if(req->auth_req)
803 logmsg("Authorization header found, as required");
804 }
805
806 if(strstr(req->reqbuf, "Authorization: Negotiate")) {
807 /* Negotiate iterations */
808 static long prev_testno = -1;
809 static long prev_partno = -1;
810 logmsg("Negotiate: prev_testno: %d, prev_partno: %d",
811 prev_testno, prev_partno);
812 if(req->testno != prev_testno) {
813 prev_testno = req->testno;
814 prev_partno = req->partno;
815 }
816 prev_partno += 1;
817 req->partno = prev_partno;
818 }
819 else if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) {
820 /* If the client is passing this Digest-header, we set the part number
821 to 1000. Not only to spice up the complexity of this, but to make
822 Digest stuff to work in the test suite. */
823 req->partno += 1000;
824 req->digest = TRUE; /* header found */
825 logmsg("Received Digest request, sending back data %ld", req->partno);
826 }
827 else if(!req->ntlm &&
828 strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) {
829 /* If the client is passing this type-3 NTLM header */
830 req->partno += 1002;
831 req->ntlm = TRUE; /* NTLM found */
832 logmsg("Received NTLM type-3, sending back data %ld", req->partno);
833 if(req->cl) {
834 logmsg(" Expecting %zu POSTed bytes", req->cl);
835 }
836 }
837 else if(!req->ntlm &&
838 strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) {
839 /* If the client is passing this type-1 NTLM header */
840 req->partno += 1001;
841 req->ntlm = TRUE; /* NTLM found */
842 logmsg("Received NTLM type-1, sending back data %ld", req->partno);
843 }
844 else if((req->partno >= 1000) &&
845 strstr(req->reqbuf, "Authorization: Basic")) {
846 /* If the client is passing this Basic-header and the part number is
847 already >=1000, we add 1 to the part number. This allows simple Basic
848 authentication negotiation to work in the test suite. */
849 req->partno += 1;
850 logmsg("Received Basic request, sending back data %ld", req->partno);
851 }
852 if(strstr(req->reqbuf, "Connection: close"))
853 req->open = FALSE; /* close connection after this request */
854
855 if(req->open &&
856 req->prot_version >= 11 &&
857 end &&
858 req->reqbuf + req->offset > end + strlen(end_of_headers) &&
859 !req->cl &&
860 (!strncmp(req->reqbuf, "GET", strlen("GET")) ||
861 !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) {
862 /* If we have a persistent connection, HTTP version >= 1.1
863 and GET/HEAD request, enable pipelining. */
864 req->checkindex = (end - req->reqbuf) + strlen(end_of_headers);
865 }
866
867 /* If authentication is required and no auth was provided, end now. This
868 makes the server NOT wait for PUT/POST data and you can then make the
869 test case send a rejection before any such data has been sent. Test case
870 154 uses this.*/
871 if(req->auth_req && !req->auth) {
872 logmsg("Return early due to auth requested by none provided");
873 return 1; /* done */
874 }
875
876 if(req->upgrade && strstr(req->reqbuf, "Upgrade:")) {
877 /* we allow upgrade and there was one! */
878 logmsg("Found Upgrade: in request and allows it");
879 req->upgrade_request = TRUE;
880 }
881
882 if(req->cl > 0) {
883 if(req->cl <= req->offset - (end - req->reqbuf) - strlen(end_of_headers))
884 return 1; /* done */
885 else
886 return 0; /* not complete yet */
887 }
888
889 return 1; /* done */
890 }
891
892 /* store the entire request in a file */
893 static void storerequest(const char *reqbuf, size_t totalsize)
894 {
895 int res;
896 int error = 0;
897 size_t written;
898 size_t writeleft;
899 FILE *dump;
900 const char *dumpfile = is_proxy?REQUEST_PROXY_DUMP:REQUEST_DUMP;
901
902 if(reqbuf == NULL)
903 return;
904 if(totalsize == 0)
905 return;
906
907 do {
908 dump = fopen(dumpfile, "ab");
909 } while((dump == NULL) && ((error = errno) == EINTR));
910 if(dump == NULL) {
911 logmsg("[2] Error opening file %s error: %d %s",
912 dumpfile, error, strerror(error));
913 logmsg("Failed to write request input ");
914 return;
915 }
916
917 writeleft = totalsize;
918 do {
919 written = fwrite(&reqbuf[totalsize-writeleft],
920 1, writeleft, dump);
921 if(got_exit_signal)
922 goto storerequest_cleanup;
923 if(written > 0)
924 writeleft -= written;
925 } while((writeleft > 0) && ((error = errno) == EINTR));
926
927 if(writeleft == 0)
928 logmsg("Wrote request (%zu bytes) input to %s", totalsize, dumpfile);
929 else if(writeleft > 0) {
930 logmsg("Error writing file %s error: %d %s",
931 dumpfile, error, strerror(error));
932 logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s",
933 totalsize-writeleft, totalsize, dumpfile);
934 }
935
936 storerequest_cleanup:
937
938 do {
939 res = fclose(dump);
940 } while(res && ((error = errno) == EINTR));
941 if(res)
942 logmsg("Error closing file %s error: %d %s",
943 dumpfile, error, strerror(error));
944 }
945
946 static void init_httprequest(struct httprequest *req)
947 {
948 req->checkindex = 0;
949 req->offset = 0;
950 req->testno = DOCNUMBER_NOTHING;
951 req->partno = 0;
952 req->connect_request = FALSE;
953 req->open = TRUE;
954 req->auth_req = FALSE;
955 req->auth = FALSE;
956 req->cl = 0;
957 req->digest = FALSE;
958 req->ntlm = FALSE;
959 req->skip = 0;
960 req->skipall = FALSE;
961 req->noexpect = FALSE;
962 req->writedelay = 0;
963 req->rcmd = RCMD_NORMALREQ;
964 req->prot_version = 0;
965 req->callcount = 0;
966 req->connect_port = 0;
967 req->done_processing = 0;
968 req->upgrade = 0;
969 req->upgrade_request = 0;
970 }
971
972 /* returns 1 if the connection should be serviced again immediately, 0 if there
973 is no data waiting, or < 0 if it should be closed */
974 static int get_request(curl_socket_t sock, struct httprequest *req)
975 {
976 int fail = 0;
977 char *reqbuf = req->reqbuf;
978 ssize_t got = 0;
979 int overflow = 0;
980
981 if(req->offset >= REQBUFSIZ-1) {
982 /* buffer is already full; do nothing */
983 overflow = 1;
984 }
985 else {
986 if(req->skip)
987 /* we are instructed to not read the entire thing, so we make sure to
988 only read what we're supposed to and NOT read the enire thing the
989 client wants to send! */
990 got = sread(sock, reqbuf + req->offset, req->cl);
991 else
992 got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset);
993
994 if(got_exit_signal)
995 return -1;
996 if(got == 0) {
997 logmsg("Connection closed by client");
998 fail = 1;
999 }
1000 else if(got < 0) {
1001 int error = SOCKERRNO;
1002 if(EAGAIN == error || EWOULDBLOCK == error) {
1003 /* nothing to read at the moment */
1004 return 0;
1005 }
1006 logmsg("recv() returned error: (%d) %s", error, strerror(error));
1007 fail = 1;
1008 }
1009 if(fail) {
1010 /* dump the request received so far to the external file */
1011 reqbuf[req->offset] = '\0';
1012 storerequest(reqbuf, req->offset);
1013 return -1;
1014 }
1015
1016 logmsg("Read %zd bytes", got);
1017
1018 req->offset += (size_t)got;
1019 reqbuf[req->offset] = '\0';
1020
1021 req->done_processing = ProcessRequest(req);
1022 if(got_exit_signal)
1023 return -1;
1024 }
1025
1026 if(overflow || (req->offset == REQBUFSIZ-1 && got > 0)) {
1027 logmsg("Request would overflow buffer, closing connection");
1028 /* dump request received so far to external file anyway */
1029 reqbuf[REQBUFSIZ-1] = '\0';
1030 fail = 1;
1031 }
1032 else if(req->offset > REQBUFSIZ-1) {
1033 logmsg("Request buffer overflow, closing connection");
1034 /* dump request received so far to external file anyway */
1035 reqbuf[REQBUFSIZ-1] = '\0';
1036 fail = 1;
1037 }
1038 else
1039 reqbuf[req->offset] = '\0';
1040
1041 /* at the end of a request dump it to an external file */
1042 if(fail || req->done_processing)
1043 storerequest(reqbuf, req->offset);
1044 if(got_exit_signal)
1045 return -1;
1046
1047 return fail ? -1 : 1;
1048 }
1049
1050 /* returns -1 on failure */
1051 static int send_doc(curl_socket_t sock, struct httprequest *req)
1052 {
1053 ssize_t written;
1054 size_t count;
1055 const char *buffer;
1056 char *ptr = NULL;
1057 FILE *stream;
1058 char *cmd = NULL;
1059 size_t cmdsize = 0;
1060 FILE *dump;
1061 bool persistent = TRUE;
1062 bool sendfailure = FALSE;
1063 size_t responsesize;
1064 int error = 0;
1065 int res;
1066 const char *responsedump = is_proxy?RESPONSE_PROXY_DUMP:RESPONSE_DUMP;
1067 static char weare[256];
1068
1069 switch(req->rcmd) {
1070 default:
1071 case RCMD_NORMALREQ:
1072 break; /* continue with business as usual */
1073 case RCMD_STREAM:
1074 #define STREAMTHIS "a string to stream 01234567890\n"
1075 count = strlen(STREAMTHIS);
1076 for(;;) {
1077 written = swrite(sock, STREAMTHIS, count);
1078 if(got_exit_signal)
1079 return -1;
1080 if(written != (ssize_t)count) {
1081 logmsg("Stopped streaming");
1082 break;
1083 }
1084 }
1085 return -1;
1086 case RCMD_IDLE:
1087 /* Do nothing. Sit idle. Pretend it rains. */
1088 return 0;
1089 }
1090
1091 req->open = FALSE;
1092
1093 if(req->testno < 0) {
1094 size_t msglen;
1095 char msgbuf[64];
1096
1097 switch(req->testno) {
1098 case DOCNUMBER_QUIT:
1099 logmsg("Replying to QUIT");
1100 buffer = docquit;
1101 break;
1102 case DOCNUMBER_WERULEZ:
1103 /* we got a "friends?" question, reply back that we sure are */
1104 logmsg("Identifying ourselves as friends");
1105 msnprintf(msgbuf, sizeof(msgbuf), "WE ROOLZ: %ld\r\n", (long)getpid());
1106 msglen = strlen(msgbuf);
1107 if(use_gopher)
1108 msnprintf(weare, sizeof(weare), "%s", msgbuf);
1109 else
1110 msnprintf(weare, sizeof(weare),
1111 "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s",
1112 msglen, msgbuf);
1113 buffer = weare;
1114 break;
1115 case DOCNUMBER_404:
1116 default:
1117 logmsg("Replying to with a 404");
1118 buffer = doc404;
1119 break;
1120 }
1121
1122 count = strlen(buffer);
1123 }
1124 else {
1125 char partbuf[80];
1126 char *filename = test2file(req->testno);
1127
1128 /* select the <data> tag for "normal" requests and the <connect> one
1129 for CONNECT requests (within the <reply> section) */
1130 const char *section = req->connect_request?"connect":"data";
1131
1132 if(req->partno)
1133 msnprintf(partbuf, sizeof(partbuf), "%s%ld", section, req->partno);
1134 else
1135 msnprintf(partbuf, sizeof(partbuf), "%s", section);
1136
1137 logmsg("Send response test%ld section <%s>", req->testno, partbuf);
1138
1139 stream = fopen(filename, "rb");
1140 if(!stream) {
1141 error = errno;
1142 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1143 logmsg(" [3] Error opening file: %s", filename);
1144 return 0;
1145 }
1146 else {
1147 error = getpart(&ptr, &count, "reply", partbuf, stream);
1148 fclose(stream);
1149 if(error) {
1150 logmsg("getpart() failed with error: %d", error);
1151 return 0;
1152 }
1153 buffer = ptr;
1154 }
1155
1156 if(got_exit_signal) {
1157 free(ptr);
1158 return -1;
1159 }
1160
1161 /* re-open the same file again */
1162 stream = fopen(filename, "rb");
1163 if(!stream) {
1164 error = errno;
1165 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1166 logmsg(" [4] Error opening file: %s", filename);
1167 free(ptr);
1168 return 0;
1169 }
1170 else {
1171 /* get the custom server control "commands" */
1172 error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream);
1173 fclose(stream);
1174 if(error) {
1175 logmsg("getpart() failed with error: %d", error);
1176 free(ptr);
1177 return 0;
1178 }
1179 }
1180 }
1181
1182 if(got_exit_signal) {
1183 free(ptr);
1184 free(cmd);
1185 return -1;
1186 }
1187
1188 /* If the word 'swsclose' is present anywhere in the reply chunk, the
1189 connection will be closed after the data has been sent to the requesting
1190 client... */
1191 if(strstr(buffer, "swsclose") || !count || req->close) {
1192 persistent = FALSE;
1193 logmsg("connection close instruction \"swsclose\" found in response");
1194 }
1195 if(strstr(buffer, "swsbounce")) {
1196 prevbounce = TRUE;
1197 logmsg("enable \"swsbounce\" in the next request");
1198 }
1199 else
1200 prevbounce = FALSE;
1201
1202 dump = fopen(responsedump, "ab");
1203 if(!dump) {
1204 error = errno;
1205 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1206 logmsg(" [5] Error opening file: %s", responsedump);
1207 free(ptr);
1208 free(cmd);
1209 return -1;
1210 }
1211
1212 responsesize = count;
1213 do {
1214 /* Ok, we send no more than N bytes at a time, just to make sure that
1215 larger chunks are split up so that the client will need to do multiple
1216 recv() calls to get it and thus we exercise that code better */
1217 size_t num = count;
1218 if(num > 20)
1219 num = 20;
1220
1221 retry:
1222 written = swrite(sock, buffer, num);
1223 if(written < 0) {
1224 if((EWOULDBLOCK == SOCKERRNO) || (EAGAIN == SOCKERRNO)) {
1225 wait_ms(10);
1226 goto retry;
1227 }
1228 sendfailure = TRUE;
1229 break;
1230 }
1231
1232 /* write to file as well */
1233 fwrite(buffer, 1, (size_t)written, dump);
1234
1235 count -= written;
1236 buffer += written;
1237
1238 if(req->writedelay) {
1239 int quarters = req->writedelay * 4;
1240 logmsg("Pausing %d seconds", req->writedelay);
1241 while((quarters > 0) && !got_exit_signal) {
1242 quarters--;
1243 wait_ms(250);
1244 }
1245 }
1246 } while((count > 0) && !got_exit_signal);
1247
1248 do {
1249 res = fclose(dump);
1250 } while(res && ((error = errno) == EINTR));
1251 if(res)
1252 logmsg("Error closing file %s error: %d %s",
1253 responsedump, error, strerror(error));
1254
1255 if(got_exit_signal) {
1256 free(ptr);
1257 free(cmd);
1258 return -1;
1259 }
1260
1261 if(sendfailure) {
1262 logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) "
1263 "were sent",
1264 responsesize-count, responsesize);
1265 prevtestno = req->testno;
1266 prevpartno = req->partno;
1267 free(ptr);
1268 free(cmd);
1269 return -1;
1270 }
1271
1272 logmsg("Response sent (%zu bytes) and written to %s",
1273 responsesize, responsedump);
1274 free(ptr);
1275
1276 if(cmdsize > 0) {
1277 char command[32];
1278 int quarters;
1279 int num;
1280 ptr = cmd;
1281 do {
1282 if(2 == sscanf(ptr, "%31s %d", command, &num)) {
1283 if(!strcmp("wait", command)) {
1284 logmsg("Told to sleep for %d seconds", num);
1285 quarters = num * 4;
1286 while((quarters > 0) && !got_exit_signal) {
1287 quarters--;
1288 res = wait_ms(250);
1289 if(res) {
1290 /* should not happen */
1291 error = errno;
1292 logmsg("wait_ms() failed with error: (%d) %s",
1293 error, strerror(error));
1294 break;
1295 }
1296 }
1297 if(!quarters)
1298 logmsg("Continuing after sleeping %d seconds", num);
1299 }
1300 else
1301 logmsg("Unknown command in reply command section");
1302 }
1303 ptr = strchr(ptr, '\n');
1304 if(ptr)
1305 ptr++;
1306 else
1307 ptr = NULL;
1308 } while(ptr && *ptr);
1309 }
1310 free(cmd);
1311 req->open = use_gopher?FALSE:persistent;
1312
1313 prevtestno = req->testno;
1314 prevpartno = req->partno;
1315
1316 return 0;
1317 }
1318
1319 static curl_socket_t connect_to(const char *ipaddr, unsigned short port)
1320 {
1321 srvr_sockaddr_union_t serveraddr;
1322 curl_socket_t serverfd;
1323 int error;
1324 int rc = 0;
1325 const char *op_br = "";
1326 const char *cl_br = "";
1327
1328 #ifdef ENABLE_IPV6
1329 if(socket_domain == AF_INET6) {
1330 op_br = "[";
1331 cl_br = "]";
1332 }
1333 #endif
1334
1335 if(!ipaddr)
1336 return CURL_SOCKET_BAD;
1337
1338 logmsg("about to connect to %s%s%s:%hu",
1339 op_br, ipaddr, cl_br, port);
1340
1341
1342 serverfd = socket(socket_domain, SOCK_STREAM, 0);
1343 if(CURL_SOCKET_BAD == serverfd) {
1344 error = SOCKERRNO;
1345 logmsg("Error creating socket for server connection: (%d) %s",
1346 error, strerror(error));
1347 return CURL_SOCKET_BAD;
1348 }
1349
1350 #ifdef TCP_NODELAY
1351 if(socket_domain_is_ip()) {
1352 /* Disable the Nagle algorithm */
1353 curl_socklen_t flag = 1;
1354 if(0 != setsockopt(serverfd, IPPROTO_TCP, TCP_NODELAY,
1355 (void *)&flag, sizeof(flag)))
1356 logmsg("====> TCP_NODELAY for server connection failed");
1357 }
1358 #endif
1359
1360 switch(socket_domain) {
1361 case AF_INET:
1362 memset(&serveraddr.sa4, 0, sizeof(serveraddr.sa4));
1363 serveraddr.sa4.sin_family = AF_INET;
1364 serveraddr.sa4.sin_port = htons(port);
1365 if(Curl_inet_pton(AF_INET, ipaddr, &serveraddr.sa4.sin_addr) < 1) {
1366 logmsg("Error inet_pton failed AF_INET conversion of '%s'", ipaddr);
1367 sclose(serverfd);
1368 return CURL_SOCKET_BAD;
1369 }
1370
1371 rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa4));
1372 break;
1373 #ifdef ENABLE_IPV6
1374 case AF_INET6:
1375 memset(&serveraddr.sa6, 0, sizeof(serveraddr.sa6));
1376 serveraddr.sa6.sin6_family = AF_INET6;
1377 serveraddr.sa6.sin6_port = htons(port);
1378 if(Curl_inet_pton(AF_INET6, ipaddr, &serveraddr.sa6.sin6_addr) < 1) {
1379 logmsg("Error inet_pton failed AF_INET6 conversion of '%s'", ipaddr);
1380 sclose(serverfd);
1381 return CURL_SOCKET_BAD;
1382 }
1383
1384 rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa6));
1385 break;
1386 #endif /* ENABLE_IPV6 */
1387 #ifdef USE_UNIX_SOCKETS
1388 case AF_UNIX:
1389 logmsg("Proxying through Unix socket is not (yet?) supported.");
1390 return CURL_SOCKET_BAD;
1391 #endif /* USE_UNIX_SOCKETS */
1392 }
1393
1394 if(got_exit_signal) {
1395 sclose(serverfd);
1396 return CURL_SOCKET_BAD;
1397 }
1398
1399 if(rc) {
1400 error = SOCKERRNO;
1401 logmsg("Error connecting to server port %hu: (%d) %s",
1402 port, error, strerror(error));
1403 sclose(serverfd);
1404 return CURL_SOCKET_BAD;
1405 }
1406
1407 logmsg("connected fine to %s%s%s:%hu, now tunnel",
1408 op_br, ipaddr, cl_br, port);
1409
1410 return serverfd;
1411 }
1412
1413 /*
1414 * A CONNECT has been received, a CONNECT response has been sent.
1415 *
1416 * This function needs to connect to the server, and then pass data between
1417 * the client and the server back and forth until the connection is closed by
1418 * either end.
1419 *
1420 * When doing FTP through a CONNECT proxy, we expect that the data connection
1421 * will be setup while the first connect is still being kept up. Therefore we
1422 * must accept a new connection and deal with it appropriately.
1423 */
1424
1425 #define data_or_ctrl(x) ((x)?"DATA":"CTRL")
1426
1427 #define CTRL 0
1428 #define DATA 1
1429
1430 static void http_connect(curl_socket_t *infdp,
1431 curl_socket_t rootfd,
1432 const char *ipaddr,
1433 unsigned short ipport)
1434 {
1435 curl_socket_t serverfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD};
1436 curl_socket_t clientfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD};
1437 ssize_t toc[2] = {0, 0}; /* number of bytes to client */
1438 ssize_t tos[2] = {0, 0}; /* number of bytes to server */
1439 char readclient[2][256];
1440 char readserver[2][256];
1441 bool poll_client_rd[2] = { TRUE, TRUE };
1442 bool poll_server_rd[2] = { TRUE, TRUE };
1443 bool poll_client_wr[2] = { TRUE, TRUE };
1444 bool poll_server_wr[2] = { TRUE, TRUE };
1445 bool primary = FALSE;
1446 bool secondary = FALSE;
1447 int max_tunnel_idx; /* CTRL or DATA */
1448 int loop;
1449 int i;
1450 int timeout_count = 0;
1451
1452 /* primary tunnel client endpoint already connected */
1453 clientfd[CTRL] = *infdp;
1454
1455 /* Sleep here to make sure the client reads CONNECT response's
1456 'end of headers' separate from the server data that follows.
1457 This is done to prevent triggering libcurl known bug #39. */
1458 for(loop = 2; (loop > 0) && !got_exit_signal; loop--)
1459 wait_ms(250);
1460 if(got_exit_signal)
1461 goto http_connect_cleanup;
1462
1463 serverfd[CTRL] = connect_to(ipaddr, ipport);
1464 if(serverfd[CTRL] == CURL_SOCKET_BAD)
1465 goto http_connect_cleanup;
1466
1467 /* Primary tunnel socket endpoints are now connected. Tunnel data back and
1468 forth over the primary tunnel until client or server breaks the primary
1469 tunnel, simultaneously allowing establishment, operation and teardown of
1470 a secondary tunnel that may be used for passive FTP data connection. */
1471
1472 max_tunnel_idx = CTRL;
1473 primary = TRUE;
1474
1475 while(!got_exit_signal) {
1476
1477 fd_set input;
1478 fd_set output;
1479 struct timeval timeout = {1, 0}; /* 1000 ms */
1480 ssize_t rc;
1481 curl_socket_t maxfd = (curl_socket_t)-1;
1482
1483 FD_ZERO(&input);
1484 FD_ZERO(&output);
1485
1486 if((clientfd[DATA] == CURL_SOCKET_BAD) &&
1487 (serverfd[DATA] == CURL_SOCKET_BAD) &&
1488 poll_client_rd[CTRL] && poll_client_wr[CTRL] &&
1489 poll_server_rd[CTRL] && poll_server_wr[CTRL]) {
1490 /* listener socket is monitored to allow client to establish
1491 secondary tunnel only when this tunnel is not established
1492 and primary one is fully operational */
1493 FD_SET(rootfd, &input);
1494 maxfd = rootfd;
1495 }
1496
1497 /* set tunnel sockets to wait for */
1498 for(i = 0; i <= max_tunnel_idx; i++) {
1499 /* client side socket monitoring */
1500 if(clientfd[i] != CURL_SOCKET_BAD) {
1501 if(poll_client_rd[i]) {
1502 /* unless told not to do so, monitor readability */
1503 FD_SET(clientfd[i], &input);
1504 if(clientfd[i] > maxfd)
1505 maxfd = clientfd[i];
1506 }
1507 if(poll_client_wr[i] && toc[i]) {
1508 /* unless told not to do so, monitor writability
1509 if there is data ready to be sent to client */
1510 FD_SET(clientfd[i], &output);
1511 if(clientfd[i] > maxfd)
1512 maxfd = clientfd[i];
1513 }
1514 }
1515 /* server side socket monitoring */
1516 if(serverfd[i] != CURL_SOCKET_BAD) {
1517 if(poll_server_rd[i]) {
1518 /* unless told not to do so, monitor readability */
1519 FD_SET(serverfd[i], &input);
1520 if(serverfd[i] > maxfd)
1521 maxfd = serverfd[i];
1522 }
1523 if(poll_server_wr[i] && tos[i]) {
1524 /* unless told not to do so, monitor writability
1525 if there is data ready to be sent to server */
1526 FD_SET(serverfd[i], &output);
1527 if(serverfd[i] > maxfd)
1528 maxfd = serverfd[i];
1529 }
1530 }
1531 }
1532 if(got_exit_signal)
1533 break;
1534
1535 do {
1536 rc = select((int)maxfd + 1, &input, &output, NULL, &timeout);
1537 } while(rc < 0 && errno == EINTR && !got_exit_signal);
1538
1539 if(got_exit_signal)
1540 break;
1541
1542 if(rc > 0) {
1543 /* socket action */
1544 bool tcp_fin_wr = FALSE;
1545 timeout_count = 0;
1546
1547 /* ---------------------------------------------------------- */
1548
1549 /* passive mode FTP may establish a secondary tunnel */
1550 if((clientfd[DATA] == CURL_SOCKET_BAD) &&
1551 (serverfd[DATA] == CURL_SOCKET_BAD) && FD_ISSET(rootfd, &input)) {
1552 /* a new connection on listener socket (most likely from client) */
1553 curl_socket_t datafd = accept(rootfd, NULL, NULL);
1554 if(datafd != CURL_SOCKET_BAD) {
1555 struct httprequest req2;
1556 int err = 0;
1557 memset(&req2, 0, sizeof(req2));
1558 logmsg("====> Client connect DATA");
1559 #ifdef TCP_NODELAY
1560 if(socket_domain_is_ip()) {
1561 /* Disable the Nagle algorithm */
1562 curl_socklen_t flag = 1;
1563 if(0 != setsockopt(datafd, IPPROTO_TCP, TCP_NODELAY,
1564 (void *)&flag, sizeof(flag)))
1565 logmsg("====> TCP_NODELAY for client DATA connection failed");
1566 }
1567 #endif
1568 init_httprequest(&req2);
1569 while(!req2.done_processing) {
1570 err = get_request(datafd, &req2);
1571 if(err < 0) {
1572 /* this socket must be closed, done or not */
1573 break;
1574 }
1575 }
1576
1577 /* skip this and close the socket if err < 0 */
1578 if(err >= 0) {
1579 err = send_doc(datafd, &req2);
1580 if(!err && req2.connect_request) {
1581 /* sleep to prevent triggering libcurl known bug #39. */
1582 for(loop = 2; (loop > 0) && !got_exit_signal; loop--)
1583 wait_ms(250);
1584 if(!got_exit_signal) {
1585 /* connect to the server */
1586 serverfd[DATA] = connect_to(ipaddr, req2.connect_port);
1587 if(serverfd[DATA] != CURL_SOCKET_BAD) {
1588 /* secondary tunnel established, now we have two
1589 connections */
1590 poll_client_rd[DATA] = TRUE;
1591 poll_client_wr[DATA] = TRUE;
1592 poll_server_rd[DATA] = TRUE;
1593 poll_server_wr[DATA] = TRUE;
1594 max_tunnel_idx = DATA;
1595 secondary = TRUE;
1596 toc[DATA] = 0;
1597 tos[DATA] = 0;
1598 clientfd[DATA] = datafd;
1599 datafd = CURL_SOCKET_BAD;
1600 }
1601 }
1602 }
1603 }
1604 if(datafd != CURL_SOCKET_BAD) {
1605 /* secondary tunnel not established */
1606 shutdown(datafd, SHUT_RDWR);
1607 sclose(datafd);
1608 }
1609 }
1610 if(got_exit_signal)
1611 break;
1612 }
1613
1614 /* ---------------------------------------------------------- */
1615
1616 /* react to tunnel endpoint readable/writable notifications */
1617 for(i = 0; i <= max_tunnel_idx; i++) {
1618 size_t len;
1619 if(clientfd[i] != CURL_SOCKET_BAD) {
1620 len = sizeof(readclient[i]) - tos[i];
1621 if(len && FD_ISSET(clientfd[i], &input)) {
1622 /* read from client */
1623 rc = sread(clientfd[i], &readclient[i][tos[i]], len);
1624 if(rc <= 0) {
1625 logmsg("[%s] got %zd, STOP READING client", data_or_ctrl(i), rc);
1626 shutdown(clientfd[i], SHUT_RD);
1627 poll_client_rd[i] = FALSE;
1628 }
1629 else {
1630 logmsg("[%s] READ %zd bytes from client", data_or_ctrl(i), rc);
1631 logmsg("[%s] READ \"%s\"", data_or_ctrl(i),
1632 data_to_hex(&readclient[i][tos[i]], rc));
1633 tos[i] += rc;
1634 }
1635 }
1636 }
1637 if(serverfd[i] != CURL_SOCKET_BAD) {
1638 len = sizeof(readserver[i])-toc[i];
1639 if(len && FD_ISSET(serverfd[i], &input)) {
1640 /* read from server */
1641 rc = sread(serverfd[i], &readserver[i][toc[i]], len);
1642 if(rc <= 0) {
1643 logmsg("[%s] got %zd, STOP READING server", data_or_ctrl(i), rc);
1644 shutdown(serverfd[i], SHUT_RD);
1645 poll_server_rd[i] = FALSE;
1646 }
1647 else {
1648 logmsg("[%s] READ %zd bytes from server", data_or_ctrl(i), rc);
1649 logmsg("[%s] READ \"%s\"", data_or_ctrl(i),
1650 data_to_hex(&readserver[i][toc[i]], rc));
1651 toc[i] += rc;
1652 }
1653 }
1654 }
1655 if(clientfd[i] != CURL_SOCKET_BAD) {
1656 if(toc[i] && FD_ISSET(clientfd[i], &output)) {
1657 /* write to client */
1658 rc = swrite(clientfd[i], readserver[i], toc[i]);
1659 if(rc <= 0) {
1660 logmsg("[%s] got %zd, STOP WRITING client", data_or_ctrl(i), rc);
1661 shutdown(clientfd[i], SHUT_WR);
1662 poll_client_wr[i] = FALSE;
1663 tcp_fin_wr = TRUE;
1664 }
1665 else {
1666 logmsg("[%s] SENT %zd bytes to client", data_or_ctrl(i), rc);
1667 logmsg("[%s] SENT \"%s\"", data_or_ctrl(i),
1668 data_to_hex(readserver[i], rc));
1669 if(toc[i] - rc)
1670 memmove(&readserver[i][0], &readserver[i][rc], toc[i]-rc);
1671 toc[i] -= rc;
1672 }
1673 }
1674 }
1675 if(serverfd[i] != CURL_SOCKET_BAD) {
1676 if(tos[i] && FD_ISSET(serverfd[i], &output)) {
1677 /* write to server */
1678 rc = swrite(serverfd[i], readclient[i], tos[i]);
1679 if(rc <= 0) {
1680 logmsg("[%s] got %zd, STOP WRITING server", data_or_ctrl(i), rc);
1681 shutdown(serverfd[i], SHUT_WR);
1682 poll_server_wr[i] = FALSE;
1683 tcp_fin_wr = TRUE;
1684 }
1685 else {
1686 logmsg("[%s] SENT %zd bytes to server", data_or_ctrl(i), rc);
1687 logmsg("[%s] SENT \"%s\"", data_or_ctrl(i),
1688 data_to_hex(readclient[i], rc));
1689 if(tos[i] - rc)
1690 memmove(&readclient[i][0], &readclient[i][rc], tos[i]-rc);
1691 tos[i] -= rc;
1692 }
1693 }
1694 }
1695 }
1696 if(got_exit_signal)
1697 break;
1698
1699 /* ---------------------------------------------------------- */
1700
1701 /* endpoint read/write disabling, endpoint closing and tunnel teardown */
1702 for(i = 0; i <= max_tunnel_idx; i++) {
1703 for(loop = 2; loop > 0; loop--) {
1704 /* loop twice to satisfy condition interdependencies without
1705 having to await select timeout or another socket event */
1706 if(clientfd[i] != CURL_SOCKET_BAD) {
1707 if(poll_client_rd[i] && !poll_server_wr[i]) {
1708 logmsg("[%s] DISABLED READING client", data_or_ctrl(i));
1709 shutdown(clientfd[i], SHUT_RD);
1710 poll_client_rd[i] = FALSE;
1711 }
1712 if(poll_client_wr[i] && !poll_server_rd[i] && !toc[i]) {
1713 logmsg("[%s] DISABLED WRITING client", data_or_ctrl(i));
1714 shutdown(clientfd[i], SHUT_WR);
1715 poll_client_wr[i] = FALSE;
1716 tcp_fin_wr = TRUE;
1717 }
1718 }
1719 if(serverfd[i] != CURL_SOCKET_BAD) {
1720 if(poll_server_rd[i] && !poll_client_wr[i]) {
1721 logmsg("[%s] DISABLED READING server", data_or_ctrl(i));
1722 shutdown(serverfd[i], SHUT_RD);
1723 poll_server_rd[i] = FALSE;
1724 }
1725 if(poll_server_wr[i] && !poll_client_rd[i] && !tos[i]) {
1726 logmsg("[%s] DISABLED WRITING server", data_or_ctrl(i));
1727 shutdown(serverfd[i], SHUT_WR);
1728 poll_server_wr[i] = FALSE;
1729 tcp_fin_wr = TRUE;
1730 }
1731 }
1732 }
1733 }
1734
1735 if(tcp_fin_wr)
1736 /* allow kernel to place FIN bit packet on the wire */
1737 wait_ms(250);
1738
1739 /* socket clearing */
1740 for(i = 0; i <= max_tunnel_idx; i++) {
1741 for(loop = 2; loop > 0; loop--) {
1742 if(clientfd[i] != CURL_SOCKET_BAD) {
1743 if(!poll_client_wr[i] && !poll_client_rd[i]) {
1744 logmsg("[%s] CLOSING client socket", data_or_ctrl(i));
1745 sclose(clientfd[i]);
1746 clientfd[i] = CURL_SOCKET_BAD;
1747 if(serverfd[i] == CURL_SOCKET_BAD) {
1748 logmsg("[%s] ENDING", data_or_ctrl(i));
1749 if(i == DATA)
1750 secondary = FALSE;
1751 else
1752 primary = FALSE;
1753 }
1754 }
1755 }
1756 if(serverfd[i] != CURL_SOCKET_BAD) {
1757 if(!poll_server_wr[i] && !poll_server_rd[i]) {
1758 logmsg("[%s] CLOSING server socket", data_or_ctrl(i));
1759 sclose(serverfd[i]);
1760 serverfd[i] = CURL_SOCKET_BAD;
1761 if(clientfd[i] == CURL_SOCKET_BAD) {
1762 logmsg("[%s] ENDING", data_or_ctrl(i));
1763 if(i == DATA)
1764 secondary = FALSE;
1765 else
1766 primary = FALSE;
1767 }
1768 }
1769 }
1770 }
1771 }
1772
1773 /* ---------------------------------------------------------- */
1774
1775 max_tunnel_idx = secondary ? DATA : CTRL;
1776
1777 if(!primary)
1778 /* exit loop upon primary tunnel teardown */
1779 break;
1780
1781 } /* (rc > 0) */
1782 else {
1783 timeout_count++;
1784 if(timeout_count > 5) {
1785 logmsg("CONNECT proxy timeout after %d idle seconds!", timeout_count);
1786 break;
1787 }
1788 }
1789 }
1790
1791 http_connect_cleanup:
1792
1793 for(i = DATA; i >= CTRL; i--) {
1794 if(serverfd[i] != CURL_SOCKET_BAD) {
1795 logmsg("[%s] CLOSING server socket (cleanup)", data_or_ctrl(i));
1796 shutdown(serverfd[i], SHUT_RDWR);
1797 sclose(serverfd[i]);
1798 }
1799 if(clientfd[i] != CURL_SOCKET_BAD) {
1800 logmsg("[%s] CLOSING client socket (cleanup)", data_or_ctrl(i));
1801 shutdown(clientfd[i], SHUT_RDWR);
1802 sclose(clientfd[i]);
1803 }
1804 if((serverfd[i] != CURL_SOCKET_BAD) ||
1805 (clientfd[i] != CURL_SOCKET_BAD)) {
1806 logmsg("[%s] ABORTING", data_or_ctrl(i));
1807 }
1808 }
1809
1810 *infdp = CURL_SOCKET_BAD;
1811 }
1812
1813 static void http2(struct httprequest *req)
1814 {
1815 (void)req;
1816 logmsg("switched to http2");
1817 /* left to implement */
1818 }
1819
1820
1821 /* returns a socket handle, or 0 if there are no more waiting sockets,
1822 or < 0 if there was an error */
1823 static curl_socket_t accept_connection(curl_socket_t sock)
1824 {
1825 curl_socket_t msgsock = CURL_SOCKET_BAD;
1826 int error;
1827 int flag = 1;
1828
1829 if(MAX_SOCKETS == num_sockets) {
1830 logmsg("Too many open sockets!");
1831 return CURL_SOCKET_BAD;
1832 }
1833
1834 msgsock = accept(sock, NULL, NULL);
1835
1836 if(got_exit_signal) {
1837 if(CURL_SOCKET_BAD != msgsock)
1838 sclose(msgsock);
1839 return CURL_SOCKET_BAD;
1840 }
1841
1842 if(CURL_SOCKET_BAD == msgsock) {
1843 error = SOCKERRNO;
1844 if(EAGAIN == error || EWOULDBLOCK == error) {
1845 /* nothing to accept */
1846 return 0;
1847 }
1848 logmsg("MAJOR ERROR: accept() failed with error: (%d) %s",
1849 error, strerror(error));
1850 return CURL_SOCKET_BAD;
1851 }
1852
1853 if(0 != curlx_nonblock(msgsock, TRUE)) {
1854 error = SOCKERRNO;
1855 logmsg("curlx_nonblock failed with error: (%d) %s",
1856 error, strerror(error));
1857 sclose(msgsock);
1858 return CURL_SOCKET_BAD;
1859 }
1860
1861 if(0 != setsockopt(msgsock, SOL_SOCKET, SO_KEEPALIVE,
1862 (void *)&flag, sizeof(flag))) {
1863 error = SOCKERRNO;
1864 logmsg("setsockopt(SO_KEEPALIVE) failed with error: (%d) %s",
1865 error, strerror(error));
1866 sclose(msgsock);
1867 return CURL_SOCKET_BAD;
1868 }
1869
1870 /*
1871 ** As soon as this server accepts a connection from the test harness it
1872 ** must set the server logs advisor read lock to indicate that server
1873 ** logs should not be read until this lock is removed by this server.
1874 */
1875
1876 if(!serverlogslocked)
1877 set_advisor_read_lock(SERVERLOGS_LOCK);
1878 serverlogslocked += 1;
1879
1880 logmsg("====> Client connect");
1881
1882 all_sockets[num_sockets] = msgsock;
1883 num_sockets += 1;
1884
1885 #ifdef TCP_NODELAY
1886 if(socket_domain_is_ip()) {
1887 /*
1888 * Disable the Nagle algorithm to make it easier to send out a large
1889 * response in many small segments to torture the clients more.
1890 */
1891 if(0 != setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
1892 (void *)&flag, sizeof(flag)))
1893 logmsg("====> TCP_NODELAY failed");
1894 }
1895 #endif
1896
1897 return msgsock;
1898 }
1899
1900 /* returns 1 if the connection should be serviced again immediately, 0 if there
1901 is no data waiting, or < 0 if it should be closed */
1902 static int service_connection(curl_socket_t msgsock, struct httprequest *req,
1903 curl_socket_t listensock,
1904 const char *connecthost)
1905 {
1906 if(got_exit_signal)
1907 return -1;
1908
1909 while(!req->done_processing) {
1910 int rc = get_request(msgsock, req);
1911 if(rc <= 0) {
1912 /* Nothing further to read now, possibly because the socket was closed */
1913 return rc;
1914 }
1915 }
1916
1917 if(prevbounce) {
1918 /* bounce treatment requested */
1919 if((req->testno == prevtestno) &&
1920 (req->partno == prevpartno)) {
1921 req->partno++;
1922 logmsg("BOUNCE part number to %ld", req->partno);
1923 }
1924 else {
1925 prevbounce = FALSE;
1926 prevtestno = -1;
1927 prevpartno = -1;
1928 }
1929 }
1930
1931 send_doc(msgsock, req);
1932 if(got_exit_signal)
1933 return -1;
1934
1935 if(req->testno < 0) {
1936 logmsg("special request received, no persistency");
1937 return -1;
1938 }
1939 if(!req->open) {
1940 logmsg("instructed to close connection after server-reply");
1941 return -1;
1942 }
1943
1944 if(req->connect_request) {
1945 /* a CONNECT request, setup and talk the tunnel */
1946 if(!is_proxy) {
1947 logmsg("received CONNECT but isn't running as proxy!");
1948 return 1;
1949 }
1950 else {
1951 http_connect(&msgsock, listensock, connecthost, req->connect_port);
1952 return -1;
1953 }
1954 }
1955
1956 if(req->upgrade_request) {
1957 /* an upgrade request, switch to http2 here */
1958 http2(req);
1959 return -1;
1960 }
1961
1962 /* if we got a CONNECT, loop and get another request as well! */
1963
1964 if(req->open) {
1965 logmsg("=> persistent connection request ended, awaits new request\n");
1966 return 1;
1967 }
1968
1969 return -1;
1970 }
1971
1972 int main(int argc, char *argv[])
1973 {
1974 srvr_sockaddr_union_t me;
1975 curl_socket_t sock = CURL_SOCKET_BAD;
1976 int wrotepidfile = 0;
1977 int flag;
1978 unsigned short port = DEFAULT_PORT;
1979 #ifdef USE_UNIX_SOCKETS
1980 const char *unix_socket = NULL;
1981 bool unlink_socket = false;
1982 #endif
1983 const char *pidname = ".http.pid";
1984 struct httprequest req;
1985 int rc = 0;
1986 int error;
1987 int arg = 1;
1988 long pid;
1989 const char *connecthost = "127.0.0.1";
1990 const char *socket_type = "IPv4";
1991 char port_str[11];
1992 const char *location_str = port_str;
1993
1994 /* a default CONNECT port is basically pointless but still ... */
1995 size_t socket_idx;
1996
1997 memset(&req, 0, sizeof(req));
1998
1999 while(argc>arg) {
2000 if(!strcmp("--version", argv[arg])) {
2001 puts("sws IPv4"
2002 #ifdef ENABLE_IPV6
2003 "/IPv6"
2004 #endif
2005 #ifdef USE_UNIX_SOCKETS
2006 "/unix"
2007 #endif
2008 );
2009 return 0;
2010 }
2011 else if(!strcmp("--pidfile", argv[arg])) {
2012 arg++;
2013 if(argc>arg)
2014 pidname = argv[arg++];
2015 }
2016 else if(!strcmp("--logfile", argv[arg])) {
2017 arg++;
2018 if(argc>arg)
2019 serverlogfile = argv[arg++];
2020 }
2021 else if(!strcmp("--gopher", argv[arg])) {
2022 arg++;
2023 use_gopher = TRUE;
2024 end_of_headers = "\r\n"; /* gopher style is much simpler */
2025 }
2026 else if(!strcmp("--ipv4", argv[arg])) {
2027 socket_type = "IPv4";
2028 socket_domain = AF_INET;
2029 location_str = port_str;
2030 arg++;
2031 }
2032 else if(!strcmp("--ipv6", argv[arg])) {
2033 #ifdef ENABLE_IPV6
2034 socket_type = "IPv6";
2035 socket_domain = AF_INET6;
2036 location_str = port_str;
2037 #endif
2038 arg++;
2039 }
2040 else if(!strcmp("--unix-socket", argv[arg])) {
2041 arg++;
2042 if(argc>arg) {
2043 #ifdef USE_UNIX_SOCKETS
2044 unix_socket = argv[arg];
2045 if(strlen(unix_socket) >= sizeof(me.sau.sun_path)) {
2046 fprintf(stderr, "sws: socket path must be shorter than %zu chars\n",
2047 sizeof(me.sau.sun_path));
2048 return 0;
2049 }
2050 socket_type = "unix";
2051 socket_domain = AF_UNIX;
2052 location_str = unix_socket;
2053 #endif
2054 arg++;
2055 }
2056 }
2057 else if(!strcmp("--port", argv[arg])) {
2058 arg++;
2059 if(argc>arg) {
2060 char *endptr;
2061 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
2062 if((endptr != argv[arg] + strlen(argv[arg])) ||
2063 (ulnum < 1025UL) || (ulnum > 65535UL)) {
2064 fprintf(stderr, "sws: invalid --port argument (%s)\n",
2065 argv[arg]);
2066 return 0;
2067 }
2068 port = curlx_ultous(ulnum);
2069 arg++;
2070 }
2071 }
2072 else if(!strcmp("--srcdir", argv[arg])) {
2073 arg++;
2074 if(argc>arg) {
2075 path = argv[arg];
2076 arg++;
2077 }
2078 }
2079 else if(!strcmp("--connect", argv[arg])) {
2080 /* The connect host IP number that the proxy will connect to no matter
2081 what the client asks for, but also use this as a hint that we run as
2082 a proxy and do a few different internal choices */
2083 arg++;
2084 if(argc>arg) {
2085 connecthost = argv[arg];
2086 arg++;
2087 is_proxy = TRUE;
2088 logmsg("Run as proxy, CONNECT to host %s", connecthost);
2089 }
2090 }
2091 else {
2092 puts("Usage: sws [option]\n"
2093 " --version\n"
2094 " --logfile [file]\n"
2095 " --pidfile [file]\n"
2096 " --ipv4\n"
2097 " --ipv6\n"
2098 " --unix-socket [file]\n"
2099 " --port [port]\n"
2100 " --srcdir [path]\n"
2101 " --connect [ip4-addr]\n"
2102 " --gopher");
2103 return 0;
2104 }
2105 }
2106
2107 msnprintf(port_str, sizeof(port_str), "port %hu", port);
2108
2109 #ifdef WIN32
2110 win32_init();
2111 atexit(win32_cleanup);
2112 #endif
2113
2114 install_signal_handlers();
2115
2116 pid = (long)getpid();
2117
2118 sock = socket(socket_domain, SOCK_STREAM, 0);
2119
2120 all_sockets[0] = sock;
2121 num_sockets = 1;
2122
2123 if(CURL_SOCKET_BAD == sock) {
2124 error = SOCKERRNO;
2125 logmsg("Error creating socket: (%d) %s",
2126 error, strerror(error));
2127 goto sws_cleanup;
2128 }
2129
2130 flag = 1;
2131 if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
2132 (void *)&flag, sizeof(flag))) {
2133 error = SOCKERRNO;
2134 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
2135 error, strerror(error));
2136 goto sws_cleanup;
2137 }
2138 if(0 != curlx_nonblock(sock, TRUE)) {
2139 error = SOCKERRNO;
2140 logmsg("curlx_nonblock failed with error: (%d) %s",
2141 error, strerror(error));
2142 goto sws_cleanup;
2143 }
2144
2145 switch(socket_domain) {
2146 case AF_INET:
2147 memset(&me.sa4, 0, sizeof(me.sa4));
2148 me.sa4.sin_family = AF_INET;
2149 me.sa4.sin_addr.s_addr = INADDR_ANY;
2150 me.sa4.sin_port = htons(port);
2151 rc = bind(sock, &me.sa, sizeof(me.sa4));
2152 break;
2153 #ifdef ENABLE_IPV6
2154 case AF_INET6:
2155 memset(&me.sa6, 0, sizeof(me.sa6));
2156 me.sa6.sin6_family = AF_INET6;
2157 me.sa6.sin6_addr = in6addr_any;
2158 me.sa6.sin6_port = htons(port);
2159 rc = bind(sock, &me.sa, sizeof(me.sa6));
2160 break;
2161 #endif /* ENABLE_IPV6 */
2162 #ifdef USE_UNIX_SOCKETS
2163 case AF_UNIX:
2164 memset(&me.sau, 0, sizeof(me.sau));
2165 me.sau.sun_family = AF_UNIX;
2166 strncpy(me.sau.sun_path, unix_socket, sizeof(me.sau.sun_path));
2167 rc = bind(sock, &me.sa, sizeof(me.sau));
2168 if(0 != rc && errno == EADDRINUSE) {
2169 struct stat statbuf;
2170 /* socket already exists. Perhaps it is stale? */
2171 int unixfd = socket(AF_UNIX, SOCK_STREAM, 0);
2172 if(CURL_SOCKET_BAD == unixfd) {
2173 error = SOCKERRNO;
2174 logmsg("Error binding socket, failed to create socket at %s: (%d) %s",
2175 unix_socket, error, strerror(error));
2176 goto sws_cleanup;
2177 }
2178 /* check whether the server is alive */
2179 rc = connect(unixfd, &me.sa, sizeof(me.sau));
2180 error = errno;
2181 close(unixfd);
2182 if(ECONNREFUSED != error) {
2183 logmsg("Error binding socket, failed to connect to %s: (%d) %s",
2184 unix_socket, error, strerror(error));
2185 goto sws_cleanup;
2186 }
2187 /* socket server is not alive, now check if it was actually a socket.
2188 * Systems which have Unix sockets will also have lstat */
2189 rc = lstat(unix_socket, &statbuf);
2190 if(0 != rc) {
2191 logmsg("Error binding socket, failed to stat %s: (%d) %s",
2192 unix_socket, errno, strerror(errno));
2193 goto sws_cleanup;
2194 }
2195 if((statbuf.st_mode & S_IFSOCK) != S_IFSOCK) {
2196 logmsg("Error binding socket, failed to stat %s: (%d) %s",
2197 unix_socket, error, strerror(error));
2198 goto sws_cleanup;
2199 }
2200 /* dead socket, cleanup and retry bind */
2201 rc = unlink(unix_socket);
2202 if(0 != rc) {
2203 logmsg("Error binding socket, failed to unlink %s: (%d) %s",
2204 unix_socket, errno, strerror(errno));
2205 goto sws_cleanup;
2206 }
2207 /* stale socket is gone, retry bind */
2208 rc = bind(sock, &me.sa, sizeof(me.sau));
2209 }
2210 break;
2211 #endif /* USE_UNIX_SOCKETS */
2212 }
2213 if(0 != rc) {
2214 error = SOCKERRNO;
2215 logmsg("Error binding socket on %s: (%d) %s",
2216 location_str, error, strerror(error));
2217 goto sws_cleanup;
2218 }
2219
2220 logmsg("Running %s %s version on %s",
2221 use_gopher?"GOPHER":"HTTP", socket_type, location_str);
2222
2223 /* start accepting connections */
2224 rc = listen(sock, 5);
2225 if(0 != rc) {
2226 error = SOCKERRNO;
2227 logmsg("listen() failed with error: (%d) %s",
2228 error, strerror(error));
2229 goto sws_cleanup;
2230 }
2231
2232 #ifdef USE_UNIX_SOCKETS
2233 /* listen succeeds, so let's assume a valid listening Unix socket */
2234 unlink_socket = true;
2235 #endif
2236
2237 /*
2238 ** As soon as this server writes its pid file the test harness will
2239 ** attempt to connect to this server and initiate its verification.
2240 */
2241
2242 wrotepidfile = write_pidfile(pidname);
2243 if(!wrotepidfile)
2244 goto sws_cleanup;
2245
2246 /* initialization of httprequest struct is done before get_request(), but
2247 the pipelining struct field must be initialized previously to FALSE
2248 every time a new connection arrives. */
2249
2250 init_httprequest(&req);
2251
2252 for(;;) {
2253 fd_set input;
2254 fd_set output;
2255 struct timeval timeout = {0, 250000L}; /* 250 ms */
2256 curl_socket_t maxfd = (curl_socket_t)-1;
2257
2258 /* Clear out closed sockets */
2259 for(socket_idx = num_sockets - 1; socket_idx >= 1; --socket_idx) {
2260 if(CURL_SOCKET_BAD == all_sockets[socket_idx]) {
2261 char *dst = (char *) (all_sockets + socket_idx);
2262 char *src = (char *) (all_sockets + socket_idx + 1);
2263 char *end = (char *) (all_sockets + num_sockets);
2264 memmove(dst, src, end - src);
2265 num_sockets -= 1;
2266 }
2267 }
2268
2269 if(got_exit_signal)
2270 goto sws_cleanup;
2271
2272 /* Set up for select */
2273 FD_ZERO(&input);
2274 FD_ZERO(&output);
2275
2276 for(socket_idx = 0; socket_idx < num_sockets; ++socket_idx) {
2277 /* Listen on all sockets */
2278 FD_SET(all_sockets[socket_idx], &input);
2279 if(all_sockets[socket_idx] > maxfd)
2280 maxfd = all_sockets[socket_idx];
2281 }
2282
2283 if(got_exit_signal)
2284 goto sws_cleanup;
2285
2286 do {
2287 rc = select((int)maxfd + 1, &input, &output, NULL, &timeout);
2288 } while(rc < 0 && errno == EINTR && !got_exit_signal);
2289
2290 if(got_exit_signal)
2291 goto sws_cleanup;
2292
2293 if(rc < 0) {
2294 error = SOCKERRNO;
2295 logmsg("select() failed with error: (%d) %s",
2296 error, strerror(error));
2297 goto sws_cleanup;
2298 }
2299
2300 if(rc == 0) {
2301 /* Timed out - try again */
2302 continue;
2303 }
2304
2305 /* Check if the listening socket is ready to accept */
2306 if(FD_ISSET(all_sockets[0], &input)) {
2307 /* Service all queued connections */
2308 curl_socket_t msgsock;
2309 do {
2310 msgsock = accept_connection(sock);
2311 logmsg("accept_connection %d returned %d", sock, msgsock);
2312 if(CURL_SOCKET_BAD == msgsock)
2313 goto sws_cleanup;
2314 } while(msgsock > 0);
2315 }
2316
2317 /* Service all connections that are ready */
2318 for(socket_idx = 1; socket_idx < num_sockets; ++socket_idx) {
2319 if(FD_ISSET(all_sockets[socket_idx], &input)) {
2320 if(got_exit_signal)
2321 goto sws_cleanup;
2322
2323 /* Service this connection until it has nothing available */
2324 do {
2325 rc = service_connection(all_sockets[socket_idx], &req, sock,
2326 connecthost);
2327 if(got_exit_signal)
2328 goto sws_cleanup;
2329
2330 if(rc < 0) {
2331 logmsg("====> Client disconnect %d", req.connmon);
2332
2333 if(req.connmon) {
2334 const char *keepopen = "[DISCONNECT]\n";
2335 storerequest(keepopen, strlen(keepopen));
2336 }
2337
2338 if(!req.open)
2339 /* When instructed to close connection after server-reply we
2340 wait a very small amount of time before doing so. If this
2341 is not done client might get an ECONNRESET before reading
2342 a single byte of server-reply. */
2343 wait_ms(50);
2344
2345 if(all_sockets[socket_idx] != CURL_SOCKET_BAD) {
2346 sclose(all_sockets[socket_idx]);
2347 all_sockets[socket_idx] = CURL_SOCKET_BAD;
2348 }
2349
2350 serverlogslocked -= 1;
2351 if(!serverlogslocked)
2352 clear_advisor_read_lock(SERVERLOGS_LOCK);
2353
2354 if(req.testno == DOCNUMBER_QUIT)
2355 goto sws_cleanup;
2356 }
2357
2358 /* Reset the request, unless we're still in the middle of reading */
2359 if(rc != 0)
2360 init_httprequest(&req);
2361 } while(rc > 0);
2362 }
2363 }
2364
2365 if(got_exit_signal)
2366 goto sws_cleanup;
2367 }
2368
2369 sws_cleanup:
2370
2371 for(socket_idx = 1; socket_idx < num_sockets; ++socket_idx)
2372 if((all_sockets[socket_idx] != sock) &&
2373 (all_sockets[socket_idx] != CURL_SOCKET_BAD))
2374 sclose(all_sockets[socket_idx]);
2375
2376 if(sock != CURL_SOCKET_BAD)
2377 sclose(sock);
2378
2379 #ifdef USE_UNIX_SOCKETS
2380 if(unlink_socket && socket_domain == AF_UNIX) {
2381 rc = unlink(unix_socket);
2382 logmsg("unlink(%s) = %d (%s)", unix_socket, rc, strerror(rc));
2383 }
2384 #endif
2385
2386 if(got_exit_signal)
2387 logmsg("signalled to die");
2388
2389 if(wrotepidfile)
2390 unlink(pidname);
2391
2392 if(serverlogslocked) {
2393 serverlogslocked = 0;
2394 clear_advisor_read_lock(SERVERLOGS_LOCK);
2395 }
2396
2397 restore_signal_handlers();
2398
2399 if(got_exit_signal) {
2400 logmsg("========> %s sws (%s pid: %ld) exits with signal (%d)",
2401 socket_type, location_str, pid, exit_signal);
2402 /*
2403 * To properly set the return status of the process we
2404 * must raise the same signal SIGINT or SIGTERM that we
2405 * caught and let the old handler take care of it.
2406 */
2407 raise(exit_signal);
2408 }
2409
2410 logmsg("========> sws quits");
2411 return 0;
2412 }