Exemplo n.º 1
0
int main()
{
    struct mg_context *ctx;
    const char *options[] = {
        "listening_ports", "3001",
        "document_root", "rpicweb",
        NULL
    };
  
	int dev = rpi_car_dev_open();

    ctx = mg_start(&callback, NULL, options);
    getchar();  // Wait until user hits "enter"
    mg_stop(ctx);

    rpi_car_dev_close(dev);
    
    return 0;
}
Exemplo n.º 2
0
// This is the entry point called by main().
void run_server() {
    assert(mongoose == NULL);
    srand((unsigned int)time(NULL));
    init_oculus();
    const char *options[] = {
        "listening_ports", "5578",
        "document_root", document_root,
        // Forbid everyone except localhost.
        "access_control_list", "-0.0.0.0/0,+127.0.0.0/8",
        // We have a lot of concurrent long-lived requests, so start a lot of
        // threads to make sure we can handle them all.
        "num_threads", "32",
        NULL
    };
    struct mg_callbacks callbacks;
    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.begin_request = mongoose_begin_request_callback;
    mongoose = mg_start(&callbacks, NULL, options);
    if (!mongoose) {
        debug_log("Failed to start server.");
        exit(1);
    }
    usleep(0);

    if (!open_browser("http://localhost:5578/")) {
        debug_log("Failed to open browser.");
    }
    // Wait for an initial keep-alive connection to be established.
    while(keep_alives == 0) {
        usleep(1000 * 1000);
    }
    // Wait for all keep-alive connections to be closed.
    while(keep_alives > 0) {
        // NOTE: If you are debugging using GDB or XCode, you may encounter signal
        // SIGPIPE on this line. SIGPIPE is harmless and you should configure your
        // debugger to ignore it. For instructions see here:
        // http://stackoverflow.com/questions/10431579/permanently-configuring-lldb-in-xcode-4-3-2-not-to-stop-on-signals
        // http://ricochen.wordpress.com/2011/07/14/debugging-with-gdb-a-couple-of-notes/
        usleep(1000 * 100);
    }
    mg_stop(mongoose);
    mongoose = NULL;
}
Exemplo n.º 3
0
int
main(int argc, char* argv[]) {
    parse_options(argc, argv);
    if (opt_show_help) {
        show_usage(argv);
        return 0;
    }

    struct mg_context *ctx;
    const char *options[] = {"listening_ports", port, NULL};

    started_at = time(NULL);

    cerr<<"INFO::Starting lib-face on port '"<<port<<"'\n";

    if (ac_file) {
        int nadded, nlines;
        const time_t start_time = time(NULL);
        int ret = do_import(ac_file, ac_sorted, minus_one, nadded, nlines);
        if (ret < 0) {
            fprintf(stderr, "ERROR::Could not add lines in file '%s'\n", ac_file);
        }
        else {
            fprintf(stderr, "INFO::Successfully added %d/%d records from \"%s\" in %d second(s)\n", 
                    nadded, nlines, ac_file, (int)(time(NULL) - start_time));
        }
    }

    ctx = mg_start(&callback, NULL, options);
    if (!ctx) {
        fprintf(stderr, "ERROR::Could not start the web server\n");
        return 1;
    }

    while (1) {
        // Never stop
        sleep(100);
    }
    mg_stop(ctx);

    return 0;
}
Exemplo n.º 4
0
/*
 * Test function that converts requested URI to the full path.
 * Since make_path honours aliases option, this also tests aliases.
 */
static void
test_make_path(void)
{
#if defined(_WIN32)
#define	SLASH	"\\"
#else
#define	SLASH	"/"
#endif
	struct {char *uri, *aliases, *root, *result;} tests[] = {
		{"/", "", "/", SLASH SLASH },
		{"/xyz", "/x=/y", "/", SLASH "yyz"},
		{"/xyz", "/x/=/y", "/", SLASH SLASH "xyz"},
		{"/xyz", "/x/=/y", "/boo", SLASH "boo" SLASH "xyz"},
		{"/", "/x=/y", "/foo", SLASH "foo" SLASH},
		{"/x/y/z", "/a=/b,/x=/y,/c=/d", "/foo",
			SLASH "y" SLASH "y" SLASH "z"},
		{NULL, NULL, NULL, NULL},
	};

	char		buf[FILENAME_MAX];
	int		i;
	struct mg_context	*ctx;

	ctx = mg_start();

	/* Loop through all URIs, making paths and comparing with expected. */
	for (i = 0; tests[i].uri != NULL; i++) {
		(void) mg_set_option(ctx, "root", tests[i].root);
		(void) mg_set_option(ctx, "aliases", tests[i].aliases);

		/* Convert URI to the full file name */
		convert_uri_to_file_name(fc(ctx),
				tests[i].uri, buf, sizeof(buf));

		/* Fail if the result is not what we expect */
		if (strcmp(buf, tests[i].result) != 0)
			fail("%s(%s): expected [%s], got [%s]",
			    __func__, tests[i].uri, tests[i].result, buf);
	}

	mg_stop(ctx);
}
Exemplo n.º 5
0
int main(int argc, char *argv[]) {
  signal(SIGCHLD, SIG_IGN);
  signal(SIGHUP, SIG_IGN);
  pid_t pid = 0;
  pid = fork();
  if (pid < 0) {
    fprintf(stderr, "fork failed!\n");
    exit(1);
  }
  if (pid > 0) {
    sleep(1);
    exit(0);
  }
  umask(0);
  setsid();
  chdir("/");

  init_server_name();
  start_server(argc, argv);
  pid = getpid();
  printf("%s started on port(s) %s with document root [%s], pid [%d]\n",
         server_name, mg_get_option(ctx, "listening_ports"),
         mg_get_option(ctx, "document_root"), pid);

  char *pidfile = (char *)mg_get_option(ctx, "pidfile");
  if (*pidfile) {
    FILE *fp = fopen(pidfile, "w+");
    fprintf(fp, "%d", pid);
    fclose(fp);
  }

  while (exit_flag == 0) {
    sleep(1);
  }
  printf("Exiting on signal %d, waiting for all threads to finish...",
         exit_flag);
  printf("%s", " done.\n");
  fflush(stdout);
  mg_stop(ctx);
  return EXIT_SUCCESS;
}
Exemplo n.º 6
0
static void test_request_replies(void) {
  char ebuf[100];
  int i, port = atoi(HTTPS_PORT);
  struct mg_connection *conn;
  struct mg_context *ctx;
  static struct { const char *request, *reply_regex; } tests[] = {
    {
      "GET test/hello.txt HTTP/1.0\r\nRange: bytes=3-5\r\n\r\n",
      "^HTTP/1.1 206 Partial Content"
    },
    {NULL, NULL},
  };

  ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);
  for (i = 0; tests[i].request != NULL; i++) {
    ASSERT((conn = mg_download("localhost", port, 1, ebuf, sizeof(ebuf), "%s",
                               tests[i].request)) != NULL);
    mg_close_connection(conn);
  }
  mg_stop(ctx);
}
Exemplo n.º 7
0
int _tmain(int argc, _TCHAR* argv[]) {
    quad_model model;
    quad_model_web_controller web_controller;

    web_controller.set_model(&model);

    dictionary routes;
    routes.insert(""    , boost::any(&web_controller));
    routes.insert("home", boost::any(&web_controller));

    int nport = 8080;

    printf("See more information on: http://www.codeproject.com/Articles/464158/Robust-MVC" "\n");
    printf("\n");

    char port[80] = "";
    snprintf(port, ARRAYSIZE(port), "%d", nport);

    const char *options[] = {"listening_ports", port, NULL};

    struct mg_context *ctx = mg_start(&callback, &routes, options);

    if( NULL == ctx ) {
        printf("Failed to start server (is the %d port already taken?)\n", nport);
        return -1;
    }

    printf("\n");
    printf("Navigate to: http://localhost:%d\n", nport);
    printf("\n\n");

    printf("Press Control+C to stop web server and exit.\n");
    printf("\n\n");

    getchar();  // Wait until user hits "enter"

    mg_stop(ctx);

    return 0;
}
Exemplo n.º 8
0
int main(void)
{
    struct mg_context *ctx = 0;
    struct mg_callbacks callback_funcs = {0};
    char inbuf[4];

    const char *server_options[] = {
        /* document_root: The path to the test function websock.htm */
        "document_root",     "../../examples/websocket",

        /* port: use http standard to match websocket url in websock.htm: ws://127.0.0.1/MyWebSock  */
        /*       if the port is changed here, it needs to be changed in websock.htm as wenn         */
        "listening_ports",   "80",

        NULL
    };

    websock_init_lib();

    callback_funcs.websocket_ready = websocket_ready_handler;
    callback_funcs.websocket_data = websocket_data_handler;
    callback_funcs.connection_close = connection_close_handler;
    ctx = mg_start(&callback_funcs, NULL, server_options);

    puts("Enter an (ASCII) character or * to exit:");
    for (;;) {
        fgets(inbuf, sizeof(inbuf), stdin);

        if (inbuf[0]=='*') {
           break;
        }
        inbuf[0] = toupper(inbuf[0]);
        websock_send_broadcast(inbuf, 1);
    }

    mg_stop(ctx);
    websock_exit_lib();

    return 0;
}
Exemplo n.º 9
0
void CProfiler2::Shutdown()
{
	ENSURE(m_Initialised);

	ENSURE(!m_GPU); // must shutdown GPU before profiler

	if (m_MgContext)
	{
		mg_stop(m_MgContext);
		m_MgContext = NULL;
	}

	// the destructor is not called for the main thread
	// we have to call it manually to avoid memory leaks
	ENSURE(ThreadUtil::IsMainThread());
	void * dataptr = pthread_getspecific(m_TLS);
	TLSDtor(dataptr);

	int err = pthread_key_delete(m_TLS);
	ENSURE(err == 0);
	m_Initialised = false;
}
Exemplo n.º 10
0
int main(int argc, char* argv[]) {
	google::ParseCommandLineFlags(&argc, &argv, true);

	if (FLAGS_action_log_dir.empty()) {
		fprintf(stderr, "--action_log_dir is a required parameter");
		return -1;
	}

	struct mg_context *ctx;
	struct mg_callbacks callbacks;

	// List of options. Last element must be NULL.
	const char *options[] = {
			"listening_ports", FLAGS_port.c_str(),
			"document_root", FLAGS_dot_temp_dir.c_str(),
			NULL};

	// Prepare callbacks structure. We have only one callback, the rest are NULL.
	memset(&callbacks, 0, sizeof(callbacks));
	callbacks.begin_request = &request_handler;

	// Creating a race app.
	//race_app = new RaceApp(argv[1]);

	// Start the web server.
	ctx = mg_start(&callbacks, NULL, options);

	printf("Web server started on port %s. Open http://localhost:%s/ in your browser...\n",
			FLAGS_port.c_str(), FLAGS_port.c_str());

	for (;;) {
		sleep(10);
	}

	// Stop the server.
	mg_stop(ctx);

	return 0;
}
Exemplo n.º 11
0
static void test_mg_upload(void) {
  static const char *boundary = "OOO___MY_BOUNDARY___OOO";
  struct mg_context *ctx;
  struct mg_connection *conn;
  char ebuf[100], buf[20], *file_data, *file2_data, *post_data;
  int file_len, file2_len, post_data_len;

  ASSERT((ctx = mg_start(OPTIONS, event_handler, NULL)) != NULL);

  // Upload two files
  ASSERT((file_data = read_file("lua_5.2.1.h", &file_len)) != NULL);
  ASSERT((file2_data = read_file("lsqlite3.c", &file2_len)) != NULL);
  post_data = NULL;
  post_data_len = alloc_printf(&post_data, 0,
      // First file
      "--%s\r\n" "Content-Disposition: form-data; " "name=\"file\"; "
      "filename=\"%s\"\r\n\r\n" "%.*s\r\n"
      // Second file
      "--%s\r\n" "Content-Disposition: form-data; " "name=\"file\"; "
      "filename=\"%s\"\r\n\r\n" "%.*s\r\n"
      // Final boundary
      "--%s--\r\n",
      boundary, "f1.txt", file_len, file_data, boundary, "f2.txt",
      file2_len, file2_data, boundary);
  ASSERT(post_data_len > 0);
  ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
                             ebuf, sizeof(ebuf),
                             "POST /upload HTTP/1.1\r\n"
                             "Content-Length: %d\r\n"
                             "Content-Type: multipart/form-data; "
                             "boundary=%s\r\n\r\n"
                             "%.*s", post_data_len, boundary,
                             post_data_len, post_data)) != NULL);
  ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  mg_close_connection(conn);

  mg_stop(ctx);
}
Exemplo n.º 12
0
static int ml_aitvaras_close(lua_State* l) {
	checkargs(0, "aitvaras.close");

	lua_getglobal(l, "aitvaras");

	const char* lobby_addr = _getstr(l, "lobby_addr");
	const char* server_addr = _getstr(l, "server_addr");
	char* remove_req = alloca(strlen(lobby_addr) + strlen("/remove") + 1);
	strcpy(remove_req, lobby_addr);
	strcat(remove_req, "/remove");

	if(server_id != -1) http_post(remove_req, false, server_addr, NULL, _remove_cb);

	mg_stop(mg_ctx);

	aatree_free(&clients);

	// Since some invocations might still be live, append
	// cleanup task to the end of the queue
	async_schedule(_cleanup_invocations, 0, NULL); 

	return 0;
}
Exemplo n.º 13
0
static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
                                   LPARAM lParam) {
  static SERVICE_TABLE_ENTRY service_table[] = {
    {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
    {NULL, NULL}
  };
  int service_installed;
  char buf[200], *service_argv[] = {__argv[0], NULL};
  POINT pt;
  HMENU hMenu;

  switch (msg) {
    case WM_CREATE:
      if (__argv[1] != NULL &&
          !strcmp(__argv[1], service_magic_argument)) {
        start_mongoose(1, service_argv);
        StartServiceCtrlDispatcher(service_table);
        exit(EXIT_SUCCESS);
      } else {
        start_mongoose(__argc, __argv);
      }
      break;
    case WM_COMMAND:
      switch (LOWORD(wParam)) {
        case ID_QUIT:
          mg_stop(ctx);
          Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
          PostQuitMessage(0);
          break;
        case ID_EDIT_CONFIG:
          edit_config_file();
          break;
        case ID_INSTALL_SERVICE:
        case ID_REMOVE_SERVICE:
          manage_service(LOWORD(wParam));
          break;
      }
      break;
    case WM_USER:
      switch (lParam) {
        case WM_RBUTTONUP:
        case WM_LBUTTONUP:
        case WM_LBUTTONDBLCLK:
          hMenu = CreatePopupMenu();
          AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
          AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
          service_installed = manage_service(0);
          snprintf(buf, sizeof(buf), "NT service: %s installed",
                   service_installed ? "" : "not");
          AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
          AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
                     ID_INSTALL_SERVICE, "Install service");
          AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
                     ID_REMOVE_SERVICE, "Deinstall service");
          AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
          AppendMenu(hMenu, MF_STRING, ID_EDIT_CONFIG, "Edit config file");
          AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
          GetCursorPos(&pt);
          SetForegroundWindow(hWnd);
          TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
          PostMessage(hWnd, WM_NULL, 0, 0);
          DestroyMenu(hMenu);
          break;
      }
      break;
    case WM_CLOSE:
      mg_stop(ctx);
      Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
      PostQuitMessage(0);
      return 0;  // We've just sent our own quit message, with proper hwnd.
  }

  return DefWindowProc(hWnd, msg, wParam, lParam);
}
Exemplo n.º 14
0
int main(int argc, char *argv[])
{
    struct mg_context *ctx = NULL;
    struct tclient_data client1_data = {NULL, 0, 0};
    struct tclient_data client2_data = {NULL, 0, 0};
    struct tclient_data client3_data = {NULL, 0, 0};
    struct mg_connection* newconn1 = NULL;
    struct mg_connection* newconn2 = NULL;
    struct mg_connection* newconn3 = NULL;
    char ebuf[100] = {0};

    assert(websocket_welcome_msg_len == strlen(websocket_welcome_msg));

    /* First set up a websocket server */
    ctx = start_websocket_server();
    assert(ctx != NULL);
    printf("Server init\n\n");

    /* Then connect a first client */
    newconn1 = mg_connect_websocket_client("localhost", atoi(PORT), 0, ebuf, sizeof(ebuf),
        "/websocket", NULL, websocket_client_data_handler, websocket_client_close_handler,
        &client1_data);

    if (newconn1 == NULL)
    {
        printf("Error: %s", ebuf);
        return 1;
    }

    sleep(1); /* Should get the websocket welcome message */
    assert(client1_data.closed == 0);
    assert(client2_data.closed == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);
    assert(client1_data.data != NULL);
    assert(client1_data.len == websocket_welcome_msg_len);
    assert(!memcmp(client1_data.data, websocket_welcome_msg, websocket_welcome_msg_len));
    free(client1_data.data);
    client1_data.data = NULL;
    client1_data.len = 0;

    mg_websocket_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data1", 5);

    sleep(1); /* Should get the acknowledge message */
    assert(client1_data.closed == 0);
    assert(client2_data.closed == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);
    assert(client1_data.data != NULL);
    assert(client1_data.len == websocket_acknowledge_msg_len);
    assert(!memcmp(client1_data.data, websocket_acknowledge_msg, websocket_acknowledge_msg_len));
    free(client1_data.data);
    client1_data.data = NULL;
    client1_data.len = 0;

    /* Now connect a second client */
    newconn2 = mg_connect_websocket_client("localhost", atoi(PORT), 0, ebuf, sizeof(ebuf),
        "/websocket", NULL, websocket_client_data_handler, websocket_client_close_handler,
        &client2_data);

    if (newconn2 == NULL)
    {
        printf("Error: %s", ebuf);
        return 1;
    }

    sleep(1); /* Client 2 should get the websocket welcome message */
    assert(client1_data.closed == 0);
    assert(client2_data.closed == 0);
    assert(client1_data.data == NULL);
    assert(client1_data.len == 0);
    assert(client2_data.data != NULL);
    assert(client2_data.len == websocket_welcome_msg_len);
    assert(!memcmp(client2_data.data, websocket_welcome_msg, websocket_welcome_msg_len));
    free(client2_data.data);
    client2_data.data = NULL;
    client2_data.len = 0;

    mg_websocket_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data2", 5);

    sleep(1); /* Should get the acknowledge message */
    assert(client1_data.closed == 0);
    assert(client2_data.closed == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);
    assert(client1_data.data != NULL);
    assert(client1_data.len == websocket_acknowledge_msg_len);
    assert(!memcmp(client1_data.data, websocket_acknowledge_msg, websocket_acknowledge_msg_len));
    free(client1_data.data);
    client1_data.data = NULL;
    client1_data.len = 0;

    mg_websocket_write(newconn1, WEBSOCKET_OPCODE_TEXT, "bye", 3);

    sleep(1); /* Should get the goodbye message */
    assert(client1_data.closed == 0);
    assert(client2_data.closed == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);
    assert(client1_data.data != NULL);
    assert(client1_data.len == websocket_goodbye_msg_len);
    assert(!memcmp(client1_data.data, websocket_goodbye_msg, websocket_goodbye_msg_len));
    free(client1_data.data);
    client1_data.data = NULL;
    client1_data.len = 0;

    mg_close_connection(newconn1);

    sleep(1); /* Won't get any message */
    assert(client1_data.closed == 1);
    assert(client2_data.closed == 0);
    assert(client1_data.data == NULL);
    assert(client1_data.len == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);

    mg_websocket_write(newconn2, WEBSOCKET_OPCODE_TEXT, "bye", 3);

    sleep(1); /* Should get the goodbye message */
    assert(client1_data.closed == 1);
    assert(client2_data.closed == 0);
    assert(client1_data.data == NULL);
    assert(client1_data.len == 0);
    assert(client2_data.data != NULL);
    assert(client2_data.len == websocket_goodbye_msg_len);
    assert(!memcmp(client2_data.data, websocket_goodbye_msg, websocket_goodbye_msg_len));
    free(client2_data.data);
    client2_data.data = NULL;
    client2_data.len = 0;

    mg_close_connection(newconn2);

    sleep(1); /* Won't get any message */
    assert(client1_data.closed == 1);
    assert(client2_data.closed == 1);
    assert(client1_data.data == NULL);
    assert(client1_data.len == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);

    /* Connect client 3 */
    newconn3 = mg_connect_websocket_client("localhost", atoi(PORT), 0, ebuf, sizeof(ebuf),
        "/websocket", NULL, websocket_client_data_handler, websocket_client_close_handler,
        &client3_data);

    sleep(1); /* Client 3 should get the websocket welcome message */
    assert(client1_data.closed == 1);
    assert(client2_data.closed == 1);
    assert(client3_data.closed == 0);
    assert(client1_data.data == NULL);
    assert(client1_data.len == 0);
    assert(client2_data.data == NULL);
    assert(client2_data.len == 0);
    assert(client3_data.data != NULL);
    assert(client3_data.len == websocket_welcome_msg_len);
    assert(!memcmp(client3_data.data, websocket_welcome_msg, websocket_welcome_msg_len));
    free(client3_data.data);
    client3_data.data = NULL;
    client3_data.len = 0;

    mg_stop(ctx);
    printf("Server shutdown\n");

    sleep(10);

    assert(client3_data.closed == 1);

    return 0;
}
Exemplo n.º 15
0
static void test_mg_download(void) {
  char *p1, *p2, ebuf[100];
  int len1, len2, port = atoi(HTTPS_PORT);
  struct mg_connection *conn;
  struct mg_context *ctx;

  ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);

  ASSERT(mg_download(NULL, port, 0, ebuf, sizeof(ebuf), "%s", "") == NULL);
  ASSERT(mg_download("localhost", 0, 0, ebuf, sizeof(ebuf), "%s", "") == NULL);
  ASSERT(mg_download("localhost", port, 1, ebuf, sizeof(ebuf),
                     "%s", "") == NULL);

  // Fetch nonexistent file, should see 404
  ASSERT((conn = mg_download("localhost", port, 1, ebuf, sizeof(ebuf), "%s",
                             "GET /gimbec HTTP/1.0\r\n\r\n")) != NULL);
  ASSERT(strcmp(conn->request_info.uri, "404") == 0);
  mg_close_connection(conn);

  ASSERT((conn = mg_download("google.com", 443, 1, ebuf, sizeof(ebuf), "%s",
                             "GET / HTTP/1.0\r\n\r\n")) != NULL);
  mg_close_connection(conn);

  // Fetch civetweb.c, should succeed
  ASSERT((conn = mg_download("localhost", port, 1, ebuf, sizeof(ebuf), "%s",
                             "GET /civetweb.c HTTP/1.0\r\n\r\n")) != NULL);
  ASSERT(!strcmp(conn->request_info.uri, "200"));
  ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  ASSERT((p2 = read_file("civetweb.c", &len2)) != NULL);
  ASSERT(len1 == len2);
  ASSERT(memcmp(p1, p2, len1) == 0);
  free(p1), free(p2);
  mg_close_connection(conn);


  // Fetch in-memory file, should succeed.
  ASSERT((conn = mg_download("localhost", port, 1, ebuf, sizeof(ebuf), "%s",
                             "GET /blah HTTP/1.1\r\n\r\n")) != NULL);
  ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  ASSERT(len1 == (int) strlen(inmemory_file_data));
  ASSERT(memcmp(p1, inmemory_file_data, len1) == 0);
  free(p1);
  mg_close_connection(conn);

  // Fetch in-memory data with no Content-Length, should succeed.
  ASSERT((conn = mg_download("localhost", port, 1, ebuf, sizeof(ebuf), "%s",
                             "GET /data HTTP/1.1\r\n\r\n")) != NULL);
  ASSERT((p1 = read_conn(conn, &len1)) != NULL);
  ASSERT(len1 == (int) strlen(fetch_data));
  ASSERT(memcmp(p1, fetch_data, len1) == 0);
  free(p1);
  mg_close_connection(conn);

  // Test SSL redirect, IP address
  ASSERT((conn = mg_download("localhost", atoi(HTTP_PORT), 0,
                             ebuf, sizeof(ebuf), "%s",
                             "GET /foo HTTP/1.1\r\n\r\n")) != NULL);
  ASSERT(strcmp(conn->request_info.uri, "302") == 0);
  ASSERT(strcmp(mg_get_header(conn, "Location"),
                "https://127.0.0.1:" HTTPS_PORT "/foo") == 0);
  mg_close_connection(conn);

  // Test SSL redirect, Host:
  ASSERT((conn = mg_download("localhost", atoi(HTTP_PORT), 0,
                             ebuf, sizeof(ebuf), "%s",
                             "GET /foo HTTP/1.1\r\nHost: a.b:77\n\n")) != NULL);
  ASSERT(strcmp(conn->request_info.uri, "302") == 0);
  ASSERT(strcmp(mg_get_header(conn, "Location"),
                "https://a.b:" HTTPS_PORT "/foo") == 0);
  mg_close_connection(conn);

  mg_stop(ctx);
}
Exemplo n.º 16
0
END_TEST


START_TEST(test_mg_server_and_client_tls)
{
#ifndef NO_SSL

	struct mg_context *ctx;

	int ports_cnt;
	struct mg_server_ports ports[16];
	struct mg_callbacks callbacks;
	char errmsg[256];

	struct mg_connection *client_conn;
	char client_err[256];
	const struct mg_request_info *client_ri;
	int client_res;
	struct mg_client_options client_options;

	const char *OPTIONS[32]; /* initializer list here is rejected by CI test */
	int opt_idx = 0;
	char server_cert[256];
	char client_cert[256];
	const char *res_dir = locate_resources();

	ck_assert(res_dir != NULL);
	strcpy(server_cert, res_dir);
	strcpy(client_cert, res_dir);
#ifdef _WIN32
	strcat(server_cert, "cert\\server.pem");
	strcat(client_cert, "cert\\client.pem");
#else
	strcat(server_cert, "cert/server.pem");
	strcat(client_cert, "cert/client.pem");
#endif

	memset((void *)OPTIONS, 0, sizeof(OPTIONS));
#if !defined(NO_FILES)
	OPTIONS[opt_idx++] = "document_root";
	OPTIONS[opt_idx++] = ".";
#endif
	OPTIONS[opt_idx++] = "listening_ports";
	OPTIONS[opt_idx++] = "8080r,8443s";
	OPTIONS[opt_idx++] = "ssl_certificate";
	OPTIONS[opt_idx++] = server_cert;
	OPTIONS[opt_idx++] = "ssl_verify_peer";
	OPTIONS[opt_idx++] = "yes";
	OPTIONS[opt_idx++] = "ssl_ca_file";
	OPTIONS[opt_idx++] = client_cert;

	ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
	ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
	ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);

	memset(ports, 0, sizeof(ports));
	memset(&callbacks, 0, sizeof(callbacks));
	memset(errmsg, 0, sizeof(errmsg));

	callbacks.log_message = log_msg_func;

	ctx = mg_start(&callbacks, (void *)errmsg, OPTIONS);
	mark_point();
	test_sleep(1);
	ck_assert_str_eq(errmsg, "");
	ck_assert(ctx != NULL);

	ports_cnt = mg_get_server_ports(ctx, 16, ports);
	ck_assert_int_eq(ports_cnt, 2);
	ck_assert_int_eq(ports[0].protocol, 1);
	ck_assert_int_eq(ports[0].port, 8080);
	ck_assert_int_eq(ports[0].is_ssl, 0);
	ck_assert_int_eq(ports[0].is_redirect, 1);
	ck_assert_int_eq(ports[1].protocol, 1);
	ck_assert_int_eq(ports[1].port, 8443);
	ck_assert_int_eq(ports[1].is_ssl, 1);
	ck_assert_int_eq(ports[1].is_redirect, 0);
	ck_assert_int_eq(ports[2].protocol, 0);
	ck_assert_int_eq(ports[2].port, 0);
	ck_assert_int_eq(ports[2].is_ssl, 0);
	ck_assert_int_eq(ports[2].is_redirect, 0);

	test_sleep(1);
	mark_point();

	memset(client_err, 0, sizeof(client_err));
	client_conn =
	    mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err));
	ck_assert(client_conn == NULL);
	ck_assert_str_ne(client_err, "");

	memset(client_err, 0, sizeof(client_err));
	memset(&client_options, 0, sizeof(client_options));
	client_options.host = "127.0.0.1";
	client_options.port = 8443;
	client_options.client_cert = client_cert;
	client_options.server_cert = server_cert;

	client_conn = mg_connect_client_secure(&client_options,
	                                       client_err,
	                                       sizeof(client_err));
	ck_assert(client_conn != NULL);
	ck_assert_str_eq(client_err, "");
	mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
	client_res =
	    mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
	ck_assert_int_ge(client_res, 0);
	ck_assert_str_eq(client_err, "");
	client_ri = mg_get_request_info(client_conn);
	ck_assert(client_ri != NULL);

#if defined(NO_FILES)
	ck_assert_str_eq(client_ri->uri, "404");
#else
	ck_assert_str_eq(client_ri->uri, "200");
	/* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
	client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
	ck_assert_int_gt(client_res, 0);
	ck_assert_int_le(client_res, sizeof(client_err));
#endif
	mg_close_connection(client_conn);

	/* TODO: A client API using a client certificate is missing */

	mark_point();
	test_sleep(1);
	mark_point();

	mg_stop(ctx);
#endif
}
Exemplo n.º 17
0
END_TEST


START_TEST(test_mg_start_stop_https_server)
{
#ifndef NO_SSL

	struct mg_context *ctx;

	size_t ports_cnt;
	int ports[16];
	int ssl[16];
	struct mg_callbacks callbacks;
	char errmsg[256];

	const char *OPTIONS[8]; /* initializer list here is rejected by CI test */
	int opt_idx = 0;
	const char *ssl_cert = locate_ssl_cert();

	struct mg_connection *client_conn;
	char client_err[256];
	const struct mg_request_info *client_ri;
	int client_res;

	ck_assert(ssl_cert != NULL);

	memset((void *)OPTIONS, 0, sizeof(OPTIONS));
#if !defined(NO_FILES)
	OPTIONS[opt_idx++] = "document_root";
	OPTIONS[opt_idx++] = ".";
#endif
	OPTIONS[opt_idx++] = "listening_ports";
	OPTIONS[opt_idx++] = "8080r,8443s";
	OPTIONS[opt_idx++] = "ssl_certificate";
	OPTIONS[opt_idx++] = ssl_cert;

	ck_assert_int_le(opt_idx, (int)(sizeof(OPTIONS) / sizeof(OPTIONS[0])));
	ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 1] == NULL);
	ck_assert(OPTIONS[sizeof(OPTIONS) / sizeof(OPTIONS[0]) - 2] == NULL);

	memset(ports, 0, sizeof(ports));
	memset(ssl, 0, sizeof(ssl));
	memset(&callbacks, 0, sizeof(callbacks));
	memset(errmsg, 0, sizeof(errmsg));

	callbacks.log_message = log_msg_func;

	ctx = mg_start(&callbacks, (void *)errmsg, OPTIONS);
	mark_point();
	test_sleep(1);
	ck_assert_str_eq(errmsg, "");
	ck_assert(ctx != NULL);

	ports_cnt = mg_get_ports(ctx, 16, ports, ssl);
	ck_assert_uint_eq(ports_cnt, 2);
	ck_assert_int_eq(ports[0], 8080);
	ck_assert_int_eq(ssl[0], 0);
	ck_assert_int_eq(ports[1], 8443);
	ck_assert_int_eq(ssl[1], 1);
	ck_assert_int_eq(ports[2], 0);
	ck_assert_int_eq(ssl[2], 0);

	test_sleep(1);
	mark_point();

	memset(client_err, 0, sizeof(client_err));
	client_conn =
	    mg_connect_client("127.0.0.1", 8443, 1, client_err, sizeof(client_err));
	ck_assert(client_conn != NULL);
	ck_assert_str_eq(client_err, "");
	mg_printf(client_conn, "GET / HTTP/1.0\r\n\r\n");
	client_res =
	    mg_get_response(client_conn, client_err, sizeof(client_err), 10000);
	ck_assert_int_ge(client_res, 0);
	ck_assert_str_eq(client_err, "");
	client_ri = mg_get_request_info(client_conn);
	ck_assert(client_ri != NULL);

#if defined(NO_FILES)
	ck_assert_str_eq(client_ri->uri, "404");
#else
	ck_assert_str_eq(client_ri->uri, "200");
	/* TODO: ck_assert_str_eq(client_ri->request_method, "HTTP/1.0"); */
	client_res = (int)mg_read(client_conn, client_err, sizeof(client_err));
	ck_assert_int_gt(client_res, 0);
	ck_assert_int_le(client_res, sizeof(client_err));
#endif
	mg_close_connection(client_conn);

	mark_point();
	test_sleep(1);
	mark_point();

	mg_stop(ctx);
#endif
}
Exemplo n.º 18
0
void server_destroy(struct server* srv)
{
  mg_stop(srv->ctx);

  free(srv);
}
Exemplo n.º 19
0
 void stopHTTPServer()
 {
     if (ctx)
         mg_stop(ctx);
 }
Exemplo n.º 20
0
void httpserver_destroy()
{
  mg_stop(s_httpserver_ctx);
}
Exemplo n.º 21
0
void App::stopWebServer() {
    if (notNull(m_webServer)) {
        mg_stop(m_webServer);
        m_webServer = NULL;
    }
}
Exemplo n.º 22
0
static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
  FILE *fp;
  int i;
  const char *name, *value, **options = mg_get_valid_option_names();

  switch (msg) {
    case WM_CLOSE:
      DestroyWindow(hDlg);
      break;

    case WM_COMMAND:
      switch (LOWORD(wParam)) {
        case ID_SAVE:
          EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
          if ((fp = fopen(config_file, "w+")) != NULL) {
            save_config(hDlg, fp);
            fclose(fp);
            mg_stop(ctx);
            start_mongoose(__argc, __argv);
          }
          EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
          break;
        case ID_RESET_DEFAULTS:
          for (i = 0; options[i] != NULL; i += 3) {
            name = options[i + 1];
            value = options[i + 2] == NULL ? "" : options[i + 2];
            if (is_boolean_option(name)) {
              CheckDlgButton(hDlg, ID_CONTROLS + i / 3, !strcmp(value, "yes") ?
                             BST_CHECKED : BST_UNCHECKED);
            } else {
              SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i / 3), value);
            }
          }
          break;
      }

      for (i = 0; options[i] != NULL; i += 3) {
        name = options[i + 1];
        if ((is_filename_option(name) || is_directory_option(name)) &&
            LOWORD(wParam) == ID_CONTROLS + i / 3 + ID_FILE_BUTTONS_DELTA) {
          OPENFILENAME of;
          BROWSEINFO bi;
          char path[PATH_MAX] = "";

          memset(&of, 0, sizeof(of));
          of.lStructSize = sizeof(of);
          of.hwndOwner = (HWND) hDlg;
          of.lpstrFile = path;
          of.nMaxFile = sizeof(path);
          of.lpstrInitialDir = mg_get_option(ctx, "document_root");
          of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR;

          memset(&bi, 0, sizeof(bi));
          bi.hwndOwner = (HWND) hDlg;
          bi.lpszTitle = "Choose WWW root directory:";
          bi.ulFlags = BIF_RETURNONLYFSDIRS;

          if (is_directory_option(name)) {
            SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
          } else {
            GetOpenFileName(&of);
          }

          if (path[0] != '\0') {
            SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i / 3), path);
          }
        }
      }

      break;

    case WM_INITDIALOG:
      SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
      SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
      SetWindowText(hDlg, "Mongoose settings");
      SetFocus(GetDlgItem(hDlg, ID_SAVE));
      for (i = 0; options[i] != NULL; i += 3) {
        name = options[i + 1];
        value = mg_get_option(ctx, name);
        if (is_boolean_option(name)) {
          CheckDlgButton(hDlg, ID_CONTROLS + i / 3, !strcmp(value, "yes") ?
                         BST_CHECKED : BST_UNCHECKED);
        } else {
          SetDlgItemText(hDlg, ID_CONTROLS + i / 3, value == NULL ? "" : value);
        }
      }
      break;
    default:
      break;
  }

  return FALSE;
}
Exemplo n.º 23
0
Arquivo: todo.c Projeto: alvarezp/todo
void term(){
  sqlite3_close(db);
  mg_stop(ctx);
}
bool finalize_restapi_manager() {
  mg_stop(ctx);
  delete_url_mapping_db( &url_mapping_db );
  memset( &callbacks, 0, sizeof( callbacks ) );
}
Exemplo n.º 25
0
Webservice::~Webservice()
{
    // Stop the server.
    mg_stop(ctx);

}
Exemplo n.º 26
0
static void test_mg_upload(void) {
  struct mg_context *ctx;
  ASSERT((ctx = mg_start(event_handler, NULL, OPTIONS)) != NULL);
  mg_stop(ctx);
}
Exemplo n.º 27
0
//停止webserver
void stop_webserver()
{
    mg_stop(ctx);//Stop server thread, and release the context.
}
Exemplo n.º 28
0
/*******************  FUNCTION  *********************/
void HttpServer::stop()
{
    assert(status == SERVER_RUNNING && ctx != NULL);
    mg_stop(ctx);
    this->ctx = NULL;
}
Exemplo n.º 29
0
int
main(int argc, char *argv[])
{
	const char *options[] = {"document_root",
	                         DOCUMENT_ROOT,
	                         "listening_ports",
	                         PORT,
	                         "request_timeout_ms",
	                         "10000",
	                         "error_log_file",
	                         "error.log",
#ifdef USE_WEBSOCKET
	                         "websocket_timeout_ms",
	                         "3600000",
#endif
#ifndef NO_SSL
	                         "ssl_certificate",
                             "../../resources/cert/server.pem",
#endif
	                         0};
	struct mg_callbacks callbacks;
	struct mg_context *ctx;
	struct mg_server_ports ports[32];
	int port_cnt, n;
	int err = 0;

/* Check if libcivetweb has been built with all required features. */
#ifdef USE_IPV6
	if (!mg_check_feature(8)) {
		fprintf(stderr,
		        "Error: Embedded example built with websocket support, "
		        "but civetweb library build without.\n");
		err = 1;
	}
#endif
#ifdef USE_WEBSOCKET
	if (!mg_check_feature(16)) {
		fprintf(stderr,
		        "Error: Embedded example built with websocket support, "
		        "but civetweb library build without.\n");
		err = 1;
	}
#endif
#ifndef NO_SSL
	if (!mg_check_feature(2)) {
		fprintf(stderr,
		        "Error: Embedded example built with SSL support, "
		        "but civetweb library build without.\n");
		err = 1;
	}
#endif
	if (err) {
		fprintf(stderr, "Cannot start CivetWeb - inconsistent build.\n");
		return EXIT_FAILURE;
	}

	/* Start CivetWeb web server */
	memset(&callbacks, 0, sizeof(callbacks));
	ctx = mg_start(&callbacks, 0, options);

	/* Add handler EXAMPLE_URI, to explain the example */
	mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
	mg_set_request_handler(ctx, EXIT_URI, ExitHandler, 0);

	/* Add handler for /A* and special handler for /A/B */
	mg_set_request_handler(ctx, "/A", AHandler, 0);
	mg_set_request_handler(ctx, "/A/B", ABHandler, 0);

	/* Add handler for /B, /B/A, /B/B but not for /B* */
	mg_set_request_handler(ctx, "/B$", BXHandler, (void *)0);
	mg_set_request_handler(ctx, "/B/A$", BXHandler, (void *)1);
	mg_set_request_handler(ctx, "/B/B$", BXHandler, (void *)2);

	/* Add handler for all files with .foo extention */
	mg_set_request_handler(ctx, "**.foo$", FooHandler, 0);

	/* Add HTTP site to open a websocket connection */
	mg_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0);

#ifdef USE_WEBSOCKET
	/* WS site for the websocket connection */
	mg_set_websocket_handler(ctx,
	                         "/websocket",
	                         WebSocketConnectHandler,
	                         WebSocketReadyHandler,
	                         WebsocketDataHandler,
	                         WebSocketCloseHandler,
	                         0);
#endif

	/* List all listening ports */
	memset(ports, 0, sizeof(ports));
	port_cnt = mg_get_server_ports(ctx, 32, ports);
	printf("\n%i listening ports:\n\n", port_cnt);

	for (n = 0; n < port_cnt && n < 32; n++) {
		const char *proto = ports[n].is_ssl ? "https" : "http";
		const char *host;

		if ((ports[n].protocol & 1) == 1) {
			/* IPv4 */
			host = "127.0.0.1";
			printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
			printf("Run example at %s://%s:%i%s\n",
			       proto,
			       host,
			       ports[n].port,
			       EXAMPLE_URI);
			printf(
			    "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
			printf("\n");
		}

		if ((ports[n].protocol & 2) == 2) {
			/* IPv6 */
			host = "[::1]";
			printf("Browse files at %s://%s:%i/\n", proto, host, ports[n].port);
			printf("Run example at %s://%s:%i%s\n",
			       proto,
			       host,
			       ports[n].port,
			       EXAMPLE_URI);
			printf(
			    "Exit at %s://%s:%i%s\n", proto, host, ports[n].port, EXIT_URI);
			printf("\n");
		}
	}

	/* Wait until the server should be closed */
	while (!exitNow) {
#ifdef _WIN32
		Sleep(1000);
#else
		sleep(1);
#endif
#ifdef USE_WEBSOCKET
		InformWebsockets(ctx);
#endif
	}

	/* Stop the server */
	mg_stop(ctx);
	printf("Server stopped.\n");
	printf("Bye!\n");

	return EXIT_SUCCESS;
}
Exemplo n.º 30
0
static void test_mg_upload(void) {
  static const char *boundary = "OOO___MY_BOUNDARY___OOO";
  struct mg_context *ctx;
  struct mg_connection *conn;
  char ebuf[100], buf[20], *file_data, *file2_data, *post_data;
  int file_len, file2_len, post_data_len;

  ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL);

  // Upload one file
  ASSERT((file_data = read_file("src/civetweb.c", &file_len)) != NULL);
  post_data = NULL;
  post_data_len = alloc_printf(&post_data, 0,
                                       "--%s\r\n"
                                       "Content-Disposition: form-data; "
                                       "name=\"file\"; "
                                       "filename=\"%s\"\r\n\r\n"
                                       "%.*s\r\n"
                                       "--%s--\r\n",
                                       boundary, upload_filename,
                                       file_len, file_data, boundary);
  ASSERT(post_data_len > 0);
  ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
                             ebuf, sizeof(ebuf),
                             "POST /upload?1 HTTP/1.1\r\n"
                             "Content-Length: %d\r\n"
                             "Content-Type: multipart/form-data; "
                             "boundary=%s\r\n\r\n"
                             "%.*s", post_data_len, boundary,
                             post_data_len, post_data)) != NULL);
  free(file_data), free(post_data);
  ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  mg_close_connection(conn);

  // Upload two files
  ASSERT((file_data = read_file("include/civetweb.h", &file_len)) != NULL);
  ASSERT((file2_data = read_file("README.md", &file2_len)) != NULL);
  post_data = NULL;
  post_data_len = alloc_printf(&post_data, 0,
                               // First file
                               "--%s\r\n"
                               "Content-Disposition: form-data; "
                               "name=\"file\"; "
                               "filename=\"%s\"\r\n\r\n"
                               "%.*s\r\n"

                               // Second file
                               "--%s\r\n"
                               "Content-Disposition: form-data; "
                               "name=\"file\"; "
                               "filename=\"%s\"\r\n\r\n"
                               "%.*s\r\n"

                               // Final boundary
                               "--%s--\r\n",
                               boundary, upload_filename,
                               file_len, file_data,
                               boundary, upload_filename2,
                               file2_len, file2_data,
                               boundary);
  ASSERT(post_data_len > 0);
  ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1,
                             ebuf, sizeof(ebuf),
                             "POST /upload?2 HTTP/1.1\r\n"
                             "Content-Length: %d\r\n"
                             "Content-Type: multipart/form-data; "
                             "boundary=%s\r\n\r\n"
                             "%.*s", post_data_len, boundary,
                             post_data_len, post_data)) != NULL);
  free(file_data), free(file2_data), free(post_data);
  ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message));
  ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0);
  mg_close_connection(conn);

  mg_stop(ctx);
}