2
0

sws.c 72 KB

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