sws.c 64 KB

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