sws.c 74 KB

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