httpsrv.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 2013 Luke Dashjr
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the Free
  6. * Software Foundation; either version 3 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. #include "config.h"
  10. #include <sys/types.h>
  11. #include <sys/select.h>
  12. #include <sys/socket.h>
  13. #include <microhttpd.h>
  14. #include "logging.h"
  15. #include "util.h"
  16. static struct MHD_Daemon *httpsrv;
  17. extern int handle_getwork(struct MHD_Connection *, bytes_t *);
  18. static
  19. int httpsrv_handle_req(struct MHD_Connection *conn, const char *url, const char *method, bytes_t *upbuf)
  20. {
  21. return handle_getwork(conn, upbuf);
  22. }
  23. static
  24. int httpsrv_handle_access(void *cls, struct MHD_Connection *conn, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls)
  25. {
  26. bytes_t *upbuf;
  27. if (!*con_cls)
  28. {
  29. *con_cls = upbuf = malloc(sizeof(bytes_t));
  30. bytes_init(upbuf);
  31. return MHD_YES;
  32. }
  33. upbuf = *con_cls;
  34. if (*upload_data_size)
  35. {
  36. bytes_append(upbuf, upload_data, *upload_data_size);
  37. *upload_data_size = 0;
  38. return MHD_YES;
  39. }
  40. return httpsrv_handle_req(conn, url, method, *con_cls);
  41. }
  42. static
  43. void httpsrv_cleanup_request(void *cls, struct MHD_Connection *conn, void **con_cls, enum MHD_RequestTerminationCode toe)
  44. {
  45. if (*con_cls)
  46. {
  47. bytes_t *upbuf = *con_cls;
  48. bytes_free(upbuf);
  49. free(upbuf);
  50. *con_cls = NULL;
  51. }
  52. }
  53. static
  54. void httpsrv_log(void *arg, const char *fmt, va_list ap)
  55. {
  56. if (!opt_debug)
  57. return;
  58. char tmp42[LOGBUFSIZ] = "HTTPSrv: ";
  59. vsnprintf(&tmp42[9], sizeof(tmp42)-9, fmt, ap);
  60. _applog(LOG_DEBUG, tmp42);
  61. }
  62. void httpsrv_start(unsigned short port)
  63. {
  64. httpsrv = MHD_start_daemon(
  65. MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
  66. port, NULL, NULL,
  67. &httpsrv_handle_access, NULL,
  68. MHD_OPTION_NOTIFY_COMPLETED, &httpsrv_cleanup_request, NULL,
  69. MHD_OPTION_EXTERNAL_LOGGER, &httpsrv_log, NULL,
  70. MHD_OPTION_END);
  71. if (httpsrv)
  72. applog(LOG_NOTICE, "HTTP server listening on port %d", (int)port);
  73. else
  74. applog(LOG_ERR, "Failed to start HTTP server on port %d", (int)port);
  75. }
  76. void httpsrv_stop()
  77. {
  78. if (!httpsrv)
  79. return;
  80. applog(LOG_DEBUG, "Stopping HTTP server");
  81. MHD_stop_daemon(httpsrv);
  82. httpsrv = NULL;
  83. }