Kagera uHTTP Daemon
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  1. /**
  2. * @PROJECT Kagera uHTTP Daemon
  3. * @COPYRIGHT See COPYING in the top level directory
  4. * @FILE kuhttpd.c
  5. * @PURPOSE HTTP Server
  6. * @DEVELOPERS Eric Bishop <eric@gargoyle-router.com>
  7. * Rafal Kupiec <belliash@asiotec.eu.org>
  8. * Jef Poskanzer <jef@acme.com>
  9. */
  10. #include <unistd.h>
  11. #include <stdlib.h>
  12. #include <stdarg.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <syslog.h>
  16. #include <limits.h>
  17. #include <sys/param.h>
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <sys/mman.h>
  21. #include <time.h>
  22. #include <pwd.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <signal.h>
  26. #include <ctype.h>
  27. #include <sys/wait.h>
  28. #include <sys/socket.h>
  29. #include <netinet/in.h>
  30. #include <netinet/tcp.h>
  31. #include <arpa/inet.h>
  32. #include <netdb.h>
  33. #include <dirent.h>
  34. #include <cyassl/openssl/ssl.h>
  35. #include <cyassl/openssl/err.h>
  36. #include <cyassl/error.h>
  37. #ifdef CROSS_BUILD
  38. #include <cyassl/cyassl_error.h>
  39. #endif
  40. #include "kuhttpd.h"
  41. #include "dateparse.h"
  42. #include "match.h"
  43. #include "mime_enc.h"
  44. #include "mime_typ.h"
  45. static void add_headers(int s, char* title, char* extra_header, char* me, char* mt, off_t b, time_t mod) {
  46. time_t now;
  47. char timebuf[100];
  48. char buf[10000];
  49. int buflen;
  50. const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT";
  51. status = s;
  52. bytes = b;
  53. make_log_entry();
  54. start_response();
  55. buflen = snprintf(buf, sizeof(buf), "%s %d %s\015\012", protocol, status, title);
  56. add_to_response(buf, buflen);
  57. buflen = snprintf(buf, sizeof(buf), "Server: %s\015\012", SERVER_SOFTWARE);
  58. add_to_response(buf, buflen);
  59. now = time((time_t*) 0);
  60. (void) strftime(timebuf, sizeof(timebuf), rfc1123_fmt, gmtime(&now));
  61. buflen = snprintf(buf, sizeof(buf), "Date: %s\015\012", timebuf);
  62. add_to_response(buf, buflen);
  63. buflen = snprintf(buf, sizeof(buf), "Expires: %s\015\012", timebuf);
  64. add_to_response(buf, buflen);
  65. if(mod != (time_t) -1) {
  66. (void) strftime(timebuf, sizeof(timebuf), rfc1123_fmt, gmtime(&mod));
  67. buflen = snprintf(buf, sizeof(buf), "Last-Modified: %s\015\012", timebuf);
  68. add_to_response(buf, buflen);
  69. }
  70. if(extra_header != (char*) 0 && extra_header[0] != '\0') {
  71. buflen = snprintf(buf, sizeof(buf), "%s\015\012", extra_header);
  72. add_to_response(buf, buflen);
  73. }
  74. if(me != (char*) 0 && me[0] != '\0') {
  75. buflen = snprintf(buf, sizeof(buf), "Content-Encoding: %s\015\012", me);
  76. add_to_response(buf, buflen);
  77. }
  78. if(mt != (char*) 0 && mt[0] != '\0') {
  79. buflen = snprintf(buf, sizeof(buf), "Content-Type: %s\015\012", mt);
  80. add_to_response(buf, buflen);
  81. }
  82. if(bytes >= 0) {
  83. buflen = snprintf(buf, sizeof(buf), "Content-Length: %lld\015\012", (long long int) bytes);
  84. add_to_response(buf, buflen);
  85. }
  86. if(p3p != (char*) 0 && p3p[0] != '\0') {
  87. buflen = snprintf(buf, sizeof(buf), "P3P: %s\015\012", p3p);
  88. add_to_response(buf, buflen);
  89. }
  90. buflen = snprintf(buf, sizeof(buf), "\015\012");
  91. add_to_response(buf, buflen);
  92. }
  93. static void add_to_buf(char** bufP, size_t* bufsizeP, size_t* buflenP, char* str, size_t len) {
  94. if(*bufsizeP == 0) {
  95. *bufsizeP = len + 500;
  96. *buflenP = 0;
  97. *bufP = (char*) e_malloc(*bufsizeP);
  98. } else if(*buflenP + len >= *bufsizeP) {
  99. *bufsizeP = *buflenP + len + 500;
  100. *bufP = (char*) e_realloc((void*) *bufP, *bufsizeP);
  101. }
  102. (void) memmove(&((*bufP)[*buflenP]), str, len);
  103. *buflenP += len;
  104. (*bufP)[*buflenP] = '\0';
  105. }
  106. static void add_to_request(char* str, size_t len) {
  107. add_to_buf(&request, &request_size, &request_len, str, len);
  108. }
  109. static void add_to_response(char* str, size_t len) {
  110. add_to_buf(&response, &response_size, &response_len, str, len);
  111. }
  112. static void auth_check(char* dirname, int is_ssl) {
  113. char authpath[10000];
  114. char realmName[500];
  115. struct stat sb;
  116. char authinfo[500];
  117. char* authpass;
  118. char* colon;
  119. static char line[10000];
  120. int l;
  121. FILE* fp;
  122. char* cryp;
  123. if(dirname[strlen(dirname) - 1] == '/') {
  124. (void) snprintf(authpath, sizeof(authpath), "%s%s", dirname, AUTH_FILE);
  125. } else {
  126. (void) snprintf(authpath, sizeof(authpath), "%s/%s", dirname, AUTH_FILE);
  127. }
  128. if(stat(authpath, &sb) < 0) {
  129. if(defaultRealmName == NULL || defaultRealmPasswordFile == NULL) {
  130. return;
  131. } else {
  132. snprintf(authpath, sizeof(authpath), "%s", defaultRealmPasswordFile);
  133. }
  134. }
  135. if(strcmp(authpath, defaultRealmPasswordFile) == 0) {
  136. snprintf(realmName, sizeof(realmName), "%s", defaultRealmName);
  137. } else {
  138. snprintf(realmName, sizeof(realmName), "%s", dirname);
  139. }
  140. if(authorization == (char*) 0) {
  141. send_authenticate(realmName, is_ssl);
  142. }
  143. if(strncmp(authorization, "Basic ", 6) != 0) {
  144. send_authenticate(realmName, is_ssl);
  145. }
  146. l = b64_decode(&(authorization[6]), (unsigned char*) authinfo, sizeof(authinfo) - 1);
  147. authinfo[l] = '\0';
  148. authpass = strchr(authinfo, ':');
  149. if(authpass == (char*) 0) {
  150. send_authenticate(realmName, is_ssl);
  151. }
  152. *authpass++ = '\0';
  153. colon = strchr(authpass, ':');
  154. if(colon != (char*) 0) {
  155. *colon = '\0';
  156. }
  157. fp = fopen(authpath, "r");
  158. if(fp == (FILE*) 0) {
  159. syslog(LOG_ERR, "%.80s auth file %.80s could not be opened - %m", ntoa(&client_addr), authpath);
  160. send_error(403, "Forbidden", "", "File is protected.", is_ssl);
  161. }
  162. while(fgets(line, sizeof(line), fp) != (char*) 0) {
  163. l = strlen(line);
  164. if(line[l - 1] == '\n') {
  165. line[l - 1] = '\0';
  166. }
  167. cryp = strchr(line, ':');
  168. if(cryp == (char*) 0) {
  169. continue;
  170. }
  171. *cryp++ = '\0';
  172. if(strcmp(line, authinfo) == 0) {
  173. (void) fclose(fp);
  174. if(strcmp(crypt(authpass, cryp), cryp) == 0) {
  175. remoteuser = line;
  176. return;
  177. } else {
  178. send_authenticate(realmName, is_ssl);
  179. }
  180. }
  181. }
  182. (void) fclose(fp);
  183. send_authenticate(realmName, is_ssl);
  184. }
  185. static int b64_decode(const char* str, unsigned char* space, int size) {
  186. const char* cp;
  187. int space_idx, phase;
  188. int d, prev_d = 0;
  189. unsigned char c;
  190. space_idx = 0;
  191. phase = 0;
  192. for(cp = str; *cp != '\0'; ++cp) {
  193. d = b64_decode_table[(int) *cp];
  194. if(d != -1) {
  195. switch(phase) {
  196. case 0:
  197. ++phase;
  198. break;
  199. case 1:
  200. c = ((prev_d << 2) | ((d & 0x30) >> 4));
  201. if(space_idx < size) {
  202. space[space_idx++] = c;
  203. }
  204. ++phase;
  205. break;
  206. case 2:
  207. c = (((prev_d & 0xf) << 4) | ((d & 0x3c) >> 2));
  208. if(space_idx < size) {
  209. space[space_idx++] = c;
  210. }
  211. ++phase;
  212. break;
  213. case 3:
  214. c = (((prev_d & 0x03) << 6) | d);
  215. if(space_idx < size) {
  216. space[space_idx++] = c;
  217. }
  218. phase = 0;
  219. break;
  220. }
  221. prev_d = d;
  222. }
  223. }
  224. return space_idx;
  225. }
  226. static char* build_env(char* fmt, char* arg) {
  227. char* cp;
  228. int size;
  229. static char* buf;
  230. static int maxbuf = 0;
  231. size = strlen(fmt) + strlen(arg);
  232. if(size > maxbuf) {
  233. if(maxbuf == 0) {
  234. maxbuf = MAX(200, size + 100);
  235. buf = (char*) e_malloc(maxbuf);
  236. } else {
  237. maxbuf = MAX(maxbuf * 2, size * 5 / 4);
  238. buf = (char*) e_realloc((void*) buf, maxbuf);
  239. }
  240. }
  241. (void) snprintf(buf, maxbuf, fmt, arg);
  242. cp = e_strdup(buf);
  243. return cp;
  244. }
  245. static void cgi_interpose_input(int wfd, int is_ssl) {
  246. size_t c;
  247. ssize_t r, r2;
  248. char buf[1024];
  249. c = request_len - request_idx;
  250. if(c > 0) {
  251. if(write(wfd, &(request[request_idx]), c) != c) {
  252. return;
  253. }
  254. }
  255. while(c < content_length) {
  256. r = my_read(buf, MIN( sizeof(buf), content_length - c), is_ssl);
  257. if(r < 0 && (errno == EINTR || errno == EAGAIN)) {
  258. sleep(1);
  259. continue;
  260. }
  261. if(r <= 0) {
  262. return;
  263. }
  264. for(;;) {
  265. r2 = write(wfd, buf, r);
  266. if(r2 < 0 && (errno == EINTR || errno == EAGAIN)) {
  267. sleep(1);
  268. continue;
  269. }
  270. if(r2 != r) {
  271. return;
  272. }
  273. break;
  274. }
  275. c += r;
  276. }
  277. post_post_garbage_hack(is_ssl);
  278. }
  279. static void cgi_interpose_output(int rfd, int parse_headers, int is_ssl) {
  280. ssize_t r, r2;
  281. char buf[1024];
  282. if(!parse_headers) {
  283. char http_head[] = "HTTP/1.0 200 OK\015\012";
  284. (void) my_write(http_head, sizeof(http_head), is_ssl);
  285. } else {
  286. size_t headers_size, headers_len;
  287. char* headers;
  288. char* br;
  289. int status;
  290. char* title;
  291. char* cp;
  292. headers_size = 0;
  293. add_to_buf(&headers, &headers_size, &headers_len, (char*) 0, 0);
  294. for(;;) {
  295. r = read(rfd, buf, sizeof(buf));
  296. if(r < 0 && (errno == EINTR || errno == EAGAIN)) {
  297. sleep(1);
  298. continue;
  299. }
  300. if(r <= 0) {
  301. br = &(headers[headers_len]);
  302. break;
  303. }
  304. add_to_buf(&headers, &headers_size, &headers_len, buf, r);
  305. if((br = strstr(headers, "\015\012\015\012")) != (char*) 0 || (br = strstr(headers, "\012\012")) != (char*) 0) {
  306. break;
  307. }
  308. }
  309. if(headers[0] == '\0') {
  310. return;
  311. }
  312. status = 200;
  313. if((cp = strstr(headers, "Status:")) != (char*) 0 && cp < br && (cp == headers || *(cp-1) == '\012')) {
  314. cp += 7;
  315. cp += strspn(cp, " \t");
  316. status = atoi(cp);
  317. }
  318. if((cp = strstr(headers, "Location:")) != (char*) 0 && cp < br && (cp == headers || *(cp-1) == '\012')) {
  319. status = 302;
  320. }
  321. switch(status) {
  322. case 200:
  323. title = "OK";
  324. break;
  325. case 302:
  326. title = "Found";
  327. break;
  328. case 304:
  329. title = "Not Modified";
  330. break;
  331. case 400:
  332. title = "Bad Request";
  333. break;
  334. case 401:
  335. title = "Unauthorized";
  336. break;
  337. case 403:
  338. title = "Forbidden";
  339. break;
  340. case 404:
  341. title = "Not Found";
  342. break;
  343. case 408:
  344. title = "Request Timeout";
  345. break;
  346. case 500:
  347. title = "Internal Error";
  348. break;
  349. case 501:
  350. title = "Not Implemented";
  351. break;
  352. case 503:
  353. title = "Service Temporarily Overloaded";
  354. break;
  355. default:
  356. title = "Something";
  357. break;
  358. }
  359. (void) snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\015\012", status, title);
  360. (void) my_write(buf, strlen(buf), is_ssl);
  361. if(strstr(headers, "Server:") == NULL) {
  362. char line[200];
  363. sprintf(line, "Server: %s\015\012", SERVER_SOFTWARE);
  364. (void) my_write(line, strlen(line), is_ssl);
  365. }
  366. if(strstr(headers, "Date:") == NULL) {
  367. char line[200];
  368. char timebuf[100];
  369. time_t now = time((time_t*) 0);
  370. const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT";
  371. (void) strftime(timebuf, sizeof(timebuf), rfc1123_fmt, gmtime(&now));
  372. sprintf(line, "Date: %s\015\012", timebuf);
  373. (void) my_write(line, strlen(line), is_ssl);
  374. if(strstr(headers, "Expires:") == NULL) {
  375. sprintf(line, "Expires: %s\015\012", timebuf);
  376. (void) my_write(line, strlen(line), is_ssl);
  377. }
  378. } else if(strstr(headers, "Expires:") == NULL) {
  379. char* line = "Expires: Thu, 01 Jan 1970 00:00:00 GMT\015\012";
  380. (void) my_write(line, strlen(line), is_ssl);
  381. }
  382. (void) my_write(headers, headers_len, is_ssl);
  383. }
  384. for(;;) {
  385. r = read(rfd, buf, sizeof(buf));
  386. if(r < 0 && (errno == EINTR || errno == EAGAIN)) {
  387. sleep(1);
  388. continue;
  389. }
  390. if(r <= 0) {
  391. goto done;
  392. }
  393. for(;;) {
  394. r2 = my_write(buf, r, is_ssl);
  395. if(r2 < 0 && (errno == EINTR || errno == EAGAIN)) {
  396. sleep(1);
  397. continue;
  398. }
  399. if(r2 != r) {
  400. goto done;
  401. }
  402. break;
  403. }
  404. }
  405. done:
  406. shutdown(conn_fd, SHUT_WR);
  407. }
  408. static void check_referer(int is_ssl) {
  409. char* cp;
  410. if(url_pattern == (char*) 0) {
  411. return;
  412. }
  413. if(really_check_referer()) {
  414. return;
  415. }
  416. cp = hostname;
  417. if(cp == (char*) 0) {
  418. cp = "";
  419. }
  420. syslog(LOG_INFO, "%.80s non-local referer \"%.80s%.80s\" \"%.80s\"", ntoa(&client_addr), cp, path, referer);
  421. send_error(403, "Forbidden", "", "You must supply a local referer.", is_ssl);
  422. }
  423. static void clear_ndelay(int fd) {
  424. int flags, newflags;
  425. flags = fcntl(fd, F_GETFL, 0);
  426. if(flags != -1) {
  427. newflags = flags & ~ (int) O_NDELAY;
  428. if(newflags != flags) {
  429. (void) fcntl(fd, F_SETFL, newflags);
  430. }
  431. }
  432. }
  433. static void de_dotdot(char* file) {
  434. char* cp;
  435. char* cp2;
  436. int l;
  437. while((cp = strstr(file, "//")) != (char*) 0) {
  438. for(cp2 = cp + 2; *cp2 == '/'; ++cp2) {
  439. continue;
  440. }
  441. (void) strcpy(cp + 1, cp2);
  442. }
  443. while(strncmp(file, "./", 2) == 0) {
  444. (void) strcpy(file, file + 2);
  445. }
  446. while((cp = strstr( file, "/./")) != (char*) 0) {
  447. (void) strcpy(cp, cp + 2);
  448. }
  449. for(;;) {
  450. while(strncmp(file, "../", 3) == 0) {
  451. (void) strcpy( file, file + 3 );
  452. }
  453. cp = strstr(file, "/../");
  454. if(cp == (char*) 0) {
  455. break;
  456. }
  457. for(cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2) {
  458. continue;
  459. }
  460. (void) strcpy(cp2 + 1, cp + 4);
  461. }
  462. while((l = strlen(file)) > 3 && strcmp((cp = file + l - 3), "/..") == 0) {
  463. for(cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2) {
  464. continue;
  465. }
  466. if(cp2 < file) {
  467. break;
  468. }
  469. *cp2 = '\0';
  470. }
  471. }
  472. static void do_cgi(int is_ssl, unsigned short conn_port) {
  473. char** argp;
  474. char** envp;
  475. int parse_headers;
  476. char* binary;
  477. char* directory;
  478. if(method != METHOD_GET && method != METHOD_POST) {
  479. send_error(501, "Not Implemented", "", "That method is not implemented for CGI.", is_ssl);
  480. }
  481. if(conn_fd == STDIN_FILENO || conn_fd == STDOUT_FILENO || conn_fd == STDERR_FILENO) {
  482. int newfd = dup2(conn_fd, STDERR_FILENO + 1);
  483. if(newfd >= 0) {
  484. conn_fd = newfd;
  485. }
  486. }
  487. envp = make_envp(is_ssl, conn_port);
  488. argp = make_argp();
  489. if((method == METHOD_POST && request_len > request_idx) || is_ssl) {
  490. int p[2];
  491. int r;
  492. if(pipe(p) < 0) {
  493. send_error(500, "Internal Error", "", "Something unexpected went wrong making a pipe.", is_ssl);
  494. }
  495. r = fork();
  496. if(r < 0) {
  497. send_error(500, "Internal Error", "", "Something unexpected went wrong forking an interposer.", is_ssl);
  498. }
  499. if(r == 0) {
  500. (void) close(p[0]);
  501. cgi_interpose_input(p[1], is_ssl);
  502. exit(0);
  503. }
  504. (void) close(p[1]);
  505. if(p[0] != STDIN_FILENO) {
  506. (void) dup2(p[0], STDIN_FILENO);
  507. (void) close(p[0]);
  508. }
  509. } else {
  510. if(conn_fd != STDIN_FILENO) {
  511. (void) dup2(conn_fd, STDIN_FILENO);
  512. }
  513. }
  514. if(strncmp(argp[0], "nph-", 4) == 0) {
  515. parse_headers = 0;
  516. } else {
  517. parse_headers = 1;
  518. }
  519. if(parse_headers || is_ssl) {
  520. int p[2];
  521. int r;
  522. if(pipe(p) < 0) {
  523. send_error(500, "Internal Error", "", "Something unexpected went wrong making a pipe.", is_ssl);
  524. }
  525. r = fork();
  526. if(r < 0) {
  527. send_error(500, "Internal Error", "", "Something unexpected went wrong forking an interposer.", is_ssl);
  528. }
  529. if(r == 0) {
  530. (void) close(p[1]);
  531. cgi_interpose_output(p[0], parse_headers, is_ssl);
  532. exit(0);
  533. }
  534. (void) close(p[0]);
  535. if(p[1] != STDOUT_FILENO) {
  536. (void) dup2(p[1], STDOUT_FILENO);
  537. }
  538. if(p[1] != STDERR_FILENO) {
  539. (void) dup2(p[1], STDERR_FILENO);
  540. }
  541. if(p[1] != STDOUT_FILENO && p[1] != STDERR_FILENO) {
  542. (void) close(p[1]);
  543. }
  544. } else {
  545. if(conn_fd != STDOUT_FILENO) {
  546. (void) dup2(conn_fd, STDOUT_FILENO);
  547. }
  548. if(conn_fd != STDERR_FILENO) {
  549. (void) dup2(conn_fd, STDERR_FILENO);
  550. }
  551. }
  552. if(logfp != (FILE*) 0) {
  553. (void) fclose(logfp);
  554. }
  555. closelog();
  556. if(nice(CGI_NICE) < 0) { ; }
  557. directory = e_strdup(file);
  558. binary = strrchr(directory, '/');
  559. if(binary == (char*) 0) {
  560. binary = file;
  561. } else {
  562. *binary++ = '\0';
  563. if(chdir(directory) < 0) { ; }
  564. }
  565. (void) signal(SIGPIPE, SIG_DFL);
  566. (void) execve(binary, argp, envp);
  567. send_error(500, "Internal Error", "", "Something unexpected went wrong running a CGI program.", is_ssl);
  568. }
  569. static void do_dir(int is_ssl) {
  570. char buf[10000];
  571. size_t buflen;
  572. char* contents;
  573. size_t contents_size, contents_len;
  574. int n, i;
  575. struct dirent **dl;
  576. char* name_info;
  577. if(pathinfo != (char*) 0) {
  578. send_error(404, "Not Found", "", "File not found.", is_ssl);
  579. }
  580. auth_check(file, is_ssl);
  581. check_referer(is_ssl);
  582. n = scandir(file, &dl, NULL, alphasort);
  583. if(n < 0) {
  584. syslog(LOG_INFO, "%.80s Directory \"%.80s\" is protected", ntoa(&client_addr), path);
  585. send_error(403, "Forbidden", "", "Directory is protected.", is_ssl);
  586. }
  587. contents_size = 0;
  588. buflen = snprintf(buf, sizeof(buf), "<html>\n<head><title>Index of %s</title></head>\n<body bgcolor=\"#FFFFFF\">\n<h1>Index of %s</h1><hr><pre>\n", file, file);
  589. add_to_buf(&contents, &contents_size, &contents_len, buf, buflen);
  590. for(i = 0; i < n; ++i) {
  591. if(strcmp(dl[i]->d_name, ".") == 0) {
  592. continue;
  593. }
  594. name_info = file_details(file, dl[i]->d_name);
  595. add_to_buf(&contents, &contents_size, &contents_len, name_info, strlen(name_info));
  596. }
  597. buflen = snprintf(buf, sizeof(buf), "</pre><hr>\n%s\n</body>\n</html>\n", SERVER_SOFTWARE);
  598. add_to_buf(&contents, &contents_size, &contents_len, buf, buflen);
  599. add_headers(200, "Ok", "", "", "text/html; charset=%s", contents_len, sb.st_mtime);
  600. if(method != METHOD_HEAD) {
  601. add_to_response(contents, contents_len);
  602. }
  603. send_response(is_ssl);
  604. }
  605. static void do_file(int is_ssl, unsigned short conn_port) {
  606. char buf[10000];
  607. char mime_encodings[500];
  608. const char* mime_type;
  609. char fixed_mime_type[500];
  610. char* cp;
  611. int fd;
  612. (void) strncpy(buf, file, sizeof(buf));
  613. cp = strrchr(buf, '/');
  614. if(cp == (char*) 0) {
  615. (void) strcpy(buf, ".");
  616. } else {
  617. *cp = '\0';
  618. }
  619. auth_check(buf, is_ssl);
  620. if(strcmp(file, AUTH_FILE) == 0 || (strcmp(&(file[strlen(file) - sizeof(AUTH_FILE) + 1]), AUTH_FILE) == 0 && file[strlen(file) - sizeof(AUTH_FILE)] == '/')) {
  621. syslog(LOG_NOTICE, "%.80s URL \"%.80s\" tried to retrieve an auth file", ntoa(&client_addr), path);
  622. send_error(403, "Forbidden", "", "File is protected.", is_ssl);
  623. }
  624. if(defaultRealmName != NULL && defaultRealmPasswordFile != NULL) {
  625. if(strcmp(file, defaultRealmPasswordFile) == 0 || strcmp(&(file[strlen(file) - sizeof(defaultRealmPasswordFile) + 1]), defaultRealmPasswordFile) == 0 && file[strlen(file) - sizeof(defaultRealmPasswordFile)] == '/') {
  626. syslog(LOG_NOTICE, "%.80s URL \"%.80s\" tried to retrieve an auth file", ntoa(&client_addr), path);
  627. send_error(403, "Forbidden", "", "File is protected.", is_ssl);
  628. }
  629. }
  630. check_referer(is_ssl);
  631. if(cgi_pattern != (char*) 0 && match(cgi_pattern, file)) {
  632. do_cgi(is_ssl, conn_port);
  633. return;
  634. } else if(pathinfo != (char*) 0) {
  635. send_error(404, "Not Found", "", "File not found.", is_ssl);
  636. }
  637. fd = open(file, O_RDONLY);
  638. if(fd < 0) {
  639. syslog(LOG_INFO, "%.80s File \"%.80s\" is protected", ntoa(&client_addr), path);
  640. send_error(403, "Forbidden", "", "File is protected.", is_ssl);
  641. }
  642. mime_type = figure_mime(file, mime_encodings, sizeof(mime_encodings));
  643. (void) snprintf(fixed_mime_type, sizeof(fixed_mime_type), mime_type, charset);
  644. if(if_modified_since != (time_t) -1 && if_modified_since >= sb.st_mtime) {
  645. add_headers(304, "Not Modified", "", mime_encodings, fixed_mime_type, (off_t) -1, sb.st_mtime);
  646. send_response(is_ssl);
  647. return;
  648. }
  649. add_headers(200, "Ok", "", mime_encodings, fixed_mime_type, sb.st_size, sb.st_mtime);
  650. send_response(is_ssl);
  651. if(method == METHOD_HEAD) {
  652. return;
  653. }
  654. if(sb.st_size > 0) {
  655. send_via_write(fd, sb.st_size, is_ssl);
  656. }
  657. (void) close(fd);
  658. }
  659. static void* e_malloc(size_t size) {
  660. void* ptr;
  661. ptr = malloc(size);
  662. if(ptr == (void*) 0) {
  663. syslog(LOG_CRIT, "out of memory");
  664. (void) fprintf(stderr, "%s: out of memory\n", argv0);
  665. exit(1);
  666. }
  667. return ptr;
  668. }
  669. static void* e_realloc(void* optr, size_t size) {
  670. void* ptr;
  671. ptr = realloc(optr, size);
  672. if(ptr == (void*) 0) {
  673. syslog(LOG_CRIT, "out of memory");
  674. (void) fprintf(stderr, "%s: out of memory\n", argv0);
  675. exit(1);
  676. }
  677. return ptr;
  678. }
  679. static char* e_strdup(char* ostr) {
  680. char* str;
  681. str = strdup(ostr);
  682. if(str == (char*) 0) {
  683. syslog(LOG_CRIT, "out of memory copying a string");
  684. (void) fprintf(stderr, "%s: out of memory copying a string\n", argv0);
  685. exit(1);
  686. }
  687. return str;
  688. }
  689. static int ext_compare(struct mime_entry* a, struct mime_entry* b) {
  690. return strcmp(a->ext, b->ext);
  691. }
  692. static const char* figure_mime(char* name, char* me, size_t me_size) {
  693. char* prev_dot;
  694. char* dot;
  695. char* ext;
  696. int me_indexes[100], n_me_indexes;
  697. size_t ext_len, me_len;
  698. int i, top, bot, mid;
  699. int r;
  700. const char* default_type = "application/octet-stream ";
  701. const char* type;
  702. n_me_indexes = 0;
  703. for(prev_dot = &name[strlen(name)]; ; prev_dot = dot) {
  704. for(dot = prev_dot - 1; dot >= name && *dot != '.'; --dot);
  705. if(dot < name) {
  706. type = default_type;
  707. goto done;
  708. }
  709. ext = dot + 1;
  710. ext_len = prev_dot - ext;
  711. for(i = 0; i < n_enc_tab; ++i) {
  712. if(ext_len == enc_tab[i].ext_len && strncasecmp(ext, enc_tab[i].ext, ext_len) == 0) {
  713. if(n_me_indexes < sizeof(me_indexes)/sizeof(*me_indexes)) {
  714. me_indexes[n_me_indexes] = i;
  715. ++n_me_indexes;
  716. }
  717. goto next;
  718. }
  719. }
  720. break;
  721. next: ;
  722. }
  723. top = n_typ_tab - 1;
  724. bot = 0;
  725. while(top >= bot) {
  726. mid = (top + bot) / 2;
  727. r = strncasecmp(ext, typ_tab[mid].ext, ext_len);
  728. if(r < 0) {
  729. top = mid - 1;
  730. } else if(r > 0) {
  731. bot = mid + 1;
  732. } else if(ext_len < typ_tab[mid].ext_len) {
  733. top = mid - 1;
  734. } else if(ext_len > typ_tab[mid].ext_len) {
  735. bot = mid + 1;
  736. } else {
  737. type = typ_tab[mid].val;
  738. goto done;
  739. }
  740. }
  741. type = default_type;
  742. done:
  743. me[0] = '\0';
  744. me_len = 0;
  745. for(i = n_me_indexes - 1; i >= 0; --i) {
  746. if(me_len + enc_tab[me_indexes[i]].val_len + 1 < me_size) {
  747. if(me[0] != '\0') {
  748. (void) strcpy(&me[me_len], ",");
  749. ++me_len;
  750. }
  751. (void) strcpy(&me[me_len], enc_tab[me_indexes[i]].val);
  752. me_len += enc_tab[me_indexes[i]].val_len;
  753. }
  754. }
  755. return type;
  756. }
  757. static char* file_details(const char* dir, const char* name) {
  758. struct stat sb;
  759. char f_time[20];
  760. static char encname[1000];
  761. static char buf[2000];
  762. (void) snprintf(buf, sizeof(buf), "%s/%s", dir, name);
  763. if(lstat(buf, &sb) < 0)
  764. return "???";
  765. (void) strftime(f_time, sizeof(f_time), "%d-%b-%Y %H:%M", localtime(&sb.st_mtime));
  766. strencode(encname, sizeof(encname), name);
  767. (void) snprintf(buf, sizeof(buf), "<a href=\"%s\">%-50s</a> %15s %14lld\n", encname, name, f_time, (long long int) sb.st_size);
  768. return buf;
  769. }
  770. static char* get_method_str(int m) {
  771. switch(m) {
  772. case METHOD_GET:
  773. return "GET";
  774. case METHOD_HEAD:
  775. return "HEAD";
  776. case METHOD_POST:
  777. return "POST";
  778. default:
  779. return "UNKNOWN";
  780. }
  781. }
  782. static int get_pathinfo(void) {
  783. int r;
  784. pathinfo = &file[strlen(file)];
  785. for(;;) {
  786. do {
  787. --pathinfo;
  788. if(pathinfo <= file) {
  789. pathinfo = (char*) 0;
  790. return -1;
  791. }
  792. } while(*pathinfo != '/');
  793. *pathinfo = '\0';
  794. r = stat(file, &sb);
  795. if(r >= 0) {
  796. ++pathinfo;
  797. return r;
  798. } else {
  799. *pathinfo = '/';
  800. }
  801. }
  802. }
  803. static char* get_request_line(void) {
  804. int i;
  805. char c;
  806. for(i = request_idx; request_idx < request_len; ++request_idx) {
  807. c = request[request_idx];
  808. if(c == '\012' || c == '\015') {
  809. request[request_idx] = '\0';
  810. ++request_idx;
  811. if(c == '\015' && request_idx < request_len && request[request_idx] == '\012') {
  812. request[request_idx] = '\0';
  813. ++request_idx;
  814. }
  815. return &(request[i]);
  816. }
  817. }
  818. return (char*) 0;
  819. }
  820. static void handle_read_timeout(int sig, int is_ssl) {
  821. syslog(LOG_INFO, "%.80s connection timed out reading", ntoa(&client_addr));
  822. send_error(408, "Request Timeout", "", "No request appeared within a reasonable time period.", is_ssl);
  823. }
  824. static void handle_read_timeout_sig(int sig) {
  825. handle_read_timeout(0,0);
  826. }
  827. static void handle_request(int is_ssl, unsigned short conn_port) {
  828. char* method_str;
  829. char* line;
  830. char* cp;
  831. int r, file_len, i;
  832. const char* index_names[] = {"default.html", "default.htm", "index.html", "index.htm", "index.cgi", "index.sh" };
  833. (void) signal(SIGALRM, handle_read_timeout_sig);
  834. (void) alarm(READ_TIMEOUT);
  835. remoteuser = (char*) 0;
  836. method = METHOD_UNKNOWN;
  837. path = (char*) 0;
  838. file = (char*) 0;
  839. pathinfo = (char*) 0;
  840. query = "";
  841. protocol = (char*) 0;
  842. status = 0;
  843. bytes = -1;
  844. authorization = (char*) 0;
  845. content_type = (char*) 0;
  846. content_length = -1;
  847. cookie = (char*) 0;
  848. host = (char*) 0;
  849. if_modified_since = (time_t) -1;
  850. referer = "";
  851. useragent = "";
  852. #ifdef TCP_NOPUSH
  853. r = 1;
  854. (void) setsockopt(conn_fd, IPPROTO_TCP, TCP_NOPUSH, (void*) &r, sizeof(r));
  855. #endif
  856. if(is_ssl) {
  857. ssl = SSL_new(ssl_ctx);
  858. SSL_set_fd(ssl, conn_fd);
  859. int accept_ret = SSL_accept(ssl);
  860. if(accept_ret <= 0) {
  861. int e = SSL_get_error(ssl, accept_ret);
  862. if(e != VERSION_ERROR) {
  863. syslog(LOG_CRIT, "error: can't initialize ssl connection, error = %d\n", e);
  864. }
  865. exit(1);
  866. }
  867. }
  868. start_request();
  869. for(;;) {
  870. char buf[10000];
  871. int r = my_read( buf, sizeof(buf), is_ssl );
  872. if(r < 0 && (errno == EINTR || errno == EAGAIN)) {
  873. continue;
  874. }
  875. if(r <= 0) {
  876. break;
  877. }
  878. (void) alarm(READ_TIMEOUT);
  879. add_to_request(buf, r);
  880. if(strstr(request, "\015\012\015\012") != (char*) 0 || strstr(request, "\012\012") != (char*) 0) {
  881. break;
  882. }
  883. }
  884. method_str = get_request_line();
  885. if(method_str == (char*) 0) {
  886. send_error(400, "Bad Request", "", "Can't parse request.", is_ssl);
  887. }
  888. path = strpbrk(method_str, " \t\012\015");
  889. if(path == (char*) 0) {
  890. send_error(400, "Bad Request", "", "Can't parse request.", is_ssl);
  891. }
  892. *path++ = '\0';
  893. path += strspn(path, " \t\012\015");
  894. protocol = strpbrk(path, " \t\012\015");
  895. if(protocol == (char*) 0) {
  896. send_error(400, "Bad Request", "", "Can't parse request.", is_ssl);
  897. }
  898. *protocol++ = '\0';
  899. protocol += strspn(protocol, " \t\012\015");
  900. query = strchr(path, '?');
  901. if(query == (char*) 0) {
  902. query = "";
  903. } else {
  904. *query++ = '\0';
  905. }
  906. while((line = get_request_line()) != (char*) 0) {
  907. if(line[0] == '\0') {
  908. break;
  909. } else if(strncasecmp(line, "Authorization:", 14) == 0) {
  910. cp = &line[14];
  911. cp += strspn(cp, " \t");
  912. authorization = cp;
  913. } else if(strncasecmp(line, "Content-Length:", 15) == 0) {
  914. cp = &line[15];
  915. cp += strspn(cp, " \t");
  916. content_length = atol(cp);
  917. } else if(strncasecmp(line, "Content-Type:", 13) == 0) {
  918. cp = &line[13];
  919. cp += strspn(cp, " \t");
  920. content_type = cp;
  921. } else if(strncasecmp(line, "Cookie:", 7) == 0) {
  922. cp = &line[7];
  923. cp += strspn(cp, " \t");
  924. cookie = cp;
  925. } else if(strncasecmp(line, "Host:", 5) == 0) {
  926. cp = &line[5];
  927. cp += strspn(cp, " \t");
  928. host = cp;
  929. if(strchr(host, '/') != (char*) 0 || host[0] == '.') {
  930. send_error(400, "Bad Request", "", "Can't parse request.", is_ssl);
  931. }
  932. } else if(strncasecmp(line, "If-Modified-Since:", 18) == 0) {
  933. cp = &line[18];
  934. cp += strspn(cp, " \t");
  935. if_modified_since = dateparse(cp);
  936. } else if(strncasecmp(line, "Referer:", 8) == 0) {
  937. cp = &line[8];
  938. cp += strspn(cp, " \t");
  939. referer = cp;
  940. } else if(strncasecmp(line, "User-Agent:", 11) == 0) {
  941. cp = &line[11];
  942. cp += strspn(cp, " \t");
  943. useragent = cp;
  944. }
  945. }
  946. if(strcasecmp(method_str, get_method_str(METHOD_GET)) == 0) {
  947. method = METHOD_GET;
  948. } else if(strcasecmp(method_str, get_method_str(METHOD_HEAD)) == 0) {
  949. method = METHOD_HEAD;
  950. } else if(strcasecmp(method_str, get_method_str(METHOD_POST)) == 0) {
  951. method = METHOD_POST;
  952. } else {
  953. send_error(501, "Not Implemented", "", "That method is not implemented.", is_ssl);
  954. }
  955. strdecode(path, path);
  956. if(path[0] != '/') {
  957. send_error(400, "Bad Request", "", "Bad filename.", is_ssl);
  958. }
  959. file = &(path[1]);
  960. de_dotdot(file);
  961. if(file[0] == '\0') {
  962. file = "./";
  963. }
  964. if(file[0] == '/' || (file[0] == '.' && file[1] == '.' && (file[2] == '\0' || file[2] == '/'))) {
  965. send_error(400, "Bad Request", "", "Illegal filename.", is_ssl);
  966. }
  967. (void) signal(SIGALRM, handle_write_timeout);
  968. (void) alarm(WRITE_TIMEOUT);
  969. r = stat(file, &sb);
  970. if(r < 0) {
  971. r = get_pathinfo();
  972. }
  973. if(r < 0) {
  974. if(pageNotFoundFile != NULL && host != NULL) {
  975. send_redirect("", host, pageNotFoundFile, is_ssl);
  976. } else {
  977. send_error(404, "Not Found", "", "File not found.", is_ssl);
  978. }
  979. }
  980. file_len = strlen( file );
  981. if(!S_ISDIR(sb.st_mode)) {
  982. while(file[file_len - 1] == '/') {
  983. file[file_len - 1] = '\0';
  984. --file_len;
  985. }
  986. do_file(is_ssl, conn_port);
  987. } else {
  988. char idx[10000];
  989. unsigned char found_index = 0;
  990. if(file[file_len - 1] != '/' && pathinfo == (char*) 0) {
  991. char location[10000];
  992. if(query[0] != '\0') {
  993. (void) snprintf(location, sizeof(location), "Location: %s/?%s", path, query);
  994. } else {
  995. (void) snprintf(location, sizeof(location), "Location: %s/", path);
  996. send_error(302, "Found", location, "Directories must end with a slash.", is_ssl);
  997. }
  998. }
  999. if(defaultPageFile != NULL) {
  1000. (void) snprintf(idx, sizeof(idx), "%s%s", file, defaultPageFile);
  1001. if(stat( idx, &sb ) >= 0) {
  1002. file = idx;
  1003. do_file(is_ssl, conn_port);
  1004. found_index = 1;
  1005. }
  1006. }
  1007. for(i = 0; i < (sizeof(index_names) / sizeof(char*)) && found_index == 0; ++i) {
  1008. (void) snprintf(idx, sizeof(idx), "%s%s", file, index_names[i]);
  1009. if(stat(idx, &sb) >= 0) {
  1010. file = idx;
  1011. do_file(is_ssl, conn_port);
  1012. found_index = 1;
  1013. }
  1014. }
  1015. if(found_index == 0) {
  1016. if(allowDirectoryListing == 0) {
  1017. if(pageNotFoundFile != NULL && host != NULL) {
  1018. send_redirect("", host, pageNotFoundFile, is_ssl);
  1019. } else {
  1020. send_error(404, "Not Found", "", "File not found.", is_ssl);
  1021. }
  1022. } else {
  1023. do_dir(is_ssl);
  1024. }
  1025. }
  1026. }
  1027. if(is_ssl) {
  1028. SSL_free(ssl);
  1029. }
  1030. }
  1031. static void handle_sigchld(int sig) {
  1032. const int oerrno = errno;
  1033. pid_t pid;
  1034. int status;
  1035. (void) signal(SIGCHLD, handle_sigchld);
  1036. for(;;) {
  1037. pid = waitpid((pid_t) -1, &status, WNOHANG);
  1038. if((int) pid == 0) {
  1039. break;
  1040. }
  1041. if((int) pid < 0) {
  1042. if(errno == EINTR || errno == EAGAIN) {
  1043. continue;
  1044. }
  1045. if(errno != ECHILD) {
  1046. syslog(LOG_ERR, "child wait - %m");
  1047. perror("child wait");
  1048. }
  1049. break;
  1050. }
  1051. }
  1052. errno = oerrno;
  1053. }
  1054. static void handle_sighup(int sig) {
  1055. const int oerrno = errno;
  1056. (void) signal(SIGHUP, handle_sighup);
  1057. got_hup = 1;
  1058. errno = oerrno;
  1059. }
  1060. static void handle_sigterm(int sig) {
  1061. syslog(LOG_NOTICE, "exiting due to signal %d", sig);
  1062. (void) fprintf(stderr, "%s: exiting due to signal %d\n", argv0, sig);
  1063. closelog();
  1064. exit(1);
  1065. }
  1066. static void handle_write_timeout(int sig) {
  1067. syslog(LOG_INFO, "%.80s connection timed out writing", ntoa(&client_addr));
  1068. exit(1);
  1069. }
  1070. static int hexit(char c) {
  1071. if(c >= '0' && c <= '9') {
  1072. return c - '0';
  1073. }
  1074. if(c >= 'a' && c <= 'f') {
  1075. return c - 'a' + 10;
  1076. }
  1077. if(c >= 'A' && c <= 'F') {
  1078. return c - 'A' + 10;
  1079. }
  1080. return 0;
  1081. }
  1082. static void init_mime(void) {
  1083. int i;
  1084. qsort(enc_tab, n_enc_tab, sizeof(*enc_tab), (int(*)(const void*, const void*)) ext_compare);
  1085. qsort(typ_tab, n_typ_tab, sizeof(*typ_tab), (int(*)(const void*, const void*)) ext_compare);
  1086. for(i = 0; i < n_enc_tab; ++i) {
  1087. enc_tab[i].ext_len = strlen(enc_tab[i].ext);
  1088. enc_tab[i].val_len = strlen(enc_tab[i].val);
  1089. }
  1090. for(i = 0; i < n_typ_tab; ++i) {
  1091. typ_tab[i].ext_len = strlen(typ_tab[i].ext);
  1092. typ_tab[i].val_len = strlen(typ_tab[i].val);
  1093. }
  1094. }
  1095. static int initialize_listen_socket(usockaddr* usaP) {
  1096. int listen_fd;
  1097. int i;
  1098. if(!sockaddr_check(usaP)) {
  1099. syslog(LOG_ERR, "unknown sockaddr family on listen socket - %d", usaP->sa.sa_family);
  1100. (void) fprintf(stderr, "%s: unknown sockaddr family on listen socket - %d\n", argv0, usaP->sa.sa_family);
  1101. return -1;
  1102. }
  1103. listen_fd = socket(usaP->sa.sa_family, SOCK_STREAM, 0);
  1104. if(listen_fd < 0) {
  1105. if(usaP->sa.sa_family == AF_INET6 && (errno == ENOPROTOOPT || errno == EPROTONOSUPPORT || errno == ESOCKTNOSUPPORT || EPFNOSUPPORT || EAFNOSUPPORT)) {
  1106. /* IPv6 not compiled into kernel, no big deal, don't print errors */
  1107. } else {
  1108. syslog(LOG_CRIT, "socket %.80s - %m", ntoa(usaP));
  1109. perror("socket");
  1110. }
  1111. return -1;
  1112. }
  1113. (void) fcntl(listen_fd, F_SETFD, 1);
  1114. i = 1;
  1115. if(setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &i, sizeof(i)) < 0) {
  1116. syslog(LOG_CRIT, "setsockopt SO_REUSEADDR - %m");
  1117. perror("setsockopt SO_REUSEADDR");
  1118. return -1;
  1119. }
  1120. if(bind(listen_fd, &usaP->sa, sockaddr_len(usaP)) < 0) {
  1121. syslog(LOG_CRIT, "bind %.80s - %m", ntoa(usaP));
  1122. perror("bind");
  1123. return -1;
  1124. }
  1125. if(listen(listen_fd, 1024) < 0) {
  1126. syslog(LOG_CRIT, "listen - %m");
  1127. perror("listen");
  1128. return -1;
  1129. }
  1130. return listen_fd;
  1131. }
  1132. static void lookup_hostname(usockaddr* usa4P, usockaddr* usa4sP, size_t sa4_len, int* gotv4P, int* gotv4sP, usockaddr* usa6P, usockaddr* usa6sP, size_t sa6_len, int* gotv6P, int* gotv6sP) {
  1133. int port_index;
  1134. unsigned short port_list[4];
  1135. port_list[0] = port;
  1136. port_list[1] = sslPort;
  1137. port_list[2] = 0;
  1138. *gotv6P = 0;
  1139. *gotv6sP = 0;
  1140. *gotv4P = 0;
  1141. *gotv4sP = 0;
  1142. for(port_index=0; port_list[port_index] != 0; port_index++) {
  1143. struct addrinfo hints;
  1144. char portstr[10];
  1145. int gaierr;
  1146. struct addrinfo* ai;
  1147. struct addrinfo* ai2;
  1148. struct addrinfo* aiv6;
  1149. struct addrinfo* aiv4;
  1150. (void) memset(&hints, 0, sizeof(hints));
  1151. hints.ai_family = PF_UNSPEC;
  1152. hints.ai_flags = AI_PASSIVE;
  1153. hints.ai_socktype = SOCK_STREAM;
  1154. (void) snprintf(portstr, sizeof(portstr), "%d", (int) port_list[port_index]);
  1155. if((gaierr = getaddrinfo(hostname, portstr, &hints, &ai)) != 0) {
  1156. syslog(LOG_CRIT, "getaddrinfo %.80s - %s", hostname, gai_strerror(gaierr));
  1157. (void) fprintf(stderr, "%s: getaddrinfo %.80s - %s\n", argv0, hostname, gai_strerror(gaierr));
  1158. exit(1);
  1159. }
  1160. aiv6 = (struct addrinfo*) 0;
  1161. aiv4 = (struct addrinfo*) 0;
  1162. for(ai2 = ai; ai2 != (struct addrinfo*) 0; ai2 = ai2->ai_next) {
  1163. switch(ai2->ai_family) {
  1164. case AF_INET6:
  1165. if(aiv6 == (struct addrinfo*) 0) {
  1166. aiv6 = ai2;
  1167. }
  1168. break;
  1169. case AF_INET:
  1170. if(aiv4 == (struct addrinfo*) 0) {
  1171. aiv4 = ai2;
  1172. }
  1173. break;
  1174. }
  1175. }
  1176. if(aiv6 != (struct addrinfo*) 0) {
  1177. if(sa6_len < aiv6->ai_addrlen) {
  1178. syslog(LOG_CRIT, "%.80s - sockaddr too small (%lu < %lu)", hostname, (unsigned long) sa6_len, (unsigned long) aiv6->ai_addrlen);
  1179. (void) fprintf(stderr, "%s: %.80s - sockaddr too small (%lu < %lu)\n", argv0, hostname, (unsigned long) sa6_len, (unsigned long) aiv6->ai_addrlen);
  1180. exit(1);
  1181. }
  1182. if(port_index==0) {
  1183. *gotv6P = 1;
  1184. (void) memset(usa6P, 0, sa6_len);
  1185. (void) memmove(usa6P, aiv6->ai_addr, aiv6->ai_addrlen);
  1186. } else {
  1187. *gotv6sP = 1;
  1188. (void) memset(usa6sP, 0, sa6_len);
  1189. (void) memmove(usa6sP, aiv6->ai_addr, aiv6->ai_addrlen);
  1190. }
  1191. }
  1192. if(aiv4 != (struct addrinfo*) 0) {
  1193. if(sa4_len < aiv4->ai_addrlen) {
  1194. syslog(LOG_CRIT, "%.80s - sockaddr too small (%lu < %lu)", hostname, (unsigned long) sa4_len, (unsigned long) aiv4->ai_addrlen);
  1195. (void) fprintf(stderr, "%s: %.80s - sockaddr too small (%lu < %lu)\n", argv0, hostname, (unsigned long) sa4_len, (unsigned long) aiv4->ai_addrlen);
  1196. exit(1);
  1197. }
  1198. if(port_index == 0) {
  1199. *gotv4P = 1;
  1200. (void) memset(usa4P, 0, sa4_len);
  1201. (void) memmove(usa4P, aiv4->ai_addr, aiv4->ai_addrlen);
  1202. } else {
  1203. *gotv4sP = 1;
  1204. (void) memset(usa4sP, 0, sa4_len);
  1205. (void) memmove(usa4sP, aiv4->ai_addr, aiv4->ai_addrlen);
  1206. }
  1207. *gotv4P = 1;
  1208. }
  1209. freeaddrinfo(ai);
  1210. }
  1211. }
  1212. int main(int argc, char** argv) {
  1213. int argn;
  1214. struct passwd* pwd;
  1215. uid_t uid = 32767;
  1216. gid_t gid = 32767;
  1217. usockaddr host_addr4;
  1218. usockaddr host_addr6;
  1219. int gotv4, gotv4s, gotv6, gotv6s;
  1220. fd_set lfdset;
  1221. int maxfd;
  1222. usockaddr usa;
  1223. int sz, r;
  1224. char* cp;
  1225. usockaddr host_addr4s;
  1226. usockaddr host_addr6s;
  1227. argv0 = argv[0];
  1228. debug = 0;
  1229. port = 0;
  1230. dir = (char*) 0;
  1231. data_dir = (char*) 0;
  1232. cgi_pattern = DEFAULT_CGI_PATTERN;
  1233. url_pattern = (char*) 0;
  1234. no_empty_referers = 0;
  1235. local_pattern = (char*) 0;
  1236. charset = DEFAULT_CHARSET;
  1237. language = DEFAULT_LANGUAGE;
  1238. p3p = (char*) 0;
  1239. max_age = -1;
  1240. user = NULL;
  1241. hostname = (char*) 0;
  1242. logfile = (char*) 0;
  1243. pidfile = (char*) 0;
  1244. logfp = (FILE*) 0;
  1245. do_ssl = 0;
  1246. certfile = DEFAULT_CERTFILE;
  1247. cipher = (char*) 0;
  1248. defaultRealmName = NULL;
  1249. defaultRealmPasswordFile = NULL;
  1250. defaultPageFile = NULL;
  1251. pageNotFoundFile = NULL;
  1252. allowDirectoryListing = 1;
  1253. sslPort = 0;
  1254. argn = 1;
  1255. while(argn < argc && argv[argn][0] == '-') {
  1256. if(strcmp( argv[argn], "-V" ) == 0) {
  1257. (void) printf("%s\n", SERVER_SOFTWARE);
  1258. exit(0);
  1259. } else if(strcmp(argv[argn], "-C") == 0 && argn + 1 < argc) {
  1260. ++argn;
  1261. read_config(argv[argn]);
  1262. } else if(strcmp(argv[argn], "-D") == 0) {
  1263. debug = 1;
  1264. } else if(strcmp(argv[argn], "-S") == 0) {
  1265. do_ssl = 1;
  1266. } else if(strcmp(argv[argn], "-E") == 0 && argn + 1 < argc) {
  1267. ++argn;
  1268. certfile = argv[argn];
  1269. } else if(strcmp(argv[argn], "-Y") == 0 && argn + 1 < argc) {
  1270. ++argn;
  1271. cipher = argv[argn];
  1272. } else if(strcmp(argv[argn], "-p") == 0 && argn + 1 < argc) {
  1273. ++argn;
  1274. port = (unsigned short) atoi(argv[argn]);
  1275. } else if(strcmp(argv[argn], "-d") == 0 && argn + 1 < argc) {
  1276. ++argn;
  1277. dir = argv[argn];
  1278. } else if(strcmp(argv[argn], "-dd") == 0 && argn + 1 < argc) {
  1279. ++argn;
  1280. data_dir = argv[argn];
  1281. } else if(strcmp(argv[argn], "-c") == 0 && argn + 1 < argc) {
  1282. ++argn;
  1283. cgi_pattern = argv[argn];
  1284. } else if(strcmp(argv[argn], "-u") == 0 && argn + 1 < argc) {
  1285. ++argn;
  1286. user = argv[argn];
  1287. } else if(strcmp(argv[argn], "-h") == 0 && argn + 1 < argc) {
  1288. ++argn;
  1289. hostname = argv[argn];
  1290. } else if(strcmp(argv[argn], "-l") == 0 && argn + 1 < argc) {
  1291. ++argn;
  1292. logfile = argv[argn];
  1293. } else if(strcmp(argv[argn], "-i") == 0 && argn + 1 < argc) {
  1294. ++argn;
  1295. pidfile = argv[argn];
  1296. } else if(strcmp(argv[argn], "-T") == 0 && argn + 1 < argc) {
  1297. ++argn;
  1298. charset = argv[argn];
  1299. } else if(strcmp(argv[argn], "-L") == 0 && argn + 1 < argc) {
  1300. ++argn;
  1301. language = argv[argn];
  1302. } else if(strcmp(argv[argn], "-P") == 0 && argn + 1 < argc) {
  1303. ++argn;
  1304. p3p = argv[argn];
  1305. } else if(strcmp(argv[argn], "-M") == 0 && argn + 1 < argc) {
  1306. ++argn;
  1307. max_age = atoi(argv[argn]);
  1308. } else if(strcmp(argv[argn], "-DRN") == 0 && argn + 1 < argc) {
  1309. ++argn;
  1310. defaultRealmName = argv[argn];
  1311. } else if(strcmp(argv[argn], "-DRP") == 0 && argn + 1 < argc) {
  1312. ++argn;
  1313. defaultRealmPasswordFile = argv[argn];
  1314. } else if(strcmp(argv[argn], "-DPF") == 0 && argn + 1 < argc) {
  1315. ++argn;
  1316. defaultPageFile = argv[argn];
  1317. } else if(strcmp(argv[argn], "-PNF") == 0 && argn + 1 < argc) {
  1318. ++argn;
  1319. pageNotFoundFile = argv[argn];
  1320. } else if(strcmp(argv[argn], "-ADL") == 0 && argn + 1 < argc) {
  1321. ++argn;
  1322. if(strcmp(argv[argn], "1") == 0 || strcmp(argv[argn], "true") == 0 || strcmp(argv[argn], "TRUE") == 0 || strcmp(argv[argn], "yes") == 0 || strcmp(argv[argn], "YES") == 0) {
  1323. allowDirectoryListing = 1;
  1324. } else {
  1325. allowDirectoryListing = 0;
  1326. }
  1327. } else if(strcmp(argv[argn], "-SP") == 0 && argn + 1 < argc) {
  1328. ++argn;
  1329. sslPort = (unsigned short) atoi(argv[argn]);
  1330. } else {
  1331. usage();
  1332. }
  1333. ++argn;
  1334. }
  1335. if(argn != argc) {
  1336. usage();
  1337. }
  1338. cp = strrchr(argv0, '/');
  1339. if(cp != (char*) 0) {
  1340. ++cp;
  1341. } else {
  1342. cp = argv0;
  1343. }
  1344. openlog(cp, LOG_NDELAY|LOG_PID, LOG_DAEMON);
  1345. if(port == 0) {
  1346. if(sslPort != 0 && do_ssl) {
  1347. port = sslPort;
  1348. sslPort = 0;
  1349. }
  1350. if(do_ssl) {
  1351. port = DEFAULT_HTTPS_PORT;
  1352. } else {
  1353. port = DEFAULT_HTTP_PORT;
  1354. }
  1355. }
  1356. if(getuid() == 0 && user != NULL) {
  1357. pwd = getpwnam(user);
  1358. if(pwd == (struct passwd*) 0) {
  1359. syslog(LOG_CRIT, "unknown user - '%s'", user);
  1360. (void) fprintf(stderr, "%s: unknown user - '%s'\n", argv0, user);
  1361. exit(1);
  1362. }
  1363. uid = pwd->pw_uid;
  1364. gid = pwd->pw_gid;
  1365. }
  1366. if(logfile != (char*) 0) {
  1367. logfp = fopen(logfile, "a");
  1368. if(logfp == (FILE*) 0) {
  1369. syslog(LOG_CRIT, "%s - %m", logfile);
  1370. perror(logfile);
  1371. exit(1);
  1372. }
  1373. if(logfile[0] != '/') {
  1374. syslog(LOG_WARNING, "logfile is not an absolute path, you may not be able to re-open it");
  1375. (void) fprintf(stderr, "%s: logfile is not an absolute path, you may not be able to re-open it\n", argv0);
  1376. }
  1377. if(getuid() == 0) {
  1378. if(fchown(fileno(logfp), uid, gid) < 0) {
  1379. syslog(LOG_WARNING, "fchown logfile - %m");
  1380. perror("fchown logfile");
  1381. }
  1382. }
  1383. }
  1384. lookup_hostname(&host_addr4, &host_addr4s, sizeof(struct sockaddr_in), &gotv4, &gotv4s, &host_addr6, &host_addr6s, sizeof(struct sockaddr_in6), &gotv6, &gotv6s);
  1385. if(hostname == (char*) 0) {
  1386. (void) gethostname(hostname_buf, sizeof(hostname_buf));
  1387. hostname = hostname_buf;
  1388. }
  1389. if(!( gotv4 || gotv4s || gotv6 || gotv6s)) {
  1390. syslog(LOG_CRIT, "can't find any valid address");
  1391. (void) fprintf(stderr, "%s: can't find any valid address\n", argv0);
  1392. exit(1);
  1393. }
  1394. listen6_fd = -1;
  1395. listen6s_fd = -1;
  1396. listen4_fd = -1;
  1397. listen4s_fd = -1;
  1398. if(gotv6) {
  1399. listen6_fd = initialize_listen_socket(&host_addr6);
  1400. }
  1401. if(gotv6s) {
  1402. listen6s_fd = initialize_listen_socket(&host_addr6s);
  1403. }
  1404. if(gotv4) {
  1405. listen4_fd = initialize_listen_socket(&host_addr4);
  1406. }
  1407. if(gotv4s) {
  1408. listen4s_fd = initialize_listen_socket(&host_addr4s);
  1409. }
  1410. if(listen4_fd == -1 && listen6_fd == -1 && listen4s_fd == -1 && listen6s_fd == -1) {
  1411. syslog(LOG_CRIT, "can't bind to any address");
  1412. (void) fprintf(stderr, "%s: can't bind to any address\n", argv0);
  1413. exit(1);
  1414. }
  1415. if(do_ssl) {
  1416. ssl_ctx = SSL_CTX_new(TLSv1_server_method());
  1417. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, 0);
  1418. if(certfile[0] != '\0') {
  1419. if(SSL_CTX_use_certificate_file(ssl_ctx, certfile, SSL_FILETYPE_PEM) != SSL_SUCCESS || SSL_CTX_use_PrivateKey_file(ssl_ctx, certfile, SSL_FILETYPE_PEM) != SSL_SUCCESS) {
  1420. syslog(LOG_CRIT, "can't load certificate and/or private key\n");
  1421. exit(1);
  1422. }
  1423. }
  1424. if(cipher != (char*) 0) {
  1425. if(SSL_CTX_set_cipher_list(ssl_ctx, cipher) <= 0) {
  1426. syslog(LOG_CRIT, "can't load certificate and/or private key\n");
  1427. exit(1);
  1428. }
  1429. }
  1430. }
  1431. if(!debug) {
  1432. if(daemon(1, 0) < 0) {
  1433. syslog(LOG_CRIT, "daemon - %m");
  1434. perror("daemon");
  1435. exit(1);
  1436. }
  1437. } else {
  1438. (void) setsid();
  1439. }
  1440. if(pidfile != (char*) 0) {
  1441. FILE* pidfp = fopen(pidfile, "w");
  1442. if(pidfp == (FILE*) 0) {
  1443. syslog(LOG_CRIT, "%s - %m", pidfile);
  1444. perror(pidfile);
  1445. exit(1);
  1446. }
  1447. (void) fprintf(pidfp, "%d\n", (int) getpid());
  1448. (void) fclose(pidfp);
  1449. }
  1450. tzset();
  1451. if(getuid() == 0 && user != NULL) {
  1452. if(setgroups(0, (gid_t*) 0) < 0) {
  1453. syslog(LOG_CRIT, "setgroups - %m");
  1454. perror("setgroups");
  1455. exit(1);
  1456. }
  1457. if(setgid(gid) < 0) {
  1458. syslog(LOG_CRIT, "setgid - %m");
  1459. perror("setgid");
  1460. exit(1);
  1461. }
  1462. if(initgroups(user, gid ) < 0) {
  1463. syslog(LOG_ERR, "initgroups - %m");
  1464. perror("initgroups");
  1465. }
  1466. }
  1467. if(dir != (char*) 0) {
  1468. if(chdir(dir) < 0) {
  1469. syslog(LOG_CRIT, "chdir - %m");
  1470. perror("chdir");
  1471. exit(1);
  1472. }
  1473. }
  1474. if(getcwd(cwd, sizeof(cwd) - 1) == NULL) { ; }
  1475. if(cwd[strlen(cwd) - 1] != '/') {
  1476. (void) strcat( cwd, "/" );
  1477. }
  1478. if(data_dir != (char*) 0) {
  1479. if(chdir(data_dir) < 0) {
  1480. syslog(LOG_CRIT, "data_dir chdir - %m");
  1481. perror("data_dir chdir");
  1482. exit(1);
  1483. }
  1484. }
  1485. if(getuid() == 0 && user != NULL) {
  1486. if(setuid(uid) < 0) {
  1487. syslog(LOG_CRIT, "setuid - %m");
  1488. perror("setuid");
  1489. exit(1);
  1490. }
  1491. }
  1492. (void) signal(SIGTERM, handle_sigterm);
  1493. (void) signal(SIGINT, handle_sigterm);
  1494. (void) signal(SIGUSR1, handle_sigterm);
  1495. (void) signal(SIGHUP, handle_sighup);
  1496. (void) signal(SIGCHLD, handle_sigchld);
  1497. (void) signal(SIGPIPE, SIG_IGN);
  1498. got_hup = 0;
  1499. init_mime();
  1500. if(hostname == (char*) 0) {
  1501. syslog(LOG_NOTICE, "%.80s starting on port %d", SERVER_SOFTWARE, (int) port);
  1502. } else {
  1503. syslog(LOG_NOTICE, "%.80s starting on %.80s, port %d", SERVER_SOFTWARE, hostname, (int) port);
  1504. }
  1505. for(;;) {
  1506. int is_ssl;
  1507. unsigned short conn_port;
  1508. if(got_hup) {
  1509. reopen_logfile();
  1510. got_hup = 0;
  1511. }
  1512. FD_ZERO(&lfdset);
  1513. maxfd = -1;
  1514. if(listen4_fd != -1) {
  1515. FD_SET(listen4_fd, &lfdset);
  1516. if(listen4_fd > maxfd) {
  1517. maxfd = listen4_fd;
  1518. }
  1519. }
  1520. if(listen4s_fd != -1) {
  1521. FD_SET(listen4s_fd, &lfdset);
  1522. if(listen4s_fd > maxfd) {
  1523. maxfd = listen4s_fd;
  1524. }
  1525. }
  1526. if(listen6_fd != -1) {
  1527. FD_SET(listen6_fd, &lfdset);
  1528. if(listen6_fd > maxfd) {
  1529. maxfd = listen6_fd;
  1530. }
  1531. }
  1532. if(listen6s_fd != -1) {
  1533. FD_SET(listen6s_fd, &lfdset);
  1534. if(listen6s_fd > maxfd) {
  1535. maxfd = listen6s_fd;
  1536. }
  1537. }
  1538. if(select(maxfd + 1, &lfdset, (fd_set*) 0, (fd_set*) 0, (struct timeval*) 0) < 0) {
  1539. if(errno == EINTR || errno == EAGAIN) {
  1540. continue;
  1541. }
  1542. syslog(LOG_CRIT, "select - %m");
  1543. perror("select");
  1544. exit(1);
  1545. }
  1546. is_ssl= 0;
  1547. conn_port = port;
  1548. if(do_ssl) {
  1549. if(sslPort == 0) {
  1550. is_ssl= 1;
  1551. } else if(listen4s_fd != -1 && FD_ISSET(listen4s_fd, &lfdset)) {
  1552. is_ssl = 1;
  1553. conn_port = sslPort;
  1554. } else if(listen6s_fd != -1 && FD_ISSET(listen6s_fd, &lfdset)) {
  1555. is_ssl = 1;
  1556. conn_port = sslPort;
  1557. }
  1558. }
  1559. sz = sizeof(usa);
  1560. if(listen4_fd != -1 && FD_ISSET(listen4_fd, &lfdset)) {
  1561. conn_fd = accept(listen4_fd, &usa.sa, &sz);
  1562. } else if(listen4s_fd != -1 && FD_ISSET(listen4s_fd, &lfdset)) {
  1563. conn_fd = accept(listen4s_fd, &usa.sa, &sz);
  1564. } else if(listen6_fd != -1 && FD_ISSET(listen6_fd, &lfdset)) {
  1565. conn_fd = accept(listen6_fd, &usa.sa, &sz);
  1566. } else if(listen6s_fd != -1 && FD_ISSET(listen6s_fd, &lfdset)) {
  1567. conn_fd = accept(listen6s_fd, &usa.sa, &sz);
  1568. } else {
  1569. syslog(LOG_CRIT, "select failure");
  1570. (void) fprintf(stderr, "%s: select failure\n", argv0);
  1571. exit(1);
  1572. }
  1573. if(conn_fd < 0) {
  1574. if(errno == EINTR || errno == EAGAIN) {
  1575. continue;
  1576. }
  1577. #ifdef EPROTO
  1578. if(errno == EPROTO) {
  1579. continue;
  1580. }
  1581. #endif
  1582. syslog(LOG_CRIT, "accept - %m");
  1583. perror("accept");
  1584. exit(1);
  1585. }
  1586. r = fork();
  1587. if(r < 0) {
  1588. syslog(LOG_CRIT, "fork - %m");
  1589. perror("fork");
  1590. exit(1);
  1591. }
  1592. if(r == 0) {
  1593. client_addr = usa;
  1594. if(listen4_fd != -1) {
  1595. (void) close(listen4_fd);
  1596. }
  1597. if(listen4s_fd != -1) {
  1598. (void) close(listen4s_fd);
  1599. }
  1600. if(listen6_fd != -1) {
  1601. (void) close(listen6_fd);
  1602. }
  1603. if(listen6s_fd != -1) {
  1604. (void) close(listen6s_fd);
  1605. }
  1606. handle_request(is_ssl, conn_port);
  1607. exit(0);
  1608. }
  1609. (void) close(conn_fd);
  1610. }
  1611. }
  1612. static char** make_argp(void) {
  1613. char** argp;
  1614. int argn;
  1615. char* cp1;
  1616. char* cp2;
  1617. argp = (char**) malloc((strlen(query) + 2) * sizeof(char*));
  1618. if(argp == NULL) {
  1619. return NULL;
  1620. }
  1621. argp[0] = strrchr(file, '/');
  1622. if(argp[0] != NULL) {
  1623. ++argp[0];
  1624. } else {
  1625. argp[0] = file;
  1626. }
  1627. argn = 1;
  1628. if(strchr(query, '=') == NULL) {
  1629. for(cp1 = cp2 = query; *cp2 != '\0'; ++cp2) {
  1630. if(*cp2 == '+') {
  1631. *cp2 = '\0';
  1632. strdecode(cp1, cp1);
  1633. argp[argn++] = cp1;
  1634. cp1 = cp2 + 1;
  1635. }
  1636. }
  1637. if(cp2 != cp1) {
  1638. strdecode(cp1, cp1);
  1639. argp[argn++] = cp1;
  1640. }
  1641. }
  1642. argp[argn] = (char*) 0;
  1643. return argp;
  1644. }
  1645. static char** make_envp(int is_ssl, unsigned short conn_port) {
  1646. static char* envp[50];
  1647. int envn;
  1648. char* cp;
  1649. char buf[256];
  1650. envn = 0;
  1651. envp[envn++] = build_env("PATH=%s", CGI_PATH);
  1652. envp[envn++] = build_env("LD_LIBRARY_PATH=%s", CGI_LD_LIBRARY_PATH);
  1653. envp[envn++] = build_env("SERVER_SOFTWARE=%s", SERVER_SOFTWARE);
  1654. envp[envn++] = build_env("WWW_LANGUAGE=%s", language);
  1655. cp = hostname;
  1656. if(cp != (char*) 0) {
  1657. envp[envn++] = build_env("SERVER_NAME=%s", cp);
  1658. }
  1659. envp[envn++] = "GATEWAY_INTERFACE=CGI/1.1";
  1660. envp[envn++] = "SERVER_PROTOCOL=HTTP/1.0";
  1661. (void) snprintf(buf, sizeof(buf), "%d", (int) conn_port);
  1662. envp[envn++] = build_env("SERVER_PORT=%s", buf);
  1663. envp[envn++] = build_env("REQUEST_METHOD=%s", get_method_str(method));
  1664. envp[envn++] = build_env("SCRIPT_NAME=%s", path);
  1665. if(pathinfo != (char*) 0) {
  1666. envp[envn++] = build_env("PATH_INFO=/%s", pathinfo);
  1667. (void) snprintf(buf, sizeof(buf), "%s%s", cwd, pathinfo);
  1668. envp[envn++] = build_env("PATH_TRANSLATED=%s", buf);
  1669. }
  1670. if(query[0] != '\0') {
  1671. envp[envn++] = build_env("QUERY_STRING=%s", query);
  1672. }
  1673. envp[envn++] = build_env("REMOTE_ADDR=%s", ntoa(&client_addr));
  1674. if(referer[0] != '\0') {
  1675. envp[envn++] = build_env("HTTP_REFERER=%s", referer);
  1676. }
  1677. if(useragent[0] != '\0') {
  1678. envp[envn++] = build_env("HTTP_USER_AGENT=%s", useragent);
  1679. }
  1680. if(cookie != (char*) 0) {
  1681. envp[envn++] = build_env("HTTP_COOKIE=%s", cookie);
  1682. }
  1683. if(host != (char*) 0) {
  1684. envp[envn++] = build_env("HTTP_HOST=%s", host);
  1685. }
  1686. if(content_type != (char*) 0) {
  1687. envp[envn++] = build_env("CONTENT_TYPE=%s", content_type);
  1688. }
  1689. if(content_length != -1) {
  1690. (void) snprintf(buf, sizeof(buf), "%lu", (unsigned long) content_length);
  1691. envp[envn++] = build_env("CONTENT_LENGTH=%s", buf);
  1692. }
  1693. if(remoteuser != (char*) 0) {
  1694. envp[envn++] = build_env("REMOTE_USER=%s", remoteuser);
  1695. }
  1696. if(authorization != (char*) 0) {
  1697. envp[envn++] = build_env("AUTH_TYPE=%s", "Basic");
  1698. }
  1699. if(getenv("TZ") != (char*) 0) {
  1700. envp[envn++] = build_env("TZ=%s", getenv("TZ"));
  1701. }
  1702. envp[envn] = (char*) 0;
  1703. return envp;
  1704. }
  1705. static void make_log_entry(void) {
  1706. char* ru;
  1707. char url[500];
  1708. char bytes_str[40];
  1709. time_t now;
  1710. struct tm* t;
  1711. const char* cernfmt_nozone = "%d/%b/%Y:%H:%M:%S";
  1712. char date_nozone[100];
  1713. int zone;
  1714. char sign;
  1715. char date[100];
  1716. if(logfp == (FILE*) 0) {
  1717. return;
  1718. }
  1719. if(protocol == (char*) 0) {
  1720. protocol = "UNKNOWN";
  1721. }
  1722. if(path == (char*) 0) {
  1723. path = "";
  1724. }
  1725. if(remoteuser != (char*) 0) {
  1726. ru = remoteuser;
  1727. } else {
  1728. ru = "-";
  1729. }
  1730. now = time((time_t*) 0);
  1731. (void) snprintf(url, sizeof(url), "%s", path);
  1732. if(bytes >= 0) {
  1733. (void) snprintf(bytes_str, sizeof(bytes_str), "%lld", (long long int) bytes );
  1734. } else {
  1735. (void) strcpy(bytes_str, "-");
  1736. }
  1737. t = localtime(&now);
  1738. (void) strftime(date_nozone, sizeof(date_nozone), cernfmt_nozone, t);
  1739. zone = t->tm_gmtoff / 60L;
  1740. if(zone >= 0) {
  1741. sign = '+';
  1742. } else {
  1743. sign = '-';
  1744. zone = -zone;
  1745. }
  1746. zone = (zone / 60) * 100 + zone % 60;
  1747. (void) snprintf(date, sizeof(date), "%s %c%04d", date_nozone, sign, zone);
  1748. (void) fprintf(logfp, "%.80s - %.80s [%s] \"%.80s %.200s %.80s\" %d %s \"%.200s\" \"%.200s\"\n", ntoa(&client_addr), ru, date, get_method_str(method), url, protocol, status, bytes_str, referer, useragent);
  1749. (void) fflush(logfp);
  1750. }
  1751. static ssize_t my_read(char* buf, size_t size, int is_ssl) {
  1752. if(is_ssl) {
  1753. return SSL_read(ssl, buf, size);
  1754. } else {
  1755. return read(conn_fd, buf, size);
  1756. }
  1757. }
  1758. static ssize_t my_write(char* buf, size_t size, int is_ssl) {
  1759. if(is_ssl) {
  1760. return SSL_write(ssl, buf, size);
  1761. } else {
  1762. return write(conn_fd, buf, size);
  1763. }
  1764. }
  1765. static void no_value_required(char* name, char* value) {
  1766. if(value != (char*) 0) {
  1767. (void) fprintf(stderr, "%s: no value required for %s option\n", argv0, name);
  1768. exit(1);
  1769. }
  1770. }
  1771. static char* ntoa(usockaddr* usaP) {
  1772. static char str[200];
  1773. if(getnameinfo(&usaP->sa, sockaddr_len(usaP), str, sizeof(str), 0, 0, NI_NUMERICHOST) != 0) {
  1774. str[0] = '?';
  1775. str[1] = '\0';
  1776. } else if(IN6_IS_ADDR_V4MAPPED(&usaP->sa_in6.sin6_addr) && strncmp(str, "::ffff:", 7) == 0) {
  1777. (void) strcpy(str, &str[7]);
  1778. }
  1779. return str;
  1780. }
  1781. static void post_post_garbage_hack(int is_ssl) {
  1782. char buf[2];
  1783. if(is_ssl) {
  1784. return;
  1785. }
  1786. set_ndelay(conn_fd);
  1787. if(read(conn_fd, buf, sizeof(buf)) < 0) { ; };
  1788. clear_ndelay(conn_fd);
  1789. }
  1790. static void read_config(char* filename) {
  1791. FILE* fp;
  1792. char line[10000];
  1793. char* cp;
  1794. char* cp2;
  1795. char* name;
  1796. char* value;
  1797. fp = fopen(filename, "r");
  1798. if(fp == (FILE*) 0) {
  1799. syslog(LOG_CRIT, "%s - %m", filename);
  1800. perror(filename);
  1801. exit(1);
  1802. }
  1803. while(fgets(line, sizeof(line), fp) != (char*) 0) {
  1804. if((cp = strchr(line, '#')) != (char*) 0) {
  1805. *cp = '\0';
  1806. }
  1807. cp = line;
  1808. cp += strspn(cp, " \t\012\015");
  1809. while(*cp != '\0') {
  1810. cp2 = cp + strcspn(cp, " \t\012\015");
  1811. while(*cp2 == ' ' || *cp2 == '\t' || *cp2 == '\012' || *cp2 == '\015') {
  1812. *cp2++ = '\0';
  1813. }
  1814. name = cp;
  1815. value = strchr(name, '=');
  1816. if(value != (char*) 0) {
  1817. *value++ = '\0';
  1818. }
  1819. if(strcasecmp(name, "debug") == 0) {
  1820. no_value_required(name, value);
  1821. debug = 1;
  1822. } else if(strcasecmp(name, "port") == 0) {
  1823. value_required(name, value);
  1824. port = (unsigned short) atoi(value);
  1825. } else if(strcasecmp(name, "dir") == 0) {
  1826. value_required(name, value);
  1827. dir = e_strdup(value);
  1828. } else if(strcasecmp(name, "data_dir") == 0) {
  1829. value_required(name, value);
  1830. data_dir = e_strdup(value);
  1831. } else if(strcasecmp(name, "user") == 0) {
  1832. value_required(name, value);
  1833. user = e_strdup(value);
  1834. } else if(strcasecmp(name, "cgipat") == 0) {
  1835. value_required(name, value);
  1836. cgi_pattern = e_strdup(value);
  1837. } else if(strcasecmp(name, "urlpat") == 0) {
  1838. value_required(name, value);
  1839. url_pattern = e_strdup(value);
  1840. } else if(strcasecmp(name, "noemptyreferers") == 0) {
  1841. value_required(name, value);
  1842. no_empty_referers = 1;
  1843. } else if(strcasecmp(name, "localpat") == 0) {
  1844. value_required(name, value);
  1845. local_pattern = e_strdup(value);
  1846. } else if(strcasecmp(name, "host") == 0) {
  1847. value_required(name, value);
  1848. hostname = e_strdup(value);
  1849. } else if(strcasecmp(name, "logfile") == 0) {
  1850. value_required(name, value);
  1851. logfile = e_strdup(value);
  1852. } else if(strcasecmp(name, "pidfile") == 0) {
  1853. value_required(name, value);
  1854. pidfile = e_strdup(value);
  1855. } else if(strcasecmp(name, "charset") == 0) {
  1856. value_required(name, value);
  1857. charset = e_strdup(value);
  1858. } else if(strcasecmp(name, "p3p") == 0) {
  1859. value_required(name, value);
  1860. p3p = e_strdup(value);
  1861. } else if(strcasecmp(name, "max_age") == 0) {
  1862. value_required(name, value);
  1863. max_age = atoi(value);
  1864. } else if(strcasecmp(name, "default_realm_name") == 0) {
  1865. value_required(name, value);
  1866. defaultRealmName = e_strdup(value);
  1867. } else if(strcasecmp(name, "default_realm_password_file") == 0) {
  1868. value_required(name, value);
  1869. defaultRealmPasswordFile = e_strdup(value);
  1870. } else if(strcasecmp(name, "default_page_file") == 0) {
  1871. value_required(name, value);
  1872. defaultPageFile = e_strdup(value);
  1873. } else if(strcasecmp(name, "page_not_found_file") == 0) {
  1874. value_required(name, value);
  1875. pageNotFoundFile = e_strdup(value);
  1876. } else if(strcasecmp(name, "allow_directory_listing") == 0) {
  1877. value_required(name, value);
  1878. if(strcmp(value, "1") == 0 || strcmp(value, "true") == 0 || strcmp(value, "TRUE") == 0 || strcmp(value, "yes") == 0 || strcmp(value, "YES") == 0) {
  1879. allowDirectoryListing = 1;
  1880. } else {
  1881. allowDirectoryListing = 0;
  1882. }
  1883. } else if(strcasecmp(name, "ssl") == 0) {
  1884. no_value_required(name, value);
  1885. do_ssl = 1;
  1886. } else if(strcasecmp(name, "certfile") == 0) {
  1887. value_required(name, value);
  1888. certfile = e_strdup(value);
  1889. } else if(strcasecmp(name, "cipher") == 0) {
  1890. value_required(name, value);
  1891. cipher = e_strdup(value);
  1892. } else {
  1893. (void) fprintf(stderr, "%s: unknown config option '%s'\n", argv0, name);
  1894. exit(1);
  1895. }
  1896. cp = cp2;
  1897. cp += strspn(cp, " \t\012\015");
  1898. }
  1899. }
  1900. (void) fclose(fp);
  1901. }
  1902. static int really_check_referer(void) {
  1903. char* cp1;
  1904. char* cp2;
  1905. char* cp3;
  1906. char* refhost;
  1907. char *lp;
  1908. if(referer == (char*) 0 || referer[0] == '\0' || (cp1 = strstr(referer, "//")) == (char*) 0) {
  1909. if(no_empty_referers && match(url_pattern, path)) {
  1910. return 0;
  1911. } else {
  1912. return 1;
  1913. }
  1914. }
  1915. cp1 += 2;
  1916. for(cp2 = cp1; *cp2 != '/' && *cp2 != ':' && *cp2 != '\0'; ++cp2) {
  1917. continue;
  1918. }
  1919. refhost = (char*) e_malloc(cp2 - cp1 + 1);
  1920. for(cp3 = refhost; cp1 < cp2; ++cp1, ++cp3) {
  1921. if(isupper(*cp1)) {
  1922. *cp3 = tolower(*cp1);
  1923. } else {
  1924. *cp3 = *cp1;
  1925. }
  1926. }
  1927. *cp3 = '\0';
  1928. if(local_pattern != (char*) 0) {
  1929. lp = local_pattern;
  1930. } else {
  1931. lp = hostname;
  1932. if(lp == (char*) 0) {
  1933. return 1;
  1934. }
  1935. }
  1936. if(!match(lp, refhost) && match(url_pattern, path)) {
  1937. return 0;
  1938. } else {
  1939. return 1;
  1940. }
  1941. }
  1942. static void reopen_logfile(void) {
  1943. if(logfp != (FILE*) 0) {
  1944. (void) fclose(logfp);
  1945. logfp = (FILE*) 0;
  1946. }
  1947. if(logfile != (char*) 0) {
  1948. syslog(LOG_NOTICE, "re-opening logfile");
  1949. logfp = fopen(logfile, "a");
  1950. if(logfp == (FILE*) 0) {
  1951. syslog(LOG_CRIT, "%s - %m", logfile);
  1952. perror(logfile);
  1953. exit(1);
  1954. }
  1955. }
  1956. }
  1957. static void send_authenticate(char* realm, int is_ssl) {
  1958. char header[10000];
  1959. (void) snprintf(header, sizeof(header), "WWW-Authenticate: Basic realm=\"%s\"", realm);
  1960. send_error(401, "Unauthorized", header, "Authorization required.", is_ssl);
  1961. }
  1962. static void send_error(int s, char* title, char* extra_header, char* text, int is_ssl) {
  1963. add_headers(s, title, extra_header, "", "text/html; charset=%s", (off_t) -1, (time_t) -1);
  1964. send_error_body(s, title, text);
  1965. send_error_tail();
  1966. send_response(is_ssl);
  1967. SSL_free(ssl);
  1968. exit(1);
  1969. }
  1970. static void send_error_body(int s, char* title, char* text) {
  1971. char filename[1000];
  1972. char buf[10000];
  1973. int buflen;
  1974. (void) snprintf(filename, sizeof(filename), "%s/err%d.html", ERR_DIR, s);
  1975. if(send_error_file(filename)) {
  1976. return;
  1977. }
  1978. buflen = snprintf(buf, sizeof(buf), "<html>\n<head><title>Error %d - %s</title></head>\n<body bgcolor=\"#cc9999\" text=\"#000000\">\n<h2>Error %d</h2>\n", s, title, s);
  1979. add_to_response(buf, buflen);
  1980. buflen = snprintf(buf, sizeof(buf), "%s\n", text);
  1981. add_to_response(buf, buflen);
  1982. }
  1983. static int send_error_file(char* filename) {
  1984. FILE* fp;
  1985. char buf[1000];
  1986. size_t r;
  1987. fp = fopen(filename, "r");
  1988. if(fp == (FILE*) 0) {
  1989. return 0;
  1990. }
  1991. for(;;) {
  1992. r = fread(buf, 1, sizeof(buf), fp);
  1993. if(r == 0) {
  1994. break;
  1995. }
  1996. add_to_response(buf, r);
  1997. }
  1998. (void) fclose(fp);
  1999. return 1;
  2000. }
  2001. static void send_error_tail(void) {
  2002. char buf[500];
  2003. int buflen;
  2004. if(match("**MSIE**", useragent)) {
  2005. int n;
  2006. buflen = snprintf(buf, sizeof(buf), "<!--\n");
  2007. add_to_response(buf, buflen);
  2008. for(n = 0; n < 6; ++n) {
  2009. buflen = snprintf(buf, sizeof(buf), "Padding so that MSIE deigns to show this error instead of its own canned one.\n");
  2010. add_to_response(buf, buflen);
  2011. }
  2012. buflen = snprintf(buf, sizeof(buf), "-->\n");
  2013. add_to_response(buf, buflen);
  2014. }
  2015. buflen = snprintf(buf, sizeof(buf), "<hr>\n%s\n</body>\n</html>\n", SERVER_SOFTWARE);
  2016. add_to_response(buf, buflen);
  2017. }
  2018. static void send_redirect(char* extra_header, char* hostname, char* new_location, int is_ssl) {
  2019. char extra_header_buf[5000];
  2020. const char *sep = new_location[0] == '/' ? "" : "/";
  2021. const char *proto = is_ssl == 1 ? "https://" : "http://";
  2022. extra_header = extra_header == NULL ? "" : extra_header;
  2023. if(strcmp(extra_header, "") == 0) {
  2024. sprintf(extra_header_buf, "Location: %s%s%s%s", proto, hostname, sep, new_location);
  2025. } else {
  2026. sprintf(extra_header_buf, "%s\r\nLocation: %s%s%s%s", extra_header, proto, hostname, sep, new_location);
  2027. }
  2028. add_headers(301, "Moved Permanently", extra_header_buf, "", "text/html; charset=%s", (off_t) -1, (time_t) -1);
  2029. send_error_body(301, "Moved Permanently", "Moved Permanently");
  2030. send_error_tail();
  2031. send_response(is_ssl);
  2032. SSL_free(ssl);
  2033. exit(1);
  2034. }
  2035. static void send_response(is_ssl) {
  2036. (void) my_write(response, response_len, is_ssl);
  2037. }
  2038. static void send_via_write(int fd, off_t size, int is_ssl) {
  2039. if(size <= SIZE_T_MAX) {
  2040. size_t size_size = (size_t) size;
  2041. void* ptr = mmap(0, size_size, PROT_READ, MAP_PRIVATE, fd, 0);
  2042. if(ptr != (void*) -1) {
  2043. (void) my_write(ptr, size_size, is_ssl);
  2044. (void) munmap(ptr, size_size);
  2045. }
  2046. #ifdef MADV_SEQUENTIAL
  2047. (void) madvise(ptr, size_size, MADV_SEQUENTIAL);
  2048. #endif
  2049. } else {
  2050. char buf[30000];
  2051. ssize_t r, r2;
  2052. for(;;) {
  2053. r = read(fd, buf, sizeof(buf));
  2054. if(r < 0 && (errno == EINTR || errno == EAGAIN)) {
  2055. sleep(1);
  2056. continue;
  2057. }
  2058. if(r <= 0) {
  2059. return;
  2060. }
  2061. for(;;) {
  2062. r2 = my_write(buf, r, is_ssl);
  2063. if(r2 < 0 && (errno == EINTR || errno == EAGAIN)) {
  2064. sleep(1);
  2065. continue;
  2066. }
  2067. if(r2 != r) {
  2068. return;
  2069. }
  2070. break;
  2071. }
  2072. }
  2073. }
  2074. }
  2075. static void set_ndelay(int fd) {
  2076. int flags, newflags;
  2077. flags = fcntl(fd, F_GETFL, 0);
  2078. if(flags != -1) {
  2079. newflags = flags | (int) O_NDELAY;
  2080. if(newflags != flags) {
  2081. (void) fcntl(fd, F_SETFL, newflags);
  2082. }
  2083. }
  2084. }
  2085. static int sockaddr_check(usockaddr* usaP) {
  2086. switch (usaP->sa.sa_family) {
  2087. case AF_INET:
  2088. return 1;
  2089. case AF_INET6:
  2090. return 1;
  2091. default:
  2092. return 0;
  2093. }
  2094. }
  2095. static size_t sockaddr_len(usockaddr* usaP) {
  2096. switch(usaP->sa.sa_family) {
  2097. case AF_INET:
  2098. return sizeof(struct sockaddr_in);
  2099. case AF_INET6:
  2100. return sizeof(struct sockaddr_in6);
  2101. default:
  2102. return 0;
  2103. }
  2104. }
  2105. static void start_request(void) {
  2106. request_size = 0;
  2107. request_idx = 0;
  2108. }
  2109. static void start_response(void) {
  2110. response_size = 0;
  2111. }
  2112. static void strdecode(char* to, char* from) {
  2113. for(; *from != '\0'; ++to, ++from) {
  2114. if(from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2])) {
  2115. *to = hexit(from[1]) * 16 + hexit(from[2]);
  2116. from += 2;
  2117. } else {
  2118. *to = *from;
  2119. }
  2120. }
  2121. *to = '\0';
  2122. }
  2123. static void strencode(char* to, size_t tosize, const char* from) {
  2124. int tolen;
  2125. for(tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from) {
  2126. if(isalnum(*from) || strchr("/_.-~", *from) != (char*) 0) {
  2127. *to = *from;
  2128. ++to;
  2129. ++tolen;
  2130. } else {
  2131. (void) sprintf(to, "%%%02x", (int) *from & 0xff);
  2132. to += 3;
  2133. tolen += 3;
  2134. }
  2135. }
  2136. *to = '\0';
  2137. }
  2138. static void usage(void) {
  2139. (void) fprintf(stderr, "Usage: %s [-C configfile] [-D] [-S use ssl, if no ssl port is specified all connections will be SSL] [-E certfile] [-SP ssl port] [-Y cipher] [-p port] [-d dir] [-dd data_dir] [-c cgipat] [-u user] [-h hostname] [-l logfile] [-i pidfile] [-T charset] [-L language] [-P P3P] [-M maxage] [-DRN default realm name] [-DRP default realm password file] [-DPF default page file] [-PNF Page to load when 404 Not Found error occurs] \n", argv0);
  2140. exit(1);
  2141. }
  2142. static void value_required(char* name, char* value) {
  2143. if(value == (char*) 0) {
  2144. (void) fprintf(stderr, "%s: value required for %s option\n", argv0, name);
  2145. exit(1);
  2146. }
  2147. }