sws.c 69 KB

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