2
0

sws.c 69 KB

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