026874d746aeee131f1b98103ea4bcc53e3ee824
[platform/upstream/curl.git] / tests / server / sws.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, 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 http://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  * $Id$
22  ***************************************************************************/
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 #include "setup.h" /* portability help from the lib directory */
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <stdarg.h>
36 #include <signal.h>
37 #include <time.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h>
46 #endif
47 #ifdef HAVE_NETINET_IN_H
48 #include <netinet/in.h>
49 #endif
50 #ifdef _XOPEN_SOURCE_EXTENDED
51 /* This define is "almost" required to build on HPUX 11 */
52 #include <arpa/inet.h>
53 #endif
54 #ifdef HAVE_NETDB_H
55 #include <netdb.h>
56 #endif
57
58 #include "curlx.h" /* from the private lib dir */
59 #include "getpart.h"
60
61 #ifdef ENABLE_IPV6
62 #define SWS_IPV6
63 #endif
64
65 #ifndef FALSE
66 #define FALSE 0
67 #endif
68 #ifndef TRUE
69 #define TRUE 1
70 #endif
71
72 #if defined(WIN32) && !defined(__CYGWIN__)
73 #include <windows.h>
74 #include <winsock2.h>
75 #include <process.h>
76
77 #define sleep(sec)   Sleep ((sec)*1000)
78
79 #define EINPROGRESS  WSAEINPROGRESS
80 #define EWOULDBLOCK  WSAEWOULDBLOCK
81 #define EISCONN      WSAEISCONN
82 #define ENOTSOCK     WSAENOTSOCK
83 #define ECONNREFUSED WSAECONNREFUSED
84
85 static void win32_cleanup(void);
86
87 #if defined(ENABLE_IPV6) && defined(__MINGW32__)
88 const struct in6_addr in6addr_any = {{ IN6ADDR_ANY_INIT }};
89 #endif
90 #endif
91
92 /* include memdebug.h last */
93 #include "memdebug.h"
94
95 #define REQBUFSIZ 150000
96 #define REQBUFSIZ_TXT "149999"
97
98 long prevtestno=-1; /* previous test number we served */
99 long prevpartno=-1; /* previous part number we served */
100 bool prevbounce;    /* instructs the server to increase the part number for
101                        a test in case the identical testno+partno request
102                        shows up again */
103
104 struct httprequest {
105   char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */
106   int offset;     /* size of the incoming request */
107   long testno;     /* test number found in the request */
108   long partno;     /* part number found in the request */
109   int open;       /* keep connection open info, as found in the request */
110   bool auth_req;  /* authentication required, don't wait for body unless
111                      there's an Authorization header */
112   bool auth;      /* Authorization header present in the incoming request */
113   size_t cl;      /* Content-Length of the incoming request */
114   bool digest;    /* Authorization digest header found */
115   bool ntlm;      /* Authorization ntlm header found */
116 };
117
118 int ProcessRequest(struct httprequest *req);
119 void storerequest(char *reqbuf);
120
121 #define DEFAULT_PORT 8999
122
123 #ifndef DEFAULT_LOGFILE
124 #define DEFAULT_LOGFILE "log/sws.log"
125 #endif
126
127 #define SWSVERSION "cURL test suite HTTP server/0.1"
128
129 #define REQUEST_DUMP  "log/server.input"
130 #define RESPONSE_DUMP "log/server.response"
131
132 #define TEST_DATA_PATH "%s/data/test%ld"
133
134 /* very-big-path support */
135 #define MAXDOCNAMELEN 140000
136 #define MAXDOCNAMELEN_TXT "139999"
137
138 #define REQUEST_KEYWORD_SIZE 256
139
140 #define CMD_AUTH_REQUIRED "auth_required"
141
142 #define END_OF_HEADERS "\r\n\r\n"
143
144 /* global variable, where to find the 'data' dir */
145 const char *path=".";
146
147 enum {
148   DOCNUMBER_NOTHING = -7,
149   DOCNUMBER_QUIT    = -6,
150   DOCNUMBER_BADCONNECT = -5,
151   DOCNUMBER_INTERNAL= -4,
152   DOCNUMBER_CONNECT = -3,
153   DOCNUMBER_WERULEZ = -2,
154   DOCNUMBER_404     = -1
155 };
156
157
158 /* sent as reply to a QUIT */
159 static const char *docquit =
160 "HTTP/1.1 200 Goodbye" END_OF_HEADERS;
161
162 /* sent as reply to a CONNECT */
163 static const char *docconnect =
164 "HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS;
165
166 /* sent as reply to a "bad" CONNECT */
167 static const char *docbadconnect =
168 "HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS;
169
170 /* send back this on 404 file not found */
171 static const char *doc404 = "HTTP/1.1 404 Not Found\r\n"
172     "Server: " SWSVERSION "\r\n"
173     "Connection: close\r\n"
174     "Content-Type: text/html"
175     END_OF_HEADERS
176     "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
177     "<HTML><HEAD>\n"
178     "<TITLE>404 Not Found</TITLE>\n"
179     "</HEAD><BODY>\n"
180     "<H1>Not Found</H1>\n"
181     "The requested URL was not found on this server.\n"
182     "<P><HR><ADDRESS>" SWSVERSION "</ADDRESS>\n" "</BODY></HTML>\n";
183
184 #ifdef SIGPIPE
185 static volatile int sigpipe;  /* Why? It's not used */
186 #endif
187
188 static void logmsg(const char *msg, ...)
189 {
190   time_t t = time(NULL);
191   va_list ap;
192   struct tm *curr_time = localtime(&t);
193   char buffer[256]; /* possible overflow if you pass in a huge string */
194   FILE *logfp;
195
196   va_start(ap, msg);
197   vsprintf(buffer, msg, ap);
198   va_end(ap);
199
200   logfp = fopen(DEFAULT_LOGFILE, "a");
201
202   fprintf(logfp?logfp:stderr, /* write to stderr if the logfile doesn't open */
203           "%02d:%02d:%02d %s\n",
204           curr_time->tm_hour,
205           curr_time->tm_min,
206           curr_time->tm_sec, buffer);
207   if(logfp)
208     fclose(logfp);
209 }
210
211
212 #ifdef SIGPIPE
213 static void sigpipe_handler(int sig)
214 {
215   (void)sig; /* prevent warning */
216   sigpipe = 1;
217 }
218 #endif
219
220 #if defined(WIN32) && !defined(__CYGWIN__)
221 #undef perror
222 #define perror(m) win32_perror(m)
223
224 static void win32_perror (const char *msg)
225 {
226   char buf[256];
227   DWORD err = WSAGetLastError();
228
229   if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
230                      LANG_NEUTRAL, buf, sizeof(buf), NULL))
231      snprintf(buf, sizeof(buf), "Unknown error %lu (%#lx)", err, err);
232   if (msg)
233      fprintf(stderr, "%s: ", msg);
234   fprintf(stderr, "%s\n", buf);
235 }
236 #endif
237
238 static char *test2file(long testno)
239 {
240   static char filename[256];
241   sprintf(filename, TEST_DATA_PATH, path, testno);
242   return filename;
243 }
244
245
246 int ProcessRequest(struct httprequest *req)
247 {
248   char *line=req->reqbuf;
249   char chunked=FALSE;
250   static char request[REQUEST_KEYWORD_SIZE];
251   static char doc[MAXDOCNAMELEN];
252   char logbuf[256];
253   int prot_major, prot_minor;
254   char *end;
255   end = strstr(req->reqbuf, END_OF_HEADERS);
256
257   /* try to figure out the request characteristics as soon as possible, but
258      only once! */
259   if((req->testno == DOCNUMBER_NOTHING) &&
260      sscanf(line, "%" REQBUFSIZ_TXT"s %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
261             request,
262             doc,
263             &prot_major,
264             &prot_minor) == 4) {
265     char *ptr;
266
267     /* find the last slash */
268     ptr = strrchr(doc, '/');
269
270     /* get the number after it */
271     if(ptr) {
272       FILE *stream;
273       char *filename;
274
275       if((strlen(doc) + strlen(request)) < 200)
276         sprintf(logbuf, "Got request: %s %s HTTP/%d.%d",
277                 request, doc, prot_major, prot_minor);
278       else
279         sprintf(logbuf, "Got a *HUGE* request HTTP/%d.%d",
280                 prot_major, prot_minor);
281       logmsg(logbuf);
282
283       if(!strncmp("/verifiedserver", ptr, 15)) {
284         logmsg("Are-we-friendly question received");
285         req->testno = DOCNUMBER_WERULEZ;
286         return 1; /* done */
287       }
288
289       if(!strncmp("/quit", ptr, 15)) {
290         logmsg("Request-to-quit received");
291         req->testno = DOCNUMBER_QUIT;
292         return 1; /* done */
293       }
294
295       ptr++; /* skip the slash */
296
297       req->testno = strtol(ptr, &ptr, 10);
298
299       if(req->testno > 10000) {
300         req->partno = req->testno % 10000;
301         req->testno /= 10000;
302       }
303       else
304         req->partno = 0;
305
306       sprintf(logbuf, "Requested test number %ld part %ld",
307               req->testno, req->partno);
308
309       logmsg(logbuf);
310
311       filename = test2file(req->testno);
312
313       stream=fopen(filename, "rb");
314       if(!stream) {
315         logmsg("Couldn't open test file %d", req->testno);
316         req->open = FALSE; /* closes connection */
317         return 0;
318       }
319       else {
320         char *cmd = NULL;
321         size_t cmdsize = 0;
322
323         /* get the custom server control "commands" */
324         cmd = (char *)spitout(stream, "reply", "servercmd", &cmdsize);
325         fclose(stream);
326
327         if(cmdsize) {
328           logmsg("Found a reply-servercmd section!");
329
330           if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) {
331             logmsg("instructed to require authorization header");
332             req->auth_req = TRUE;
333           }
334           free(cmd);
335         }
336       }
337     }
338     else {
339       if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
340                 doc, &prot_major, &prot_minor) == 3) {
341         sprintf(logbuf, "Receiced a CONNECT %s HTTP/%d.%d request",
342                 doc, prot_major, prot_minor);
343         logmsg(logbuf);
344
345         if(prot_major*10+prot_minor == 10)
346           req->open = FALSE; /* HTTP 1.0 closes connection by default */
347
348         if(!strncmp(doc, "bad", 3))
349           /* if the host name starts with bad, we fake an error here */
350           req->testno = DOCNUMBER_BADCONNECT;
351         else if(!strncmp(doc, "test", 4)) {
352           /* if the host name starts with test, the port number used in the
353              CONNECT line will be used as test number! */
354           char *ptr = strchr(doc, ':');
355           if(ptr)
356             req->testno = atoi(ptr+1);
357           else
358             req->testno = DOCNUMBER_CONNECT;
359         }
360         else
361           req->testno = DOCNUMBER_CONNECT;
362       }
363       else {
364         logmsg("Did not find test number in PATH");
365         req->testno = DOCNUMBER_404;
366       }
367     }
368   }
369
370   if(!end)
371     /* we don't have a complete request yet! */
372     return 0;
373
374   /* **** Persistancy ****
375    *
376    * If the request is a HTTP/1.0 one, we close the connection unconditionally
377    * when we're done.
378    *
379    * If the request is a HTTP/1.1 one, we MUST check for a "Connection:"
380    * header that might say "close". If it does, we close a connection when
381    * this request is processed. Otherwise, we keep the connection alive for X
382    * seconds.
383    */
384
385   do {
386     if(!req->cl && curlx_strnequal("Content-Length:", line, 15)) {
387       /* If we don't ignore content-length, we read it and we read the whole
388          request including the body before we return. If we've been told to
389          ignore the content-length, we will return as soon as all headers
390          have been received */
391       req->cl = strtol(line+15, &line, 10);
392
393       logmsg("Found Content-Length: %d in the request", req->cl);
394       break;
395     }
396     else if(curlx_strnequal("Transfer-Encoding: chunked", line,
397                             strlen("Transfer-Encoding: chunked"))) {
398       /* chunked data coming in */
399       chunked = TRUE;
400     }
401
402     if(chunked) {
403       if(strstr(req->reqbuf, "\r\n0\r\n"))
404         /* end of chunks reached */
405         return 1; /* done */
406       else
407         return 0; /* not done */
408     }
409
410     line = strchr(line, '\n');
411     if(line)
412       line++;
413   } while(line);
414
415   if(!req->auth && strstr(req->reqbuf, "Authorization:")) {
416     req->auth = TRUE; /* Authorization: header present! */
417     if(req->auth_req)
418       logmsg("Authorization header found, as required");
419   }
420
421   if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) {
422     /* If the client is passing this Digest-header, we set the part number
423        to 1000. Not only to spice up the complexity of this, but to make
424        Digest stuff to work in the test suite. */
425     req->partno += 1000;
426     req->digest = TRUE; /* header found */
427     logmsg("Received Digest request, sending back data %d", req->partno);
428   }
429   else if(!req->ntlm &&
430           strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) {
431     /* If the client is passing this type-3 NTLM header */
432     req->partno += 1002;
433     req->ntlm = TRUE; /* NTLM found */
434     logmsg("Received NTLM type-3, xxxxxxxxxxxxx sending back data %d", req->partno);
435     if(req->cl) {
436       logmsg("  Expecting %d POSTed bytes", req->cl);
437     }
438   }
439   else if(!req->ntlm &&
440           strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) {
441     /* If the client is passing this type-1 NTLM header */
442     req->partno += 1001;
443     req->ntlm = TRUE; /* NTLM found */
444     logmsg("Received NTLM type-1, sending back data %d", req->partno);
445   }
446   if(strstr(req->reqbuf, "Connection: close"))
447     req->open = FALSE; /* close connection after this request */
448
449   /* If authentication is required and no auth was provided, end now. This
450      makes the server NOT wait for PUT/POST data and you can then make the
451      test case send a rejection before any such data has been sent. Test case
452      154 uses this.*/
453   if(req->auth_req && !req->auth)
454     return 1;
455
456   if(req->cl) {
457     if(req->cl <= strlen(end+strlen(END_OF_HEADERS)))
458       return 1; /* done */
459     else
460       return 0; /* not complete yet */
461   }
462   return 1; /* done */
463 }
464
465 /* store the entire request in a file */
466 void storerequest(char *reqbuf)
467 {
468   FILE *dump;
469
470   dump = fopen(REQUEST_DUMP, "ab"); /* b is for windows-preparing */
471   if(dump) {
472     size_t len = strlen(reqbuf);
473     fwrite(reqbuf, 1, len, dump);
474
475     fclose(dump);
476     logmsg("Wrote request (%d bytes) input to " REQUEST_DUMP,
477            (int)len);
478   }
479   else {
480     logmsg("Failed to write request input to " REQUEST_DUMP);
481   }
482 }
483
484 /* return 0 on success, non-zero on failure */
485 static int get_request(int sock, struct httprequest *req)
486 {
487   int fail= FALSE;
488   char *reqbuf = req->reqbuf;
489
490   /*** Init the httpreqest structure properly for the upcoming request ***/
491   memset(req, 0, sizeof(struct httprequest));
492
493   /* here's what should not be 0 from the start */
494   req->testno = DOCNUMBER_NOTHING; /* safe default */
495   req->open = TRUE; /* connection should remain open and wait for more
496                        commands */
497
498   /*** end of httprequest init ***/
499
500   while (req->offset < REQBUFSIZ) {
501     int got = sread(sock, reqbuf + req->offset, REQBUFSIZ - req->offset);
502     if (got <= 0) {
503       if (got < 0) {
504         perror("recv");
505         logmsg("recv() returned error");
506         return DOCNUMBER_INTERNAL;
507       }
508       logmsg("Connection closed by client");
509       reqbuf[req->offset]=0;
510
511       /* dump the request receivied so far to the external file */
512       storerequest(reqbuf);
513       return DOCNUMBER_INTERNAL;
514     }
515     req->offset += got;
516
517     reqbuf[req->offset] = 0;
518
519     if(ProcessRequest(req))
520       break;
521   }
522
523   if (req->offset >= REQBUFSIZ) {
524     logmsg("Request buffer overflow, closing connection");
525     reqbuf[REQBUFSIZ-1]=0;
526     fail = TRUE;
527     /* dump the request to an external file anyway */
528   }
529   else
530     reqbuf[req->offset]=0;
531
532   /* dump the request to an external file */
533   storerequest(reqbuf);
534
535   return fail; /* success */
536 }
537
538 /* returns -1 on failure */
539 static int send_doc(int sock, struct httprequest *req)
540 {
541   int written;
542   size_t count;
543   const char *buffer;
544   char *ptr;
545   FILE *stream;
546   char *cmd=NULL;
547   size_t cmdsize=0;
548   FILE *dump;
549   int persistant = TRUE;
550   size_t responsesize;
551
552   static char weare[256];
553
554   char partbuf[80]="data";
555
556   req->open = FALSE;
557
558   logmsg("Send response number %d part %d", req->testno, req->partno);
559
560   if(req->testno < 0) {
561     switch(req->testno) {
562     case DOCNUMBER_QUIT:
563       logmsg("Replying to QUIT");
564       buffer = docquit;
565       break;
566     case DOCNUMBER_WERULEZ:
567       /* we got a "friends?" question, reply back that we sure are */
568       logmsg("Identifying ourselves as friends");
569       sprintf(weare, "HTTP/1.1 200 OK\r\n\r\nWE ROOLZ: %d\r\n",
570               (int)getpid());
571       buffer = weare;
572       break;
573     case DOCNUMBER_INTERNAL:
574       logmsg("Bailing out due to internal error");
575       return -1;
576     case DOCNUMBER_CONNECT:
577       logmsg("Replying to CONNECT");
578       buffer = docconnect;
579       break;
580     case DOCNUMBER_BADCONNECT:
581       logmsg("Replying to a bad CONNECT");
582       buffer = docbadconnect;
583       break;
584     case DOCNUMBER_404:
585     default:
586       logmsg("Replying to with a 404");
587       buffer = doc404;
588       break;
589     }
590     ptr = NULL;
591     stream=NULL;
592
593     count = strlen(buffer);
594   }
595   else {
596     char *filename = test2file(req->testno);
597
598     if(0 != req->partno)
599       sprintf(partbuf, "data%ld", req->partno);
600
601     stream=fopen(filename, "rb");
602     if(!stream) {
603       logmsg("Couldn't open test file");
604       return 0;
605     }
606     else {
607       buffer = spitout(stream, "reply", partbuf, &count);
608       ptr = (char *)buffer;
609       fclose(stream);
610     }
611
612     /* re-open the same file again */
613     stream=fopen(filename, "rb");
614     if(!stream) {
615       logmsg("Couldn't open test file");
616       return 0;
617     }
618     else {
619       /* get the custom server control "commands" */
620       cmd = (char *)spitout(stream, "reply", "postcmd", &cmdsize);
621       fclose(stream);
622     }
623   }
624
625   dump = fopen(RESPONSE_DUMP, "ab"); /* b is for windows-preparing */
626   if(!dump) {
627     logmsg("couldn't create logfile: " RESPONSE_DUMP);
628     return -1;
629   }
630
631   /* If the word 'swsclose' is present anywhere in the reply chunk, the
632      connection will be closed after the data has been sent to the requesting
633      client... */
634   if(strstr(buffer, "swsclose") || !count) {
635     persistant = FALSE;
636     logmsg("connection close instruction \"swsclose\" found in response");
637   }
638   if(strstr(buffer, "swsbounce")) {
639     prevbounce = TRUE;
640     logmsg("enable \"swsbounce\" in the next request");
641   }
642   else
643     prevbounce = FALSE;
644
645
646   responsesize = count;
647   do {
648     written = swrite(sock, buffer, count);
649     if (written < 0) {
650       logmsg("Sending response failed and we bailed out!");
651       return -1;
652     }
653     /* write to file as well */
654     fwrite(buffer, 1, written, dump);
655
656     count -= written;
657     buffer += written;
658   } while(count>0);
659
660   fclose(dump);
661
662   logmsg("Response sent (%d bytes) and written to " RESPONSE_DUMP,
663          responsesize);
664
665   if(ptr)
666     free(ptr);
667
668   if(cmdsize > 0 ) {
669     char command[32];
670     int num;
671     char *ptr=cmd;
672     do {
673       if(2 == sscanf(ptr, "%31s %d", command, &num)) {
674         if(!strcmp("wait", command)) {
675           logmsg("Told to sleep for %d seconds", num);
676           sleep(num); /* wait this many seconds */
677         }
678         else
679           logmsg("Unknown command in reply command section");
680       }
681       ptr = strchr(ptr, '\n');
682       if(ptr)
683         ptr++;
684       else
685         ptr = NULL;
686     } while(ptr && *ptr);
687   }
688   if(cmd)
689     free(cmd);
690
691   req->open = persistant;
692
693   prevtestno = req->testno;
694   prevpartno = req->partno;
695
696   return 0;
697 }
698
699 #if defined(WIN32) && !defined(__CYGWIN__)
700 static void win32_init(void)
701 {
702   WORD wVersionRequested;
703   WSADATA wsaData;
704   int err;
705   wVersionRequested = MAKEWORD(2, 0);
706
707   err = WSAStartup(wVersionRequested, &wsaData);
708
709   if (err != 0) {
710     perror("Winsock init failed");
711     logmsg("Error initialising winsock -- aborting\n");
712     exit(1);
713   }
714
715   if ( LOBYTE( wsaData.wVersion ) != 2 ||
716        HIBYTE( wsaData.wVersion ) != 0 ) {
717
718     WSACleanup();
719     perror("Winsock init failed");
720     logmsg("No suitable winsock.dll found -- aborting\n");
721     exit(1);
722   }
723 }
724 static void win32_cleanup(void)
725 {
726   WSACleanup();
727 }
728 #endif
729
730 char use_ipv6=FALSE;
731
732 int main(int argc, char *argv[])
733 {
734   struct sockaddr_in me;
735 #ifdef ENABLE_IPV6
736   struct sockaddr_in6 me6;
737 #endif /* ENABLE_IPV6 */
738   int sock, msgsock, flag;
739   unsigned short port = DEFAULT_PORT;
740   FILE *pidfile;
741   char *pidname= (char *)".http.pid";
742   struct httprequest req;
743   int rc;
744   int arg=1;
745
746   while(argc>arg) {
747     if(!strcmp("--version", argv[arg])) {
748       printf("sws IPv4%s\n",
749 #ifdef ENABLE_IPV6
750              "/IPv6"
751 #else
752              ""
753 #endif
754              );
755       return 0;
756     }
757     else if(!strcmp("--pidfile", argv[arg])) {
758       arg++;
759       if(argc>arg)
760         pidname = argv[arg++];
761     }
762     else if(!strcmp("--ipv6", argv[arg])) {
763 #ifdef ENABLE_IPV6
764       use_ipv6=TRUE;
765 #endif
766       arg++;
767     }
768     else if(argc>arg) {
769
770       if(atoi(argv[arg]))
771         port = (unsigned short)atoi(argv[arg++]);
772
773       if(argc>arg)
774         path = argv[arg++];
775     }
776   }
777
778 #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
779   win32_init();
780   atexit(win32_cleanup);
781 #else
782
783 #ifdef SIGPIPE
784 #ifdef HAVE_SIGNAL
785   signal(SIGPIPE, sigpipe_handler);
786 #endif
787 #ifdef HAVE_SIGINTERRUPT
788   siginterrupt(SIGPIPE, 1);
789 #endif
790 #endif
791 #endif
792
793 #ifdef ENABLE_IPV6
794   if(!use_ipv6)
795 #endif
796     sock = socket(AF_INET, SOCK_STREAM, 0);
797 #ifdef ENABLE_IPV6
798   else
799     sock = socket(AF_INET6, SOCK_STREAM, 0);
800 #endif
801
802   if (sock < 0) {
803     perror("opening stream socket");
804     logmsg("Error opening socket");
805     exit(1);
806   }
807
808   flag = 1;
809   if (setsockopt
810       (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
811        sizeof(int)) < 0) {
812     perror("setsockopt(SO_REUSEADDR)");
813   }
814
815 #ifdef ENABLE_IPV6
816   if(!use_ipv6) {
817 #endif
818     me.sin_family = AF_INET;
819     me.sin_addr.s_addr = INADDR_ANY;
820     me.sin_port = htons(port);
821     rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
822 #ifdef ENABLE_IPV6
823   }
824   else {
825     memset(&me6, 0, sizeof(struct sockaddr_in6));
826     me6.sin6_family = AF_INET6;
827     me6.sin6_addr = in6addr_any;
828     me6.sin6_port = htons(port);
829     rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
830   }
831 #endif /* ENABLE_IPV6 */
832   if(rc < 0) {
833     perror("binding stream socket");
834     logmsg("Error binding socket");
835     exit(1);
836   }
837
838   pidfile = fopen(pidname, "w");
839   if(pidfile) {
840     fprintf(pidfile, "%d\n", (int)getpid());
841     fclose(pidfile);
842   }
843   else
844     fprintf(stderr, "Couldn't write pid file\n");
845
846   logmsg("Running IPv%d version",
847 #ifdef ENABLE_IPV6
848          (use_ipv6?6:4)
849 #else
850          4
851 #endif
852     );
853
854   /* start accepting connections */
855   listen(sock, 5);
856
857   while (1) {
858     msgsock = accept(sock, NULL, NULL);
859
860     if (msgsock == -1)
861       continue;
862
863     logmsg("====> Client connect");
864
865     do {
866       if(get_request(msgsock, &req))
867         /* non-zero means error, break out of loop */
868         break;
869
870       if(prevbounce) {
871         /* bounce treatment requested */
872         if((req.testno == prevtestno) &&
873            (req.partno == prevpartno)) {
874           req.partno++;
875           logmsg("BOUNCE part number to %ld", req.partno);
876         }
877       }
878
879       send_doc(msgsock, &req);
880
881       if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) {
882         logmsg("special request received, no persistancy");
883         break;
884       }
885       if(!req.open) {
886         logmsg("instructed to close connection after server-reply");
887         break;
888       }
889
890       if(req.open)
891         logmsg("=> persistant connection request ended, awaits new request");
892       /* if we got a CONNECT, loop and get another request as well! */
893     } while(req.open || (req.testno == DOCNUMBER_CONNECT));
894
895     logmsg("====> Client disconnect");
896     sclose(msgsock);
897
898     if (req.testno == DOCNUMBER_QUIT)
899       break;
900   }
901
902   sclose(sock);
903
904   return 0;
905 }
906