sws.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566
  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 = {0};
  787. timeout.tv_sec = 1; /* 1000 ms */
  788. logmsg("Got EAGAIN from sread");
  789. FD_ZERO(&input);
  790. FD_ZERO(&output);
  791. got = 0;
  792. #if defined(__DJGPP__)
  793. #pragma GCC diagnostic push
  794. #pragma GCC diagnostic ignored "-Warith-conversion"
  795. #endif
  796. FD_SET(sock, &input);
  797. #if defined(__DJGPP__)
  798. #pragma GCC diagnostic pop
  799. #endif
  800. do {
  801. logmsg("Wait until readable");
  802. rc = select((int)sock + 1, &input, &output, NULL, &timeout);
  803. } while(rc < 0 && errno == EINTR && !got_exit_signal);
  804. logmsg("readable %d", rc);
  805. if(rc)
  806. got = 1;
  807. }
  808. } while(got > 0);
  809. }
  810. else {
  811. logmsg("NO wait for websocket traffic");
  812. }
  813. if(req->offset) {
  814. logmsg("log the websocket traffic");
  815. /* dump the incoming websocket traffic to the external file */
  816. reqbuf[req->offset] = '\0';
  817. storerequest(reqbuf, req->offset);
  818. req->offset = 0;
  819. }
  820. init_httprequest(req);
  821. return -1;
  822. }
  823. if(req->offset >= REQBUFSIZ-1) {
  824. /* buffer is already full; do nothing */
  825. overflow = 1;
  826. }
  827. else {
  828. if(req->skip)
  829. /* we are instructed to not read the entire thing, so we make sure to
  830. only read what we're supposed to and NOT read the entire thing the
  831. client wants to send! */
  832. got = sread(sock, reqbuf + req->offset, req->cl);
  833. else
  834. got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset);
  835. if(got_exit_signal)
  836. return -1;
  837. if(got == 0) {
  838. logmsg("Connection closed by client");
  839. fail = 1;
  840. }
  841. else if(got < 0) {
  842. int error = SOCKERRNO;
  843. if(EAGAIN == error || EWOULDBLOCK == error) {
  844. /* nothing to read at the moment */
  845. return 0;
  846. }
  847. logmsg("recv() returned error: (%d) %s", error, sstrerror(error));
  848. fail = 1;
  849. }
  850. if(fail) {
  851. /* dump the request received so far to the external file */
  852. reqbuf[req->offset] = '\0';
  853. storerequest(reqbuf, req->offset);
  854. return -1;
  855. }
  856. logmsg("Read %zd bytes", got);
  857. req->offset += (size_t)got;
  858. reqbuf[req->offset] = '\0';
  859. req->done_processing = ProcessRequest(req);
  860. if(got_exit_signal)
  861. return -1;
  862. }
  863. if(overflow || (req->offset == REQBUFSIZ-1 && got > 0)) {
  864. logmsg("Request would overflow buffer, closing connection");
  865. /* dump request received so far to external file anyway */
  866. reqbuf[REQBUFSIZ-1] = '\0';
  867. fail = 1;
  868. }
  869. else if(req->offset > REQBUFSIZ-1) {
  870. logmsg("Request buffer overflow, closing connection");
  871. /* dump request received so far to external file anyway */
  872. reqbuf[REQBUFSIZ-1] = '\0';
  873. fail = 1;
  874. }
  875. else
  876. reqbuf[req->offset] = '\0';
  877. /* at the end of a request dump it to an external file */
  878. if(fail || req->done_processing)
  879. storerequest(reqbuf, req->offset);
  880. if(got_exit_signal)
  881. return -1;
  882. return fail ? -1 : 1;
  883. }
  884. /* returns -1 on failure */
  885. static int send_doc(curl_socket_t sock, struct httprequest *req)
  886. {
  887. ssize_t written;
  888. size_t count;
  889. const char *buffer;
  890. char *ptr = NULL;
  891. FILE *stream;
  892. char *cmd = NULL;
  893. size_t cmdsize = 0;
  894. FILE *dump;
  895. bool persistent = TRUE;
  896. bool sendfailure = FALSE;
  897. size_t responsesize;
  898. int error = 0;
  899. int res;
  900. static char weare[256];
  901. char responsedump[256];
  902. msnprintf(responsedump, sizeof(responsedump), "%s/%s",
  903. logdir, is_proxy ? RESPONSE_PROXY_DUMP : RESPONSE_DUMP);
  904. switch(req->rcmd) {
  905. default:
  906. case RCMD_NORMALREQ:
  907. break; /* continue with business as usual */
  908. case RCMD_STREAM:
  909. #define STREAMTHIS "a string to stream 01234567890\n"
  910. count = strlen(STREAMTHIS);
  911. for(;;) {
  912. written = swrite(sock, STREAMTHIS, count);
  913. if(got_exit_signal)
  914. return -1;
  915. if(written != (ssize_t)count) {
  916. logmsg("Stopped streaming");
  917. break;
  918. }
  919. }
  920. return -1;
  921. case RCMD_IDLE:
  922. /* Do nothing. Sit idle. Pretend it rains. */
  923. return 0;
  924. }
  925. req->open = FALSE;
  926. if(req->testno < 0) {
  927. size_t msglen;
  928. char msgbuf[64];
  929. switch(req->testno) {
  930. case DOCNUMBER_QUIT:
  931. logmsg("Replying to QUIT");
  932. buffer = docquit;
  933. break;
  934. case DOCNUMBER_WERULEZ:
  935. /* we got a "friends?" question, reply back that we sure are */
  936. logmsg("Identifying ourselves as friends");
  937. msnprintf(msgbuf, sizeof(msgbuf), "WE ROOLZ: %"
  938. CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid());
  939. msglen = strlen(msgbuf);
  940. if(use_gopher)
  941. msnprintf(weare, sizeof(weare), "%s", msgbuf);
  942. else
  943. msnprintf(weare, sizeof(weare),
  944. "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s",
  945. msglen, msgbuf);
  946. buffer = weare;
  947. break;
  948. case DOCNUMBER_404:
  949. default:
  950. logmsg("Replying to with a 404");
  951. buffer = doc404;
  952. break;
  953. }
  954. count = strlen(buffer);
  955. }
  956. else {
  957. char partbuf[80];
  958. /* select the <data> tag for "normal" requests and the <connect> one
  959. for CONNECT requests (within the <reply> section) */
  960. const char *section = req->connect_request ? "connect" : "data";
  961. if(req->partno)
  962. msnprintf(partbuf, sizeof(partbuf), "%s%ld", section, req->partno);
  963. else
  964. msnprintf(partbuf, sizeof(partbuf), "%s", section);
  965. logmsg("Send response test%ld section <%s>", req->testno, partbuf);
  966. stream = test2fopen(req->testno, logdir);
  967. if(!stream) {
  968. error = errno;
  969. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  970. return 0;
  971. }
  972. else {
  973. error = getpart(&ptr, &count, "reply", partbuf, stream);
  974. fclose(stream);
  975. if(error) {
  976. logmsg("getpart() failed with error: %d", error);
  977. return 0;
  978. }
  979. buffer = ptr;
  980. }
  981. if(got_exit_signal) {
  982. free(ptr);
  983. return -1;
  984. }
  985. /* re-open the same file again */
  986. stream = test2fopen(req->testno, logdir);
  987. if(!stream) {
  988. error = errno;
  989. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  990. free(ptr);
  991. return 0;
  992. }
  993. else {
  994. /* get the custom server control "commands" */
  995. error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream);
  996. fclose(stream);
  997. if(error) {
  998. logmsg("getpart() failed with error: %d", error);
  999. free(ptr);
  1000. return 0;
  1001. }
  1002. }
  1003. }
  1004. if(got_exit_signal) {
  1005. free(ptr);
  1006. free(cmd);
  1007. return -1;
  1008. }
  1009. /* If the word 'swsclose' is present anywhere in the reply chunk, the
  1010. connection will be closed after the data has been sent to the requesting
  1011. client... */
  1012. if(strstr(buffer, "swsclose") || !count || req->close) {
  1013. persistent = FALSE;
  1014. logmsg("connection close instruction \"swsclose\" found in response");
  1015. }
  1016. if(strstr(buffer, "swsbounce")) {
  1017. prevbounce = TRUE;
  1018. logmsg("enable \"swsbounce\" in the next request");
  1019. }
  1020. else
  1021. prevbounce = FALSE;
  1022. dump = fopen(responsedump, "ab");
  1023. if(!dump) {
  1024. error = errno;
  1025. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  1026. logmsg(" [5] Error opening file: %s", responsedump);
  1027. free(ptr);
  1028. free(cmd);
  1029. return -1;
  1030. }
  1031. responsesize = count;
  1032. do {
  1033. /* Ok, we send no more than N bytes at a time, just to make sure that
  1034. larger chunks are split up so that the client will need to do multiple
  1035. recv() calls to get it and thus we exercise that code better */
  1036. size_t num = count;
  1037. if(num > 20)
  1038. num = 20;
  1039. retry:
  1040. written = swrite(sock, buffer, num);
  1041. if(written < 0) {
  1042. if((EWOULDBLOCK == SOCKERRNO) || (EAGAIN == SOCKERRNO)) {
  1043. wait_ms(10);
  1044. goto retry;
  1045. }
  1046. sendfailure = TRUE;
  1047. break;
  1048. }
  1049. /* write to file as well */
  1050. fwrite(buffer, 1, (size_t)written, dump);
  1051. count -= written;
  1052. buffer += written;
  1053. if(req->writedelay) {
  1054. int msecs_left = req->writedelay;
  1055. int intervals = msecs_left / MAX_SLEEP_TIME_MS;
  1056. if(msecs_left%MAX_SLEEP_TIME_MS)
  1057. intervals++;
  1058. logmsg("Pausing %d milliseconds after writing %zd bytes",
  1059. msecs_left, written);
  1060. while((intervals > 0) && !got_exit_signal) {
  1061. int sleep_time = msecs_left > MAX_SLEEP_TIME_MS ?
  1062. MAX_SLEEP_TIME_MS : msecs_left;
  1063. intervals--;
  1064. wait_ms(sleep_time);
  1065. msecs_left -= sleep_time;
  1066. }
  1067. }
  1068. } while((count > 0) && !got_exit_signal);
  1069. do {
  1070. res = fclose(dump);
  1071. } while(res && ((error = errno) == EINTR));
  1072. if(res)
  1073. logmsg("Error closing file %s error: %d %s",
  1074. responsedump, error, strerror(error));
  1075. if(got_exit_signal) {
  1076. free(ptr);
  1077. free(cmd);
  1078. return -1;
  1079. }
  1080. if(sendfailure) {
  1081. logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) "
  1082. "were sent",
  1083. responsesize-count, responsesize);
  1084. prevtestno = req->testno;
  1085. prevpartno = req->partno;
  1086. free(ptr);
  1087. free(cmd);
  1088. return -1;
  1089. }
  1090. logmsg("Response sent (%zu bytes) and written to %s",
  1091. responsesize, responsedump);
  1092. free(ptr);
  1093. if(cmdsize > 0) {
  1094. char command[32];
  1095. int quarters;
  1096. int num;
  1097. ptr = cmd;
  1098. do {
  1099. if(2 == sscanf(ptr, "%31s %d", command, &num)) {
  1100. if(!strcmp("wait", command)) {
  1101. logmsg("Told to sleep for %d seconds", num);
  1102. quarters = num * 4;
  1103. while((quarters > 0) && !got_exit_signal) {
  1104. quarters--;
  1105. res = wait_ms(250);
  1106. if(res) {
  1107. /* should not happen */
  1108. error = errno;
  1109. logmsg("wait_ms() failed with error: (%d) %s",
  1110. error, strerror(error));
  1111. break;
  1112. }
  1113. }
  1114. if(!quarters)
  1115. logmsg("Continuing after sleeping %d seconds", num);
  1116. }
  1117. else
  1118. logmsg("Unknown command in reply command section");
  1119. }
  1120. ptr = strchr(ptr, '\n');
  1121. if(ptr)
  1122. ptr++;
  1123. else
  1124. ptr = NULL;
  1125. } while(ptr && *ptr);
  1126. }
  1127. free(cmd);
  1128. req->open = use_gopher ? FALSE : persistent;
  1129. prevtestno = req->testno;
  1130. prevpartno = req->partno;
  1131. return 0;
  1132. }
  1133. static curl_socket_t connect_to(const char *ipaddr, unsigned short port)
  1134. {
  1135. srvr_sockaddr_union_t serveraddr;
  1136. curl_socket_t serverfd;
  1137. int error;
  1138. int rc = 0;
  1139. const char *op_br = "";
  1140. const char *cl_br = "";
  1141. #ifdef USE_IPV6
  1142. if(socket_domain == AF_INET6) {
  1143. op_br = "[";
  1144. cl_br = "]";
  1145. }
  1146. #endif
  1147. if(!ipaddr)
  1148. return CURL_SOCKET_BAD;
  1149. logmsg("about to connect to %s%s%s:%hu",
  1150. op_br, ipaddr, cl_br, port);
  1151. serverfd = socket(socket_domain, SOCK_STREAM, 0);
  1152. if(CURL_SOCKET_BAD == serverfd) {
  1153. error = SOCKERRNO;
  1154. logmsg("Error creating socket for server connection: (%d) %s",
  1155. error, sstrerror(error));
  1156. return CURL_SOCKET_BAD;
  1157. }
  1158. #ifdef TCP_NODELAY
  1159. if(socket_domain_is_ip()) {
  1160. /* Disable the Nagle algorithm */
  1161. curl_socklen_t flag = 1;
  1162. if(0 != setsockopt(serverfd, IPPROTO_TCP, TCP_NODELAY,
  1163. (void *)&flag, sizeof(flag)))
  1164. logmsg("====> TCP_NODELAY for server connection failed");
  1165. }
  1166. #endif
  1167. /* We want to do the connect() in a non-blocking mode, since
  1168. * Windows has an internal retry logic that may lead to long
  1169. * timeouts if the peer is not listening. */
  1170. if(0 != curlx_nonblock(serverfd, TRUE)) {
  1171. error = SOCKERRNO;
  1172. logmsg("curlx_nonblock(TRUE) failed with error: (%d) %s",
  1173. error, sstrerror(error));
  1174. sclose(serverfd);
  1175. return CURL_SOCKET_BAD;
  1176. }
  1177. switch(socket_domain) {
  1178. case AF_INET:
  1179. memset(&serveraddr.sa4, 0, sizeof(serveraddr.sa4));
  1180. serveraddr.sa4.sin_family = AF_INET;
  1181. serveraddr.sa4.sin_port = htons(port);
  1182. if(Curl_inet_pton(AF_INET, ipaddr, &serveraddr.sa4.sin_addr) < 1) {
  1183. logmsg("Error inet_pton failed AF_INET conversion of '%s'", ipaddr);
  1184. sclose(serverfd);
  1185. return CURL_SOCKET_BAD;
  1186. }
  1187. rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa4));
  1188. break;
  1189. #ifdef USE_IPV6
  1190. case AF_INET6:
  1191. memset(&serveraddr.sa6, 0, sizeof(serveraddr.sa6));
  1192. serveraddr.sa6.sin6_family = AF_INET6;
  1193. serveraddr.sa6.sin6_port = htons(port);
  1194. if(Curl_inet_pton(AF_INET6, ipaddr, &serveraddr.sa6.sin6_addr) < 1) {
  1195. logmsg("Error inet_pton failed AF_INET6 conversion of '%s'", ipaddr);
  1196. sclose(serverfd);
  1197. return CURL_SOCKET_BAD;
  1198. }
  1199. rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa6));
  1200. break;
  1201. #endif /* USE_IPV6 */
  1202. #ifdef USE_UNIX_SOCKETS
  1203. case AF_UNIX:
  1204. logmsg("Proxying through Unix socket is not (yet?) supported.");
  1205. return CURL_SOCKET_BAD;
  1206. #endif /* USE_UNIX_SOCKETS */
  1207. }
  1208. if(got_exit_signal) {
  1209. sclose(serverfd);
  1210. return CURL_SOCKET_BAD;
  1211. }
  1212. if(rc) {
  1213. error = SOCKERRNO;
  1214. if((error == EINPROGRESS) || (error == EWOULDBLOCK)) {
  1215. fd_set output;
  1216. struct timeval timeout = {0};
  1217. timeout.tv_sec = 1; /* 1000 ms */
  1218. FD_ZERO(&output);
  1219. #if defined(__DJGPP__)
  1220. #pragma GCC diagnostic push
  1221. #pragma GCC diagnostic ignored "-Warith-conversion"
  1222. #endif
  1223. FD_SET(serverfd, &output);
  1224. #if defined(__DJGPP__)
  1225. #pragma GCC diagnostic pop
  1226. #endif
  1227. while(1) {
  1228. rc = select((int)serverfd + 1, NULL, &output, NULL, &timeout);
  1229. if(rc < 0 && SOCKERRNO != EINTR)
  1230. goto error;
  1231. else if(rc > 0) {
  1232. curl_socklen_t errSize = sizeof(error);
  1233. if(0 != getsockopt(serverfd, SOL_SOCKET, SO_ERROR,
  1234. (void *)&error, &errSize))
  1235. error = SOCKERRNO;
  1236. if((0 == error) || (EISCONN == error))
  1237. goto success;
  1238. else if((error != EINPROGRESS) && (error != EWOULDBLOCK))
  1239. goto error;
  1240. }
  1241. else if(!rc) {
  1242. logmsg("Timeout connecting to server port %hu", port);
  1243. sclose(serverfd);
  1244. return CURL_SOCKET_BAD;
  1245. }
  1246. }
  1247. }
  1248. error:
  1249. logmsg("Error connecting to server port %hu: (%d) %s",
  1250. port, error, sstrerror(error));
  1251. sclose(serverfd);
  1252. return CURL_SOCKET_BAD;
  1253. }
  1254. success:
  1255. logmsg("connected fine to %s%s%s:%hu, now tunnel",
  1256. op_br, ipaddr, cl_br, port);
  1257. if(0 != curlx_nonblock(serverfd, FALSE)) {
  1258. error = SOCKERRNO;
  1259. logmsg("curlx_nonblock(FALSE) failed with error: (%d) %s",
  1260. error, sstrerror(error));
  1261. sclose(serverfd);
  1262. return CURL_SOCKET_BAD;
  1263. }
  1264. return serverfd;
  1265. }
  1266. /*
  1267. * A CONNECT has been received, a CONNECT response has been sent.
  1268. *
  1269. * This function needs to connect to the server, and then pass data between
  1270. * the client and the server back and forth until the connection is closed by
  1271. * either end.
  1272. *
  1273. * When doing FTP through a CONNECT proxy, we expect that the data connection
  1274. * will be setup while the first connect is still being kept up. Therefore we
  1275. * must accept a new connection and deal with it appropriately.
  1276. */
  1277. #define data_or_ctrl(x) ((x)?"DATA":"CTRL")
  1278. #define SWS_CTRL 0
  1279. #define SWS_DATA 1
  1280. static void http_connect(curl_socket_t *infdp,
  1281. curl_socket_t rootfd,
  1282. const char *ipaddr,
  1283. unsigned short ipport,
  1284. int keepalive_secs)
  1285. {
  1286. curl_socket_t serverfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD};
  1287. curl_socket_t clientfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD};
  1288. ssize_t toc[2] = {0, 0}; /* number of bytes to client */
  1289. ssize_t tos[2] = {0, 0}; /* number of bytes to server */
  1290. char readclient[2][256];
  1291. char readserver[2][256];
  1292. bool poll_client_rd[2] = { TRUE, TRUE };
  1293. bool poll_server_rd[2] = { TRUE, TRUE };
  1294. bool poll_client_wr[2] = { TRUE, TRUE };
  1295. bool poll_server_wr[2] = { TRUE, TRUE };
  1296. bool primary = FALSE;
  1297. bool secondary = FALSE;
  1298. int max_tunnel_idx; /* SWS_CTRL or SWS_DATA */
  1299. int loop;
  1300. int i;
  1301. int timeout_count = 0;
  1302. /* primary tunnel client endpoint already connected */
  1303. clientfd[SWS_CTRL] = *infdp;
  1304. /* Sleep here to make sure the client reads CONNECT response's
  1305. 'end of headers' separate from the server data that follows.
  1306. This is done to prevent triggering libcurl known bug #39. */
  1307. for(loop = 2; (loop > 0) && !got_exit_signal; loop--)
  1308. wait_ms(250);
  1309. if(got_exit_signal)
  1310. goto http_connect_cleanup;
  1311. serverfd[SWS_CTRL] = connect_to(ipaddr, ipport);
  1312. if(serverfd[SWS_CTRL] == CURL_SOCKET_BAD)
  1313. goto http_connect_cleanup;
  1314. /* Primary tunnel socket endpoints are now connected. Tunnel data back and
  1315. forth over the primary tunnel until client or server breaks the primary
  1316. tunnel, simultaneously allowing establishment, operation and teardown of
  1317. a secondary tunnel that may be used for passive FTP data connection. */
  1318. max_tunnel_idx = SWS_CTRL;
  1319. primary = TRUE;
  1320. while(!got_exit_signal) {
  1321. fd_set input;
  1322. fd_set output;
  1323. ssize_t rc;
  1324. curl_socket_t maxfd = (curl_socket_t)-1;
  1325. struct timeval timeout = {0};
  1326. timeout.tv_sec = 1; /* 1000 ms */
  1327. FD_ZERO(&input);
  1328. FD_ZERO(&output);
  1329. if((clientfd[SWS_DATA] == CURL_SOCKET_BAD) &&
  1330. (serverfd[SWS_DATA] == CURL_SOCKET_BAD) &&
  1331. poll_client_rd[SWS_CTRL] && poll_client_wr[SWS_CTRL] &&
  1332. poll_server_rd[SWS_CTRL] && poll_server_wr[SWS_CTRL]) {
  1333. /* listener socket is monitored to allow client to establish
  1334. secondary tunnel only when this tunnel is not established
  1335. and primary one is fully operational */
  1336. #if defined(__DJGPP__)
  1337. #pragma GCC diagnostic push
  1338. #pragma GCC diagnostic ignored "-Warith-conversion"
  1339. #endif
  1340. FD_SET(rootfd, &input);
  1341. #if defined(__DJGPP__)
  1342. #pragma GCC diagnostic pop
  1343. #endif
  1344. maxfd = rootfd;
  1345. }
  1346. /* set tunnel sockets to wait for */
  1347. for(i = 0; i <= max_tunnel_idx; i++) {
  1348. /* client side socket monitoring */
  1349. if(clientfd[i] != CURL_SOCKET_BAD) {
  1350. if(poll_client_rd[i]) {
  1351. /* unless told not to do so, monitor readability */
  1352. #if defined(__DJGPP__)
  1353. #pragma GCC diagnostic push
  1354. #pragma GCC diagnostic ignored "-Warith-conversion"
  1355. #endif
  1356. FD_SET(clientfd[i], &input);
  1357. #if defined(__DJGPP__)
  1358. #pragma GCC diagnostic pop
  1359. #endif
  1360. if(clientfd[i] > maxfd)
  1361. maxfd = clientfd[i];
  1362. }
  1363. if(poll_client_wr[i] && toc[i]) {
  1364. /* unless told not to do so, monitor writability
  1365. if there is data ready to be sent to client */
  1366. #if defined(__DJGPP__)
  1367. #pragma GCC diagnostic push
  1368. #pragma GCC diagnostic ignored "-Warith-conversion"
  1369. #endif
  1370. FD_SET(clientfd[i], &output);
  1371. #if defined(__DJGPP__)
  1372. #pragma GCC diagnostic pop
  1373. #endif
  1374. if(clientfd[i] > maxfd)
  1375. maxfd = clientfd[i];
  1376. }
  1377. }
  1378. /* server side socket monitoring */
  1379. if(serverfd[i] != CURL_SOCKET_BAD) {
  1380. if(poll_server_rd[i]) {
  1381. /* unless told not to do so, monitor readability */
  1382. #if defined(__DJGPP__)
  1383. #pragma GCC diagnostic push
  1384. #pragma GCC diagnostic ignored "-Warith-conversion"
  1385. #endif
  1386. FD_SET(serverfd[i], &input);
  1387. #if defined(__DJGPP__)
  1388. #pragma GCC diagnostic pop
  1389. #endif
  1390. if(serverfd[i] > maxfd)
  1391. maxfd = serverfd[i];
  1392. }
  1393. if(poll_server_wr[i] && tos[i]) {
  1394. /* unless told not to do so, monitor writability
  1395. if there is data ready to be sent to server */
  1396. #if defined(__DJGPP__)
  1397. #pragma GCC diagnostic push
  1398. #pragma GCC diagnostic ignored "-Warith-conversion"
  1399. #endif
  1400. FD_SET(serverfd[i], &output);
  1401. #if defined(__DJGPP__)
  1402. #pragma GCC diagnostic pop
  1403. #endif
  1404. if(serverfd[i] > maxfd)
  1405. maxfd = serverfd[i];
  1406. }
  1407. }
  1408. }
  1409. if(got_exit_signal)
  1410. break;
  1411. do {
  1412. rc = select((int)maxfd + 1, &input, &output, NULL, &timeout);
  1413. } while(rc < 0 && errno == EINTR && !got_exit_signal);
  1414. if(got_exit_signal)
  1415. break;
  1416. if(rc > 0) {
  1417. /* socket action */
  1418. bool tcp_fin_wr = FALSE;
  1419. timeout_count = 0;
  1420. /* ---------------------------------------------------------- */
  1421. /* passive mode FTP may establish a secondary tunnel */
  1422. if((clientfd[SWS_DATA] == CURL_SOCKET_BAD) &&
  1423. (serverfd[SWS_DATA] == CURL_SOCKET_BAD) && FD_ISSET(rootfd, &input)) {
  1424. /* a new connection on listener socket (most likely from client) */
  1425. curl_socket_t datafd = accept(rootfd, NULL, NULL);
  1426. if(datafd != CURL_SOCKET_BAD) {
  1427. static struct httprequest *req2;
  1428. int err = 0;
  1429. if(!req2) {
  1430. req2 = malloc(sizeof(*req2));
  1431. if(!req2)
  1432. exit(1);
  1433. }
  1434. memset(req2, 0, sizeof(*req2));
  1435. logmsg("====> Client connect DATA");
  1436. #ifdef TCP_NODELAY
  1437. if(socket_domain_is_ip()) {
  1438. /* Disable the Nagle algorithm */
  1439. curl_socklen_t flag = 1;
  1440. if(0 != setsockopt(datafd, IPPROTO_TCP, TCP_NODELAY,
  1441. (void *)&flag, sizeof(flag)))
  1442. logmsg("====> TCP_NODELAY for client DATA connection failed");
  1443. }
  1444. #endif
  1445. init_httprequest(req2);
  1446. while(!req2->done_processing) {
  1447. err = get_request(datafd, req2);
  1448. if(err < 0) {
  1449. /* this socket must be closed, done or not */
  1450. break;
  1451. }
  1452. }
  1453. /* skip this and close the socket if err < 0 */
  1454. if(err >= 0) {
  1455. err = send_doc(datafd, req2);
  1456. if(!err && req2->connect_request) {
  1457. /* sleep to prevent triggering libcurl known bug #39. */
  1458. for(loop = 2; (loop > 0) && !got_exit_signal; loop--)
  1459. wait_ms(250);
  1460. if(!got_exit_signal) {
  1461. /* connect to the server */
  1462. serverfd[SWS_DATA] = connect_to(ipaddr, req2->connect_port);
  1463. if(serverfd[SWS_DATA] != CURL_SOCKET_BAD) {
  1464. /* secondary tunnel established, now we have two
  1465. connections */
  1466. poll_client_rd[SWS_DATA] = TRUE;
  1467. poll_client_wr[SWS_DATA] = TRUE;
  1468. poll_server_rd[SWS_DATA] = TRUE;
  1469. poll_server_wr[SWS_DATA] = TRUE;
  1470. max_tunnel_idx = SWS_DATA;
  1471. secondary = TRUE;
  1472. toc[SWS_DATA] = 0;
  1473. tos[SWS_DATA] = 0;
  1474. clientfd[SWS_DATA] = datafd;
  1475. datafd = CURL_SOCKET_BAD;
  1476. }
  1477. }
  1478. }
  1479. }
  1480. if(datafd != CURL_SOCKET_BAD) {
  1481. /* secondary tunnel not established */
  1482. shutdown(datafd, SHUT_RDWR);
  1483. sclose(datafd);
  1484. }
  1485. }
  1486. if(got_exit_signal)
  1487. break;
  1488. }
  1489. /* ---------------------------------------------------------- */
  1490. /* react to tunnel endpoint readable/writable notifications */
  1491. for(i = 0; i <= max_tunnel_idx; i++) {
  1492. size_t len;
  1493. if(clientfd[i] != CURL_SOCKET_BAD) {
  1494. len = sizeof(readclient[i]) - tos[i];
  1495. if(len && FD_ISSET(clientfd[i], &input)) {
  1496. /* read from client */
  1497. rc = sread(clientfd[i], &readclient[i][tos[i]], len);
  1498. if(rc <= 0) {
  1499. logmsg("[%s] got %zd, STOP READING client", data_or_ctrl(i), rc);
  1500. shutdown(clientfd[i], SHUT_RD);
  1501. poll_client_rd[i] = FALSE;
  1502. }
  1503. else {
  1504. logmsg("[%s] READ %zd bytes from client", data_or_ctrl(i), rc);
  1505. logmsg("[%s] READ \"%s\"", data_or_ctrl(i),
  1506. data_to_hex(&readclient[i][tos[i]], rc));
  1507. tos[i] += rc;
  1508. }
  1509. }
  1510. }
  1511. if(serverfd[i] != CURL_SOCKET_BAD) {
  1512. len = sizeof(readserver[i])-toc[i];
  1513. if(len && FD_ISSET(serverfd[i], &input)) {
  1514. /* read from server */
  1515. rc = sread(serverfd[i], &readserver[i][toc[i]], len);
  1516. if(rc <= 0) {
  1517. logmsg("[%s] got %zd, STOP READING server", data_or_ctrl(i), rc);
  1518. shutdown(serverfd[i], SHUT_RD);
  1519. poll_server_rd[i] = FALSE;
  1520. }
  1521. else {
  1522. logmsg("[%s] READ %zd bytes from server", data_or_ctrl(i), rc);
  1523. logmsg("[%s] READ \"%s\"", data_or_ctrl(i),
  1524. data_to_hex(&readserver[i][toc[i]], rc));
  1525. toc[i] += rc;
  1526. }
  1527. }
  1528. }
  1529. if(clientfd[i] != CURL_SOCKET_BAD) {
  1530. if(toc[i] && FD_ISSET(clientfd[i], &output)) {
  1531. /* write to client */
  1532. rc = swrite(clientfd[i], readserver[i], toc[i]);
  1533. if(rc <= 0) {
  1534. logmsg("[%s] got %zd, STOP WRITING client", data_or_ctrl(i), rc);
  1535. shutdown(clientfd[i], SHUT_WR);
  1536. poll_client_wr[i] = FALSE;
  1537. tcp_fin_wr = TRUE;
  1538. }
  1539. else {
  1540. logmsg("[%s] SENT %zd bytes to client", data_or_ctrl(i), rc);
  1541. logmsg("[%s] SENT \"%s\"", data_or_ctrl(i),
  1542. data_to_hex(readserver[i], rc));
  1543. if(toc[i] - rc)
  1544. memmove(&readserver[i][0], &readserver[i][rc], toc[i]-rc);
  1545. toc[i] -= rc;
  1546. }
  1547. }
  1548. }
  1549. if(serverfd[i] != CURL_SOCKET_BAD) {
  1550. if(tos[i] && FD_ISSET(serverfd[i], &output)) {
  1551. /* write to server */
  1552. rc = swrite(serverfd[i], readclient[i], tos[i]);
  1553. if(rc <= 0) {
  1554. logmsg("[%s] got %zd, STOP WRITING server", data_or_ctrl(i), rc);
  1555. shutdown(serverfd[i], SHUT_WR);
  1556. poll_server_wr[i] = FALSE;
  1557. tcp_fin_wr = TRUE;
  1558. }
  1559. else {
  1560. logmsg("[%s] SENT %zd bytes to server", data_or_ctrl(i), rc);
  1561. logmsg("[%s] SENT \"%s\"", data_or_ctrl(i),
  1562. data_to_hex(readclient[i], rc));
  1563. if(tos[i] - rc)
  1564. memmove(&readclient[i][0], &readclient[i][rc], tos[i]-rc);
  1565. tos[i] -= rc;
  1566. }
  1567. }
  1568. }
  1569. }
  1570. if(got_exit_signal)
  1571. break;
  1572. /* ---------------------------------------------------------- */
  1573. /* endpoint read/write disabling, endpoint closing and tunnel teardown */
  1574. for(i = 0; i <= max_tunnel_idx; i++) {
  1575. for(loop = 2; loop > 0; loop--) {
  1576. /* loop twice to satisfy condition interdependencies without
  1577. having to await select timeout or another socket event */
  1578. if(clientfd[i] != CURL_SOCKET_BAD) {
  1579. if(poll_client_rd[i] && !poll_server_wr[i]) {
  1580. logmsg("[%s] DISABLED READING client", data_or_ctrl(i));
  1581. shutdown(clientfd[i], SHUT_RD);
  1582. poll_client_rd[i] = FALSE;
  1583. }
  1584. if(poll_client_wr[i] && !poll_server_rd[i] && !toc[i]) {
  1585. logmsg("[%s] DISABLED WRITING client", data_or_ctrl(i));
  1586. shutdown(clientfd[i], SHUT_WR);
  1587. poll_client_wr[i] = FALSE;
  1588. tcp_fin_wr = TRUE;
  1589. }
  1590. }
  1591. if(serverfd[i] != CURL_SOCKET_BAD) {
  1592. if(poll_server_rd[i] && !poll_client_wr[i]) {
  1593. logmsg("[%s] DISABLED READING server", data_or_ctrl(i));
  1594. shutdown(serverfd[i], SHUT_RD);
  1595. poll_server_rd[i] = FALSE;
  1596. }
  1597. if(poll_server_wr[i] && !poll_client_rd[i] && !tos[i]) {
  1598. logmsg("[%s] DISABLED WRITING server", data_or_ctrl(i));
  1599. shutdown(serverfd[i], SHUT_WR);
  1600. poll_server_wr[i] = FALSE;
  1601. tcp_fin_wr = TRUE;
  1602. }
  1603. }
  1604. }
  1605. }
  1606. if(tcp_fin_wr)
  1607. /* allow kernel to place FIN bit packet on the wire */
  1608. wait_ms(250);
  1609. /* socket clearing */
  1610. for(i = 0; i <= max_tunnel_idx; i++) {
  1611. for(loop = 2; loop > 0; loop--) {
  1612. if(clientfd[i] != CURL_SOCKET_BAD) {
  1613. if(!poll_client_wr[i] && !poll_client_rd[i]) {
  1614. logmsg("[%s] CLOSING client socket", data_or_ctrl(i));
  1615. sclose(clientfd[i]);
  1616. clientfd[i] = CURL_SOCKET_BAD;
  1617. if(serverfd[i] == CURL_SOCKET_BAD) {
  1618. logmsg("[%s] ENDING", data_or_ctrl(i));
  1619. if(i == SWS_DATA)
  1620. secondary = FALSE;
  1621. else
  1622. primary = FALSE;
  1623. }
  1624. }
  1625. }
  1626. if(serverfd[i] != CURL_SOCKET_BAD) {
  1627. if(!poll_server_wr[i] && !poll_server_rd[i]) {
  1628. logmsg("[%s] CLOSING server socket", data_or_ctrl(i));
  1629. sclose(serverfd[i]);
  1630. serverfd[i] = CURL_SOCKET_BAD;
  1631. if(clientfd[i] == CURL_SOCKET_BAD) {
  1632. logmsg("[%s] ENDING", data_or_ctrl(i));
  1633. if(i == SWS_DATA)
  1634. secondary = FALSE;
  1635. else
  1636. primary = FALSE;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. }
  1642. /* ---------------------------------------------------------- */
  1643. max_tunnel_idx = secondary ? SWS_DATA : SWS_CTRL;
  1644. if(!primary)
  1645. /* exit loop upon primary tunnel teardown */
  1646. break;
  1647. } /* (rc > 0) */
  1648. else {
  1649. timeout_count++;
  1650. if(timeout_count > keepalive_secs) {
  1651. logmsg("CONNECT proxy timeout after %d idle seconds!", timeout_count);
  1652. break;
  1653. }
  1654. }
  1655. }
  1656. http_connect_cleanup:
  1657. for(i = SWS_DATA; i >= SWS_CTRL; i--) {
  1658. if(serverfd[i] != CURL_SOCKET_BAD) {
  1659. logmsg("[%s] CLOSING server socket (cleanup)", data_or_ctrl(i));
  1660. shutdown(serverfd[i], SHUT_RDWR);
  1661. sclose(serverfd[i]);
  1662. }
  1663. if(clientfd[i] != CURL_SOCKET_BAD) {
  1664. logmsg("[%s] CLOSING client socket (cleanup)", data_or_ctrl(i));
  1665. shutdown(clientfd[i], SHUT_RDWR);
  1666. sclose(clientfd[i]);
  1667. }
  1668. if((serverfd[i] != CURL_SOCKET_BAD) ||
  1669. (clientfd[i] != CURL_SOCKET_BAD)) {
  1670. logmsg("[%s] ABORTING", data_or_ctrl(i));
  1671. }
  1672. }
  1673. *infdp = CURL_SOCKET_BAD;
  1674. }
  1675. static void http_upgrade(struct httprequest *req)
  1676. {
  1677. (void)req;
  1678. logmsg("Upgraded to ... %u", req->upgrade_request);
  1679. /* left to implement */
  1680. }
  1681. /* returns a socket handle, or 0 if there are no more waiting sockets,
  1682. or < 0 if there was an error */
  1683. static curl_socket_t accept_connection(curl_socket_t sock)
  1684. {
  1685. curl_socket_t msgsock = CURL_SOCKET_BAD;
  1686. int error;
  1687. int flag = 1;
  1688. if(MAX_SOCKETS == num_sockets) {
  1689. logmsg("Too many open sockets!");
  1690. return CURL_SOCKET_BAD;
  1691. }
  1692. msgsock = accept(sock, NULL, NULL);
  1693. if(got_exit_signal) {
  1694. if(CURL_SOCKET_BAD != msgsock)
  1695. sclose(msgsock);
  1696. return CURL_SOCKET_BAD;
  1697. }
  1698. if(CURL_SOCKET_BAD == msgsock) {
  1699. error = SOCKERRNO;
  1700. if(EAGAIN == error || EWOULDBLOCK == error) {
  1701. /* nothing to accept */
  1702. return 0;
  1703. }
  1704. logmsg("MAJOR ERROR: accept() failed with error: (%d) %s",
  1705. error, sstrerror(error));
  1706. return CURL_SOCKET_BAD;
  1707. }
  1708. if(0 != curlx_nonblock(msgsock, TRUE)) {
  1709. error = SOCKERRNO;
  1710. logmsg("curlx_nonblock failed with error: (%d) %s",
  1711. error, sstrerror(error));
  1712. sclose(msgsock);
  1713. return CURL_SOCKET_BAD;
  1714. }
  1715. if(0 != setsockopt(msgsock, SOL_SOCKET, SO_KEEPALIVE,
  1716. (void *)&flag, sizeof(flag))) {
  1717. error = SOCKERRNO;
  1718. logmsg("setsockopt(SO_KEEPALIVE) failed with error: (%d) %s",
  1719. error, sstrerror(error));
  1720. sclose(msgsock);
  1721. return CURL_SOCKET_BAD;
  1722. }
  1723. /*
  1724. ** As soon as this server accepts a connection from the test harness it
  1725. ** must set the server logs advisor read lock to indicate that server
  1726. ** logs should not be read until this lock is removed by this server.
  1727. */
  1728. if(!serverlogslocked)
  1729. set_advisor_read_lock(loglockfile);
  1730. serverlogslocked += 1;
  1731. logmsg("====> Client connect");
  1732. all_sockets[num_sockets] = msgsock;
  1733. num_sockets += 1;
  1734. #ifdef TCP_NODELAY
  1735. if(socket_domain_is_ip()) {
  1736. /*
  1737. * Disable the Nagle algorithm to make it easier to send out a large
  1738. * response in many small segments to torture the clients more.
  1739. */
  1740. if(0 != setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
  1741. (void *)&flag, sizeof(flag)))
  1742. logmsg("====> TCP_NODELAY failed");
  1743. }
  1744. #endif
  1745. return msgsock;
  1746. }
  1747. /* returns 1 if the connection should be serviced again immediately, 0 if there
  1748. is no data waiting, or < 0 if it should be closed */
  1749. static int service_connection(curl_socket_t msgsock, struct httprequest *req,
  1750. curl_socket_t listensock,
  1751. const char *connecthost,
  1752. int keepalive_secs)
  1753. {
  1754. if(got_exit_signal)
  1755. return -1;
  1756. while(!req->done_processing) {
  1757. int rc = get_request(msgsock, req);
  1758. if(rc <= 0) {
  1759. /* Nothing further to read now, possibly because the socket was closed */
  1760. return rc;
  1761. }
  1762. }
  1763. if(prevbounce) {
  1764. /* bounce treatment requested */
  1765. if((req->testno == prevtestno) &&
  1766. (req->partno == prevpartno)) {
  1767. req->partno++;
  1768. logmsg("BOUNCE part number to %ld", req->partno);
  1769. }
  1770. else {
  1771. prevbounce = FALSE;
  1772. prevtestno = -1;
  1773. prevpartno = -1;
  1774. }
  1775. }
  1776. send_doc(msgsock, req);
  1777. if(got_exit_signal)
  1778. return -1;
  1779. if(req->testno < 0) {
  1780. logmsg("special request received, no persistency");
  1781. return -1;
  1782. }
  1783. if(!req->open) {
  1784. logmsg("instructed to close connection after server-reply");
  1785. return -1;
  1786. }
  1787. if(req->connect_request) {
  1788. /* a CONNECT request, setup and talk the tunnel */
  1789. if(!is_proxy) {
  1790. logmsg("received CONNECT but isn't running as proxy!");
  1791. return 1;
  1792. }
  1793. else {
  1794. http_connect(&msgsock, listensock, connecthost, req->connect_port,
  1795. keepalive_secs);
  1796. return -1;
  1797. }
  1798. }
  1799. if(req->upgrade_request) {
  1800. /* an upgrade request, switch to another protocol here */
  1801. http_upgrade(req);
  1802. return 1;
  1803. }
  1804. /* if we got a CONNECT, loop and get another request as well! */
  1805. if(req->open) {
  1806. logmsg("=> persistent connection request ended, awaits new request\n");
  1807. return 1;
  1808. }
  1809. else {
  1810. logmsg("=> NOT a persistent connection, close close CLOSE\n");
  1811. }
  1812. return -1;
  1813. }
  1814. int main(int argc, char *argv[])
  1815. {
  1816. srvr_sockaddr_union_t me;
  1817. curl_socket_t sock = CURL_SOCKET_BAD;
  1818. int wrotepidfile = 0;
  1819. int wroteportfile = 0;
  1820. int flag;
  1821. unsigned short port = DEFAULT_PORT;
  1822. #ifdef USE_UNIX_SOCKETS
  1823. const char *unix_socket = NULL;
  1824. bool unlink_socket = false;
  1825. #endif
  1826. const char *pidname = ".http.pid";
  1827. const char *portname = ".http.port";
  1828. struct httprequest *req = NULL;
  1829. int rc = 0;
  1830. int error;
  1831. int arg = 1;
  1832. const char *connecthost = "127.0.0.1";
  1833. const char *socket_type = "IPv4";
  1834. char port_str[11];
  1835. const char *location_str = port_str;
  1836. int keepalive_secs = 5;
  1837. const char *protocol_type = "HTTP";
  1838. /* a default CONNECT port is basically pointless but still ... */
  1839. size_t socket_idx;
  1840. while(argc > arg) {
  1841. if(!strcmp("--version", argv[arg])) {
  1842. puts("sws IPv4"
  1843. #ifdef USE_IPV6
  1844. "/IPv6"
  1845. #endif
  1846. #ifdef USE_UNIX_SOCKETS
  1847. "/unix"
  1848. #endif
  1849. );
  1850. return 0;
  1851. }
  1852. else if(!strcmp("--pidfile", argv[arg])) {
  1853. arg++;
  1854. if(argc > arg)
  1855. pidname = argv[arg++];
  1856. }
  1857. else if(!strcmp("--portfile", argv[arg])) {
  1858. arg++;
  1859. if(argc > arg)
  1860. portname = argv[arg++];
  1861. }
  1862. else if(!strcmp("--logfile", argv[arg])) {
  1863. arg++;
  1864. if(argc > arg)
  1865. serverlogfile = argv[arg++];
  1866. }
  1867. else if(!strcmp("--logdir", argv[arg])) {
  1868. arg++;
  1869. if(argc > arg)
  1870. logdir = argv[arg++];
  1871. }
  1872. else if(!strcmp("--cmdfile", argv[arg])) {
  1873. arg++;
  1874. if(argc > arg)
  1875. cmdfile = argv[arg++];
  1876. }
  1877. else if(!strcmp("--gopher", argv[arg])) {
  1878. arg++;
  1879. use_gopher = TRUE;
  1880. protocol_type = "GOPHER";
  1881. end_of_headers = "\r\n"; /* gopher style is much simpler */
  1882. }
  1883. else if(!strcmp("--ipv4", argv[arg])) {
  1884. socket_type = "IPv4";
  1885. socket_domain = AF_INET;
  1886. location_str = port_str;
  1887. arg++;
  1888. }
  1889. else if(!strcmp("--ipv6", argv[arg])) {
  1890. #ifdef USE_IPV6
  1891. socket_type = "IPv6";
  1892. socket_domain = AF_INET6;
  1893. location_str = port_str;
  1894. #endif
  1895. arg++;
  1896. }
  1897. else if(!strcmp("--unix-socket", argv[arg])) {
  1898. arg++;
  1899. if(argc > arg) {
  1900. #ifdef USE_UNIX_SOCKETS
  1901. unix_socket = argv[arg];
  1902. if(strlen(unix_socket) >= sizeof(me.sau.sun_path)) {
  1903. fprintf(stderr,
  1904. "sws: socket path must be shorter than %zu chars: %s\n",
  1905. sizeof(me.sau.sun_path), unix_socket);
  1906. return 0;
  1907. }
  1908. socket_type = "unix";
  1909. socket_domain = AF_UNIX;
  1910. location_str = unix_socket;
  1911. #endif
  1912. arg++;
  1913. }
  1914. }
  1915. else if(!strcmp("--port", argv[arg])) {
  1916. arg++;
  1917. if(argc > arg) {
  1918. char *endptr;
  1919. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1920. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1921. (ulnum && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
  1922. fprintf(stderr, "sws: invalid --port argument (%s)\n",
  1923. argv[arg]);
  1924. return 0;
  1925. }
  1926. port = curlx_ultous(ulnum);
  1927. arg++;
  1928. }
  1929. }
  1930. else if(!strcmp("--srcdir", argv[arg])) {
  1931. arg++;
  1932. if(argc > arg) {
  1933. path = argv[arg];
  1934. arg++;
  1935. }
  1936. }
  1937. else if(!strcmp("--keepalive", argv[arg])) {
  1938. arg++;
  1939. if(argc > arg) {
  1940. char *endptr;
  1941. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  1942. if((endptr != argv[arg] + strlen(argv[arg])) ||
  1943. (ulnum && (ulnum > 65535UL))) {
  1944. fprintf(stderr, "sws: invalid --keepalive argument (%s), must "
  1945. "be number of seconds\n", argv[arg]);
  1946. return 0;
  1947. }
  1948. keepalive_secs = curlx_ultous(ulnum);
  1949. arg++;
  1950. }
  1951. }
  1952. else if(!strcmp("--connect", argv[arg])) {
  1953. /* The connect host IP number that the proxy will connect to no matter
  1954. what the client asks for, but also use this as a hint that we run as
  1955. a proxy and do a few different internal choices */
  1956. arg++;
  1957. if(argc > arg) {
  1958. connecthost = argv[arg];
  1959. arg++;
  1960. is_proxy = TRUE;
  1961. logmsg("Run as proxy, CONNECT to host %s", connecthost);
  1962. }
  1963. }
  1964. else {
  1965. puts("Usage: sws [option]\n"
  1966. " --version\n"
  1967. " --logfile [file]\n"
  1968. " --logdir [directory]\n"
  1969. " --pidfile [file]\n"
  1970. " --portfile [file]\n"
  1971. " --ipv4\n"
  1972. " --ipv6\n"
  1973. " --unix-socket [file]\n"
  1974. " --port [port]\n"
  1975. " --srcdir [path]\n"
  1976. " --connect [ip4-addr]\n"
  1977. " --gopher");
  1978. return 0;
  1979. }
  1980. }
  1981. msnprintf(loglockfile, sizeof(loglockfile), "%s/%s/sws-%s%s-%s.lock",
  1982. logdir, SERVERLOGS_LOCKDIR, protocol_type,
  1983. is_proxy ? "-proxy" : "", socket_type);
  1984. #ifdef _WIN32
  1985. win32_init();
  1986. atexit(win32_cleanup);
  1987. #endif
  1988. install_signal_handlers(false);
  1989. req = calloc(1, sizeof(*req));
  1990. if(!req)
  1991. goto sws_cleanup;
  1992. sock = socket(socket_domain, SOCK_STREAM, 0);
  1993. all_sockets[0] = sock;
  1994. num_sockets = 1;
  1995. if(CURL_SOCKET_BAD == sock) {
  1996. error = SOCKERRNO;
  1997. logmsg("Error creating socket: (%d) %s", error, sstrerror(error));
  1998. goto sws_cleanup;
  1999. }
  2000. flag = 1;
  2001. if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  2002. (void *)&flag, sizeof(flag))) {
  2003. error = SOCKERRNO;
  2004. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  2005. error, sstrerror(error));
  2006. goto sws_cleanup;
  2007. }
  2008. if(0 != curlx_nonblock(sock, TRUE)) {
  2009. error = SOCKERRNO;
  2010. logmsg("curlx_nonblock failed with error: (%d) %s",
  2011. error, sstrerror(error));
  2012. goto sws_cleanup;
  2013. }
  2014. switch(socket_domain) {
  2015. case AF_INET:
  2016. memset(&me.sa4, 0, sizeof(me.sa4));
  2017. me.sa4.sin_family = AF_INET;
  2018. me.sa4.sin_addr.s_addr = INADDR_ANY;
  2019. me.sa4.sin_port = htons(port);
  2020. rc = bind(sock, &me.sa, sizeof(me.sa4));
  2021. break;
  2022. #ifdef USE_IPV6
  2023. case AF_INET6:
  2024. memset(&me.sa6, 0, sizeof(me.sa6));
  2025. me.sa6.sin6_family = AF_INET6;
  2026. me.sa6.sin6_addr = in6addr_any;
  2027. me.sa6.sin6_port = htons(port);
  2028. rc = bind(sock, &me.sa, sizeof(me.sa6));
  2029. break;
  2030. #endif /* USE_IPV6 */
  2031. #ifdef USE_UNIX_SOCKETS
  2032. case AF_UNIX:
  2033. rc = bind_unix_socket(sock, unix_socket, &me.sau);
  2034. #endif /* USE_UNIX_SOCKETS */
  2035. }
  2036. if(0 != rc) {
  2037. error = SOCKERRNO;
  2038. #ifdef USE_UNIX_SOCKETS
  2039. if(socket_domain == AF_UNIX)
  2040. logmsg("Error binding socket on path %s: (%d) %s",
  2041. unix_socket, error, sstrerror(error));
  2042. else
  2043. #endif
  2044. logmsg("Error binding socket on port %hu: (%d) %s",
  2045. port, error, sstrerror(error));
  2046. goto sws_cleanup;
  2047. }
  2048. if(!port) {
  2049. /* The system was supposed to choose a port number, figure out which
  2050. port we actually got and update the listener port value with it. */
  2051. curl_socklen_t la_size;
  2052. srvr_sockaddr_union_t localaddr;
  2053. #ifdef USE_IPV6
  2054. if(socket_domain != AF_INET6)
  2055. #endif
  2056. la_size = sizeof(localaddr.sa4);
  2057. #ifdef USE_IPV6
  2058. else
  2059. la_size = sizeof(localaddr.sa6);
  2060. #endif
  2061. memset(&localaddr.sa, 0, (size_t)la_size);
  2062. if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
  2063. error = SOCKERRNO;
  2064. logmsg("getsockname() failed with error: (%d) %s",
  2065. error, sstrerror(error));
  2066. sclose(sock);
  2067. goto sws_cleanup;
  2068. }
  2069. switch(localaddr.sa.sa_family) {
  2070. case AF_INET:
  2071. port = ntohs(localaddr.sa4.sin_port);
  2072. break;
  2073. #ifdef USE_IPV6
  2074. case AF_INET6:
  2075. port = ntohs(localaddr.sa6.sin6_port);
  2076. break;
  2077. #endif
  2078. default:
  2079. break;
  2080. }
  2081. if(!port) {
  2082. /* Real failure, listener port shall not be zero beyond this point. */
  2083. logmsg("Apparently getsockname() succeeded, with listener port zero.");
  2084. logmsg("A valid reason for this failure is a binary built without");
  2085. logmsg("proper network library linkage. This might not be the only");
  2086. logmsg("reason, but double check it before anything else.");
  2087. sclose(sock);
  2088. goto sws_cleanup;
  2089. }
  2090. }
  2091. #ifdef USE_UNIX_SOCKETS
  2092. if(socket_domain != AF_UNIX)
  2093. #endif
  2094. msnprintf(port_str, sizeof(port_str), "port %hu", port);
  2095. logmsg("Running %s %s version on %s",
  2096. protocol_type, socket_type, location_str);
  2097. /* start accepting connections */
  2098. rc = listen(sock, 50);
  2099. if(0 != rc) {
  2100. error = SOCKERRNO;
  2101. logmsg("listen() failed with error: (%d) %s", error, sstrerror(error));
  2102. goto sws_cleanup;
  2103. }
  2104. #ifdef USE_UNIX_SOCKETS
  2105. /* listen succeeds, so let's assume a valid listening Unix socket */
  2106. unlink_socket = true;
  2107. #endif
  2108. /*
  2109. ** As soon as this server writes its pid file the test harness will
  2110. ** attempt to connect to this server and initiate its verification.
  2111. */
  2112. wrotepidfile = write_pidfile(pidname);
  2113. if(!wrotepidfile)
  2114. goto sws_cleanup;
  2115. wroteportfile = write_portfile(portname, port);
  2116. if(!wroteportfile)
  2117. goto sws_cleanup;
  2118. /* initialization of httprequest struct is done before get_request(), but
  2119. the pipelining struct field must be initialized previously to FALSE
  2120. every time a new connection arrives. */
  2121. init_httprequest(req);
  2122. for(;;) {
  2123. fd_set input;
  2124. fd_set output;
  2125. curl_socket_t maxfd = (curl_socket_t)-1;
  2126. int active;
  2127. struct timeval timeout = {0};
  2128. timeout.tv_usec = 250000L; /* 250 ms */
  2129. /* Clear out closed sockets */
  2130. for(socket_idx = num_sockets - 1; socket_idx >= 1; --socket_idx) {
  2131. if(CURL_SOCKET_BAD == all_sockets[socket_idx]) {
  2132. char *dst = (char *) (all_sockets + socket_idx);
  2133. char *src = (char *) (all_sockets + socket_idx + 1);
  2134. char *end = (char *) (all_sockets + num_sockets);
  2135. memmove(dst, src, end - src);
  2136. num_sockets -= 1;
  2137. }
  2138. }
  2139. if(got_exit_signal)
  2140. goto sws_cleanup;
  2141. /* Set up for select */
  2142. FD_ZERO(&input);
  2143. FD_ZERO(&output);
  2144. for(socket_idx = 0; socket_idx < num_sockets; ++socket_idx) {
  2145. /* Listen on all sockets */
  2146. #if defined(__DJGPP__)
  2147. #pragma GCC diagnostic push
  2148. #pragma GCC diagnostic ignored "-Warith-conversion"
  2149. #endif
  2150. FD_SET(all_sockets[socket_idx], &input);
  2151. #if defined(__DJGPP__)
  2152. #pragma GCC diagnostic pop
  2153. #endif
  2154. if(all_sockets[socket_idx] > maxfd)
  2155. maxfd = all_sockets[socket_idx];
  2156. }
  2157. if(got_exit_signal)
  2158. goto sws_cleanup;
  2159. do {
  2160. rc = select((int)maxfd + 1, &input, &output, NULL, &timeout);
  2161. } while(rc < 0 && errno == EINTR && !got_exit_signal);
  2162. if(got_exit_signal)
  2163. goto sws_cleanup;
  2164. if(rc < 0) {
  2165. error = SOCKERRNO;
  2166. logmsg("select() failed with error: (%d) %s", error, sstrerror(error));
  2167. goto sws_cleanup;
  2168. }
  2169. if(rc == 0) {
  2170. /* Timed out - try again */
  2171. continue;
  2172. }
  2173. active = rc; /* a positive number */
  2174. /* Check if the listening socket is ready to accept */
  2175. if(FD_ISSET(all_sockets[0], &input)) {
  2176. /* Service all queued connections */
  2177. curl_socket_t msgsock;
  2178. do {
  2179. msgsock = accept_connection(sock);
  2180. logmsg("accept_connection %" FMT_SOCKET_T
  2181. " returned %" FMT_SOCKET_T, sock, msgsock);
  2182. if(CURL_SOCKET_BAD == msgsock)
  2183. goto sws_cleanup;
  2184. if(req->delay)
  2185. wait_ms(req->delay);
  2186. } while(msgsock > 0);
  2187. active--;
  2188. }
  2189. /* Service all connections that are ready */
  2190. for(socket_idx = 1; (socket_idx < num_sockets) && active; ++socket_idx) {
  2191. if(FD_ISSET(all_sockets[socket_idx], &input)) {
  2192. active--;
  2193. if(got_exit_signal)
  2194. goto sws_cleanup;
  2195. /* Service this connection until it has nothing available */
  2196. do {
  2197. rc = service_connection(all_sockets[socket_idx], req, sock,
  2198. connecthost, keepalive_secs);
  2199. if(got_exit_signal)
  2200. goto sws_cleanup;
  2201. if(rc < 0) {
  2202. logmsg("====> Client disconnect %d", req->connmon);
  2203. if(req->connmon) {
  2204. const char *keepopen = "[DISCONNECT]\n";
  2205. storerequest(keepopen, strlen(keepopen));
  2206. }
  2207. if(!req->open)
  2208. /* When instructed to close connection after server-reply we
  2209. wait a very small amount of time before doing so. If this
  2210. is not done client might get an ECONNRESET before reading
  2211. a single byte of server-reply. */
  2212. wait_ms(50);
  2213. if(all_sockets[socket_idx] != CURL_SOCKET_BAD) {
  2214. sclose(all_sockets[socket_idx]);
  2215. all_sockets[socket_idx] = CURL_SOCKET_BAD;
  2216. }
  2217. serverlogslocked -= 1;
  2218. if(!serverlogslocked)
  2219. clear_advisor_read_lock(loglockfile);
  2220. if(req->testno == DOCNUMBER_QUIT)
  2221. goto sws_cleanup;
  2222. }
  2223. /* Reset the request, unless we're still in the middle of reading */
  2224. if(rc && !req->upgrade_request)
  2225. /* Note: resetting the HTTP request here can cause problems if:
  2226. * 1) req->skipall is TRUE,
  2227. * 2) the socket is still open, and
  2228. * 3) (stale) data is still available (or about to be available)
  2229. * on that socket
  2230. * In that case, this loop will run once more and treat that stale
  2231. * data (in service_connection()) as the first data received on
  2232. * this new HTTP request and report "** Unusual request" (skipall
  2233. * would have otherwise caused that data to be ignored). Normally,
  2234. * that socket will be closed by the client and there won't be any
  2235. * stale data to cause this, but stranger things have happened (see
  2236. * issue #11678).
  2237. */
  2238. init_httprequest(req);
  2239. } while(rc > 0);
  2240. }
  2241. }
  2242. if(got_exit_signal)
  2243. goto sws_cleanup;
  2244. }
  2245. sws_cleanup:
  2246. for(socket_idx = 1; socket_idx < num_sockets; ++socket_idx)
  2247. if((all_sockets[socket_idx] != sock) &&
  2248. (all_sockets[socket_idx] != CURL_SOCKET_BAD))
  2249. sclose(all_sockets[socket_idx]);
  2250. if(sock != CURL_SOCKET_BAD)
  2251. sclose(sock);
  2252. #ifdef USE_UNIX_SOCKETS
  2253. if(unlink_socket && socket_domain == AF_UNIX) {
  2254. rc = unlink(unix_socket);
  2255. logmsg("unlink(%s) = %d (%s)", unix_socket, rc, strerror(rc));
  2256. }
  2257. #endif
  2258. free(req);
  2259. if(got_exit_signal)
  2260. logmsg("signalled to die");
  2261. if(wrotepidfile)
  2262. unlink(pidname);
  2263. if(wroteportfile)
  2264. unlink(portname);
  2265. if(serverlogslocked) {
  2266. serverlogslocked = 0;
  2267. clear_advisor_read_lock(loglockfile);
  2268. }
  2269. restore_signal_handlers(false);
  2270. if(got_exit_signal) {
  2271. logmsg("========> %s sws (%s pid: %ld) exits with signal (%d)",
  2272. socket_type, location_str, (long)Curl_getpid(), exit_signal);
  2273. /*
  2274. * To properly set the return status of the process we
  2275. * must raise the same signal SIGINT or SIGTERM that we
  2276. * caught and let the old handler take care of it.
  2277. */
  2278. raise(exit_signal);
  2279. }
  2280. logmsg("========> sws quits");
  2281. return 0;
  2282. }