2
0

sws.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2012, 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. ***************************************************************************/
  22. #include "server_setup.h"
  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. #ifdef HAVE_SIGNAL_H
  28. #include <signal.h>
  29. #endif
  30. #ifdef HAVE_UNISTD_H
  31. #include <unistd.h>
  32. #endif
  33. #ifdef HAVE_SYS_SOCKET_H
  34. #include <sys/socket.h>
  35. #endif
  36. #ifdef HAVE_NETINET_IN_H
  37. #include <netinet/in.h>
  38. #endif
  39. #ifdef HAVE_ARPA_INET_H
  40. #include <arpa/inet.h>
  41. #endif
  42. #ifdef HAVE_NETDB_H
  43. #include <netdb.h>
  44. #endif
  45. #ifdef HAVE_NETINET_TCP_H
  46. #include <netinet/tcp.h> /* for TCP_NODELAY */
  47. #endif
  48. #define ENABLE_CURLX_PRINTF
  49. /* make the curlx header define all printf() functions to use the curlx_*
  50. versions instead */
  51. #include "curlx.h" /* from the private lib dir */
  52. #include "getpart.h"
  53. #include "inet_pton.h"
  54. #include "util.h"
  55. #include "server_sockaddr.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 bool use_gopher = FALSE;
  70. static const char *ipv_inuse = "IPv4";
  71. static int serverlogslocked = 0;
  72. static bool is_proxy = FALSE;
  73. #define REQBUFSIZ 150000
  74. #define REQBUFSIZ_TXT "149999"
  75. static long prevtestno=-1; /* previous test number we served */
  76. static long prevpartno=-1; /* previous part number we served */
  77. static bool prevbounce=FALSE; /* instructs the server to increase the part
  78. number for a test in case the identical
  79. testno+partno request shows up again */
  80. #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */
  81. #define RCMD_IDLE 1 /* told to sit idle */
  82. #define RCMD_STREAM 2 /* told to stream */
  83. struct httprequest {
  84. char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */
  85. size_t checkindex; /* where to start checking of the request */
  86. size_t offset; /* size of the incoming request */
  87. long testno; /* test number found in the request */
  88. long partno; /* part number found in the request */
  89. bool open; /* keep connection open info, as found in the request */
  90. bool auth_req; /* authentication required, don't wait for body unless
  91. there's an Authorization header */
  92. bool auth; /* Authorization header present in the incoming request */
  93. size_t cl; /* Content-Length of the incoming request */
  94. bool digest; /* Authorization digest header found */
  95. bool ntlm; /* Authorization ntlm header found */
  96. int writedelay; /* if non-zero, delay this number of seconds between
  97. writes in the response */
  98. int pipe; /* if non-zero, expect this many requests to do a "piped"
  99. request/response */
  100. int skip; /* if non-zero, the server is instructed to not read this
  101. many bytes from a PUT/POST request. Ie the client sends N
  102. bytes said in Content-Length, but the server only reads N
  103. - skip bytes. */
  104. int rcmd; /* doing a special command, see defines above */
  105. int prot_version; /* HTTP version * 10 */
  106. bool pipelining; /* true if request is pipelined */
  107. int callcount; /* times ProcessRequest() gets called */
  108. unsigned short connect_port; /* the port number CONNECT used */
  109. };
  110. static int ProcessRequest(struct httprequest *req);
  111. static void storerequest(char *reqbuf, size_t totalsize);
  112. #define DEFAULT_PORT 8999
  113. #ifndef DEFAULT_LOGFILE
  114. #define DEFAULT_LOGFILE "log/sws.log"
  115. #endif
  116. const char *serverlogfile = DEFAULT_LOGFILE;
  117. #define SWSVERSION "cURL test suite HTTP server/0.1"
  118. #define REQUEST_DUMP "log/server.input"
  119. #define RESPONSE_DUMP "log/server.response"
  120. /* when told to run as proxy, we store the logs in different files so that
  121. they can co-exist with the same program running as a "server" */
  122. #define REQUEST_PROXY_DUMP "log/proxy.input"
  123. #define RESPONSE_PROXY_DUMP "log/proxy.response"
  124. /* very-big-path support */
  125. #define MAXDOCNAMELEN 140000
  126. #define MAXDOCNAMELEN_TXT "139999"
  127. #define REQUEST_KEYWORD_SIZE 256
  128. #define REQUEST_KEYWORD_SIZE_TXT "255"
  129. #define CMD_AUTH_REQUIRED "auth_required"
  130. /* 'idle' means that it will accept the request fine but never respond
  131. any data. Just keep the connection alive. */
  132. #define CMD_IDLE "idle"
  133. /* 'stream' means to send a never-ending stream of data */
  134. #define CMD_STREAM "stream"
  135. #define END_OF_HEADERS "\r\n\r\n"
  136. enum {
  137. DOCNUMBER_NOTHING = -7,
  138. DOCNUMBER_QUIT = -6,
  139. DOCNUMBER_BADCONNECT = -5,
  140. DOCNUMBER_INTERNAL= -4,
  141. DOCNUMBER_CONNECT = -3,
  142. DOCNUMBER_WERULEZ = -2,
  143. DOCNUMBER_404 = -1
  144. };
  145. static const char *end_of_headers = END_OF_HEADERS;
  146. /* sent as reply to a QUIT */
  147. static const char *docquit =
  148. "HTTP/1.1 200 Goodbye" END_OF_HEADERS;
  149. /* sent as reply to a CONNECT */
  150. static const char *docconnect =
  151. "HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS;
  152. /* sent as reply to a "bad" CONNECT */
  153. static const char *docbadconnect =
  154. "HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS;
  155. /* send back this on 404 file not found */
  156. static const char *doc404 = "HTTP/1.1 404 Not Found\r\n"
  157. "Server: " SWSVERSION "\r\n"
  158. "Connection: close\r\n"
  159. "Content-Type: text/html"
  160. END_OF_HEADERS
  161. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
  162. "<HTML><HEAD>\n"
  163. "<TITLE>404 Not Found</TITLE>\n"
  164. "</HEAD><BODY>\n"
  165. "<H1>Not Found</H1>\n"
  166. "The requested URL was not found on this server.\n"
  167. "<P><HR><ADDRESS>" SWSVERSION "</ADDRESS>\n" "</BODY></HTML>\n";
  168. /* do-nothing macro replacement for systems which lack siginterrupt() */
  169. #ifndef HAVE_SIGINTERRUPT
  170. #define siginterrupt(x,y) do {} while(0)
  171. #endif
  172. /* vars used to keep around previous signal handlers */
  173. typedef RETSIGTYPE (*SIGHANDLER_T)(int);
  174. #ifdef SIGHUP
  175. static SIGHANDLER_T old_sighup_handler = SIG_ERR;
  176. #endif
  177. #ifdef SIGPIPE
  178. static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
  179. #endif
  180. #ifdef SIGALRM
  181. static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
  182. #endif
  183. #ifdef SIGINT
  184. static SIGHANDLER_T old_sigint_handler = SIG_ERR;
  185. #endif
  186. #ifdef SIGTERM
  187. static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
  188. #endif
  189. /* var which if set indicates that the program should finish execution */
  190. SIG_ATOMIC_T got_exit_signal = 0;
  191. /* if next is set indicates the first signal handled in exit_signal_handler */
  192. static volatile int exit_signal = 0;
  193. /* signal handler that will be triggered to indicate that the program
  194. should finish its execution in a controlled manner as soon as possible.
  195. The first time this is called it will set got_exit_signal to one and
  196. store in exit_signal the signal that triggered its execution. */
  197. static RETSIGTYPE exit_signal_handler(int signum)
  198. {
  199. int old_errno = ERRNO;
  200. if(got_exit_signal == 0) {
  201. got_exit_signal = 1;
  202. exit_signal = signum;
  203. }
  204. (void)signal(signum, exit_signal_handler);
  205. SET_ERRNO(old_errno);
  206. }
  207. static void install_signal_handlers(void)
  208. {
  209. #ifdef SIGHUP
  210. /* ignore SIGHUP signal */
  211. if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
  212. logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
  213. #endif
  214. #ifdef SIGPIPE
  215. /* ignore SIGPIPE signal */
  216. if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
  217. logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
  218. #endif
  219. #ifdef SIGALRM
  220. /* ignore SIGALRM signal */
  221. if((old_sigalrm_handler = signal(SIGALRM, SIG_IGN)) == SIG_ERR)
  222. logmsg("cannot install SIGALRM handler: %s", strerror(ERRNO));
  223. #endif
  224. #ifdef SIGINT
  225. /* handle SIGINT signal with our exit_signal_handler */
  226. if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
  227. logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
  228. else
  229. siginterrupt(SIGINT, 1);
  230. #endif
  231. #ifdef SIGTERM
  232. /* handle SIGTERM signal with our exit_signal_handler */
  233. if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
  234. logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
  235. else
  236. siginterrupt(SIGTERM, 1);
  237. #endif
  238. }
  239. static void restore_signal_handlers(void)
  240. {
  241. #ifdef SIGHUP
  242. if(SIG_ERR != old_sighup_handler)
  243. (void)signal(SIGHUP, old_sighup_handler);
  244. #endif
  245. #ifdef SIGPIPE
  246. if(SIG_ERR != old_sigpipe_handler)
  247. (void)signal(SIGPIPE, old_sigpipe_handler);
  248. #endif
  249. #ifdef SIGALRM
  250. if(SIG_ERR != old_sigalrm_handler)
  251. (void)signal(SIGALRM, old_sigalrm_handler);
  252. #endif
  253. #ifdef SIGINT
  254. if(SIG_ERR != old_sigint_handler)
  255. (void)signal(SIGINT, old_sigint_handler);
  256. #endif
  257. #ifdef SIGTERM
  258. if(SIG_ERR != old_sigterm_handler)
  259. (void)signal(SIGTERM, old_sigterm_handler);
  260. #endif
  261. }
  262. static int ProcessRequest(struct httprequest *req)
  263. {
  264. char *line=&req->reqbuf[req->checkindex];
  265. bool chunked = FALSE;
  266. static char request[REQUEST_KEYWORD_SIZE];
  267. static char doc[MAXDOCNAMELEN];
  268. char logbuf[456];
  269. int prot_major, prot_minor;
  270. char *end;
  271. int error;
  272. end = strstr(line, end_of_headers);
  273. req->callcount++;
  274. logmsg("Process %d bytes request%s", req->offset,
  275. req->callcount > 1?" [CONTINUED]":"");
  276. /* try to figure out the request characteristics as soon as possible, but
  277. only once! */
  278. if(use_gopher &&
  279. (req->testno == DOCNUMBER_NOTHING) &&
  280. !strncmp("/verifiedserver", line, 15)) {
  281. logmsg("Are-we-friendly question received");
  282. req->testno = DOCNUMBER_WERULEZ;
  283. return 1; /* done */
  284. }
  285. else if((req->testno == DOCNUMBER_NOTHING) &&
  286. sscanf(line,
  287. "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
  288. request,
  289. doc,
  290. &prot_major,
  291. &prot_minor) == 4) {
  292. char *ptr;
  293. req->prot_version = prot_major*10 + prot_minor;
  294. /* find the last slash */
  295. ptr = strrchr(doc, '/');
  296. /* get the number after it */
  297. if(ptr) {
  298. FILE *stream;
  299. char *filename;
  300. if((strlen(doc) + strlen(request)) < 400)
  301. sprintf(logbuf, "Got request: %s %s HTTP/%d.%d",
  302. request, doc, prot_major, prot_minor);
  303. else
  304. sprintf(logbuf, "Got a *HUGE* request HTTP/%d.%d",
  305. prot_major, prot_minor);
  306. logmsg("%s", logbuf);
  307. if(!strncmp("/verifiedserver", ptr, 15)) {
  308. logmsg("Are-we-friendly question received");
  309. req->testno = DOCNUMBER_WERULEZ;
  310. return 1; /* done */
  311. }
  312. if(!strncmp("/quit", ptr, 5)) {
  313. logmsg("Request-to-quit received");
  314. req->testno = DOCNUMBER_QUIT;
  315. return 1; /* done */
  316. }
  317. ptr++; /* skip the slash */
  318. /* skip all non-numericals following the slash */
  319. while(*ptr && !ISDIGIT(*ptr))
  320. ptr++;
  321. req->testno = strtol(ptr, &ptr, 10);
  322. if(req->testno > 10000) {
  323. req->partno = req->testno % 10000;
  324. req->testno /= 10000;
  325. }
  326. else
  327. req->partno = 0;
  328. sprintf(logbuf, "Requested test number %ld part %ld",
  329. req->testno, req->partno);
  330. logmsg("%s", logbuf);
  331. filename = test2file(req->testno);
  332. stream=fopen(filename, "rb");
  333. if(!stream) {
  334. error = ERRNO;
  335. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  336. logmsg("Error opening file: %s", filename);
  337. logmsg("Couldn't open test file %ld", req->testno);
  338. req->open = FALSE; /* closes connection */
  339. return 1; /* done */
  340. }
  341. else {
  342. char *orgcmd = NULL;
  343. char *cmd = NULL;
  344. size_t cmdsize = 0;
  345. int num=0;
  346. /* get the custom server control "commands" */
  347. error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
  348. fclose(stream);
  349. if(error) {
  350. logmsg("getpart() failed with error: %d", error);
  351. req->open = FALSE; /* closes connection */
  352. return 1; /* done */
  353. }
  354. cmd = orgcmd;
  355. while(cmd && cmdsize) {
  356. char *check;
  357. if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) {
  358. logmsg("instructed to require authorization header");
  359. req->auth_req = TRUE;
  360. }
  361. else if(!strncmp(CMD_IDLE, cmd, strlen(CMD_IDLE))) {
  362. logmsg("instructed to idle");
  363. req->rcmd = RCMD_IDLE;
  364. req->open = TRUE;
  365. }
  366. else if(!strncmp(CMD_STREAM, cmd, strlen(CMD_STREAM))) {
  367. logmsg("instructed to stream");
  368. req->rcmd = RCMD_STREAM;
  369. }
  370. else if(1 == sscanf(cmd, "pipe: %d", &num)) {
  371. logmsg("instructed to allow a pipe size of %d", num);
  372. if(num < 0)
  373. logmsg("negative pipe size ignored");
  374. else if(num > 0)
  375. req->pipe = num-1; /* decrease by one since we don't count the
  376. first request in this number */
  377. }
  378. else if(1 == sscanf(cmd, "skip: %d", &num)) {
  379. logmsg("instructed to skip this number of bytes %d", num);
  380. req->skip = num;
  381. }
  382. else if(1 == sscanf(cmd, "writedelay: %d", &num)) {
  383. logmsg("instructed to delay %d secs between packets", num);
  384. req->writedelay = num;
  385. }
  386. else {
  387. logmsg("funny instruction found: %s", cmd);
  388. }
  389. /* try to deal with CRLF or just LF */
  390. check = strchr(cmd, '\r');
  391. if(!check)
  392. check = strchr(cmd, '\n');
  393. if(check) {
  394. /* get to the letter following the newline */
  395. while((*check == '\r') || (*check == '\n'))
  396. check++;
  397. if(!*check)
  398. /* if we reached a zero, get out */
  399. break;
  400. cmd = check;
  401. }
  402. else
  403. break;
  404. }
  405. if(orgcmd)
  406. free(orgcmd);
  407. }
  408. }
  409. else {
  410. if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
  411. doc, &prot_major, &prot_minor) == 3) {
  412. char *portp = NULL;
  413. sprintf(logbuf, "Received a CONNECT %s HTTP/%d.%d request",
  414. doc, prot_major, prot_minor);
  415. logmsg("%s", logbuf);
  416. if(req->prot_version == 10)
  417. req->open = FALSE; /* HTTP 1.0 closes connection by default */
  418. if(doc[0] == '[') {
  419. char *p = &doc[1];
  420. while(*p && (ISXDIGIT(*p) || (*p == ':') || (*p == '.')))
  421. p++;
  422. if(*p != ']')
  423. logmsg("Invalid CONNECT IPv6 address format");
  424. else if (*(p+1) != ':')
  425. logmsg("Invalid CONNECT IPv6 port format");
  426. else
  427. portp = p+1;
  428. }
  429. else
  430. portp = strchr(doc, ':');
  431. if(portp && (*(portp+1) != '\0') && ISDIGIT(*(portp+1))) {
  432. unsigned long ulnum = strtoul(portp+1, NULL, 10);
  433. if(!ulnum || (ulnum > 65535UL))
  434. logmsg("Invalid CONNECT port received");
  435. else
  436. req->connect_port = curlx_ultous(ulnum);
  437. }
  438. if(!strncmp(doc, "bad", 3))
  439. /* if the host name starts with bad, we fake an error here */
  440. req->testno = DOCNUMBER_BADCONNECT;
  441. else if(!strncmp(doc, "test", 4))
  442. /* if the host name starts with test, the port number used in the
  443. CONNECT line will be used as test number! */
  444. req->testno = req->connect_port?req->connect_port:DOCNUMBER_CONNECT;
  445. else
  446. req->testno = req->connect_port?DOCNUMBER_CONNECT:DOCNUMBER_BADCONNECT;
  447. }
  448. else {
  449. logmsg("Did not find test number in PATH");
  450. req->testno = DOCNUMBER_404;
  451. }
  452. }
  453. }
  454. else if((req->offset >= 3) && (req->testno == DOCNUMBER_NOTHING)) {
  455. logmsg("** Unusual request. Starts with %02x %02x %02x",
  456. line[0], line[1], line[2]);
  457. }
  458. if(!end) {
  459. /* we don't have a complete request yet! */
  460. logmsg("request not complete yet");
  461. return 0; /* not complete yet */
  462. }
  463. logmsg("- request found to be complete");
  464. if(use_gopher) {
  465. /* when using gopher we cannot check the request until the entire
  466. thing has been received */
  467. char *ptr;
  468. /* find the last slash in the line */
  469. ptr = strrchr(line, '/');
  470. if(ptr) {
  471. ptr++; /* skip the slash */
  472. /* skip all non-numericals following the slash */
  473. while(*ptr && !ISDIGIT(*ptr))
  474. ptr++;
  475. req->testno = strtol(ptr, &ptr, 10);
  476. if(req->testno > 10000) {
  477. req->partno = req->testno % 10000;
  478. req->testno /= 10000;
  479. }
  480. else
  481. req->partno = 0;
  482. sprintf(logbuf, "Requested GOPHER test number %ld part %ld",
  483. req->testno, req->partno);
  484. logmsg("%s", logbuf);
  485. }
  486. }
  487. if(req->pipe)
  488. /* we do have a full set, advance the checkindex to after the end of the
  489. headers, for the pipelining case mostly */
  490. req->checkindex += (end - line) + strlen(end_of_headers);
  491. /* **** Persistence ****
  492. *
  493. * If the request is a HTTP/1.0 one, we close the connection unconditionally
  494. * when we're done.
  495. *
  496. * If the request is a HTTP/1.1 one, we MUST check for a "Connection:"
  497. * header that might say "close". If it does, we close a connection when
  498. * this request is processed. Otherwise, we keep the connection alive for X
  499. * seconds.
  500. */
  501. do {
  502. if(got_exit_signal)
  503. return 1; /* done */
  504. if((req->cl==0) && curlx_strnequal("Content-Length:", line, 15)) {
  505. /* If we don't ignore content-length, we read it and we read the whole
  506. request including the body before we return. If we've been told to
  507. ignore the content-length, we will return as soon as all headers
  508. have been received */
  509. char *endptr;
  510. char *ptr = line + 15;
  511. unsigned long clen = 0;
  512. while(*ptr && ISSPACE(*ptr))
  513. ptr++;
  514. endptr = ptr;
  515. SET_ERRNO(0);
  516. clen = strtoul(ptr, &endptr, 10);
  517. if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == ERRNO)) {
  518. /* this assumes that a zero Content-Length is valid */
  519. logmsg("Found invalid Content-Length: (%s) in the request", ptr);
  520. req->open = FALSE; /* closes connection */
  521. return 1; /* done */
  522. }
  523. req->cl = clen - req->skip;
  524. logmsg("Found Content-Length: %lu in the request", clen);
  525. if(req->skip)
  526. logmsg("... but will abort after %zu bytes", req->cl);
  527. break;
  528. }
  529. else if(curlx_strnequal("Transfer-Encoding: chunked", line,
  530. strlen("Transfer-Encoding: chunked"))) {
  531. /* chunked data coming in */
  532. chunked = TRUE;
  533. }
  534. if(chunked) {
  535. if(strstr(req->reqbuf, "\r\n0\r\n\r\n"))
  536. /* end of chunks reached */
  537. return 1; /* done */
  538. else
  539. return 0; /* not done */
  540. }
  541. line = strchr(line, '\n');
  542. if(line)
  543. line++;
  544. } while(line);
  545. if(!req->auth && strstr(req->reqbuf, "Authorization:")) {
  546. req->auth = TRUE; /* Authorization: header present! */
  547. if(req->auth_req)
  548. logmsg("Authorization header found, as required");
  549. }
  550. if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) {
  551. /* If the client is passing this Digest-header, we set the part number
  552. to 1000. Not only to spice up the complexity of this, but to make
  553. Digest stuff to work in the test suite. */
  554. req->partno += 1000;
  555. req->digest = TRUE; /* header found */
  556. logmsg("Received Digest request, sending back data %ld", req->partno);
  557. }
  558. else if(!req->ntlm &&
  559. strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) {
  560. /* If the client is passing this type-3 NTLM header */
  561. req->partno += 1002;
  562. req->ntlm = TRUE; /* NTLM found */
  563. logmsg("Received NTLM type-3, sending back data %ld", req->partno);
  564. if(req->cl) {
  565. logmsg(" Expecting %zu POSTed bytes", req->cl);
  566. }
  567. }
  568. else if(!req->ntlm &&
  569. strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) {
  570. /* If the client is passing this type-1 NTLM header */
  571. req->partno += 1001;
  572. req->ntlm = TRUE; /* NTLM found */
  573. logmsg("Received NTLM type-1, sending back data %ld", req->partno);
  574. }
  575. else if((req->partno >= 1000) &&
  576. strstr(req->reqbuf, "Authorization: Basic")) {
  577. /* If the client is passing this Basic-header and the part number is
  578. already >=1000, we add 1 to the part number. This allows simple Basic
  579. authentication negotiation to work in the test suite. */
  580. req->partno += 1;
  581. logmsg("Received Basic request, sending back data %ld", req->partno);
  582. }
  583. if(strstr(req->reqbuf, "Connection: close"))
  584. req->open = FALSE; /* close connection after this request */
  585. if(!req->pipe &&
  586. req->open &&
  587. req->prot_version >= 11 &&
  588. end &&
  589. req->reqbuf + req->offset > end + strlen(end_of_headers) &&
  590. !req->cl &&
  591. (!strncmp(req->reqbuf, "GET", strlen("GET")) ||
  592. !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) {
  593. /* If we have a persistent connection, HTTP version >= 1.1
  594. and GET/HEAD request, enable pipelining. */
  595. req->checkindex = (end - req->reqbuf) + strlen(end_of_headers);
  596. req->pipelining = TRUE;
  597. }
  598. while(req->pipe) {
  599. if(got_exit_signal)
  600. return 1; /* done */
  601. /* scan for more header ends within this chunk */
  602. line = &req->reqbuf[req->checkindex];
  603. end = strstr(line, end_of_headers);
  604. if(!end)
  605. break;
  606. req->checkindex += (end - line) + strlen(end_of_headers);
  607. req->pipe--;
  608. }
  609. /* If authentication is required and no auth was provided, end now. This
  610. makes the server NOT wait for PUT/POST data and you can then make the
  611. test case send a rejection before any such data has been sent. Test case
  612. 154 uses this.*/
  613. if(req->auth_req && !req->auth) {
  614. logmsg("Return early due to auth requested by none provided");
  615. return 1; /* done */
  616. }
  617. if(req->cl > 0) {
  618. if(req->cl <= req->offset - (end - req->reqbuf) - strlen(end_of_headers))
  619. return 1; /* done */
  620. else
  621. return 0; /* not complete yet */
  622. }
  623. return 1; /* done */
  624. }
  625. /* store the entire request in a file */
  626. static void storerequest(char *reqbuf, size_t totalsize)
  627. {
  628. int res;
  629. int error = 0;
  630. size_t written;
  631. size_t writeleft;
  632. FILE *dump;
  633. const char *dumpfile=is_proxy?REQUEST_PROXY_DUMP:REQUEST_DUMP;
  634. if (reqbuf == NULL)
  635. return;
  636. if (totalsize == 0)
  637. return;
  638. do {
  639. dump = fopen(dumpfile, "ab");
  640. } while ((dump == NULL) && ((error = ERRNO) == EINTR));
  641. if (dump == NULL) {
  642. logmsg("Error opening file %s error: %d %s",
  643. dumpfile, error, strerror(error));
  644. logmsg("Failed to write request input ");
  645. return;
  646. }
  647. writeleft = totalsize;
  648. do {
  649. written = fwrite(&reqbuf[totalsize-writeleft],
  650. 1, writeleft, dump);
  651. if(got_exit_signal)
  652. goto storerequest_cleanup;
  653. if(written > 0)
  654. writeleft -= written;
  655. } while ((writeleft > 0) && ((error = ERRNO) == EINTR));
  656. if(writeleft == 0)
  657. logmsg("Wrote request (%zu bytes) input to %s", totalsize, dumpfile);
  658. else if(writeleft > 0) {
  659. logmsg("Error writing file %s error: %d %s",
  660. dumpfile, error, strerror(error));
  661. logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s",
  662. totalsize-writeleft, totalsize, dumpfile);
  663. }
  664. storerequest_cleanup:
  665. do {
  666. res = fclose(dump);
  667. } while(res && ((error = ERRNO) == EINTR));
  668. if(res)
  669. logmsg("Error closing file %s error: %d %s",
  670. dumpfile, error, strerror(error));
  671. }
  672. /* return 0 on success, non-zero on failure */
  673. static int get_request(curl_socket_t sock, struct httprequest *req)
  674. {
  675. int error;
  676. int fail = 0;
  677. int done_processing = 0;
  678. char *reqbuf = req->reqbuf;
  679. ssize_t got = 0;
  680. char *pipereq = NULL;
  681. size_t pipereq_length = 0;
  682. if(req->pipelining) {
  683. pipereq = reqbuf + req->checkindex;
  684. pipereq_length = req->offset - req->checkindex;
  685. }
  686. /*** Init the httprequest structure properly for the upcoming request ***/
  687. req->checkindex = 0;
  688. req->offset = 0;
  689. req->testno = DOCNUMBER_NOTHING;
  690. req->partno = 0;
  691. req->open = TRUE;
  692. req->auth_req = FALSE;
  693. req->auth = FALSE;
  694. req->cl = 0;
  695. req->digest = FALSE;
  696. req->ntlm = FALSE;
  697. req->pipe = 0;
  698. req->skip = 0;
  699. req->writedelay = 0;
  700. req->rcmd = RCMD_NORMALREQ;
  701. req->prot_version = 0;
  702. req->pipelining = FALSE;
  703. req->callcount = 0;
  704. req->connect_port = 0;
  705. /*** end of httprequest init ***/
  706. while(!done_processing && (req->offset < REQBUFSIZ-1)) {
  707. if(pipereq_length && pipereq) {
  708. memmove(reqbuf, pipereq, pipereq_length);
  709. got = curlx_uztosz(pipereq_length);
  710. pipereq_length = 0;
  711. }
  712. else {
  713. if(req->skip)
  714. /* we are instructed to not read the entire thing, so we make sure to
  715. only read what we're supposed to and NOT read the enire thing the
  716. client wants to send! */
  717. got = sread(sock, reqbuf + req->offset, req->cl);
  718. else
  719. got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset);
  720. }
  721. if(got_exit_signal)
  722. return 1;
  723. if(got == 0) {
  724. logmsg("Connection closed by client");
  725. fail = 1;
  726. }
  727. else if(got < 0) {
  728. error = SOCKERRNO;
  729. logmsg("recv() returned error: (%d) %s", error, strerror(error));
  730. fail = 1;
  731. }
  732. if(fail) {
  733. /* dump the request received so far to the external file */
  734. reqbuf[req->offset] = '\0';
  735. storerequest(reqbuf, req->offset);
  736. return 1;
  737. }
  738. logmsg("Read %zd bytes", got);
  739. req->offset += (size_t)got;
  740. reqbuf[req->offset] = '\0';
  741. done_processing = ProcessRequest(req);
  742. if(got_exit_signal)
  743. return 1;
  744. if(done_processing && req->pipe) {
  745. logmsg("Waiting for another piped request");
  746. done_processing = 0;
  747. req->pipe--;
  748. }
  749. }
  750. if((req->offset == REQBUFSIZ-1) && (got > 0)) {
  751. logmsg("Request would overflow buffer, closing connection");
  752. /* dump request received so far to external file anyway */
  753. reqbuf[REQBUFSIZ-1] = '\0';
  754. fail = 1;
  755. }
  756. else if(req->offset > REQBUFSIZ-1) {
  757. logmsg("Request buffer overflow, closing connection");
  758. /* dump request received so far to external file anyway */
  759. reqbuf[REQBUFSIZ-1] = '\0';
  760. fail = 1;
  761. }
  762. else
  763. reqbuf[req->offset] = '\0';
  764. /* dump the request to an external file */
  765. storerequest(reqbuf, req->pipelining ? req->checkindex : req->offset);
  766. if(got_exit_signal)
  767. return 1;
  768. return fail; /* return 0 on success */
  769. }
  770. /* returns -1 on failure */
  771. static int send_doc(curl_socket_t sock, struct httprequest *req)
  772. {
  773. ssize_t written;
  774. size_t count;
  775. const char *buffer;
  776. char *ptr=NULL;
  777. FILE *stream;
  778. char *cmd=NULL;
  779. size_t cmdsize=0;
  780. FILE *dump;
  781. bool persistant = TRUE;
  782. bool sendfailure = FALSE;
  783. size_t responsesize;
  784. int error = 0;
  785. int res;
  786. const char *responsedump = is_proxy?RESPONSE_PROXY_DUMP:RESPONSE_DUMP;
  787. static char weare[256];
  788. char partbuf[80]="data";
  789. logmsg("Send response test%ld section <data%ld>", req->testno, req->partno);
  790. switch(req->rcmd) {
  791. default:
  792. case RCMD_NORMALREQ:
  793. break; /* continue with business as usual */
  794. case RCMD_STREAM:
  795. #define STREAMTHIS "a string to stream 01234567890\n"
  796. count = strlen(STREAMTHIS);
  797. for (;;) {
  798. written = swrite(sock, STREAMTHIS, count);
  799. if(got_exit_signal)
  800. return -1;
  801. if(written != (ssize_t)count) {
  802. logmsg("Stopped streaming");
  803. break;
  804. }
  805. }
  806. return -1;
  807. case RCMD_IDLE:
  808. /* Do nothing. Sit idle. Pretend it rains. */
  809. return 0;
  810. }
  811. req->open = FALSE;
  812. if(req->testno < 0) {
  813. size_t msglen;
  814. char msgbuf[64];
  815. switch(req->testno) {
  816. case DOCNUMBER_QUIT:
  817. logmsg("Replying to QUIT");
  818. buffer = docquit;
  819. break;
  820. case DOCNUMBER_WERULEZ:
  821. /* we got a "friends?" question, reply back that we sure are */
  822. logmsg("Identifying ourselves as friends");
  823. sprintf(msgbuf, "WE ROOLZ: %ld\r\n", (long)getpid());
  824. msglen = strlen(msgbuf);
  825. if(use_gopher)
  826. sprintf(weare, "%s", msgbuf);
  827. else
  828. sprintf(weare, "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s",
  829. msglen, msgbuf);
  830. buffer = weare;
  831. break;
  832. case DOCNUMBER_INTERNAL:
  833. logmsg("Bailing out due to internal error");
  834. return -1;
  835. case DOCNUMBER_CONNECT:
  836. logmsg("Replying to CONNECT");
  837. buffer = docconnect;
  838. break;
  839. case DOCNUMBER_BADCONNECT:
  840. logmsg("Replying to a bad CONNECT");
  841. buffer = docbadconnect;
  842. break;
  843. case DOCNUMBER_404:
  844. default:
  845. logmsg("Replying to with a 404");
  846. buffer = doc404;
  847. break;
  848. }
  849. count = strlen(buffer);
  850. }
  851. else {
  852. char *filename = test2file(req->testno);
  853. if(0 != req->partno)
  854. sprintf(partbuf, "data%ld", req->partno);
  855. stream=fopen(filename, "rb");
  856. if(!stream) {
  857. error = ERRNO;
  858. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  859. logmsg("Error opening file: %s", filename);
  860. logmsg("Couldn't open test file");
  861. return 0;
  862. }
  863. else {
  864. error = getpart(&ptr, &count, "reply", partbuf, stream);
  865. fclose(stream);
  866. if(error) {
  867. logmsg("getpart() failed with error: %d", error);
  868. return 0;
  869. }
  870. buffer = ptr;
  871. }
  872. if(got_exit_signal) {
  873. if(ptr)
  874. free(ptr);
  875. return -1;
  876. }
  877. /* re-open the same file again */
  878. stream=fopen(filename, "rb");
  879. if(!stream) {
  880. error = ERRNO;
  881. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  882. logmsg("Error opening file: %s", filename);
  883. logmsg("Couldn't open test file");
  884. if(ptr)
  885. free(ptr);
  886. return 0;
  887. }
  888. else {
  889. /* get the custom server control "commands" */
  890. error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream);
  891. fclose(stream);
  892. if(error) {
  893. logmsg("getpart() failed with error: %d", error);
  894. if(ptr)
  895. free(ptr);
  896. return 0;
  897. }
  898. }
  899. }
  900. if(got_exit_signal) {
  901. if(ptr)
  902. free(ptr);
  903. if(cmd)
  904. free(cmd);
  905. return -1;
  906. }
  907. /* If the word 'swsclose' is present anywhere in the reply chunk, the
  908. connection will be closed after the data has been sent to the requesting
  909. client... */
  910. if(strstr(buffer, "swsclose") || !count) {
  911. persistant = FALSE;
  912. logmsg("connection close instruction \"swsclose\" found in response");
  913. }
  914. if(strstr(buffer, "swsbounce")) {
  915. prevbounce = TRUE;
  916. logmsg("enable \"swsbounce\" in the next request");
  917. }
  918. else
  919. prevbounce = FALSE;
  920. dump = fopen(responsedump, "ab");
  921. if(!dump) {
  922. error = ERRNO;
  923. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  924. logmsg("Error opening file: %s", responsedump);
  925. if(ptr)
  926. free(ptr);
  927. if(cmd)
  928. free(cmd);
  929. return -1;
  930. }
  931. responsesize = count;
  932. do {
  933. /* Ok, we send no more than 200 bytes at a time, just to make sure that
  934. larger chunks are split up so that the client will need to do multiple
  935. recv() calls to get it and thus we exercise that code better */
  936. size_t num = count;
  937. if(num > 200)
  938. num = 200;
  939. written = swrite(sock, buffer, num);
  940. if (written < 0) {
  941. sendfailure = TRUE;
  942. break;
  943. }
  944. else {
  945. logmsg("Sent off %zd bytes", written);
  946. }
  947. /* write to file as well */
  948. fwrite(buffer, 1, (size_t)written, dump);
  949. count -= written;
  950. buffer += written;
  951. if(req->writedelay) {
  952. int quarters = req->writedelay * 4;
  953. logmsg("Pausing %d seconds", req->writedelay);
  954. while((quarters > 0) && !got_exit_signal) {
  955. quarters--;
  956. wait_ms(250);
  957. }
  958. }
  959. } while((count > 0) && !got_exit_signal);
  960. do {
  961. res = fclose(dump);
  962. } while(res && ((error = ERRNO) == EINTR));
  963. if(res)
  964. logmsg("Error closing file %s error: %d %s",
  965. responsedump, error, strerror(error));
  966. if(got_exit_signal) {
  967. if(ptr)
  968. free(ptr);
  969. if(cmd)
  970. free(cmd);
  971. return -1;
  972. }
  973. if(sendfailure) {
  974. logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) were sent",
  975. responsesize-count, responsesize);
  976. if(ptr)
  977. free(ptr);
  978. if(cmd)
  979. free(cmd);
  980. return -1;
  981. }
  982. logmsg("Response sent (%zu bytes) and written to %s",
  983. responsesize, responsedump);
  984. if(ptr)
  985. free(ptr);
  986. if(cmdsize > 0 ) {
  987. char command[32];
  988. int quarters;
  989. int num;
  990. ptr=cmd;
  991. do {
  992. if(2 == sscanf(ptr, "%31s %d", command, &num)) {
  993. if(!strcmp("wait", command)) {
  994. logmsg("Told to sleep for %d seconds", num);
  995. quarters = num * 4;
  996. while((quarters > 0) && !got_exit_signal) {
  997. quarters--;
  998. res = wait_ms(250);
  999. if(res) {
  1000. /* should not happen */
  1001. error = SOCKERRNO;
  1002. logmsg("wait_ms() failed with error: (%d) %s",
  1003. error, strerror(error));
  1004. break;
  1005. }
  1006. }
  1007. if(!quarters)
  1008. logmsg("Continuing after sleeping %d seconds", num);
  1009. }
  1010. else
  1011. logmsg("Unknown command in reply command section");
  1012. }
  1013. ptr = strchr(ptr, '\n');
  1014. if(ptr)
  1015. ptr++;
  1016. else
  1017. ptr = NULL;
  1018. } while(ptr && *ptr);
  1019. }
  1020. if(cmd)
  1021. free(cmd);
  1022. req->open = use_gopher?FALSE:persistant;
  1023. prevtestno = req->testno;
  1024. prevpartno = req->partno;
  1025. return 0;
  1026. }
  1027. static curl_socket_t connect_to(const char *ipaddr, unsigned short port)
  1028. {
  1029. srvr_sockaddr_union_t serveraddr;
  1030. curl_socket_t serverfd;
  1031. int error;
  1032. int rc;
  1033. const char *op_br = "";
  1034. const char *cl_br = "";
  1035. #ifdef TCP_NODELAY
  1036. curl_socklen_t flag;
  1037. #endif
  1038. #ifdef ENABLE_IPV6
  1039. if(use_ipv6) {
  1040. op_br = "[";
  1041. cl_br = "]";
  1042. }
  1043. #endif
  1044. if(!ipaddr)
  1045. return CURL_SOCKET_BAD;
  1046. logmsg("about to connect to %s%s%s:%hu",
  1047. op_br, ipaddr, cl_br, port);
  1048. #ifdef ENABLE_IPV6
  1049. if(!use_ipv6)
  1050. #endif
  1051. serverfd = socket(AF_INET, SOCK_STREAM, 0);
  1052. #ifdef ENABLE_IPV6
  1053. else
  1054. serverfd = socket(AF_INET6, SOCK_STREAM, 0);
  1055. #endif
  1056. if(CURL_SOCKET_BAD == serverfd) {
  1057. error = SOCKERRNO;
  1058. logmsg("Error creating socket for server conection: (%d) %s",
  1059. error, strerror(error));
  1060. return CURL_SOCKET_BAD;
  1061. }
  1062. #ifdef TCP_NODELAY
  1063. /* Disable the Nagle algorithm */
  1064. flag = 1;
  1065. if(0 != setsockopt(serverfd, IPPROTO_TCP, TCP_NODELAY,
  1066. (void *)&flag, sizeof(flag)))
  1067. logmsg("====> TCP_NODELAY for server conection failed");
  1068. else
  1069. logmsg("TCP_NODELAY set for server conection");
  1070. #endif
  1071. #ifdef ENABLE_IPV6
  1072. if(!use_ipv6) {
  1073. #endif
  1074. memset(&serveraddr.sa4, 0, sizeof(serveraddr.sa4));
  1075. serveraddr.sa4.sin_family = AF_INET;
  1076. serveraddr.sa4.sin_port = htons(port);
  1077. if(Curl_inet_pton(AF_INET, ipaddr, &serveraddr.sa4.sin_addr) < 1) {
  1078. logmsg("Error inet_pton failed AF_INET conversion of '%s'", ipaddr);
  1079. sclose(serverfd);
  1080. return CURL_SOCKET_BAD;
  1081. }
  1082. rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa4));
  1083. #ifdef ENABLE_IPV6
  1084. }
  1085. else {
  1086. memset(&serveraddr.sa6, 0, sizeof(serveraddr.sa6));
  1087. serveraddr.sa6.sin6_family = AF_INET6;
  1088. serveraddr.sa6.sin6_port = htons(port);
  1089. if(Curl_inet_pton(AF_INET6, ipaddr, &serveraddr.sa6.sin6_addr) < 1) {
  1090. logmsg("Error inet_pton failed AF_INET6 conversion of '%s'", ipaddr);
  1091. sclose(serverfd);
  1092. return CURL_SOCKET_BAD;
  1093. }
  1094. rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa6));
  1095. }
  1096. #endif /* ENABLE_IPV6 */
  1097. if(got_exit_signal) {
  1098. sclose(serverfd);
  1099. return CURL_SOCKET_BAD;
  1100. }
  1101. if(rc) {
  1102. error = SOCKERRNO;
  1103. logmsg("Error connecting to server port %hu: (%d) %s",
  1104. port, error, strerror(error));
  1105. sclose(serverfd);
  1106. return CURL_SOCKET_BAD;
  1107. }
  1108. logmsg("connected fine to %s%s%s:%hu, now tunnel",
  1109. op_br, ipaddr, cl_br, port);
  1110. return serverfd;
  1111. }
  1112. /*
  1113. * A CONNECT has been received, a CONNECT response has been sent.
  1114. *
  1115. * This function needs to connect to the server, and then pass data between
  1116. * the client and the server back and forth until the connection is closed by
  1117. * either end.
  1118. *
  1119. * When doing FTP through a CONNECT proxy, we expect that the data connection
  1120. * will be setup while the first connect is still being kept up. Therefor we
  1121. * must accept a new connection and deal with it appropriately.
  1122. */
  1123. #define data_or_ctrl(x) ((x)?"DATA":"CTRL")
  1124. #define CTRL 0
  1125. #define DATA 1
  1126. static void http_connect(curl_socket_t *infdp,
  1127. curl_socket_t rootfd,
  1128. struct httprequest *req,
  1129. const char *ipaddr)
  1130. {
  1131. curl_socket_t serverfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD};
  1132. curl_socket_t clientfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD};
  1133. ssize_t toc[2] = {0, 0}; /* number of bytes to client */
  1134. ssize_t tos[2] = {0, 0}; /* number of bytes to server */
  1135. char readclient[2][256];
  1136. char readserver[2][256];
  1137. bool poll_client_rd[2] = { TRUE, TRUE };
  1138. bool poll_server_rd[2] = { TRUE, TRUE };
  1139. bool poll_client_wr[2] = { TRUE, TRUE };
  1140. bool poll_server_wr[2] = { TRUE, TRUE };
  1141. #ifdef TCP_NODELAY
  1142. curl_socklen_t flag;
  1143. #endif
  1144. bool primary = FALSE;
  1145. bool secondary = FALSE;
  1146. int max_tunnel_idx; /* CTRL or DATA */
  1147. int loop;
  1148. int i;
  1149. /* primary tunnel client endpoint already connected */
  1150. clientfd[CTRL] = *infdp;
  1151. /* Sleep here to make sure the client reads CONNECT response's
  1152. 'end of headers' separate from the server data that follows.
  1153. This is done to prevent triggering libcurl known bug #39. */
  1154. for(loop = 2; (loop > 0) && !got_exit_signal; loop--)
  1155. wait_ms(250);
  1156. if(got_exit_signal)
  1157. goto http_connect_cleanup;
  1158. serverfd[CTRL] = connect_to(ipaddr, req->connect_port);
  1159. if(serverfd[CTRL] == CURL_SOCKET_BAD)
  1160. goto http_connect_cleanup;
  1161. /* Primary tunnel socket endpoints are now connected. Tunnel data back and
  1162. forth over the primary tunnel until client or server breaks the primary
  1163. tunnel, simultaneously allowing establishment, operation and teardown of
  1164. a secondary tunnel that may be used for passive FTP data connection. */
  1165. max_tunnel_idx = CTRL;
  1166. primary = TRUE;
  1167. while(!got_exit_signal) {
  1168. fd_set input;
  1169. fd_set output;
  1170. struct timeval timeout = {0, 250000L}; /* 250 ms */
  1171. ssize_t rc;
  1172. curl_socket_t maxfd = (curl_socket_t)-1;
  1173. FD_ZERO(&input);
  1174. FD_ZERO(&output);
  1175. if((clientfd[DATA] == CURL_SOCKET_BAD) &&
  1176. (serverfd[DATA] == CURL_SOCKET_BAD) &&
  1177. poll_client_rd[CTRL] && poll_client_wr[CTRL] &&
  1178. poll_server_rd[CTRL] && poll_server_wr[CTRL]) {
  1179. /* listener socket is monitored to allow client to establish
  1180. secondary tunnel only when this tunnel is not established
  1181. and primary one is fully operational */
  1182. FD_SET(rootfd, &input);
  1183. maxfd = rootfd;
  1184. }
  1185. /* set tunnel sockets to wait for */
  1186. for(i = 0; i <= max_tunnel_idx; i++) {
  1187. /* client side socket monitoring */
  1188. if(clientfd[i] != CURL_SOCKET_BAD) {
  1189. if(poll_client_rd[i]) {
  1190. /* unless told not to do so, monitor readability */
  1191. FD_SET(clientfd[i], &input);
  1192. if(clientfd[i] > maxfd)
  1193. maxfd = clientfd[i];
  1194. }
  1195. if(poll_client_wr[i] && toc[i]) {
  1196. /* unless told not to do so, monitor writeability
  1197. if there is data ready to be sent to client */
  1198. FD_SET(clientfd[i], &output);
  1199. if(clientfd[i] > maxfd)
  1200. maxfd = clientfd[i];
  1201. }
  1202. }
  1203. /* server side socket monitoring */
  1204. if(serverfd[i] != CURL_SOCKET_BAD) {
  1205. if(poll_server_rd[i]) {
  1206. /* unless told not to do so, monitor readability */
  1207. FD_SET(serverfd[i], &input);
  1208. if(serverfd[i] > maxfd)
  1209. maxfd = serverfd[i];
  1210. }
  1211. if(poll_server_wr[i] && tos[i]) {
  1212. /* unless told not to do so, monitor writeability
  1213. if there is data ready to be sent to server */
  1214. FD_SET(serverfd[i], &output);
  1215. if(serverfd[i] > maxfd)
  1216. maxfd = serverfd[i];
  1217. }
  1218. }
  1219. }
  1220. if(got_exit_signal)
  1221. break;
  1222. rc = select((int)maxfd + 1, &input, &output, NULL, &timeout);
  1223. if(rc > 0) {
  1224. /* socket action */
  1225. bool tcp_fin_wr;
  1226. if(got_exit_signal)
  1227. break;
  1228. tcp_fin_wr = FALSE;
  1229. /* ---------------------------------------------------------- */
  1230. /* passive mode FTP may establish a secondary tunnel */
  1231. if((clientfd[DATA] == CURL_SOCKET_BAD) &&
  1232. (serverfd[DATA] == CURL_SOCKET_BAD) && FD_ISSET(rootfd, &input)) {
  1233. /* a new connection on listener socket (most likely from client) */
  1234. curl_socket_t datafd = accept(rootfd, NULL, NULL);
  1235. if(datafd != CURL_SOCKET_BAD) {
  1236. struct httprequest req2;
  1237. int err;
  1238. logmsg("====> Client connect DATA");
  1239. #ifdef TCP_NODELAY
  1240. /* Disable the Nagle algorithm */
  1241. flag = 1;
  1242. if(0 != setsockopt(datafd, IPPROTO_TCP, TCP_NODELAY,
  1243. (void *)&flag, sizeof(flag)))
  1244. logmsg("====> TCP_NODELAY for client DATA conection failed");
  1245. else
  1246. logmsg("TCP_NODELAY set for client DATA conection");
  1247. #endif
  1248. req2.pipelining = FALSE;
  1249. err = get_request(datafd, &req2);
  1250. if(!err) {
  1251. err = send_doc(datafd, &req2);
  1252. if(!err && (req2.testno == DOCNUMBER_CONNECT)) {
  1253. /* sleep to prevent triggering libcurl known bug #39. */
  1254. for(loop = 2; (loop > 0) && !got_exit_signal; loop--)
  1255. wait_ms(250);
  1256. if(!got_exit_signal) {
  1257. /* connect to the server */
  1258. serverfd[DATA] = connect_to(ipaddr, req2.connect_port);
  1259. if(serverfd[DATA] != CURL_SOCKET_BAD) {
  1260. /* secondary tunnel established, now we have two connections */
  1261. poll_client_rd[DATA] = TRUE;
  1262. poll_client_wr[DATA] = TRUE;
  1263. poll_server_rd[DATA] = TRUE;
  1264. poll_server_wr[DATA] = TRUE;
  1265. max_tunnel_idx = DATA;
  1266. secondary = TRUE;
  1267. toc[DATA] = 0;
  1268. tos[DATA] = 0;
  1269. clientfd[DATA] = datafd;
  1270. datafd = CURL_SOCKET_BAD;
  1271. }
  1272. }
  1273. }
  1274. }
  1275. if(datafd != CURL_SOCKET_BAD) {
  1276. /* secondary tunnel not established */
  1277. shutdown(datafd, SHUT_RDWR);
  1278. sclose(datafd);
  1279. }
  1280. }
  1281. if(got_exit_signal)
  1282. break;
  1283. }
  1284. /* ---------------------------------------------------------- */
  1285. /* react to tunnel endpoint readable/writeable notifications */
  1286. for(i = 0; i <= max_tunnel_idx; i++) {
  1287. size_t len;
  1288. if(clientfd[i] != CURL_SOCKET_BAD) {
  1289. len = sizeof(readclient[i]) - tos[i];
  1290. if(len && FD_ISSET(clientfd[i], &input)) {
  1291. /* read from client */
  1292. rc = sread(clientfd[i], &readclient[i][tos[i]], len);
  1293. if(rc <= 0) {
  1294. logmsg("[%s] got %zd, STOP READING client", data_or_ctrl(i), rc);
  1295. shutdown(clientfd[i], SHUT_RD);
  1296. poll_client_rd[i] = FALSE;
  1297. }
  1298. else {
  1299. logmsg("[%s] READ %zd bytes from client", data_or_ctrl(i), rc);
  1300. logmsg("[%s] READ \"%s\"", data_or_ctrl(i),
  1301. data_to_hex(&readclient[i][tos[i]], rc));
  1302. tos[i] += rc;
  1303. }
  1304. }
  1305. }
  1306. if(serverfd[i] != CURL_SOCKET_BAD) {
  1307. len = sizeof(readserver[i])-toc[i];
  1308. if(len && FD_ISSET(serverfd[i], &input)) {
  1309. /* read from server */
  1310. rc = sread(serverfd[i], &readserver[i][toc[i]], len);
  1311. if(rc <= 0) {
  1312. logmsg("[%s] got %zd, STOP READING server", data_or_ctrl(i), rc);
  1313. shutdown(serverfd[i], SHUT_RD);
  1314. poll_server_rd[i] = FALSE;
  1315. }
  1316. else {
  1317. logmsg("[%s] READ %zd bytes from server", data_or_ctrl(i), rc);
  1318. logmsg("[%s] READ \"%s\"", data_or_ctrl(i),
  1319. data_to_hex(&readserver[i][toc[i]], rc));
  1320. toc[i] += rc;
  1321. }
  1322. }
  1323. }
  1324. if(clientfd[i] != CURL_SOCKET_BAD) {
  1325. if(toc[i] && FD_ISSET(clientfd[i], &output)) {
  1326. /* write to client */
  1327. rc = swrite(clientfd[i], readserver[i], toc[i]);
  1328. if(rc <= 0) {
  1329. logmsg("[%s] got %zd, STOP WRITING client", data_or_ctrl(i), rc);
  1330. shutdown(clientfd[i], SHUT_WR);
  1331. poll_client_wr[i] = FALSE;
  1332. tcp_fin_wr = TRUE;
  1333. }
  1334. else {
  1335. logmsg("[%s] SENT %zd bytes to client", data_or_ctrl(i), rc);
  1336. logmsg("[%s] SENT \"%s\"", data_or_ctrl(i),
  1337. data_to_hex(readserver[i], rc));
  1338. if(toc[i] - rc)
  1339. memmove(&readserver[i][0], &readserver[i][rc], toc[i]-rc);
  1340. toc[i] -= rc;
  1341. }
  1342. }
  1343. }
  1344. if(serverfd[i] != CURL_SOCKET_BAD) {
  1345. if(tos[i] && FD_ISSET(serverfd[i], &output)) {
  1346. /* write to server */
  1347. rc = swrite(serverfd[i], readclient[i], tos[i]);
  1348. if(rc <= 0) {
  1349. logmsg("[%s] got %zd, STOP WRITING server", data_or_ctrl(i), rc);
  1350. shutdown(serverfd[i], SHUT_WR);
  1351. poll_server_wr[i] = FALSE;
  1352. tcp_fin_wr = TRUE;
  1353. }
  1354. else {
  1355. logmsg("[%s] SENT %zd bytes to server", data_or_ctrl(i), rc);
  1356. logmsg("[%s] SENT \"%s\"", data_or_ctrl(i),
  1357. data_to_hex(readclient[i], rc));
  1358. if(tos[i] - rc)
  1359. memmove(&readclient[i][0], &readclient[i][rc], tos[i]-rc);
  1360. tos[i] -= rc;
  1361. }
  1362. }
  1363. }
  1364. }
  1365. if(got_exit_signal)
  1366. break;
  1367. /* ---------------------------------------------------------- */
  1368. /* endpoint read/write disabling, endpoint closing and tunnel teardown */
  1369. for(i = 0; i <= max_tunnel_idx; i++) {
  1370. for(loop = 2; loop > 0; loop--) {
  1371. /* loop twice to satisfy condition interdependencies without
  1372. having to await select timeout or another socket event */
  1373. if(clientfd[i] != CURL_SOCKET_BAD) {
  1374. if(poll_client_rd[i] && !poll_server_wr[i]) {
  1375. logmsg("[%s] DISABLED READING client", data_or_ctrl(i));
  1376. shutdown(clientfd[i], SHUT_RD);
  1377. poll_client_rd[i] = FALSE;
  1378. }
  1379. if(poll_client_wr[i] && !poll_server_rd[i] && !toc[i]) {
  1380. logmsg("[%s] DISABLED WRITING client", data_or_ctrl(i));
  1381. shutdown(clientfd[i], SHUT_WR);
  1382. poll_client_wr[i] = FALSE;
  1383. tcp_fin_wr = TRUE;
  1384. }
  1385. }
  1386. if(serverfd[i] != CURL_SOCKET_BAD) {
  1387. if(poll_server_rd[i] && !poll_client_wr[i]) {
  1388. logmsg("[%s] DISABLED READING server", data_or_ctrl(i));
  1389. shutdown(serverfd[i], SHUT_RD);
  1390. poll_server_rd[i] = FALSE;
  1391. }
  1392. if(poll_server_wr[i] && !poll_client_rd[i] && !tos[i]) {
  1393. logmsg("[%s] DISABLED WRITING server", data_or_ctrl(i));
  1394. shutdown(serverfd[i], SHUT_WR);
  1395. poll_server_wr[i] = FALSE;
  1396. tcp_fin_wr = TRUE;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. if(tcp_fin_wr)
  1402. /* allow kernel to place FIN bit packet on the wire */
  1403. wait_ms(250);
  1404. /* socket clearing */
  1405. for(i = 0; i <= max_tunnel_idx; i++) {
  1406. for(loop = 2; loop > 0; loop--) {
  1407. if(clientfd[i] != CURL_SOCKET_BAD) {
  1408. if(!poll_client_wr[i] && !poll_client_rd[i]) {
  1409. logmsg("[%s] CLOSING client socket", data_or_ctrl(i));
  1410. sclose(clientfd[i]);
  1411. clientfd[i] = CURL_SOCKET_BAD;
  1412. if(serverfd[i] == CURL_SOCKET_BAD) {
  1413. logmsg("[%s] ENDING", data_or_ctrl(i));
  1414. if(i == DATA)
  1415. secondary = FALSE;
  1416. else
  1417. primary = FALSE;
  1418. }
  1419. }
  1420. }
  1421. if(serverfd[i] != CURL_SOCKET_BAD) {
  1422. if(!poll_server_wr[i] && !poll_server_rd[i]) {
  1423. logmsg("[%s] CLOSING server socket", data_or_ctrl(i));
  1424. sclose(serverfd[i]);
  1425. serverfd[i] = CURL_SOCKET_BAD;
  1426. if(clientfd[i] == CURL_SOCKET_BAD) {
  1427. logmsg("[%s] ENDING", data_or_ctrl(i));
  1428. if(i == DATA)
  1429. secondary = FALSE;
  1430. else
  1431. primary = FALSE;
  1432. }
  1433. }
  1434. }
  1435. }
  1436. }
  1437. /* ---------------------------------------------------------- */
  1438. max_tunnel_idx = secondary ? DATA : CTRL;
  1439. if(!primary)
  1440. /* exit loop upon primary tunnel teardown */
  1441. break;
  1442. } /* (rc > 0) */
  1443. }
  1444. http_connect_cleanup:
  1445. for(i = DATA; i >= CTRL; i--) {
  1446. if(serverfd[i] != CURL_SOCKET_BAD) {
  1447. logmsg("[%s] CLOSING server socket (cleanup)", data_or_ctrl(i));
  1448. shutdown(serverfd[i], SHUT_RDWR);
  1449. sclose(serverfd[i]);
  1450. }
  1451. if(clientfd[i] != CURL_SOCKET_BAD) {
  1452. logmsg("[%s] CLOSING client socket (cleanup)", data_or_ctrl(i));
  1453. shutdown(clientfd[i], SHUT_RDWR);
  1454. sclose(clientfd[i]);
  1455. }
  1456. if((serverfd[i] != CURL_SOCKET_BAD) ||
  1457. (clientfd[i] != CURL_SOCKET_BAD)) {
  1458. logmsg("[%s] ABORTING", data_or_ctrl(i));
  1459. }
  1460. }
  1461. *infdp = CURL_SOCKET_BAD;
  1462. }
  1463. int main(int argc, char *argv[])
  1464. {
  1465. srvr_sockaddr_union_t me;
  1466. curl_socket_t sock = CURL_SOCKET_BAD;
  1467. curl_socket_t msgsock = CURL_SOCKET_BAD;
  1468. int wrotepidfile = 0;
  1469. int flag;
  1470. unsigned short port = DEFAULT_PORT;
  1471. char *pidname= (char *)".http.pid";
  1472. struct httprequest req;
  1473. int rc;
  1474. int error;
  1475. int arg=1;
  1476. long pid;
  1477. const char *hostport = "127.0.0.1";
  1478. #ifdef CURL_SWS_FORK_ENABLED
  1479. bool use_fork = FALSE;
  1480. #endif
  1481. while(argc>arg) {
  1482. if(!strcmp("--version", argv[arg])) {
  1483. printf("sws IPv4%s"
  1484. #ifdef CURL_SWS_FORK_ENABLED
  1485. " FORK"
  1486. #endif
  1487. "\n"
  1488. ,
  1489. #ifdef ENABLE_IPV6
  1490. "/IPv6"
  1491. #else
  1492. ""
  1493. #endif
  1494. );
  1495. return 0;
  1496. }
  1497. else if(!strcmp("--pidfile", argv[arg])) {
  1498. arg++;
  1499. if(argc>arg)
  1500. pidname = argv[arg++];
  1501. }
  1502. else if(!strcmp("--logfile", argv[arg])) {
  1503. arg++;
  1504. if(argc>arg)
  1505. serverlogfile = argv[arg++];
  1506. }
  1507. else if(!strcmp("--gopher", argv[arg])) {
  1508. arg++;
  1509. use_gopher = TRUE;
  1510. end_of_headers = "\r\n"; /* gopher style is much simpler */
  1511. }
  1512. else if(!strcmp("--ipv4", argv[arg])) {
  1513. #ifdef ENABLE_IPV6
  1514. ipv_inuse = "IPv4";
  1515. use_ipv6 = FALSE;
  1516. #endif
  1517. arg++;
  1518. }
  1519. else if(!strcmp("--ipv6", argv[arg])) {
  1520. #ifdef ENABLE_IPV6
  1521. ipv_inuse = "IPv6";
  1522. use_ipv6 = TRUE;
  1523. #endif
  1524. arg++;
  1525. }
  1526. #ifdef CURL_SWS_FORK_ENABLED
  1527. else if(!strcmp("--fork", argv[arg])) {
  1528. use_fork=TRUE;
  1529. arg++;
  1530. }
  1531. #endif
  1532. else if(!strcmp("--port", argv[arg])) {
  1533. arg++;
  1534. if(argc>arg) {
  1535. char *endptr;
  1536. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1537. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1538. (ulnum < 1025UL) || (ulnum > 65535UL)) {
  1539. fprintf(stderr, "sws: invalid --port argument (%s)\n",
  1540. argv[arg]);
  1541. return 0;
  1542. }
  1543. port = curlx_ultous(ulnum);
  1544. arg++;
  1545. }
  1546. }
  1547. else if(!strcmp("--srcdir", argv[arg])) {
  1548. arg++;
  1549. if(argc>arg) {
  1550. path = argv[arg];
  1551. arg++;
  1552. }
  1553. }
  1554. else if(!strcmp("--connect", argv[arg])) {
  1555. /* store the connect host, but also use this as a hint that we
  1556. run as a proxy and do a few different internal choices */
  1557. arg++;
  1558. if(argc>arg) {
  1559. hostport = argv[arg];
  1560. arg++;
  1561. is_proxy = TRUE;
  1562. logmsg("Run as proxy, CONNECT to %s", hostport);
  1563. }
  1564. }
  1565. else {
  1566. puts("Usage: sws [option]\n"
  1567. " --version\n"
  1568. " --logfile [file]\n"
  1569. " --pidfile [file]\n"
  1570. " --ipv4\n"
  1571. " --ipv6\n"
  1572. " --port [port]\n"
  1573. " --srcdir [path]\n"
  1574. " --connect [ip4-addr]\n"
  1575. " --gopher\n"
  1576. " --fork");
  1577. return 0;
  1578. }
  1579. }
  1580. #ifdef WIN32
  1581. win32_init();
  1582. atexit(win32_cleanup);
  1583. #endif
  1584. install_signal_handlers();
  1585. pid = (long)getpid();
  1586. #ifdef ENABLE_IPV6
  1587. if(!use_ipv6)
  1588. #endif
  1589. sock = socket(AF_INET, SOCK_STREAM, 0);
  1590. #ifdef ENABLE_IPV6
  1591. else
  1592. sock = socket(AF_INET6, SOCK_STREAM, 0);
  1593. #endif
  1594. if(CURL_SOCKET_BAD == sock) {
  1595. error = SOCKERRNO;
  1596. logmsg("Error creating socket: (%d) %s",
  1597. error, strerror(error));
  1598. goto sws_cleanup;
  1599. }
  1600. flag = 1;
  1601. if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  1602. (void *)&flag, sizeof(flag))) {
  1603. error = SOCKERRNO;
  1604. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  1605. error, strerror(error));
  1606. goto sws_cleanup;
  1607. }
  1608. #ifdef ENABLE_IPV6
  1609. if(!use_ipv6) {
  1610. #endif
  1611. memset(&me.sa4, 0, sizeof(me.sa4));
  1612. me.sa4.sin_family = AF_INET;
  1613. me.sa4.sin_addr.s_addr = INADDR_ANY;
  1614. me.sa4.sin_port = htons(port);
  1615. rc = bind(sock, &me.sa, sizeof(me.sa4));
  1616. #ifdef ENABLE_IPV6
  1617. }
  1618. else {
  1619. memset(&me.sa6, 0, sizeof(me.sa6));
  1620. me.sa6.sin6_family = AF_INET6;
  1621. me.sa6.sin6_addr = in6addr_any;
  1622. me.sa6.sin6_port = htons(port);
  1623. rc = bind(sock, &me.sa, sizeof(me.sa6));
  1624. }
  1625. #endif /* ENABLE_IPV6 */
  1626. if(0 != rc) {
  1627. error = SOCKERRNO;
  1628. logmsg("Error binding socket on port %hu: (%d) %s",
  1629. port, error, strerror(error));
  1630. goto sws_cleanup;
  1631. }
  1632. logmsg("Running %s %s version on port %d",
  1633. use_gopher?"GOPHER":"HTTP", ipv_inuse, (int)port);
  1634. /* start accepting connections */
  1635. rc = listen(sock, 5);
  1636. if(0 != rc) {
  1637. error = SOCKERRNO;
  1638. logmsg("listen() failed with error: (%d) %s",
  1639. error, strerror(error));
  1640. goto sws_cleanup;
  1641. }
  1642. /*
  1643. ** As soon as this server writes its pid file the test harness will
  1644. ** attempt to connect to this server and initiate its verification.
  1645. */
  1646. wrotepidfile = write_pidfile(pidname);
  1647. if(!wrotepidfile)
  1648. goto sws_cleanup;
  1649. for (;;) {
  1650. msgsock = accept(sock, NULL, NULL);
  1651. if(got_exit_signal)
  1652. break;
  1653. if (CURL_SOCKET_BAD == msgsock) {
  1654. error = SOCKERRNO;
  1655. logmsg("MAJOR ERROR: accept() failed with error: (%d) %s",
  1656. error, strerror(error));
  1657. break;
  1658. }
  1659. /*
  1660. ** As soon as this server acepts a connection from the test harness it
  1661. ** must set the server logs advisor read lock to indicate that server
  1662. ** logs should not be read until this lock is removed by this server.
  1663. */
  1664. set_advisor_read_lock(SERVERLOGS_LOCK);
  1665. serverlogslocked = 1;
  1666. #ifdef CURL_SWS_FORK_ENABLED
  1667. if(use_fork) {
  1668. /* The fork enabled version just forks off the child and don't care
  1669. about it anymore, so don't assume otherwise. Beware and don't do
  1670. this at home. */
  1671. rc = fork();
  1672. if(-1 == rc) {
  1673. printf("MAJOR ERROR: fork() failed!\n");
  1674. break;
  1675. }
  1676. }
  1677. else
  1678. /* not a fork, just set rc so the following proceeds nicely */
  1679. rc = 0;
  1680. /* 0 is returned to the child */
  1681. if(0 == rc) {
  1682. #endif
  1683. logmsg("====> Client connect");
  1684. #ifdef TCP_NODELAY
  1685. /*
  1686. * Disable the Nagle algorithm to make it easier to send out a large
  1687. * response in many small segments to torture the clients more.
  1688. */
  1689. flag = 1;
  1690. if(0 != setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
  1691. (void *)&flag, sizeof(flag)))
  1692. logmsg("====> TCP_NODELAY failed");
  1693. else
  1694. logmsg("TCP_NODELAY set");
  1695. #endif
  1696. /* initialization of httprequest struct is done in get_request(), but due
  1697. to pipelining treatment the pipelining struct field must be initialized
  1698. previously to FALSE every time a new connection arrives. */
  1699. req.pipelining = FALSE;
  1700. do {
  1701. if(got_exit_signal)
  1702. break;
  1703. if(get_request(msgsock, &req))
  1704. /* non-zero means error, break out of loop */
  1705. break;
  1706. if(prevbounce) {
  1707. /* bounce treatment requested */
  1708. if((req.testno == prevtestno) &&
  1709. (req.partno == prevpartno)) {
  1710. req.partno++;
  1711. logmsg("BOUNCE part number to %ld", req.partno);
  1712. }
  1713. else {
  1714. prevbounce = FALSE;
  1715. prevtestno = -1;
  1716. prevpartno = -1;
  1717. }
  1718. }
  1719. send_doc(msgsock, &req);
  1720. if(got_exit_signal)
  1721. break;
  1722. if(DOCNUMBER_CONNECT == req.testno) {
  1723. /* a CONNECT request, setup and talk the tunnel */
  1724. if(!is_proxy) {
  1725. logmsg("received CONNECT but isn't running as proxy! EXIT");
  1726. }
  1727. else
  1728. http_connect(&msgsock, sock, &req, hostport);
  1729. break;
  1730. }
  1731. if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) {
  1732. logmsg("special request received, no persistency");
  1733. break;
  1734. }
  1735. if(!req.open) {
  1736. logmsg("instructed to close connection after server-reply");
  1737. break;
  1738. }
  1739. if(req.open) {
  1740. logmsg("=> persistant connection request ended, awaits new request\n");
  1741. /*
  1742. const char *keepopen="[KEEPING CONNECTION OPEN]";
  1743. storerequest((char *)keepopen, strlen(keepopen));
  1744. */
  1745. }
  1746. /* if we got a CONNECT, loop and get another request as well! */
  1747. } while(req.open || (req.testno == DOCNUMBER_CONNECT));
  1748. if(got_exit_signal)
  1749. break;
  1750. logmsg("====> Client disconnect");
  1751. if(!req.open)
  1752. /* When instructed to close connection after server-reply we
  1753. wait a very small amount of time before doing so. If this
  1754. is not done client might get an ECONNRESET before reading
  1755. a single byte of server-reply. */
  1756. wait_ms(50);
  1757. if(msgsock != CURL_SOCKET_BAD) {
  1758. sclose(msgsock);
  1759. msgsock = CURL_SOCKET_BAD;
  1760. }
  1761. if(serverlogslocked) {
  1762. serverlogslocked = 0;
  1763. clear_advisor_read_lock(SERVERLOGS_LOCK);
  1764. }
  1765. if (req.testno == DOCNUMBER_QUIT)
  1766. break;
  1767. #ifdef CURL_SWS_FORK_ENABLED
  1768. }
  1769. #endif
  1770. }
  1771. sws_cleanup:
  1772. if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
  1773. sclose(msgsock);
  1774. if(sock != CURL_SOCKET_BAD)
  1775. sclose(sock);
  1776. if(got_exit_signal)
  1777. logmsg("signalled to die");
  1778. if(wrotepidfile)
  1779. unlink(pidname);
  1780. if(serverlogslocked) {
  1781. serverlogslocked = 0;
  1782. clear_advisor_read_lock(SERVERLOGS_LOCK);
  1783. }
  1784. restore_signal_handlers();
  1785. if(got_exit_signal) {
  1786. logmsg("========> %s sws (port: %d pid: %ld) exits with signal (%d)",
  1787. ipv_inuse, (int)port, pid, exit_signal);
  1788. /*
  1789. * To properly set the return status of the process we
  1790. * must raise the same signal SIGINT or SIGTERM that we
  1791. * caught and let the old handler take care of it.
  1792. */
  1793. raise(exit_signal);
  1794. }
  1795. logmsg("========> sws quits");
  1796. return 0;
  1797. }