sws.c 74 KB

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