web.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #include "web.h"
  2. #include "mongoose.h"
  3. #include "thread.h"
  4. #include "cfg.h"
  5. typedef void (*http_fn_t)(void *arg);
  6. #ifdef USE_MG714
  7. typedef struct mg_tls_opts mg_tls_t;
  8. #else
  9. typedef struct mg_serve_http_opts mg_opts_t;
  10. #define MG_PATH_MAX 128
  11. #endif
  12. typedef struct {
  13. struct mg_connection *c;
  14. int ev;
  15. void *ev_data;
  16. }mg_stream_t;
  17. typedef struct {
  18. pthread_t tid;
  19. #ifdef USE_MG714
  20. mg_tls_t tls;
  21. #else
  22. mg_opts_t opts;
  23. #endif
  24. char rootDir[MG_PATH_MAX];
  25. }web_handle_t;
  26. static web_handle_t webHandle={0};
  27. static void http_fn(struct mg_connection *c, int ev, void *ev_data)
  28. {
  29. int i,j,flag=0;
  30. web_handle_t *h=&webHandle;
  31. mg_stream_t s={c,ev,ev_data};
  32. #ifdef USE_MG714
  33. if (ev == MG_EV_HTTP_MSG) {
  34. struct mg_http_serve_opts opts = {.root_dir = h->rootDir};
  35. mg_http_serve_dir(c, ev_data, &opts);
  36. }
  37. else if(ev == MG_EV_ACCEPT) {
  38. if (c->fn_data) {
  39. mg_tls_init(c, &h->tls);
  40. }
  41. }
  42. #else
  43. if (ev == MG_EV_HTTP_REQUEST) {
  44. mg_serve_http(c, (struct http_message *)ev_data, h->opts);
  45. }
  46. #endif
  47. }
  48. static void *web_thread(void *arg)
  49. {
  50. thread_handle_t *th=(thread_handle_t*)arg;
  51. struct mg_mgr mgr;
  52. struct mg_connection *nc;
  53. const char *http_addr="http://[::]:80";
  54. const char *https_addr="https://[::]:443";
  55. web_handle_t *h=&webHandle;
  56. #ifdef USE_MG714
  57. //mg_log_set(MG_LL_DEBUG);
  58. mg_mgr_init(&mgr);
  59. //sys_get_path(mh->rootDir, WEB_ROOT);
  60. strcpy(h->rootDir, "/web");
  61. if (mg_http_listen(&mgr, http_addr, http_fn, NULL) == NULL) {
  62. MG_ERROR(("cannot listen on %s\n", http_addr));
  63. return NULL;
  64. }
  65. if (mg_http_listen(&mgr, https_addr, http_fn, (void*)1) == NULL) {
  66. MG_ERROR(("cannot listen on %s\n", https_addr));
  67. return NULL;
  68. }
  69. //mh->tls.cert = mg_str(file_load2("/root/run/app/cert/server.crt",0));
  70. //mh->tls.key = mg_str(file_load2("/root/run/app/cert/server.key",0));
  71. //mh->tls.name = mg_url_host(https_addr);
  72. #else
  73. mg_mgr_init(&mgr, NULL);
  74. nc = mg_bind(&mgr, "80", http_fn);
  75. strcpy(h->rootDir, "/web");
  76. mg_set_protocol_http_websocket(nc);
  77. h->opts.document_root = h->rootDir;
  78. h->opts.enable_directory_listing = "yes";
  79. #endif
  80. while(th->quit==0) {
  81. mg_mgr_poll(&mgr, 200);
  82. }
  83. mg_mgr_free(&mgr);
  84. pthread_exit(NULL);
  85. }
  86. int web_init(void)
  87. {
  88. thread_start(THREAD_ID_WEB, web_thread, NULL);
  89. return 0;
  90. }