2
0

sws.c 72 KB

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