main.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright (c) 2004-2009 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  22. #else
  23. #define _XOPEN_SOURCE 600 // For PATH_MAX on linux
  24. #endif
  25. #include <sys/stat.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <signal.h>
  29. #include <string.h>
  30. #include <errno.h>
  31. #include <limits.h>
  32. #include <stddef.h>
  33. #include <stdarg.h>
  34. #include "mongoose.h"
  35. #ifdef _WIN32
  36. #include <windows.h>
  37. #include <winsvc.h>
  38. #define PATH_MAX MAX_PATH
  39. #define S_ISDIR(x) ((x) & _S_IFDIR)
  40. #define DIRSEP '\\'
  41. #define snprintf _snprintf
  42. #define vsnprintf _vsnprintf
  43. #define sleep(x) Sleep((x) * 1000)
  44. #else
  45. #include <sys/wait.h>
  46. #include <unistd.h>
  47. #define DIRSEP '/'
  48. #endif // _WIN32
  49. #define MAX_OPTIONS 40
  50. static int exit_flag;
  51. static char *options[MAX_OPTIONS];
  52. static char server_name[40];
  53. static struct mg_context *ctx;
  54. #if !defined(CONFIG_FILE)
  55. #define CONFIG_FILE "mongoose.conf"
  56. #endif /* !CONFIG_FILE */
  57. static void signal_handler(int sig_num) {
  58. #if !defined(_WIN32)
  59. if (sig_num == SIGCHLD) {
  60. do {
  61. } while (waitpid(-1, &sig_num, WNOHANG) > 0);
  62. } else
  63. #endif /* !_WIN32 */
  64. {
  65. exit_flag = sig_num;
  66. }
  67. }
  68. static void die(const char *fmt, ...) {
  69. va_list ap;
  70. char msg[200];
  71. va_start(ap, fmt);
  72. vsnprintf(msg, sizeof(msg), fmt, ap);
  73. va_end(ap);
  74. #if defined(_WIN32)
  75. MessageBox(NULL, msg, "Error", MB_OK);
  76. #else
  77. fprintf(stderr, "%s\n", msg);
  78. #endif
  79. exit(EXIT_FAILURE);
  80. }
  81. /*
  82. * Edit the passwords file.
  83. */
  84. static int mg_edit_passwords(const char *fname, const char *domain,
  85. const char *user, const char *pass) {
  86. struct mg_context *ctx;
  87. const char *options[] = {"authentication_domain", NULL, NULL};
  88. int success;
  89. options[1] = domain;
  90. ctx = mg_start(NULL, options);
  91. success = mg_modify_passwords_file(ctx, fname, user, pass);
  92. mg_stop(ctx);
  93. return success;
  94. }
  95. static void show_usage_and_exit(void) {
  96. const char **names;
  97. int i;
  98. fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka\n", mg_version());
  99. fprintf(stderr, "Usage:\n");
  100. fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
  101. fprintf(stderr, " mongoose <config_file>\n");
  102. fprintf(stderr, " mongoose [-option value ...]\n");
  103. fprintf(stderr, "OPTIONS:\n");
  104. names = mg_get_valid_option_names();
  105. for (i = 0; names[i] != NULL; i += 3) {
  106. fprintf(stderr, " -%s %s (default: \"%s\")\n",
  107. names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
  108. }
  109. fprintf(stderr, "See http://code.google.com/p/mongoose/wiki/MongooseManual"
  110. " for more details.\n");
  111. fprintf(stderr, "Example:\n mongoose -s cert.pem -p 80,443s -d no\n");
  112. exit(EXIT_FAILURE);
  113. }
  114. static void verify_document_root(const char *root) {
  115. const char *p, *path;
  116. char buf[PATH_MAX];
  117. struct stat st;
  118. path = root;
  119. if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
  120. strncpy(buf, root, p - root);
  121. path = buf;
  122. }
  123. if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
  124. die("Invalid root directory: \"%s\"", root);
  125. }
  126. }
  127. static char *sdup(const char *str) {
  128. char *p;
  129. if ((p = malloc(strlen(str) + 1)) != NULL) {
  130. strcpy(p, str);
  131. }
  132. return p;
  133. }
  134. static void set_option(char **options, const char *name, const char *value) {
  135. int i;
  136. if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
  137. verify_document_root(value);
  138. }
  139. for (i = 0; i < MAX_OPTIONS - 3; i++) {
  140. if (options[i] == NULL) {
  141. options[i] = sdup(name);
  142. options[i + 1] = sdup(value);
  143. options[i + 2] = NULL;
  144. break;
  145. }
  146. }
  147. if (i == MAX_OPTIONS - 3) {
  148. die("%s", "Too many options specified");
  149. }
  150. }
  151. static void process_command_line_arguments(char *argv[], char **options) {
  152. const char *config_file = NULL;
  153. char line[512], opt[512], val[512], path[PATH_MAX];
  154. FILE *fp = NULL;
  155. struct stat st;
  156. size_t i, line_no = 0;
  157. /* Should we use a config file ? */
  158. if (argv[1] != NULL && argv[2] == NULL) {
  159. config_file = argv[1];
  160. } else if (argv[1] == NULL) {
  161. // No command line flags specified. Look where binary lives
  162. // TODO(lsm): do proper error handling here
  163. getcwd(path, sizeof(path));
  164. snprintf(path + strlen(path), sizeof(path) - strlen(path), "%c%s",
  165. DIRSEP, CONFIG_FILE);
  166. if (stat(path, &st) == 0) {
  167. config_file = path;
  168. }
  169. }
  170. /* If config file was set in command line and open failed, exit */
  171. if (config_file != NULL && (fp = fopen(config_file, "r")) == NULL) {
  172. die("Cannot open config file %s: %s", config_file, strerror(errno));
  173. }
  174. if (fp != NULL) {
  175. fprintf(stderr, "Loading config file %s\n", config_file);
  176. /* Loop over the lines in config file */
  177. while (fgets(line, sizeof(line), fp) != NULL) {
  178. line_no++;
  179. /* Ignore empty lines and comments */
  180. if (line[0] == '#' || line[0] == '\n')
  181. continue;
  182. if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
  183. die("%s: line %d is invalid", config_file, (int) line_no);
  184. }
  185. set_option(options, opt, val);
  186. }
  187. (void) fclose(fp);
  188. } else {
  189. for (i = 1; argv[i] != NULL; i += 2) {
  190. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  191. show_usage_and_exit();
  192. }
  193. set_option(options, &argv[i][1], argv[i + 1]);
  194. }
  195. }
  196. }
  197. static void start_mongoose(int argc, char *argv[]) {
  198. int i;
  199. snprintf(server_name, sizeof(server_name),
  200. "Mongoose %s web server", mg_version());
  201. /* Edit passwords file if -A option is specified */
  202. if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'A') {
  203. if (argc != 6) {
  204. show_usage_and_exit();
  205. }
  206. exit(mg_edit_passwords(argv[2], argv[3], argv[4], argv[5]) ?
  207. EXIT_SUCCESS : EXIT_FAILURE);
  208. }
  209. /* Show usage if -h or --help options are specified */
  210. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
  211. show_usage_and_exit();
  212. }
  213. /* Update config based on command line arguments */
  214. process_command_line_arguments(argv, options);
  215. /* Setup signal handler: quit on Ctrl-C */
  216. #ifndef _WIN32
  217. signal(SIGCHLD, signal_handler);
  218. #endif /* _WIN32 */
  219. signal(SIGTERM, signal_handler);
  220. signal(SIGINT, signal_handler);
  221. /* Start Mongoose */
  222. ctx = mg_start(NULL, (const char **) options);
  223. for (i = 0; options[i] != NULL; i++) {
  224. free(options[i]);
  225. }
  226. if (ctx == NULL) {
  227. die("%s", "Failed to start Mongoose. Maybe some options are "
  228. "assigned bad values?\nTry to run with '-e error_log.txt' "
  229. "and check error_log.txt for more information.");
  230. }
  231. }
  232. #ifdef _WIN32
  233. static SERVICE_STATUS ss;
  234. static SERVICE_STATUS_HANDLE hStatus;
  235. static void WINAPI ControlHandler(DWORD code) {
  236. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  237. ss.dwWin32ExitCode = 0;
  238. ss.dwCurrentState = SERVICE_STOPPED;
  239. }
  240. SetServiceStatus(hStatus, &ss);
  241. }
  242. static void WINAPI ServiceMain(void) {
  243. ss.dwServiceType = SERVICE_WIN32;
  244. ss.dwCurrentState = SERVICE_RUNNING;
  245. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  246. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  247. SetServiceStatus(hStatus, &ss);
  248. //Sleep(3000);
  249. while (ss.dwCurrentState == SERVICE_RUNNING) {
  250. Sleep(1000);
  251. }
  252. mg_stop(ctx);
  253. ss.dwCurrentState = SERVICE_STOPPED;
  254. ss.dwWin32ExitCode = (DWORD) -1;
  255. SetServiceStatus(hStatus, &ss);
  256. }
  257. static void try_to_run_as_nt_service(void) {
  258. static SERVICE_TABLE_ENTRY service_table[] = {
  259. {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
  260. {NULL, NULL}
  261. };
  262. if (StartServiceCtrlDispatcher(service_table)) {
  263. exit(EXIT_SUCCESS);
  264. }
  265. }
  266. #define ID_TRAYICON 100
  267. #define ID_QUIT 101
  268. static NOTIFYICONDATA ni;
  269. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  270. LPARAM lParam) {
  271. POINT pt;
  272. HMENU hMenu;
  273. switch (msg) {
  274. case WM_COMMAND:
  275. switch (LOWORD(wParam)) {
  276. case ID_QUIT:
  277. exit(EXIT_SUCCESS);
  278. break;
  279. }
  280. break;
  281. case WM_USER:
  282. switch (lParam) {
  283. case WM_RBUTTONUP:
  284. case WM_LBUTTONUP:
  285. case WM_LBUTTONDBLCLK:
  286. hMenu = CreatePopupMenu();
  287. AppendMenu(hMenu, 0, ID_QUIT, "Exit");
  288. GetCursorPos(&pt);
  289. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  290. DestroyMenu(hMenu);
  291. break;
  292. }
  293. break;
  294. }
  295. return DefWindowProc(hWnd, msg, wParam, lParam);
  296. }
  297. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  298. WNDCLASS cls;
  299. HWND hWnd;
  300. MSG msg;
  301. // Win32 runtime must prepare __argc and __argv for us
  302. start_mongoose(__argc, __argv);
  303. try_to_run_as_nt_service();
  304. memset(&cls, 0, sizeof(cls));
  305. cls.lpfnWndProc = (WNDPROC) WindowProc;
  306. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  307. cls.lpszClassName = server_name;
  308. RegisterClass(&cls);
  309. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  310. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  311. ShowWindow(hWnd, SW_HIDE);
  312. ni.cbSize = sizeof(ni);
  313. ni.uID = ID_TRAYICON;
  314. ni.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  315. ni.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  316. ni.hWnd = hWnd;
  317. snprintf(ni.szTip, sizeof(ni.szTip), "%s", server_name);
  318. ni.uCallbackMessage = WM_USER;
  319. Shell_NotifyIcon(NIM_ADD, &ni);
  320. while (GetMessage(&msg, hWnd, 0, 0)) {
  321. TranslateMessage(&msg);
  322. DispatchMessage(&msg);
  323. }
  324. }
  325. #endif /* _WIN32 */
  326. int main(int argc, char *argv[]) {
  327. start_mongoose(argc, argv);
  328. printf("%s started on port(s) %s with web root [%s]\n",
  329. server_name, mg_get_option(ctx, "listening_ports"),
  330. mg_get_option(ctx, "document_root"));
  331. while (exit_flag == 0) {
  332. sleep(1);
  333. }
  334. printf("Exiting on signal %d, waiting for all threads to finish...",
  335. exit_flag);
  336. fflush(stdout);
  337. mg_stop(ctx);
  338. printf("%s", " done.\n");
  339. return EXIT_SUCCESS;
  340. }