main.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. #define WINCDECL __cdecl
  45. #else
  46. #include <sys/wait.h>
  47. #include <unistd.h>
  48. #define DIRSEP '/'
  49. #define WINCDECL
  50. #endif // _WIN32
  51. #define MAX_OPTIONS 40
  52. static int exit_flag;
  53. static char *options[MAX_OPTIONS];
  54. static char server_name[40];
  55. static struct mg_context *ctx;
  56. #if !defined(CONFIG_FILE)
  57. #define CONFIG_FILE "mongoose.conf"
  58. #endif /* !CONFIG_FILE */
  59. static void WINCDECL signal_handler(int sig_num) {
  60. #if !defined(_WIN32)
  61. if (sig_num == SIGCHLD) {
  62. do {
  63. } while (waitpid(-1, &sig_num, WNOHANG) > 0);
  64. } else
  65. #endif /* !_WIN32 */
  66. {
  67. exit_flag = sig_num;
  68. }
  69. }
  70. static void die(const char *fmt, ...) {
  71. va_list ap;
  72. char msg[200];
  73. va_start(ap, fmt);
  74. vsnprintf(msg, sizeof(msg), fmt, ap);
  75. va_end(ap);
  76. #if defined(_WIN32)
  77. MessageBox(NULL, msg, "Error", MB_OK);
  78. #else
  79. fprintf(stderr, "%s\n", msg);
  80. #endif
  81. exit(EXIT_FAILURE);
  82. }
  83. /*
  84. * Edit the passwords file.
  85. */
  86. static int mg_edit_passwords(const char *fname, const char *domain,
  87. const char *user, const char *pass) {
  88. struct mg_context *ctx;
  89. const char *options[] = {"authentication_domain", NULL, NULL};
  90. int success;
  91. options[1] = domain;
  92. ctx = mg_start(NULL, options);
  93. success = mg_modify_passwords_file(ctx, fname, user, pass);
  94. mg_stop(ctx);
  95. return success;
  96. }
  97. static void show_usage_and_exit(void) {
  98. const char **names;
  99. int i;
  100. fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka\n", mg_version());
  101. fprintf(stderr, "Usage:\n");
  102. fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
  103. fprintf(stderr, " mongoose <config_file>\n");
  104. fprintf(stderr, " mongoose [-option value ...]\n");
  105. fprintf(stderr, "OPTIONS:\n");
  106. names = mg_get_valid_option_names();
  107. for (i = 0; names[i] != NULL; i += 3) {
  108. fprintf(stderr, " -%s %s (default: \"%s\")\n",
  109. names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
  110. }
  111. fprintf(stderr, "See http://code.google.com/p/mongoose/wiki/MongooseManual"
  112. " for more details.\n");
  113. fprintf(stderr, "Example:\n mongoose -s cert.pem -p 80,443s -d no\n");
  114. exit(EXIT_FAILURE);
  115. }
  116. static void verify_document_root(const char *root) {
  117. const char *p, *path;
  118. char buf[PATH_MAX];
  119. struct stat st;
  120. path = root;
  121. if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
  122. strncpy(buf, root, p - root);
  123. path = buf;
  124. }
  125. if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
  126. die("Invalid root directory: \"%s\"", root);
  127. }
  128. }
  129. static char *sdup(const char *str) {
  130. char *p;
  131. if ((p = malloc(strlen(str) + 1)) != NULL) {
  132. strcpy(p, str);
  133. }
  134. return p;
  135. }
  136. static void set_option(char **options, const char *name, const char *value) {
  137. int i;
  138. if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
  139. verify_document_root(value);
  140. }
  141. for (i = 0; i < MAX_OPTIONS - 3; i++) {
  142. if (options[i] == NULL) {
  143. options[i] = sdup(name);
  144. options[i + 1] = sdup(value);
  145. options[i + 2] = NULL;
  146. break;
  147. }
  148. }
  149. if (i == MAX_OPTIONS - 3) {
  150. die("%s", "Too many options specified");
  151. }
  152. }
  153. static void process_command_line_arguments(char *argv[], char **options) {
  154. const char *config_file = NULL;
  155. char line[512], opt[512], val[512], path[PATH_MAX], *p;
  156. FILE *fp = NULL;
  157. struct stat st;
  158. size_t i, line_no = 0;
  159. /* Should we use a config file ? */
  160. if (argv[1] != NULL && argv[2] == NULL) {
  161. config_file = argv[1];
  162. } else if (argv[1] == NULL && (p = strchr(argv[0], DIRSEP)) == NULL) {
  163. // No command line flags specified. Look where binary lives
  164. config_file = CONFIG_FILE;
  165. } else if (argv[1] == NULL) {
  166. snprintf(path, sizeof(path), "%.*s%c%s",
  167. (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  168. if (stat(path, &st) == 0) {
  169. config_file = path;
  170. }
  171. }
  172. /* If config file was set in command line and open failed, exit */
  173. if (config_file != NULL && (fp = fopen(config_file, "r")) == NULL) {
  174. die("Cannot open config file %s: %s", config_file, strerror(errno));
  175. }
  176. if (fp != NULL) {
  177. fprintf(stderr, "Loading config file %s\n", config_file);
  178. /* Loop over the lines in config file */
  179. while (fgets(line, sizeof(line), fp) != NULL) {
  180. line_no++;
  181. /* Ignore empty lines and comments */
  182. if (line[0] == '#' || line[0] == '\n')
  183. continue;
  184. if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
  185. die("%s: line %d is invalid", config_file, (int) line_no);
  186. }
  187. set_option(options, opt, val);
  188. }
  189. (void) fclose(fp);
  190. } else {
  191. for (i = 1; argv[i] != NULL; i += 2) {
  192. if (argv[i][0] != '-' || argv[i + 1] == NULL) {
  193. show_usage_and_exit();
  194. }
  195. set_option(options, &argv[i][1], argv[i + 1]);
  196. }
  197. }
  198. }
  199. static void start_mongoose(int argc, char *argv[]) {
  200. int i;
  201. snprintf(server_name, sizeof(server_name),
  202. "Mongoose %s web server", mg_version());
  203. /* Edit passwords file if -A option is specified */
  204. if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'A') {
  205. if (argc != 6) {
  206. show_usage_and_exit();
  207. }
  208. exit(mg_edit_passwords(argv[2], argv[3], argv[4], argv[5]) ?
  209. EXIT_SUCCESS : EXIT_FAILURE);
  210. }
  211. /* Show usage if -h or --help options are specified */
  212. if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
  213. show_usage_and_exit();
  214. }
  215. /* Update config based on command line arguments */
  216. process_command_line_arguments(argv, options);
  217. /* Setup signal handler: quit on Ctrl-C */
  218. #ifndef _WIN32
  219. signal(SIGCHLD, signal_handler);
  220. #endif /* _WIN32 */
  221. signal(SIGTERM, signal_handler);
  222. signal(SIGINT, signal_handler);
  223. /* Start Mongoose */
  224. ctx = mg_start(NULL, (const char **) options);
  225. for (i = 0; options[i] != NULL; i++) {
  226. free(options[i]);
  227. }
  228. if (ctx == NULL) {
  229. die("%s", "Failed to start Mongoose. Maybe some options are "
  230. "assigned bad values?\nTry to run with '-e error_log.txt' "
  231. "and check error_log.txt for more information.");
  232. }
  233. }
  234. #ifdef _WIN32
  235. static SERVICE_STATUS ss;
  236. static SERVICE_STATUS_HANDLE hStatus;
  237. static void WINAPI ControlHandler(DWORD code) {
  238. if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
  239. ss.dwWin32ExitCode = 0;
  240. ss.dwCurrentState = SERVICE_STOPPED;
  241. }
  242. SetServiceStatus(hStatus, &ss);
  243. }
  244. static void WINAPI ServiceMain(void) {
  245. ss.dwServiceType = SERVICE_WIN32;
  246. ss.dwCurrentState = SERVICE_RUNNING;
  247. ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  248. hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
  249. SetServiceStatus(hStatus, &ss);
  250. //Sleep(3000);
  251. while (ss.dwCurrentState == SERVICE_RUNNING) {
  252. Sleep(1000);
  253. }
  254. mg_stop(ctx);
  255. ss.dwCurrentState = SERVICE_STOPPED;
  256. ss.dwWin32ExitCode = (DWORD) -1;
  257. SetServiceStatus(hStatus, &ss);
  258. }
  259. static void try_to_run_as_nt_service(void) {
  260. static SERVICE_TABLE_ENTRY service_table[] = {
  261. {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
  262. {NULL, NULL}
  263. };
  264. if (StartServiceCtrlDispatcher(service_table)) {
  265. exit(EXIT_SUCCESS);
  266. }
  267. }
  268. #define ID_TRAYICON 100
  269. #define ID_QUIT 101
  270. static NOTIFYICONDATA ni;
  271. static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
  272. LPARAM lParam) {
  273. POINT pt;
  274. HMENU hMenu;
  275. switch (msg) {
  276. case WM_COMMAND:
  277. switch (LOWORD(wParam)) {
  278. case ID_QUIT:
  279. exit(EXIT_SUCCESS);
  280. break;
  281. }
  282. break;
  283. case WM_USER:
  284. switch (lParam) {
  285. case WM_RBUTTONUP:
  286. case WM_LBUTTONUP:
  287. case WM_LBUTTONDBLCLK:
  288. hMenu = CreatePopupMenu();
  289. AppendMenu(hMenu, 0, ID_QUIT, "Exit");
  290. GetCursorPos(&pt);
  291. TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
  292. DestroyMenu(hMenu);
  293. break;
  294. }
  295. break;
  296. }
  297. return DefWindowProc(hWnd, msg, wParam, lParam);
  298. }
  299. int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
  300. WNDCLASS cls;
  301. HWND hWnd;
  302. MSG msg;
  303. // Win32 runtime must prepare __argc and __argv for us
  304. start_mongoose(__argc, __argv);
  305. try_to_run_as_nt_service();
  306. memset(&cls, 0, sizeof(cls));
  307. cls.lpfnWndProc = (WNDPROC) WindowProc;
  308. cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  309. cls.lpszClassName = server_name;
  310. RegisterClass(&cls);
  311. hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
  312. 0, 0, 0, 0, NULL, NULL, NULL, NULL);
  313. ShowWindow(hWnd, SW_HIDE);
  314. ni.cbSize = sizeof(ni);
  315. ni.uID = ID_TRAYICON;
  316. ni.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  317. ni.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  318. ni.hWnd = hWnd;
  319. snprintf(ni.szTip, sizeof(ni.szTip), "%s", server_name);
  320. ni.uCallbackMessage = WM_USER;
  321. Shell_NotifyIcon(NIM_ADD, &ni);
  322. while (GetMessage(&msg, hWnd, 0, 0)) {
  323. TranslateMessage(&msg);
  324. DispatchMessage(&msg);
  325. }
  326. }
  327. #endif /* _WIN32 */
  328. int main(int argc, char *argv[]) {
  329. start_mongoose(argc, argv);
  330. printf("%s started on port(s) %s with web root [%s]\n",
  331. server_name, mg_get_option(ctx, "listening_ports"),
  332. mg_get_option(ctx, "document_root"));
  333. while (exit_flag == 0) {
  334. sleep(1);
  335. }
  336. printf("Exiting on signal %d, waiting for all threads to finish...",
  337. exit_flag);
  338. fflush(stdout);
  339. mg_stop(ctx);
  340. printf("%s", " done.\n");
  341. return EXIT_SUCCESS;
  342. }