sws.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2008, 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. /* sws.c: simple (silly?) web server
  24. This code was originally graciously donated to the project by Juergen
  25. Wilke. Thanks a bunch!
  26. */
  27. #include "setup.h" /* portability help from the lib directory */
  28. #ifdef HAVE_SIGNAL_H
  29. #include <signal.h>
  30. #endif
  31. #ifdef HAVE_UNISTD_H
  32. #include <unistd.h>
  33. #endif
  34. #ifdef HAVE_SYS_SOCKET_H
  35. #include <sys/socket.h>
  36. #endif
  37. #ifdef HAVE_NETINET_IN_H
  38. #include <netinet/in.h>
  39. #endif
  40. #ifdef _XOPEN_SOURCE_EXTENDED
  41. /* This define is "almost" required to build on HPUX 11 */
  42. #include <arpa/inet.h>
  43. #endif
  44. #ifdef HAVE_NETDB_H
  45. #include <netdb.h>
  46. #endif
  47. #ifdef HAVE_NETINET_TCP_H
  48. #include <netinet/tcp.h> /* for TCP_NODELAY */
  49. #endif
  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 "util.h"
  56. /* include memdebug.h last */
  57. #include "memdebug.h"
  58. #if !defined(CURL_SWS_FORK_ENABLED) && defined(HAVE_FORK)
  59. /*
  60. * The normal sws build for the plain standard curl test suite has no use for
  61. * fork(), but if you feel wild and crazy and want to setup some more exotic
  62. * tests. Define this and run...
  63. */
  64. #define CURL_SWS_FORK_ENABLED
  65. #endif
  66. #ifdef ENABLE_IPV6
  67. static bool use_ipv6 = FALSE;
  68. #endif
  69. static const char *ipv_inuse = "IPv4";
  70. #define REQBUFSIZ 150000
  71. #define REQBUFSIZ_TXT "149999"
  72. static long prevtestno=-1; /* previous test number we served */
  73. static long prevpartno=-1; /* previous part number we served */
  74. static bool prevbounce=FALSE; /* instructs the server to increase the part
  75. number for a test in case the identical
  76. testno+partno request shows up again */
  77. #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */
  78. #define RCMD_IDLE 1 /* told to sit idle */
  79. #define RCMD_STREAM 2 /* told to stream */
  80. struct httprequest {
  81. char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */
  82. int checkindex; /* where to start checking of the request */
  83. int offset; /* size of the incoming request */
  84. long testno; /* test number found in the request */
  85. long partno; /* part number found in the request */
  86. bool open; /* keep connection open info, as found in the request */
  87. bool auth_req; /* authentication required, don't wait for body unless
  88. there's an Authorization header */
  89. bool auth; /* Authorization header present in the incoming request */
  90. size_t cl; /* Content-Length of the incoming request */
  91. bool digest; /* Authorization digest header found */
  92. bool ntlm; /* Authorization ntlm header found */
  93. int pipe; /* if non-zero, expect this many requests to do a "piped"
  94. request/response */
  95. int skip; /* if non-zero, the server is instructed to not read this
  96. many bytes from a PUT/POST request. Ie the client sends N
  97. bytes said in Content-Length, but the server only reads N
  98. - skip bytes. */
  99. int rcmd; /* doing a special command, see defines above */
  100. int prot_version; /* HTTP version * 10 */
  101. bool pipelining; /* true if request is pipelined */
  102. };
  103. static int ProcessRequest(struct httprequest *req);
  104. static void storerequest(char *reqbuf, ssize_t totalsize);
  105. #define DEFAULT_PORT 8999
  106. #ifndef DEFAULT_LOGFILE
  107. #define DEFAULT_LOGFILE "log/sws.log"
  108. #endif
  109. const char *serverlogfile = DEFAULT_LOGFILE;
  110. #define SWSVERSION "cURL test suite HTTP server/0.1"
  111. #define REQUEST_DUMP "log/server.input"
  112. #define RESPONSE_DUMP "log/server.response"
  113. /* very-big-path support */
  114. #define MAXDOCNAMELEN 140000
  115. #define MAXDOCNAMELEN_TXT "139999"
  116. #define REQUEST_KEYWORD_SIZE 256
  117. #define REQUEST_KEYWORD_SIZE_TXT "255"
  118. #define CMD_AUTH_REQUIRED "auth_required"
  119. /* 'idle' means that it will accept the request fine but never respond
  120. any data. Just keep the connection alive. */
  121. #define CMD_IDLE "idle"
  122. /* 'stream' means to send a never-ending stream of data */
  123. #define CMD_STREAM "stream"
  124. #define END_OF_HEADERS "\r\n\r\n"
  125. enum {
  126. DOCNUMBER_NOTHING = -7,
  127. DOCNUMBER_QUIT = -6,
  128. DOCNUMBER_BADCONNECT = -5,
  129. DOCNUMBER_INTERNAL= -4,
  130. DOCNUMBER_CONNECT = -3,
  131. DOCNUMBER_WERULEZ = -2,
  132. DOCNUMBER_404 = -1
  133. };
  134. /* sent as reply to a QUIT */
  135. static const char *docquit =
  136. "HTTP/1.1 200 Goodbye" END_OF_HEADERS;
  137. /* sent as reply to a CONNECT */
  138. static const char *docconnect =
  139. "HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS;
  140. /* sent as reply to a "bad" CONNECT */
  141. static const char *docbadconnect =
  142. "HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS;
  143. /* send back this on 404 file not found */
  144. static const char *doc404 = "HTTP/1.1 404 Not Found\r\n"
  145. "Server: " SWSVERSION "\r\n"
  146. "Connection: close\r\n"
  147. "Content-Type: text/html"
  148. END_OF_HEADERS
  149. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
  150. "<HTML><HEAD>\n"
  151. "<TITLE>404 Not Found</TITLE>\n"
  152. "</HEAD><BODY>\n"
  153. "<H1>Not Found</H1>\n"
  154. "The requested URL was not found on this server.\n"
  155. "<P><HR><ADDRESS>" SWSVERSION "</ADDRESS>\n" "</BODY></HTML>\n";
  156. #ifdef SIGPIPE
  157. static volatile int sigpipe; /* Why? It's not used */
  158. #endif
  159. #ifdef SIGPIPE
  160. static void sigpipe_handler(int sig)
  161. {
  162. (void)sig; /* prevent warning */
  163. sigpipe = 1;
  164. }
  165. #endif
  166. static int ProcessRequest(struct httprequest *req)
  167. {
  168. char *line=&req->reqbuf[req->checkindex];
  169. bool chunked = FALSE;
  170. static char request[REQUEST_KEYWORD_SIZE];
  171. static char doc[MAXDOCNAMELEN];
  172. char logbuf[256];
  173. int prot_major, prot_minor;
  174. char *end;
  175. int error;
  176. end = strstr(line, END_OF_HEADERS);
  177. logmsg("ProcessRequest() called");
  178. /* try to figure out the request characteristics as soon as possible, but
  179. only once! */
  180. if((req->testno == DOCNUMBER_NOTHING) &&
  181. sscanf(line,
  182. "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
  183. request,
  184. doc,
  185. &prot_major,
  186. &prot_minor) == 4) {
  187. char *ptr;
  188. req->prot_version = prot_major*10 + prot_minor;
  189. /* find the last slash */
  190. ptr = strrchr(doc, '/');
  191. /* get the number after it */
  192. if(ptr) {
  193. FILE *stream;
  194. char *filename;
  195. if((strlen(doc) + strlen(request)) < 200)
  196. sprintf(logbuf, "Got request: %s %s HTTP/%d.%d",
  197. request, doc, prot_major, prot_minor);
  198. else
  199. sprintf(logbuf, "Got a *HUGE* request HTTP/%d.%d",
  200. prot_major, prot_minor);
  201. logmsg("%s", logbuf);
  202. if(!strncmp("/verifiedserver", ptr, 15)) {
  203. logmsg("Are-we-friendly question received");
  204. req->testno = DOCNUMBER_WERULEZ;
  205. return 1; /* done */
  206. }
  207. if(!strncmp("/quit", ptr, 5)) {
  208. logmsg("Request-to-quit received");
  209. req->testno = DOCNUMBER_QUIT;
  210. return 1; /* done */
  211. }
  212. ptr++; /* skip the slash */
  213. /* skip all non-numericals following the slash */
  214. while(*ptr && !ISDIGIT(*ptr))
  215. ptr++;
  216. req->testno = strtol(ptr, &ptr, 10);
  217. if(req->testno > 10000) {
  218. req->partno = req->testno % 10000;
  219. req->testno /= 10000;
  220. }
  221. else
  222. req->partno = 0;
  223. sprintf(logbuf, "Requested test number %ld part %ld",
  224. req->testno, req->partno);
  225. logmsg("%s", logbuf);
  226. filename = test2file(req->testno);
  227. stream=fopen(filename, "rb");
  228. if(!stream) {
  229. error = ERRNO;
  230. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  231. logmsg("Error opening file: %s", filename);
  232. logmsg("Couldn't open test file %ld", req->testno);
  233. req->open = FALSE; /* closes connection */
  234. return 1; /* done */
  235. }
  236. else {
  237. char *cmd = NULL;
  238. size_t cmdsize = 0;
  239. int num=0;
  240. /* get the custom server control "commands" */
  241. cmd = (char *)spitout(stream, "reply", "servercmd", &cmdsize);
  242. fclose(stream);
  243. if(cmdsize) {
  244. logmsg("Found a reply-servercmd section!");
  245. if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) {
  246. logmsg("instructed to require authorization header");
  247. req->auth_req = TRUE;
  248. }
  249. else if(!strncmp(CMD_IDLE, cmd, strlen(CMD_IDLE))) {
  250. logmsg("instructed to idle");
  251. req->rcmd = RCMD_IDLE;
  252. req->open = TRUE;
  253. }
  254. else if(!strncmp(CMD_STREAM, cmd, strlen(CMD_STREAM))) {
  255. logmsg("instructed to stream");
  256. req->rcmd = RCMD_STREAM;
  257. }
  258. else if(1 == sscanf(cmd, "pipe: %d", &num)) {
  259. logmsg("instructed to allow a pipe size %d", num);
  260. req->pipe = num-1; /* decrease by one since we don't count the
  261. first request in this number */
  262. }
  263. else if(1 == sscanf(cmd, "skip: %d", &num)) {
  264. logmsg("instructed to skip this number of bytes %d", num);
  265. req->skip = num;
  266. }
  267. else {
  268. logmsg("funny instruction found: %s", cmd);
  269. }
  270. free(cmd);
  271. }
  272. }
  273. }
  274. else {
  275. if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
  276. doc, &prot_major, &prot_minor) == 3) {
  277. sprintf(logbuf, "Received a CONNECT %s HTTP/%d.%d request",
  278. doc, prot_major, prot_minor);
  279. logmsg("%s", logbuf);
  280. if(req->prot_version == 10)
  281. req->open = FALSE; /* HTTP 1.0 closes connection by default */
  282. if(!strncmp(doc, "bad", 3))
  283. /* if the host name starts with bad, we fake an error here */
  284. req->testno = DOCNUMBER_BADCONNECT;
  285. else if(!strncmp(doc, "test", 4)) {
  286. /* if the host name starts with test, the port number used in the
  287. CONNECT line will be used as test number! */
  288. char *portp = strchr(doc, ':');
  289. if(portp)
  290. req->testno = atoi(portp+1);
  291. else
  292. req->testno = DOCNUMBER_CONNECT;
  293. }
  294. else
  295. req->testno = DOCNUMBER_CONNECT;
  296. }
  297. else {
  298. logmsg("Did not find test number in PATH");
  299. req->testno = DOCNUMBER_404;
  300. }
  301. }
  302. }
  303. if(!end) {
  304. /* we don't have a complete request yet! */
  305. logmsg("ProcessRequest returned without a complete request");
  306. return 0;
  307. }
  308. logmsg("ProcessRequest found a complete request");
  309. if(req->pipe)
  310. /* we do have a full set, advance the checkindex to after the end of the
  311. headers, for the pipelining case mostly */
  312. req->checkindex += (end - line) + strlen(END_OF_HEADERS);
  313. /* **** Persistence ****
  314. *
  315. * If the request is a HTTP/1.0 one, we close the connection unconditionally
  316. * when we're done.
  317. *
  318. * If the request is a HTTP/1.1 one, we MUST check for a "Connection:"
  319. * header that might say "close". If it does, we close a connection when
  320. * this request is processed. Otherwise, we keep the connection alive for X
  321. * seconds.
  322. */
  323. do {
  324. if((req->cl==0) && curlx_strnequal("Content-Length:", line, 15)) {
  325. /* If we don't ignore content-length, we read it and we read the whole
  326. request including the body before we return. If we've been told to
  327. ignore the content-length, we will return as soon as all headers
  328. have been received */
  329. size_t cl = strtol(line+15, &line, 10);
  330. req->cl = cl - req->skip;
  331. logmsg("Found Content-Length: %zu in the request", cl);
  332. if(req->skip)
  333. logmsg("... but will abort after %zu bytes", req->cl);
  334. break;
  335. }
  336. else if(curlx_strnequal("Transfer-Encoding: chunked", line,
  337. strlen("Transfer-Encoding: chunked"))) {
  338. /* chunked data coming in */
  339. chunked = TRUE;
  340. }
  341. if(chunked) {
  342. if(strstr(req->reqbuf, "\r\n0\r\n\r\n"))
  343. /* end of chunks reached */
  344. return 1; /* done */
  345. else
  346. return 0; /* not done */
  347. }
  348. line = strchr(line, '\n');
  349. if(line)
  350. line++;
  351. } while(line);
  352. if(!req->auth && strstr(req->reqbuf, "Authorization:")) {
  353. req->auth = TRUE; /* Authorization: header present! */
  354. if(req->auth_req)
  355. logmsg("Authorization header found, as required");
  356. }
  357. if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) {
  358. /* If the client is passing this Digest-header, we set the part number
  359. to 1000. Not only to spice up the complexity of this, but to make
  360. Digest stuff to work in the test suite. */
  361. req->partno += 1000;
  362. req->digest = TRUE; /* header found */
  363. logmsg("Received Digest request, sending back data %ld", req->partno);
  364. }
  365. else if(!req->ntlm &&
  366. strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) {
  367. /* If the client is passing this type-3 NTLM header */
  368. req->partno += 1002;
  369. req->ntlm = TRUE; /* NTLM found */
  370. logmsg("Received NTLM type-3, sending back data %ld", req->partno);
  371. if(req->cl) {
  372. logmsg(" Expecting %zu POSTed bytes", req->cl);
  373. }
  374. }
  375. else if(!req->ntlm &&
  376. strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) {
  377. /* If the client is passing this type-1 NTLM header */
  378. req->partno += 1001;
  379. req->ntlm = TRUE; /* NTLM found */
  380. logmsg("Received NTLM type-1, sending back data %ld", req->partno);
  381. }
  382. else if((req->partno >= 1000) && strstr(req->reqbuf, "Authorization: Basic")) {
  383. /* If the client is passing this Basic-header and the part number is already
  384. >=1000, we add 1 to the part number. This allows simple Basic authentication
  385. negotiation to work in the test suite. */
  386. req->partno += 1;
  387. logmsg("Received Basic request, sending back data %ld", req->partno);
  388. }
  389. if(strstr(req->reqbuf, "Connection: close"))
  390. req->open = FALSE; /* close connection after this request */
  391. if(!req->pipe &&
  392. req->open &&
  393. req->prot_version >= 11 &&
  394. end &&
  395. req->reqbuf + req->offset > end + strlen(END_OF_HEADERS) &&
  396. (!strncmp(req->reqbuf, "GET", strlen("GET")) ||
  397. !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) {
  398. /* If we have a persistent connection, HTTP version >= 1.1
  399. and GET/HEAD request, enable pipelining. */
  400. req->checkindex = (end - req->reqbuf) + strlen(END_OF_HEADERS);
  401. req->pipelining = TRUE;
  402. }
  403. while(req->pipe) {
  404. /* scan for more header ends within this chunk */
  405. line = &req->reqbuf[req->checkindex];
  406. end = strstr(line, END_OF_HEADERS);
  407. if(!end)
  408. break;
  409. req->checkindex += (end - line) + strlen(END_OF_HEADERS);
  410. req->pipe--;
  411. }
  412. /* If authentication is required and no auth was provided, end now. This
  413. makes the server NOT wait for PUT/POST data and you can then make the
  414. test case send a rejection before any such data has been sent. Test case
  415. 154 uses this.*/
  416. if(req->auth_req && !req->auth)
  417. return 1;
  418. if(req->cl > 0) {
  419. if(req->cl <= req->offset - (end - req->reqbuf) - strlen(END_OF_HEADERS))
  420. return 1; /* done */
  421. else
  422. return 0; /* not complete yet */
  423. }
  424. return 1; /* done */
  425. }
  426. /* store the entire request in a file */
  427. static void storerequest(char *reqbuf, ssize_t totalsize)
  428. {
  429. int res;
  430. int error = 0;
  431. ssize_t written;
  432. ssize_t writeleft;
  433. FILE *dump;
  434. if (reqbuf == NULL)
  435. return;
  436. if (totalsize == 0)
  437. return;
  438. else if (totalsize < 0) {
  439. logmsg("Invalid size (%zd bytes) for request input. Not written to %s",
  440. totalsize, REQUEST_DUMP);
  441. return;
  442. }
  443. do {
  444. dump = fopen(REQUEST_DUMP, "ab");
  445. } while ((dump == NULL) && ((error = ERRNO) == EINTR));
  446. if (dump == NULL) {
  447. logmsg("Error opening file %s error: %d %s",
  448. REQUEST_DUMP, error, strerror(error));
  449. logmsg("Failed to write request input to " REQUEST_DUMP);
  450. return;
  451. }
  452. writeleft = totalsize;
  453. do {
  454. written = (ssize_t)fwrite((void *) &reqbuf[totalsize-writeleft],
  455. 1, (size_t)writeleft, dump);
  456. if (written > 0)
  457. writeleft -= written;
  458. } while ((writeleft > 0) && ((error = ERRNO) == EINTR));
  459. if (writeleft > 0) {
  460. logmsg("Error writing file %s error: %d %s",
  461. REQUEST_DUMP, error, strerror(error));
  462. logmsg("Wrote only (%zd bytes) of (%zd bytes) request input to %s",
  463. totalsize-writeleft, totalsize, REQUEST_DUMP);
  464. }
  465. do {
  466. res = fclose(dump);
  467. } while(res && ((error = ERRNO) == EINTR));
  468. if(res)
  469. logmsg("Error closing file %s error: %d %s",
  470. REQUEST_DUMP, error, strerror(error));
  471. if(!writeleft)
  472. logmsg("Wrote request (%zd bytes) input to " REQUEST_DUMP,
  473. totalsize);
  474. }
  475. /* return 0 on success, non-zero on failure */
  476. static int get_request(curl_socket_t sock, struct httprequest *req)
  477. {
  478. int fail = 0;
  479. char *reqbuf = req->reqbuf;
  480. ssize_t got = 0;
  481. char *pipereq = NULL;
  482. int pipereq_length = 0;
  483. if(req->pipelining) {
  484. pipereq = reqbuf + req->checkindex;
  485. pipereq_length = req->offset - req->checkindex;
  486. }
  487. /*** Init the httprequest structure properly for the upcoming request ***/
  488. req->checkindex = 0;
  489. req->offset = 0;
  490. req->testno = DOCNUMBER_NOTHING;
  491. req->partno = 0;
  492. req->open = TRUE;
  493. req->auth_req = FALSE;
  494. req->auth = FALSE;
  495. req->cl = 0;
  496. req->digest = FALSE;
  497. req->ntlm = FALSE;
  498. req->pipe = 0;
  499. req->skip = 0;
  500. req->rcmd = RCMD_NORMALREQ;
  501. req->prot_version = 0;
  502. req->pipelining = FALSE;
  503. /*** end of httprequest init ***/
  504. while (req->offset < REQBUFSIZ-1) {
  505. if(pipereq_length) {
  506. memmove(reqbuf, pipereq, pipereq_length);
  507. got = pipereq_length;
  508. pipereq_length = 0;
  509. }
  510. else {
  511. if(req->skip)
  512. /* we are instructed to not read the entire thing, so we make sure to only
  513. read what we're supposed to and NOT read the enire thing the client
  514. wants to send! */
  515. got = sread(sock, reqbuf + req->offset, req->cl);
  516. else
  517. got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset);
  518. }
  519. if (got <= 0) {
  520. if (got < 0) {
  521. logmsg("recv() returned error: %d", SOCKERRNO);
  522. return DOCNUMBER_INTERNAL;
  523. }
  524. logmsg("Connection closed by client");
  525. reqbuf[req->offset] = '\0';
  526. /* dump the request receivied so far to the external file */
  527. storerequest(reqbuf, req->offset);
  528. return DOCNUMBER_INTERNAL;
  529. }
  530. logmsg("Read %zd bytes", got);
  531. req->offset += got;
  532. reqbuf[req->offset] = '\0';
  533. if(ProcessRequest(req)) {
  534. if(req->pipe--) {
  535. logmsg("Waiting for another piped request");
  536. continue;
  537. }
  538. break;
  539. }
  540. }
  541. if((req->offset == REQBUFSIZ-1) && (got > 0)) {
  542. logmsg("Request would overflow buffer, closing connection");
  543. /* dump request received so far to external file anyway */
  544. reqbuf[REQBUFSIZ-1] = '\0';
  545. fail = 1;
  546. }
  547. else if(req->offset > REQBUFSIZ-1) {
  548. logmsg("Request buffer overflow, closing connection");
  549. /* dump request received so far to external file anyway */
  550. reqbuf[REQBUFSIZ-1] = '\0';
  551. fail = 1;
  552. }
  553. else
  554. reqbuf[req->offset] = '\0';
  555. /* dump the request to an external file */
  556. storerequest(reqbuf, req->pipelining ? req->checkindex : req->offset);
  557. return fail; /* return 0 on success */
  558. }
  559. /* returns -1 on failure */
  560. static int send_doc(curl_socket_t sock, struct httprequest *req)
  561. {
  562. ssize_t written;
  563. size_t count;
  564. const char *buffer;
  565. char *ptr=NULL;
  566. FILE *stream;
  567. char *cmd=NULL;
  568. size_t cmdsize=0;
  569. FILE *dump;
  570. bool persistant = TRUE;
  571. bool sendfailure = FALSE;
  572. size_t responsesize;
  573. int error = 0;
  574. int res;
  575. static char weare[256];
  576. char partbuf[80]="data";
  577. logmsg("Send response number %ld part %ld", req->testno, req->partno);
  578. switch(req->rcmd) {
  579. default:
  580. case RCMD_NORMALREQ:
  581. break; /* continue with business as usual */
  582. case RCMD_STREAM:
  583. #define STREAMTHIS "a string to stream 01234567890\n"
  584. count = strlen(STREAMTHIS);
  585. while(1) {
  586. written = swrite(sock, STREAMTHIS, count);
  587. if(written != (ssize_t)count) {
  588. logmsg("Stopped streaming");
  589. break;
  590. }
  591. }
  592. return -1;
  593. case RCMD_IDLE:
  594. /* Do nothing. Sit idle. Pretend it rains. */
  595. return 0;
  596. }
  597. req->open = FALSE;
  598. if(req->testno < 0) {
  599. size_t msglen;
  600. char msgbuf[64];
  601. switch(req->testno) {
  602. case DOCNUMBER_QUIT:
  603. logmsg("Replying to QUIT");
  604. buffer = docquit;
  605. break;
  606. case DOCNUMBER_WERULEZ:
  607. /* we got a "friends?" question, reply back that we sure are */
  608. logmsg("Identifying ourselves as friends");
  609. sprintf(msgbuf, "WE ROOLZ: %ld\r\n", (long)getpid());
  610. msglen = strlen(msgbuf);
  611. sprintf(weare, "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s",
  612. msglen, msgbuf);
  613. buffer = weare;
  614. break;
  615. case DOCNUMBER_INTERNAL:
  616. logmsg("Bailing out due to internal error");
  617. return -1;
  618. case DOCNUMBER_CONNECT:
  619. logmsg("Replying to CONNECT");
  620. buffer = docconnect;
  621. break;
  622. case DOCNUMBER_BADCONNECT:
  623. logmsg("Replying to a bad CONNECT");
  624. buffer = docbadconnect;
  625. break;
  626. case DOCNUMBER_404:
  627. default:
  628. logmsg("Replying to with a 404");
  629. buffer = doc404;
  630. break;
  631. }
  632. ptr = NULL;
  633. stream=NULL;
  634. count = strlen(buffer);
  635. }
  636. else {
  637. char *filename = test2file(req->testno);
  638. if(0 != req->partno)
  639. sprintf(partbuf, "data%ld", req->partno);
  640. stream=fopen(filename, "rb");
  641. if(!stream) {
  642. error = ERRNO;
  643. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  644. logmsg("Error opening file: %s", filename);
  645. logmsg("Couldn't open test file");
  646. return 0;
  647. }
  648. else {
  649. buffer = spitout(stream, "reply", partbuf, &count);
  650. ptr = (char *)buffer;
  651. fclose(stream);
  652. }
  653. /* re-open the same file again */
  654. stream=fopen(filename, "rb");
  655. if(!stream) {
  656. error = ERRNO;
  657. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  658. logmsg("Error opening file: %s", filename);
  659. logmsg("Couldn't open test file");
  660. return 0;
  661. }
  662. else {
  663. /* get the custom server control "commands" */
  664. cmd = (char *)spitout(stream, "reply", "postcmd", &cmdsize);
  665. fclose(stream);
  666. }
  667. }
  668. dump = fopen(RESPONSE_DUMP, "ab"); /* b is for windows-preparing */
  669. if(!dump) {
  670. error = ERRNO;
  671. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  672. logmsg("Error opening file: %s", RESPONSE_DUMP);
  673. logmsg("couldn't create logfile: " RESPONSE_DUMP);
  674. return -1;
  675. }
  676. /* If the word 'swsclose' is present anywhere in the reply chunk, the
  677. connection will be closed after the data has been sent to the requesting
  678. client... */
  679. if(strstr(buffer, "swsclose") || !count) {
  680. persistant = FALSE;
  681. logmsg("connection close instruction \"swsclose\" found in response");
  682. }
  683. if(strstr(buffer, "swsbounce")) {
  684. prevbounce = TRUE;
  685. logmsg("enable \"swsbounce\" in the next request");
  686. }
  687. else
  688. prevbounce = FALSE;
  689. responsesize = count;
  690. do {
  691. /* Ok, we send no more than 200 bytes at a time, just to make sure that
  692. larger chunks are split up so that the client will need to do multiple
  693. recv() calls to get it and thus we exercise that code better */
  694. size_t num = count;
  695. if(num > 200)
  696. num = 200;
  697. written = swrite(sock, buffer, num);
  698. if (written < 0) {
  699. sendfailure = TRUE;
  700. break;
  701. }
  702. else {
  703. logmsg("Sent off %zd bytes", written);
  704. }
  705. /* write to file as well */
  706. fwrite(buffer, 1, written, dump);
  707. count -= written;
  708. buffer += written;
  709. } while(count>0);
  710. do {
  711. res = fclose(dump);
  712. } while(res && ((error = ERRNO) == EINTR));
  713. if(res)
  714. logmsg("Error closing file %s error: %d %s",
  715. RESPONSE_DUMP, error, strerror(error));
  716. if(sendfailure) {
  717. logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) were sent",
  718. responsesize-count, responsesize);
  719. if(ptr)
  720. free(ptr);
  721. if(cmd)
  722. free(cmd);
  723. return -1;
  724. }
  725. logmsg("Response sent (%zu bytes) and written to " RESPONSE_DUMP,
  726. responsesize);
  727. if(ptr)
  728. free(ptr);
  729. if(cmdsize > 0 ) {
  730. char command[32];
  731. int num;
  732. ptr=cmd;
  733. do {
  734. if(2 == sscanf(ptr, "%31s %d", command, &num)) {
  735. if(!strcmp("wait", command)) {
  736. logmsg("Told to sleep for %d seconds", num);
  737. sleep(num); /* wait this many seconds */
  738. }
  739. else
  740. logmsg("Unknown command in reply command section");
  741. }
  742. ptr = strchr(ptr, '\n');
  743. if(ptr)
  744. ptr++;
  745. else
  746. ptr = NULL;
  747. } while(ptr && *ptr);
  748. }
  749. if(cmd)
  750. free(cmd);
  751. req->open = persistant;
  752. prevtestno = req->testno;
  753. prevpartno = req->partno;
  754. return 0;
  755. }
  756. int main(int argc, char *argv[])
  757. {
  758. struct sockaddr_in me;
  759. #ifdef ENABLE_IPV6
  760. struct sockaddr_in6 me6;
  761. #endif /* ENABLE_IPV6 */
  762. curl_socket_t sock, msgsock;
  763. int flag;
  764. unsigned short port = DEFAULT_PORT;
  765. char *pidname= (char *)".http.pid";
  766. struct httprequest req;
  767. int rc;
  768. int arg=1;
  769. #ifdef CURL_SWS_FORK_ENABLED
  770. bool use_fork = FALSE;
  771. #endif
  772. while(argc>arg) {
  773. if(!strcmp("--version", argv[arg])) {
  774. printf("sws IPv4%s"
  775. #ifdef CURL_SWS_FORK_ENABLED
  776. " FORK"
  777. #endif
  778. "\n"
  779. ,
  780. #ifdef ENABLE_IPV6
  781. "/IPv6"
  782. #else
  783. ""
  784. #endif
  785. );
  786. return 0;
  787. }
  788. else if(!strcmp("--pidfile", argv[arg])) {
  789. arg++;
  790. if(argc>arg)
  791. pidname = argv[arg++];
  792. }
  793. else if(!strcmp("--ipv6", argv[arg])) {
  794. #ifdef ENABLE_IPV6
  795. ipv_inuse = "IPv6";
  796. use_ipv6 = TRUE;
  797. #endif
  798. arg++;
  799. }
  800. #ifdef CURL_SWS_FORK_ENABLED
  801. else if(!strcmp("--fork", argv[arg])) {
  802. use_fork=TRUE;
  803. arg++;
  804. }
  805. #endif
  806. else if(argc>arg) {
  807. if(atoi(argv[arg]))
  808. port = (unsigned short)atoi(argv[arg++]);
  809. if(argc>arg)
  810. path = argv[arg++];
  811. }
  812. }
  813. #ifdef WIN32
  814. win32_init();
  815. atexit(win32_cleanup);
  816. #else
  817. #ifdef SIGPIPE
  818. #ifdef HAVE_SIGNAL
  819. signal(SIGPIPE, sigpipe_handler);
  820. #endif
  821. #ifdef HAVE_SIGINTERRUPT
  822. siginterrupt(SIGPIPE, 1);
  823. #endif
  824. #endif
  825. #endif
  826. #ifdef ENABLE_IPV6
  827. if(!use_ipv6)
  828. #endif
  829. sock = socket(AF_INET, SOCK_STREAM, 0);
  830. #ifdef ENABLE_IPV6
  831. else
  832. sock = socket(AF_INET6, SOCK_STREAM, 0);
  833. #endif
  834. if (CURL_SOCKET_BAD == sock) {
  835. logmsg("Error opening socket: %d", SOCKERRNO);
  836. return 1;
  837. }
  838. flag = 1;
  839. if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  840. (void *) &flag, sizeof(flag))) {
  841. logmsg("setsockopt(SO_REUSEADDR) failed: %d", SOCKERRNO);
  842. sclose(sock);
  843. return 1;
  844. }
  845. #ifdef ENABLE_IPV6
  846. if(!use_ipv6) {
  847. #endif
  848. memset(&me, 0, sizeof(me));
  849. me.sin_family = AF_INET;
  850. me.sin_addr.s_addr = INADDR_ANY;
  851. me.sin_port = htons(port);
  852. rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
  853. #ifdef ENABLE_IPV6
  854. }
  855. else {
  856. memset(&me6, 0, sizeof(me6));
  857. me6.sin6_family = AF_INET6;
  858. me6.sin6_addr = in6addr_any;
  859. me6.sin6_port = htons(port);
  860. rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
  861. }
  862. #endif /* ENABLE_IPV6 */
  863. if(0 != rc) {
  864. logmsg("Error binding socket: %d", SOCKERRNO);
  865. sclose(sock);
  866. return 1;
  867. }
  868. if(!write_pidfile(pidname)) {
  869. sclose(sock);
  870. return 1;
  871. }
  872. logmsg("Running %s version on port %d", ipv_inuse, (int)port);
  873. /* start accepting connections */
  874. rc = listen(sock, 5);
  875. if(0 != rc) {
  876. logmsg("listen() failed with error: %d", SOCKERRNO);
  877. sclose(sock);
  878. return 1;
  879. }
  880. while (1) {
  881. msgsock = accept(sock, NULL, NULL);
  882. if (CURL_SOCKET_BAD == msgsock) {
  883. printf("MAJOR ERROR: accept() failed with error: %d\n", SOCKERRNO);
  884. break;
  885. }
  886. set_advisor_read_lock(SERVERLOGS_LOCK);
  887. #ifdef CURL_SWS_FORK_ENABLED
  888. if(use_fork) {
  889. /* The fork enabled version just forks off the child and don't care
  890. about it anymore, so don't assume otherwise. Beware and don't do
  891. this at home. */
  892. rc = fork();
  893. if(-1 == rc) {
  894. printf("MAJOR ERROR: fork() failed!\n");
  895. break;
  896. }
  897. }
  898. else
  899. /* not a fork, just set rc so the following proceeds nicely */
  900. rc = 0;
  901. /* 0 is returned to the child */
  902. if(0 == rc) {
  903. #endif
  904. logmsg("====> Client connect");
  905. #ifdef TCP_NODELAY
  906. /*
  907. * Disable the Nagle algorithm to make it easier to send out a large
  908. * response in many small segments to torture the clients more.
  909. */
  910. flag = 1;
  911. if (setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
  912. (void *)&flag, sizeof(flag)) == -1) {
  913. logmsg("====> TCP_NODELAY failed");
  914. }
  915. #endif
  916. /* initialization of httprequest struct is done in get_request(), but due
  917. to pipelining treatment the pipelining struct field must be initialized
  918. previously to FALSE every time a new connection arrives. */
  919. req.pipelining = FALSE;
  920. do {
  921. if(get_request(msgsock, &req))
  922. /* non-zero means error, break out of loop */
  923. break;
  924. if(prevbounce) {
  925. /* bounce treatment requested */
  926. if((req.testno == prevtestno) &&
  927. (req.partno == prevpartno)) {
  928. req.partno++;
  929. logmsg("BOUNCE part number to %ld", req.partno);
  930. }
  931. else {
  932. prevbounce = FALSE;
  933. prevtestno = -1;
  934. prevpartno = -1;
  935. }
  936. }
  937. send_doc(msgsock, &req);
  938. if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) {
  939. logmsg("special request received, no persistency");
  940. break;
  941. }
  942. if(!req.open) {
  943. logmsg("instructed to close connection after server-reply");
  944. break;
  945. }
  946. if(req.open)
  947. logmsg("=> persistant connection request ended, awaits new request");
  948. /* if we got a CONNECT, loop and get another request as well! */
  949. } while(req.open || (req.testno == DOCNUMBER_CONNECT));
  950. logmsg("====> Client disconnect");
  951. sclose(msgsock);
  952. clear_advisor_read_lock(SERVERLOGS_LOCK);
  953. if (req.testno == DOCNUMBER_QUIT)
  954. break;
  955. #ifdef CURL_SWS_FORK_ENABLED
  956. }
  957. #endif
  958. }
  959. sclose(sock);
  960. clear_advisor_read_lock(SERVERLOGS_LOCK);
  961. return 0;
  962. }