sws.c 65 KB

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