You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1356 lines
28 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /******************************************************************
  2. * $Id: nanohttp-server.c,v 1.62 2006/07/09 16:24:19 snowdrop Exp $
  3. *
  4. * CSOAP Project: A http client/server library in C
  5. * Copyright (C) 2003 Ferhat Ayaz
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Library General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Library General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public
  18. * License along with this library; if not, write to the
  19. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  20. * Boston, MA 02111-1307, USA.
  21. *
  22. * Email: ayaz@jprogrammer.net
  23. ******************************************************************/
  24. #ifdef HAVE_CONFIG_H
  25. #include <config.h>
  26. #endif
  27. #ifdef HAVE_SYS_SELECT_H
  28. #include <sys/select.h>
  29. #endif
  30. #ifdef HAVE_SOCKET_H
  31. #include <sys/socket.h>
  32. #endif
  33. #ifdef HAVE_SYS_TIME_H
  34. #include <sys/time.h>
  35. #endif
  36. #ifdef HAVE_SYS_TYPES_H
  37. #include <sys/types.h>
  38. #endif
  39. #ifdef HAVE_STDIO_H
  40. #include <stdio.h>
  41. #endif
  42. #ifdef HAVE_STDLIB_H
  43. #include <stdlib.h>
  44. #endif
  45. #ifdef HAVE_SIGNAL_H
  46. #include <signal.h>
  47. #endif
  48. #ifdef HAVE_STRING_H
  49. #include <string.h>
  50. #endif
  51. #ifdef HAVE_UNISTD_H
  52. #include <unistd.h>
  53. #endif
  54. #ifdef HAVE_ERRNO_H
  55. #include <errno.h>
  56. #endif
  57. #ifdef HAVE_PTHREAD_H
  58. #include <pthread.h>
  59. #endif
  60. #ifdef HAVE_PROCESS_H
  61. #include <process.h>
  62. #endif
  63. #ifdef MEM_DEBUG
  64. #include <utils/alloc.h>
  65. #endif
  66. #include "nanohttp-logging.h"
  67. #include "nanohttp-server.h"
  68. #include "nanohttp-base64.h"
  69. #include "nanohttp-ssl.h"
  70. typedef struct _conndata
  71. {
  72. volatile int flag;
  73. hsocket_t sock;
  74. #ifdef WIN32
  75. HANDLE tid;
  76. #else
  77. pthread_t tid;
  78. pthread_attr_t attr;
  79. #endif
  80. time_t atime;
  81. }
  82. conndata_t;
  83. #define CONNECTION_FREE 0
  84. #define CONNECTION_IN_USE 1
  85. /*
  86. * -----------------------------------------------------
  87. * nano httpd
  88. * internally globals
  89. * -----------------------------------------------------
  90. */
  91. static volatile int _httpd_run = 1;
  92. static hsocket_t _httpd_socket;
  93. static int _httpd_port = 10000;
  94. static int _httpd_max_connections = 20;
  95. static int _httpd_timeout = 10;
  96. static hservice_t *_httpd_services_default = NULL;
  97. static hservice_t *_httpd_services_head = NULL;
  98. static hservice_t *_httpd_services_tail = NULL;
  99. static conndata_t *_httpd_connection;
  100. static int _httpd_enable_service_list = 0;
  101. static int _httpd_enable_statistics = 0;
  102. #ifdef WIN32
  103. static DWORD _httpd_terminate_signal = CTRL_C_EVENT;
  104. static int _httpd_max_idle = 120;
  105. static void WSAReaper(void *x);
  106. HANDLE _httpd_connection_lock;
  107. LPCTSTR _httpd_connection_lock_str;
  108. #define strncasecmp(s1, s2, num) strncmp(s1, s2, num)
  109. #define snprintf(buffer, num, s1, s2) sprintf(buffer, s1,s2)
  110. #else
  111. static int _httpd_terminate_signal = SIGINT;
  112. static sigset_t thrsigset;
  113. static pthread_mutex_t _httpd_connection_lock;
  114. #endif
  115. static void
  116. _httpd_parse_arguments(int argc, char **argv)
  117. {
  118. int i;
  119. for (i = 1; i < argc; i++)
  120. {
  121. if (!strcmp(argv[i - 1], NHTTPD_ARG_PORT))
  122. {
  123. _httpd_port = atoi(argv[i]);
  124. }
  125. else if (!strcmp(argv[i - 1], NHTTPD_ARG_TERMSIG))
  126. {
  127. _httpd_terminate_signal = atoi(argv[i]);
  128. }
  129. else if (!strcmp(argv[i - 1], NHTTPD_ARG_MAXCONN))
  130. {
  131. _httpd_max_connections = atoi(argv[i]);
  132. }
  133. else if (!strcmp(argv[i - 1], NHTTPD_ARG_TIMEOUT))
  134. {
  135. _httpd_timeout = atoi(argv[i]);
  136. }
  137. }
  138. log_verbose2("socket bind to port '%d'", _httpd_port);
  139. return;
  140. }
  141. static void
  142. _httpd_connection_slots_init(void)
  143. {
  144. int i;
  145. #ifdef WIN32
  146. _httpd_connection_lock = CreateMutex( NULL, TRUE, _httpd_connection_lock_str );
  147. #else
  148. pthread_mutex_init(&_httpd_connection_lock, NULL);
  149. #endif
  150. _httpd_connection = calloc(_httpd_max_connections, sizeof(conndata_t));
  151. for (i = 0; i < _httpd_max_connections; i++)
  152. hsocket_init(&(_httpd_connection[i].sock));
  153. return;
  154. }
  155. static void
  156. _httpd_register_builtin_services(void)
  157. {
  158. if (_httpd_enable_service_list)
  159. ; /* httpd_register("/httpd/services",
  160. _httpd_list_services); */
  161. if (_httpd_enable_statistics)
  162. ; /* httpd_register("/httpd/statistics",
  163. _httpd_statistics); */
  164. return;
  165. }
  166. /*
  167. * -----------------------------------------------------
  168. * FUNCTION: httpd_init
  169. * NOTE: This will be called from soap_server_init_args()
  170. * -----------------------------------------------------
  171. */
  172. herror_t
  173. httpd_init(int argc, char *argv[])
  174. {
  175. herror_t status;
  176. _httpd_parse_arguments(argc, argv);
  177. if ((status = hsocket_module_init(argc, argv)) != H_OK)
  178. return status;
  179. log_verbose2("socket bind to port '%d'", _httpd_port);
  180. _httpd_connection_slots_init();
  181. _httpd_register_builtin_services();
  182. #ifdef WIN32
  183. /*
  184. if (_beginthread (WSAReaper, 0, NULL) == -1) { log_error1 ("Winsock
  185. reaper thread failed to start"); return herror_new("httpd_init",
  186. THREAD_BEGIN_ERROR, "_beginthread() failed while starting WSAReaper"); }
  187. */
  188. #endif
  189. if ((status = hsocket_init(&_httpd_socket)) != H_OK)
  190. {
  191. log_error2("hsocket_init failed (%s)", herror_message(status));
  192. return status;
  193. }
  194. return hsocket_bind(&_httpd_socket, _httpd_port);
  195. }
  196. /*
  197. * -----------------------------------------------------
  198. * FUNCTION: httpd_register
  199. * -----------------------------------------------------
  200. */
  201. int
  202. httpd_register_secure(const char *ctx, httpd_service func, httpd_auth auth)
  203. {
  204. hservice_t *service;
  205. if (!(service = (hservice_t *) malloc(sizeof(hservice_t))))
  206. {
  207. log_error2("malloc failed (%s)", strerror(errno));
  208. return -1;
  209. }
  210. service->next = NULL;
  211. service->auth = auth;
  212. service->func = func;
  213. strcpy(service->ctx, ctx);
  214. log_verbose3("register service:t(%p):%s", service, SAVE_STR(ctx));
  215. if (_httpd_services_head == NULL)
  216. {
  217. _httpd_services_head = _httpd_services_tail = service;
  218. }
  219. else
  220. {
  221. _httpd_services_tail->next = service;
  222. _httpd_services_tail = service;
  223. }
  224. return 1;
  225. }
  226. int
  227. httpd_register(const char *ctx, httpd_service service)
  228. {
  229. return httpd_register_secure(ctx, service, NULL);
  230. }
  231. int
  232. httpd_register_default_secure(const char *ctx, httpd_service service,
  233. httpd_auth auth)
  234. {
  235. int ret;
  236. ret = httpd_register_secure(ctx, service, auth);
  237. /* XXX: this is broken, but working */
  238. _httpd_services_default = _httpd_services_tail;
  239. return ret;
  240. }
  241. int
  242. httpd_register_default(const char *ctx, httpd_service service)
  243. {
  244. return httpd_register_default_secure(ctx, service, NULL);
  245. }
  246. int
  247. httpd_get_port(void)
  248. {
  249. return _httpd_port;
  250. }
  251. int
  252. httpd_get_timeout(void)
  253. {
  254. return _httpd_timeout;
  255. }
  256. void
  257. httpd_set_timeout(int t)
  258. {
  259. _httpd_timeout = t;
  260. }
  261. const char *
  262. httpd_get_protocol(void)
  263. {
  264. return hssl_enabled()? "https" : "http";
  265. }
  266. /*--------------------------------------------------
  267. FUNCTION: httpd_get_conncount
  268. ----------------------------------------------------*/
  269. int
  270. httpd_get_conncount(void)
  271. {
  272. int i;
  273. int c=0;
  274. for (i = 0;i<_httpd_max_connections; i++)
  275. {
  276. if (_httpd_connection[i].flag == CONNECTION_IN_USE)
  277. {
  278. c++;
  279. }
  280. }
  281. return c;
  282. }
  283. /*
  284. * -----------------------------------------------------
  285. * FUNCTION: httpd_services
  286. * -----------------------------------------------------
  287. */
  288. hservice_t *
  289. httpd_services(void)
  290. {
  291. return _httpd_services_head;
  292. }
  293. /*
  294. * -----------------------------------------------------
  295. * FUNCTION: httpd_services
  296. * -----------------------------------------------------
  297. */
  298. static void
  299. hservice_free(hservice_t * service)
  300. {
  301. free(service);
  302. return;
  303. }
  304. /*
  305. * -----------------------------------------------------
  306. * FUNCTION: httpd_find_service
  307. * -----------------------------------------------------
  308. */
  309. static hservice_t *
  310. httpd_find_service(const char *ctx)
  311. {
  312. hservice_t *cur = _httpd_services_head;
  313. while (cur != NULL)
  314. {
  315. if (!strcmp(cur->ctx, ctx))
  316. {
  317. return cur;
  318. }
  319. cur = cur->next;
  320. }
  321. return _httpd_services_default;
  322. }
  323. /*
  324. * -----------------------------------------------------
  325. * FUNCTION: httpd_response_set_content_type
  326. * -----------------------------------------------------
  327. */
  328. void
  329. httpd_response_set_content_type(httpd_conn_t * res, const char *content_type)
  330. {
  331. strncpy(res->content_type, content_type, 25);
  332. return;
  333. }
  334. /*
  335. * -----------------------------------------------------
  336. * FUNCTION: httpd_response_send_header
  337. * -----------------------------------------------------
  338. */
  339. herror_t
  340. httpd_send_header(httpd_conn_t * res, int code, const char *text)
  341. {
  342. struct tm stm;
  343. time_t nw;
  344. char buffer[255];
  345. char header[1024];
  346. hpair_t *cur;
  347. herror_t status;
  348. /* set status code */
  349. sprintf(header, "HTTP/1.1 %d %s\r\n", code, text);
  350. /* set date */
  351. nw = time(NULL);
  352. localtime_r(&nw, &stm);
  353. strftime(buffer, 255, "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &stm);
  354. strcat(header, buffer);
  355. /* set content-type */
  356. /*
  357. * if (res->content_type[0] == '\0') { strcat(header, "Content-Type:
  358. * text/html\r\n"); } else { sprintf(buffer, "Content-Type: %s\r\n",
  359. * res->content_type); strcat(header, buffer); }
  360. */
  361. /* set server name */
  362. strcat(header, "Server: Nano HTTPD library\r\n");
  363. /* set _httpd_connection status */
  364. /* strcat (header, "Connection: close\r\n"); */
  365. /* add pairs */
  366. for (cur = res->header; cur; cur = cur->next)
  367. {
  368. sprintf(buffer, "%s: %s\r\n", cur->key, cur->value);
  369. strcat(header, buffer);
  370. }
  371. /* set end of header */
  372. strcat(header, "\r\n");
  373. /* send header */
  374. if ((status = hsocket_nsend(res->sock, header, strlen(header))) != H_OK)
  375. return status;
  376. res->out = http_output_stream_new(res->sock, res->header);
  377. return H_OK;
  378. }
  379. herror_t
  380. httpd_send_internal_error(httpd_conn_t * conn, const char *errmsg)
  381. {
  382. const char *template1 =
  383. "<html><body><h3>Error!</h3><hr> Message: '%s' </body></html>\r\n";
  384. char buffer[4064];
  385. char buflen[5];
  386. sprintf(buffer, template1, errmsg);
  387. snprintf(buflen, 5, "%d", strlen(buffer));
  388. httpd_set_header(conn, HEADER_CONTENT_LENGTH, buflen);
  389. httpd_send_header(conn, 500, "INTERNAL");
  390. return http_output_stream_write_string(conn->out, buffer);
  391. }
  392. /*
  393. * -----------------------------------------------------
  394. * FUNCTION: httpd_request_print
  395. * -----------------------------------------------------
  396. */
  397. static void
  398. httpd_request_print(hrequest_t * req)
  399. {
  400. hpair_t *pair;
  401. log_verbose1("++++++ Request +++++++++");
  402. log_verbose2(" Method : '%s'",
  403. (req->method == HTTP_REQUEST_POST) ? "POST" : "GET");
  404. log_verbose2(" Path : '%s'", req->path);
  405. log_verbose2(" Spec : '%s'",
  406. (req->version == HTTP_1_0) ? "HTTP/1.0" : "HTTP/1.1");
  407. log_verbose1(" Parsed query string :");
  408. for (pair = req->query; pair; pair = pair->next)
  409. log_verbose3(" %s = '%s'", pair->key, pair->value);
  410. log_verbose1(" Parsed header :");
  411. for (pair = req->header; pair; pair = pair->next)
  412. log_verbose3(" %s = '%s'", pair->key, pair->value);
  413. log_verbose1("++++++++++++++++++++++++");
  414. return;
  415. }
  416. httpd_conn_t *
  417. httpd_new(hsocket_t * sock)
  418. {
  419. httpd_conn_t *conn;
  420. if (!(conn = (httpd_conn_t *) malloc(sizeof(httpd_conn_t))))
  421. {
  422. log_error2("malloc failed (%s)", strerror(errno));
  423. return NULL;
  424. }
  425. conn->sock = sock;
  426. conn->out = NULL;
  427. conn->content_type[0] = '\0';
  428. conn->header = NULL;
  429. return conn;
  430. }
  431. void
  432. httpd_free(httpd_conn_t * conn)
  433. {
  434. if (!conn)
  435. return;
  436. if (conn->out)
  437. http_output_stream_free(conn->out);
  438. if (conn->header)
  439. hpairnode_free_deep(conn->header);
  440. free(conn);
  441. return;
  442. }
  443. void
  444. do_req_timeout(int signum)
  445. {
  446. /*
  447. struct sigaction req_timeout;
  448. memset(&req_timeout, 0, sizeof(&req_timeout));
  449. req_timeout.sa_handler=SIG_IGN;
  450. sigaction(SIGALRM, &req_timeout, NULL);
  451. */
  452. /* XXX this is not real pretty, is there a better way? */
  453. log_verbose1("Thread timeout.");
  454. #ifdef WIN32
  455. _endthread();
  456. #else
  457. pthread_exit(0);
  458. #endif
  459. }
  460. static int
  461. _httpd_decode_authorization(const char *value, char **user, char **pass)
  462. {
  463. unsigned char *tmp, *tmp2;
  464. size_t len;
  465. len = strlen(value) * 2;
  466. if (!(tmp = (char *) calloc(1, len)))
  467. {
  468. log_error2("calloc failed (%s)", strerror(errno));
  469. return -1;
  470. }
  471. value = strstr(value, " ") + 1;
  472. log_verbose2("Authorization (base64) = \"%s\"", value);
  473. base64_decode(value, tmp);
  474. log_verbose2("Authorization (ascii) = \"%s\"", tmp);
  475. if ((tmp2 = strstr(tmp, ":")))
  476. {
  477. *tmp2++ = '\0';
  478. *pass = strdup(tmp2);
  479. }
  480. else
  481. {
  482. *pass = strdup("");
  483. }
  484. *user = strdup(tmp);
  485. free(tmp);
  486. return 0;
  487. }
  488. static int
  489. _httpd_authenticate_request(hrequest_t * req, httpd_auth auth)
  490. {
  491. char *user, *pass;
  492. char *authorization;
  493. int ret;
  494. if (!auth)
  495. return 1;
  496. if (!
  497. (authorization =
  498. hpairnode_get_ignore_case(req->header, HEADER_AUTHORIZATION)))
  499. {
  500. log_debug2("%s header not set", HEADER_AUTHORIZATION);
  501. return 0;
  502. }
  503. if (_httpd_decode_authorization(authorization, &user, &pass))
  504. {
  505. log_error1("httpd_base64_decode_failed");
  506. return 0;
  507. }
  508. if ((ret = auth(req, user, pass)))
  509. log_debug2("Access granted for user=\"%s\"", user);
  510. else
  511. log_info2("Authentication failed for user=\"%s\"", user);
  512. free(user);
  513. free(pass);
  514. return ret;
  515. }
  516. /*
  517. * -----------------------------------------------------
  518. * FUNCTION: httpd_session_main
  519. * -----------------------------------------------------
  520. */
  521. #ifdef WIN32
  522. static unsigned _stdcall
  523. httpd_session_main(void *data)
  524. #else
  525. static void *
  526. httpd_session_main(void *data)
  527. #endif
  528. {
  529. hrequest_t *req; /* only for test */
  530. conndata_t *conn;
  531. httpd_conn_t *rconn;
  532. hservice_t *service;
  533. herror_t status;
  534. int done;
  535. conn = (conndata_t *) data;
  536. log_verbose2("starting new httpd session on socket %d", conn->sock);
  537. rconn = httpd_new(&(conn->sock));
  538. done = 0;
  539. while (!done)
  540. {
  541. log_verbose3("starting HTTP request on socket %p (%d)", conn->sock, conn->sock.sock);
  542. /* XXX: only used in WSAreaper */
  543. conn->atime = time(NULL);
  544. if ((status = hrequest_new_from_socket(&(conn->sock), &req)) != H_OK)
  545. {
  546. int code;
  547. switch ((code = herror_code(status)))
  548. {
  549. case HSOCKET_ERROR_SSLCLOSE:
  550. case HSOCKET_ERROR_RECEIVE:
  551. log_error2("hrequest_new_from_socket failed (%s)",
  552. herror_message(status));
  553. break;
  554. default:
  555. httpd_send_internal_error(rconn, herror_message(status));
  556. break;
  557. }
  558. herror_release(status);
  559. done = 1;
  560. }
  561. else
  562. {
  563. char *conn_str;
  564. httpd_request_print(req);
  565. conn_str = hpairnode_get_ignore_case(req->header, HEADER_CONNECTION);
  566. if (conn_str && strncasecmp(conn_str, "close", 6) == 0)
  567. done = 1;
  568. if (!done)
  569. done = req->version == HTTP_1_0 ? 1 : 0;
  570. if ((service = httpd_find_service(req->path)))
  571. {
  572. log_verbose3("service '%s' for '%s' found", service->ctx, req->path);
  573. if (_httpd_authenticate_request(req, service->auth))
  574. {
  575. if (service->func != NULL)
  576. {
  577. service->func(rconn, req);
  578. if (rconn->out
  579. && rconn->out->type == HTTP_TRANSFER_CONNECTION_CLOSE)
  580. {
  581. log_verbose1("Connection close requested");
  582. done = 1;
  583. }
  584. }
  585. else
  586. {
  587. char buffer[256];
  588. sprintf(buffer,
  589. "service '%s' not registered properly (func == NULL)",
  590. req->path);
  591. log_verbose1(buffer);
  592. httpd_send_internal_error(rconn, buffer);
  593. }
  594. }
  595. else
  596. {
  597. char *template =
  598. "<html>"
  599. "<head>"
  600. "<title>Unauthorized</title>"
  601. "</head>"
  602. "<body>"
  603. "<h1>Unauthorized request logged</h1>" "</body>" "</html>";
  604. httpd_set_header(rconn, HEADER_WWW_AUTHENTICATE,
  605. "Basic realm=\"nanoHTTP\"");
  606. httpd_send_header(rconn, 401, "Unauthorized");
  607. http_output_stream_write_string(rconn->out, template);
  608. done = 1;
  609. }
  610. }
  611. else
  612. {
  613. char buffer[256];
  614. sprintf(buffer, "no service for '%s' found", req->path);
  615. log_verbose1(buffer);
  616. httpd_send_internal_error(rconn, buffer);
  617. done = 1;
  618. }
  619. hrequest_free(req);
  620. }
  621. }
  622. httpd_free(rconn);
  623. hsocket_close(&(conn->sock));
  624. #ifdef WIN32
  625. CloseHandle((HANDLE) conn->tid);
  626. #else
  627. pthread_attr_destroy(&(conn->attr));
  628. #endif
  629. conn->flag = CONNECTION_FREE;
  630. #ifdef WIN32
  631. _endthread();
  632. return 0;
  633. #else
  634. /* pthread_exits automagically */
  635. return NULL;
  636. #endif
  637. }
  638. int
  639. httpd_set_header(httpd_conn_t * conn, const char *key, const char *value)
  640. {
  641. hpair_t *p;
  642. if (conn == NULL)
  643. {
  644. log_warn1("Connection object is NULL");
  645. return 0;
  646. }
  647. for (p = conn->header; p; p = p->next)
  648. {
  649. if (p->key && !strcmp(p->key, key))
  650. {
  651. free(p->value);
  652. p->value = strdup(value);
  653. return 1;
  654. }
  655. }
  656. conn->header = hpairnode_new(key, value, conn->header);
  657. return 0;
  658. }
  659. void
  660. httpd_set_headers(httpd_conn_t * conn, hpair_t * header)
  661. {
  662. while (header)
  663. {
  664. httpd_set_header(conn, header->key, header->value);
  665. header = header->next;
  666. }
  667. }
  668. int
  669. httpd_add_header(httpd_conn_t * conn, const char *key, const char *value)
  670. {
  671. if (!conn)
  672. {
  673. log_warn1("Connection object is NULL");
  674. return 0;
  675. }
  676. conn->header = hpairnode_new(key, value, conn->header);
  677. return 1;
  678. }
  679. void
  680. httpd_add_headers(httpd_conn_t * conn, const hpair_t * values)
  681. {
  682. if (!conn)
  683. {
  684. log_warn1("Connection object is NULL");
  685. return;
  686. }
  687. while (values)
  688. {
  689. httpd_add_header(conn, values->key, values->value);
  690. values = values->next;
  691. }
  692. return;
  693. }
  694. /*
  695. * -----------------------------------------------------
  696. * FUNCTION: httpd_term
  697. * -----------------------------------------------------
  698. */
  699. #ifdef WIN32
  700. BOOL WINAPI
  701. httpd_term(DWORD sig)
  702. {
  703. /* log_debug2 ("Got signal %d", sig); */
  704. if (sig == _httpd_terminate_signal)
  705. _httpd_run = 0;
  706. return TRUE;
  707. }
  708. #else
  709. void
  710. httpd_term(int sig)
  711. {
  712. log_debug2("Got signal %d", sig);
  713. if (sig == _httpd_terminate_signal)
  714. _httpd_run = 0;
  715. return;
  716. }
  717. #endif
  718. /*
  719. * -----------------------------------------------------
  720. * FUNCTION: _httpd_register_signal_handler
  721. * -----------------------------------------------------
  722. */
  723. static void
  724. _httpd_register_signal_handler(void)
  725. {
  726. log_verbose2("registering termination signal handler (SIGNAL:%d)",
  727. _httpd_terminate_signal);
  728. #ifdef WIN32
  729. if (SetConsoleCtrlHandler((PHANDLER_ROUTINE) httpd_term, TRUE) == FALSE)
  730. {
  731. log_error1("Unable to install console event handler!");
  732. }
  733. #else
  734. signal(_httpd_terminate_signal, httpd_term);
  735. #endif
  736. return;
  737. }
  738. /*--------------------------------------------------
  739. FUNCTION: _httpd_wait_for_empty_conn
  740. ----------------------------------------------------*/
  741. static conndata_t *
  742. _httpd_wait_for_empty_conn(void)
  743. {
  744. int i;
  745. #ifdef WIN32
  746. WaitForSingleObject(_httpd_connection_lock, INFINITE);
  747. #else
  748. pthread_mutex_lock(&_httpd_connection_lock);
  749. #endif
  750. for (i = 0;; i++)
  751. {
  752. if (!_httpd_run)
  753. {
  754. #ifdef WIN32
  755. ReleaseMutex(_httpd_connection_lock);
  756. #else
  757. pthread_mutex_unlock(&_httpd_connection_lock);
  758. #endif
  759. return NULL;
  760. }
  761. if (i >= _httpd_max_connections)
  762. {
  763. system_sleep(1);
  764. i = -1;
  765. }
  766. else if (_httpd_connection[i].flag == CONNECTION_FREE)
  767. {
  768. _httpd_connection[i].flag = CONNECTION_IN_USE;
  769. break;
  770. }
  771. }
  772. #ifdef WIN32
  773. ReleaseMutex(_httpd_connection_lock);
  774. #else
  775. pthread_mutex_unlock(&_httpd_connection_lock);
  776. #endif
  777. return &_httpd_connection[i];
  778. }
  779. /*
  780. * -----------------------------------------------------
  781. * FUNCTION: _httpd_start_thread
  782. * -----------------------------------------------------
  783. */
  784. static void
  785. _httpd_start_thread(conndata_t * conn)
  786. {
  787. int err;
  788. #ifdef WIN32
  789. conn->tid =
  790. (HANDLE) _beginthreadex(NULL, 65535, httpd_session_main, conn, 0, &err);
  791. #else
  792. pthread_attr_init(&(conn->attr));
  793. #ifdef PTHREAD_CREATE_DETACHED
  794. pthread_attr_setdetachstate(&(conn->attr), PTHREAD_CREATE_DETACHED);
  795. #endif
  796. pthread_sigmask(SIG_BLOCK, &thrsigset, NULL);
  797. if ((err =
  798. pthread_create(&(conn->tid), &(conn->attr), httpd_session_main, conn)))
  799. log_error2("pthread_create failed (%s)", strerror(err));
  800. #endif
  801. return;
  802. }
  803. /*
  804. * -----------------------------------------------------
  805. * FUNCTION: httpd_run
  806. * -----------------------------------------------------
  807. */
  808. herror_t
  809. httpd_run(void)
  810. {
  811. struct timeval timeout;
  812. conndata_t *conn;
  813. herror_t err;
  814. fd_set fds;
  815. log_verbose1("starting run routine");
  816. #ifndef WIN32
  817. sigemptyset(&thrsigset);
  818. sigaddset(&thrsigset, SIGALRM);
  819. #endif
  820. _httpd_register_signal_handler();
  821. if ((err = hsocket_listen(&_httpd_socket)) != H_OK)
  822. {
  823. log_error2("hsocket_listen failed (%s)", herror_message(err));
  824. return err;
  825. }
  826. while (_httpd_run)
  827. {
  828. conn = _httpd_wait_for_empty_conn();
  829. if (!_httpd_run)
  830. break;
  831. /* Wait for a socket to accept */
  832. while (_httpd_run)
  833. {
  834. /* set struct timeval to the proper timeout */
  835. timeout.tv_sec = 1;
  836. timeout.tv_usec = 0;
  837. /* zero and set file descriptior */
  838. FD_ZERO(&fds);
  839. FD_SET(_httpd_socket.sock, &fds);
  840. /* select socket descriptor */
  841. switch (select(_httpd_socket.sock + 1, &fds, NULL, NULL, &timeout))
  842. {
  843. case 0:
  844. /* descriptor is not ready */
  845. continue;
  846. case -1:
  847. /* got a signal? */
  848. continue;
  849. default:
  850. /* no nothing */
  851. break;
  852. }
  853. if (FD_ISSET(_httpd_socket.sock, &fds))
  854. {
  855. break;
  856. }
  857. }
  858. /* check signal status */
  859. if (!_httpd_run)
  860. break;
  861. if ((err = hsocket_accept(&_httpd_socket, &(conn->sock))) != H_OK)
  862. {
  863. log_error2("hsocket_accept failed (%s)", herror_message(err));
  864. hsocket_close(&(conn->sock));
  865. continue;
  866. }
  867. _httpd_start_thread(conn);
  868. }
  869. return 0;
  870. }
  871. void
  872. httpd_destroy(void)
  873. {
  874. hservice_t *tmp, *cur = _httpd_services_head;
  875. while (cur != NULL)
  876. {
  877. tmp = cur->next;
  878. hservice_free(cur);
  879. cur = tmp;
  880. }
  881. hsocket_module_destroy();
  882. free(_httpd_connection);
  883. return;
  884. }
  885. #ifdef WIN32
  886. static void
  887. WSAReaper(void *x)
  888. {
  889. short int connections;
  890. short int i;
  891. char junk[10];
  892. int rc;
  893. time_t ctime;
  894. for (;;)
  895. {
  896. connections = 0;
  897. ctime = time((time_t) 0);
  898. for (i = 0; i < _httpd_max_connections; i++)
  899. {
  900. if (_httpd_connection[i].tid == 0)
  901. continue;
  902. GetExitCodeThread((HANDLE) _httpd_connection[i].tid, (PDWORD) & rc);
  903. if (rc != STILL_ACTIVE)
  904. continue;
  905. connections++;
  906. if ((ctime - _httpd_connection[i].atime < _httpd_max_idle) ||
  907. (_httpd_connection[i].atime == 0))
  908. continue;
  909. log_verbose3("Reaping socket %u from (runtime ~= %d seconds)",
  910. _httpd_connection[i].sock,
  911. ctime - _httpd_connection[i].atime);
  912. shutdown(_httpd_connection[i].sock.sock, 2);
  913. while (recv(_httpd_connection[i].sock.sock, junk, sizeof(junk), 0) > 0)
  914. {
  915. };
  916. closesocket(_httpd_connection[i].sock.sock);
  917. _httpd_connection[i].sock.sock = 0;
  918. TerminateThread(_httpd_connection[i].tid, (DWORD) & rc);
  919. CloseHandle(_httpd_connection[i].tid);
  920. memset((char *) &_httpd_connection[i], 0, sizeof(_httpd_connection[i]));
  921. }
  922. Sleep(100);
  923. }
  924. return;
  925. }
  926. #endif
  927. unsigned char *
  928. httpd_get_postdata(httpd_conn_t * conn, hrequest_t * req, long *received,
  929. long max)
  930. {
  931. char *content_length_str;
  932. long content_length = 0;
  933. unsigned char *postdata = NULL;
  934. if (req->method == HTTP_REQUEST_POST)
  935. {
  936. content_length_str =
  937. hpairnode_get_ignore_case(req->header, HEADER_CONTENT_LENGTH);
  938. if (content_length_str != NULL)
  939. content_length = atol(content_length_str);
  940. }
  941. else
  942. {
  943. log_warn1("Not a POST method");
  944. return NULL;
  945. }
  946. if (content_length > max && max != -1)
  947. return NULL;
  948. if (content_length == 0)
  949. {
  950. *received = 0;
  951. if (!(postdata = (char *) malloc(1)))
  952. {
  953. log_error2("malloc failed (%s)", strerror(errno));
  954. return NULL;
  955. }
  956. postdata[0] = '\0';
  957. return postdata;
  958. }
  959. if (!(postdata = (unsigned char *) malloc(content_length + 1)))
  960. {
  961. log_error2("malloc failed (%)", strerror(errno));
  962. return NULL;
  963. }
  964. if (http_input_stream_read(req->in, postdata, (int) content_length) > 0)
  965. {
  966. *received = content_length;
  967. postdata[content_length] = '\0';
  968. return postdata;
  969. }
  970. free(postdata);
  971. return NULL;
  972. }
  973. /*
  974. MIME support httpd_mime_* function set
  975. */
  976. static void
  977. _httpd_mime_get_boundary(httpd_conn_t * conn, char *dest)
  978. {
  979. sprintf(dest, "---=.Part_NH_%p", conn);
  980. log_verbose2("boundary= \"%s\"", dest);
  981. return;
  982. }
  983. /**
  984. Begin MIME multipart/related POST
  985. Returns: H_OK or error flag
  986. */
  987. herror_t
  988. httpd_mime_send_header(httpd_conn_t * conn, const char *related_start,
  989. const char *related_start_info,
  990. const char *related_type, int code, const char *text)
  991. {
  992. char buffer[300];
  993. char temp[250];
  994. char boundary[250];
  995. /* Set Content-type Set multipart/related parameter type=..; start=.. ;
  996. start-info= ..; boundary=... using sprintf instead of snprintf because
  997. visual c does not support snprintf */
  998. sprintf(buffer, "multipart/related;");
  999. if (related_type)
  1000. {
  1001. snprintf(temp, 75, " type=\"%s\";", related_type);
  1002. strcat(buffer, temp);
  1003. }
  1004. if (related_start)
  1005. {
  1006. snprintf(temp, 250, " start=\"%s\";", related_start);
  1007. strcat(buffer, temp);
  1008. }
  1009. if (related_start_info)
  1010. {
  1011. snprintf(temp, 250, " start-info=\"%s\";", related_start_info);
  1012. strcat(buffer, temp);
  1013. }
  1014. _httpd_mime_get_boundary(conn, boundary);
  1015. snprintf(temp, 250, " boundary=\"%s\"", boundary);
  1016. strcat(buffer, temp);
  1017. httpd_set_header(conn, HEADER_CONTENT_TYPE, buffer);
  1018. return httpd_send_header(conn, code, text);
  1019. }
  1020. /**
  1021. Send boundary and part header and continue
  1022. with next part
  1023. */
  1024. herror_t
  1025. httpd_mime_next(httpd_conn_t * conn, const char *content_id,
  1026. const char *content_type, const char *transfer_encoding)
  1027. {
  1028. herror_t status;
  1029. char buffer[512];
  1030. char boundary[75];
  1031. /* Get the boundary string */
  1032. _httpd_mime_get_boundary(conn, boundary);
  1033. sprintf(buffer, "\r\n--%s\r\n", boundary);
  1034. /* Send boundary */
  1035. status =
  1036. http_output_stream_write(conn->out, (const byte_t *) buffer,
  1037. strlen(buffer));
  1038. if (status != H_OK)
  1039. return status;
  1040. /* Send Content header */
  1041. sprintf(buffer, "%s: %s\r\n%s: %s\r\n%s: %s\r\n\r\n",
  1042. HEADER_CONTENT_TYPE, content_type ? content_type : "text/plain",
  1043. HEADER_CONTENT_TRANSFER_ENCODING,
  1044. transfer_encoding ? transfer_encoding : "binary",
  1045. HEADER_CONTENT_ID,
  1046. content_id ? content_id : "<content-id-not-set>");
  1047. status =
  1048. http_output_stream_write(conn->out, (const byte_t *) buffer,
  1049. strlen(buffer));
  1050. return status;
  1051. }
  1052. /**
  1053. Send boundary and part header and continue
  1054. with next part
  1055. */
  1056. herror_t
  1057. httpd_mime_send_file(httpd_conn_t * conn, const char *content_id,
  1058. const char *content_type, const char *transfer_encoding,
  1059. const char *filename)
  1060. {
  1061. byte_t buffer[MAX_FILE_BUFFER_SIZE];
  1062. herror_t status;
  1063. FILE *fd;
  1064. size_t size;
  1065. if ((fd = fopen(filename, "rb")) == NULL)
  1066. return herror_new("httpd_mime_send_file", FILE_ERROR_OPEN,
  1067. "Can not open file '%d'", filename);
  1068. status = httpd_mime_next(conn, content_id, content_type, transfer_encoding);
  1069. if (status != H_OK)
  1070. {
  1071. fclose(fd);
  1072. return status;
  1073. }
  1074. while (!feof(fd))
  1075. {
  1076. size = fread(buffer, 1, MAX_FILE_BUFFER_SIZE, fd);
  1077. if (size == -1)
  1078. {
  1079. fclose(fd);
  1080. return herror_new("httpd_mime_send_file", FILE_ERROR_READ,
  1081. "Can not read from file '%d'", filename);
  1082. }
  1083. if ((status = http_output_stream_write(conn->out, buffer, size)) != H_OK)
  1084. {
  1085. fclose(fd);
  1086. return status;
  1087. }
  1088. }
  1089. fclose(fd);
  1090. return H_OK;
  1091. }
  1092. /**
  1093. Finish MIME request
  1094. Returns: H_OK or error flag
  1095. */
  1096. herror_t
  1097. httpd_mime_end(httpd_conn_t * conn)
  1098. {
  1099. herror_t status;
  1100. char buffer[512];
  1101. char boundary[75];
  1102. /* Get the boundary string */
  1103. _httpd_mime_get_boundary(conn, boundary);
  1104. sprintf(buffer, "\r\n--%s--\r\n\r\n", boundary);
  1105. /* Send boundary */
  1106. status =
  1107. http_output_stream_write(conn->out, (const byte_t *) buffer,
  1108. strlen(buffer));
  1109. if (status != H_OK)
  1110. return status;
  1111. /* Flush put stream */
  1112. status = http_output_stream_flush(conn->out);
  1113. return status;
  1114. }