Esempio n. 1
0
web_engine::web_engine(emu_options &options)
	: m_options(options),
		m_machine(NULL),
		m_ctx(NULL),
		m_lastupdatetime(0),
		m_exiting_core(false)

{
	struct mg_callbacks callbacks;

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

	// Prepare callbacks structure.
	memset(&callbacks, 0, sizeof(callbacks));
	callbacks.begin_request = begin_request_handler_static;
	callbacks.websocket_ready = websocket_ready_handler_static;
	callbacks.websocket_data = websocket_data_handler_static;
	callbacks.http_error = begin_http_error_handler_static;

	// Start the web server.
	if (m_options.http()) {
		m_ctx = mg_start(&callbacks, this, web_options);

		mg_start_thread(websocket_keepalive_static, this);
	}

}
Esempio n. 2
0
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;
  char *addr = argv[1];

  if (argc < 2) {
    fprintf(stderr, "Usage: %s <server_address>\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  /* Start separate thread that generates MJPG data */
  mg_start_thread(generate_mjpg_data_thread_func, NULL);

  printf("Streaming [%s] to [%s]\n", s_mjpg_file, addr);

  mg_mgr_init(&mgr, NULL);

  for (;;) {
    mg_mgr_poll(&mgr, s_poll_interval_ms);

    /* Reconnect if disconnected */
    if (!client) {
      sleep(1); /* limit reconnections frequency */
      printf("Reconnecting to %s...\n", addr);
      client = mg_connect(&mgr, addr, ev_handler);
      if (client) mg_set_protocol_http_websocket(client);
    }
  }

  return EXIT_SUCCESS;
}
Esempio n. 3
0
void websock_init_lib(void) {

    int ret;
    ret = pthread_mutex_init(&sMutex, 0);
    assert(ret==0);

    memset(socketList,0,sizeof(socketList));

    mg_start_thread(eventMain, 0);
}
Esempio n. 4
0
void server::warmup() {
    for (int i = 0; i < 4; ++i) {
        struct mg_mgr* mgMgr = new mg_mgr;
        vectorMgr.push_back(mgMgr);
        mg_mgr_init(mgMgr, this);
        mg_bind(mgMgr, s_http_port, ev_handler);
    }
    for(mg_mgr*mgMgr: vectorMgr){ mg_start_thread(run,mgMgr); }
    while(true){
        sleep(1);
    }
    std::cout<< "this is a test" << std::endl;
}
Esempio n. 5
0
int main(void) {
  struct mg_server *proxy_server = mg_create_server(NULL, ev_handler);
  struct mg_server *ws1_server = mg_create_server(NULL, ws_handler);
  struct mg_server *ws2_server = mg_create_server(NULL, ws_handler);
  size_t i;

  // Configure proxy server to listen on port 2014
  mg_set_option(proxy_server, "listening_port", "2014");
  //mg_set_option(proxy_server, "enable_proxy", "yes");

  // Configure two websocket echo servers:
  //    ws1 is WS, listening on 9001
  //    ws2 is WSS, listening on 9002
  // Note that HTML page thinks that ws1 is WSS, and ws2 is WS,
  // where in reality it is vice versa and proxy server makes the decision.
  mg_set_option(ws1_server, "listening_port", "9001");
  mg_set_option(ws2_server, "listening_port", "9002");
  mg_set_option(ws2_server, "ssl_certificate", "certs/ws2_server.pem");

  // Setup signal handlers
  signal(SIGTERM, signal_handler);
  signal(SIGINT, signal_handler);
  
  // Start SSL wrappers, each in it's own thread
  for (i = 0; i < ARRAY_SIZE(s_wrappers); i++) {
    ns_start_thread(wrapper_thread_func, &s_wrappers[i]);
  }

  // Start websocket servers in separate threads
  mg_start_thread(serve_thread_func, ws1_server);
  mg_start_thread(serve_thread_func, ws2_server);
  
  // Finally, start proxy server in this thread: this call blocks
  serve_thread_func(proxy_server);

  printf("Existing on signal %d\n", s_received_signal);
  return EXIT_SUCCESS;
}
Esempio n. 6
0
// Once websocket negotiation is complete, start a server for the connection
void websocket_ready_handler(struct mg_connection *conn)
{ 
  wsserver* object = static_cast<wsserver*>(mg_get_request_info(conn)->user_data);

  if(object->getDebug()) post("ready handler\n");
  
  for(int i=0; i < object->getMaxNConnections(); ++i) 
  {
    if (object->getConnection(i)->conn == conn) 
    {
      if(object->getDebug()) post("...start server %d\n", i);
      mg_start_thread(ws_server_thread, (void *) object->getConnection(i));
      break;
    }
  }
}
Esempio n. 7
0
int main(int argc, char *argv[]) {
  struct mg_server *server = mg_create_server(NULL);

  mg_set_option(server, "listening_port", "8080");
  mg_set_option(server, "document_root", argc > 1 ? argv[1] : ".");
  mg_add_uri_handler(server, "/ws", handler);
  mg_start_thread(timer_thread, server);

  printf("Started on port %s\n", mg_get_option(server, "listening_port"));
  for (;;) {
    mg_poll_server(server, 3000);
  }

  mg_destroy_server(&server);
  return 0;
}
Esempio n. 8
0
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;

  if (argc != 3) {
    fprintf(stderr, "Usage: %s <port> <client|server>\n", argv[0]);
    exit(EXIT_FAILURE);
  } else if (strcmp(argv[2], "client") == 0) {
    sock_t fds[2];
    struct mg_connection *ioconn, *server_conn;

    mg_mgr_init(&mgr, NULL);

    // Connect to the pubsub server
    server_conn = mg_connect(&mgr, argv[1], client_handler);
    if (server_conn == NULL) {
      fprintf(stderr, "Cannot connect to port %s\n", argv[1]);
      exit(EXIT_FAILURE);
    }
    server_conn->flags |= MG_F_USER_2;  // Mark this as a client connection

    // Create a socketpair and give one end to the thread that reads stdin
    mg_socketpair(fds, SOCK_STREAM);
    mg_start_thread(stdin_thread, &fds[1]);

    // The other end of a pair goes inside the server
    ioconn = mg_add_sock(&mgr, fds[0], client_handler);
    ioconn->flags |= MG_F_USER_1;  // Mark this so we know this is a stdin
    ioconn->user_data = server_conn;

  } else {
    // Server code path
    mg_mgr_init(&mgr, NULL);
    mg_bind(&mgr, argv[1], server_handler);
    printf("Starting pubsub server on port %s\n", argv[1]);
  }

  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);

  return EXIT_SUCCESS;
}
Esempio n. 9
0
int main(void) {
  struct mg_server *server1, *server2;

  server1 = mg_create_server((void *) "1");
  server2 = mg_create_server((void *) "2");

  mg_add_uri_handler(server1, "/", request_handler);
  mg_add_uri_handler(server2, "/", request_handler);

  // Make both server1 and server2 listen on the same socket
  mg_set_option(server1, "listening_port", "8080");
  mg_set_listening_socket(server2, mg_get_listening_socket(server1));

  // server1 goes to separate thread, server 2 runs in main thread.
  // IMPORTANT: NEVER LET DIFFERENT THREADS HANDLE THE SAME SERVER.
  mg_start_thread(serve, server1);
  serve(server2);

  return 0;
}
Esempio n. 10
0
File: Server.cpp Progetto: tits0/bet
    void Server::start()
    {
        if (server == NULL) {
#ifdef ENABLE_STATS
            requests = 0;
            startTime = getTime();
#endif
            server = mg_create_server(this, event_handler);

            map<string, string>::iterator it;
            for (it=optionsMap.begin(); it!=optionsMap.end(); it++) {
                mg_set_option(server, (*it).first.c_str(), (*it).second.c_str());
            }

            //mg_add_uri_handler(server, "/", event_handler);
            //mg_server_do_i_handle(server, do_i_handle);

            stopped = false;
            mg_start_thread(server_poll, this);
        } else {
            throw string("Server is already running");
        }
    }
Esempio n. 11
0
void lua_engine::start_console()
{
	mg_start_thread(::serve_lua, this);
}
Esempio n. 12
0
void SV_SpawnServer( char *server, qboolean killBots, ForceReload_e eForceReload ) {
	int			i;
	int			checksum;
	qboolean	isBot;
	char		systemInfo[16384];
	const char	*p;

	Com_Printf("------ Server Initialization ------\n");
	Com_Printf("Server: %s\n", server);

	SV_SendMapChange();

	RE_RegisterMedia_LevelLoadBegin(server, eForceReload);

	// shut down the existing game if it is running
	SV_ShutdownGameProgs();

	FixGhoul2InfoLeaks(false,true);

/*
Ghoul2 Insert Start
*/
 	// de allocate the snapshot entities
	if (svs.snapshotEntities)
	{
		delete[] svs.snapshotEntities;
		svs.snapshotEntities = NULL;
	}
/*
Ghoul2 Insert End
*/

	SV_SendMapChange();

	// if not running a dedicated server CL_MapLoading will connect the client to the server
	// also print some status stuff
	CL_MapLoading();

#ifndef DEDICATED
	// make sure all the client stuff is unloaded
	CL_ShutdownAll();
#endif

	CM_ClearMap();

	// clear the whole hunk because we're (re)loading the server
	Hunk_Clear();

/*
Ghoul2 Insert Start
*/
	// clear out those shaders, images and Models as long as this
	// isnt a dedicated server.
	if ( !com_dedicated->integer )
	{
#ifndef DEDICATED
		R_InitImages();

		R_InitShaders();

		R_ModelInit();
#endif
	}
	else
	{
		R_SVModelInit();

#ifdef G2_COLLISION_ENABLED
		if (!G2VertSpaceServer)
		{
			G2VertSpaceServer = new CMiniHeap(G2_VERT_SPACE_SERVER_SIZE * 1024);
		}
#endif
	}

	SV_SendMapChange();

	// init client structures and svs.numSnapshotEntities
	if ( !Cvar_VariableValue("sv_running") ) {
		SV_Startup();
	} else {
		// check for maxclients change
		if ( sv_maxclients->modified ) {
			SV_ChangeMaxClients();
		}
	}

	SV_SendMapChange();

	// clear pak references
	FS_ClearPakReferences(0);

/*
Ghoul2 Insert Start
*/
	// allocate the snapshot entities on the hunk
//	svs.snapshotEntities = (struct entityState_s *)Hunk_Alloc( sizeof(entityState_t)*svs.numSnapshotEntities, h_high );
	svs.nextSnapshotEntities = 0;

	// allocate the snapshot entities
	svs.snapshotEntities = new entityState_s[svs.numSnapshotEntities];
	// we CAN afford to do this here, since we know the STL vectors in Ghoul2 are empty
	memset(svs.snapshotEntities, 0, sizeof(entityState_t)*svs.numSnapshotEntities);

/*
Ghoul2 Insert End
*/

	// toggle the server bit so clients can detect that a
	// server has changed
	svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT;

	// set nextmap to the same map, but it may be overriden
	// by the game startup or another console command
	Cvar_Set( "nextmap", "map_restart 0");
//	Cvar_Set( "nextmap", va("map %s", server) );

	// wipe the entire per-level structure
	SV_ClearServer();
	for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) {
		sv.configstrings[i] = CopyString("");
	}

	// decide which serverversion to host
	mv_serverversion = Cvar_Get("mv_serverversion", "1.04", CVAR_ARCHIVE | CVAR_LATCH | CVAR_GLOBAL);
	if (FS_AllPath_Base_FileExists("assets5.pk3") && (!strcmp(mv_serverversion->string, "auto") || !strcmp(mv_serverversion->string, "1.04"))) {
		Com_Printf("serverversion set to 1.04\n");
		MV_SetCurrentGameversion(VERSION_1_04);
	}
	else if (FS_AllPath_Base_FileExists("assets2.pk3") && (!strcmp(mv_serverversion->string, "auto") || !strcmp(mv_serverversion->string, "1.03"))) {
		Com_Printf("serverversion set to 1.03\n");
		MV_SetCurrentGameversion(VERSION_1_03);
	} else {
		Com_Printf("serverversion set to 1.02\n");
		MV_SetCurrentGameversion(VERSION_1_02);
	}

	Cvar_Set("protocol", va("%i", MV_GetCurrentProtocol()));

	// make sure we are not paused
	Cvar_Set("cl_paused", "0");

	// get a new checksum feed and restart the file system
	srand(Com_Milliseconds());
	sv.checksumFeed = ( ((int) rand() << 16) ^ rand() ) ^ Com_Milliseconds();

	FS_PureServerSetReferencedPaks("", "");
	FS_Restart( sv.checksumFeed );

	CM_LoadMap( va("maps/%s.bsp", server), qfalse, &checksum );

	SV_SendMapChange();

	// set serverinfo visible name
	Cvar_Set( "mapname", server );

	Cvar_Set( "sv_mapChecksum", va("%i",checksum) );

	// serverid should be different each time
	sv.serverId = com_frameTime;
	sv.restartedServerId = sv.serverId;
	Cvar_Set( "sv_serverid", va("%i", sv.serverId ) );

	// clear physics interaction links
	SV_ClearWorld ();

	// media configstring setting should be done during
	// the loading stage, so connected clients don't have
	// to load during actual gameplay
	sv.state = SS_LOADING;

	// load and spawn all other entities
	SV_InitGameProgs();

	// don't allow a map_restart if game is modified
	sv_gametype->modified = qfalse;

	// run a few frames to allow everything to settle
	for ( i = 0 ;i < 3 ; i++ ) {
		VM_Call( gvm, GAME_RUN_FRAME, svs.time );
		SV_BotFrame( svs.time );
		svs.time += 100;
	}

	// create a baseline for more efficient communications
	SV_CreateBaseline ();

	for (i=0 ; i<sv_maxclients->integer ; i++) {
		// send the new gamestate to all connected clients
		if (svs.clients[i].state >= CS_CONNECTED) {
			char	*denied;

			if ( svs.clients[i].netchan.remoteAddress.type == NA_BOT ) {
				if ( killBots ) {
					SV_DropClient( &svs.clients[i], "" );
					continue;
				}
				isBot = qtrue;
			}
			else {
				isBot = qfalse;
			}

			// connect the client again
			denied = (char *)VM_ExplicitArgPtr( gvm, VM_Call( gvm, GAME_CLIENT_CONNECT, i, qfalse, isBot ) );	// firstTime = qfalse
			if ( denied ) {
				// this generally shouldn't happen, because the client
				// was connected before the level change
				SV_DropClient( &svs.clients[i], denied );
			} else {
				if( !isBot ) {
					// when we get the next packet from a connected client,
					// the new gamestate will be sent
					svs.clients[i].state = CS_CONNECTED;
				}
				else {
					client_t		*client;
					sharedEntity_t	*ent;

					client = &svs.clients[i];
					client->state = CS_ACTIVE;
					ent = SV_GentityNum( i );
					ent->s.number = i;
					client->gentity = ent;

					client->deltaMessage = -1;
					client->nextSnapshotTime = svs.time;	// generate a snapshot immediately

					VM_Call( gvm, GAME_CLIENT_BEGIN, i );
				}
			}
		}
	}

	// run another frame to allow things to look at all the players
	VM_Call( gvm, GAME_RUN_FRAME, svs.time );
	SV_BotFrame( svs.time );
	svs.time += 100;

	if ( sv_pure->integer ) {
		// the server sends these to the clients so they will only
		// load pk3s also loaded at the server
		p = FS_LoadedPakChecksums();
		Cvar_Set( "sv_paks", p );
		if (strlen(p) == 0) {
			Com_Printf( "WARNING: sv_pure set but no PK3 files loaded\n" );
		}
		p = FS_LoadedPakNames();
		Cvar_Set( "sv_pakNames", p );

		// if a dedicated pure server we need to touch the cgame because it could be in a
		// seperate pk3 file and the client will need to load the latest cgame.qvm
		if ( com_dedicated->integer ) {
			SV_TouchCGame();
		}
	}
	else {
		Cvar_Set( "sv_paks", "" );
		Cvar_Set( "sv_pakNames", "" );
	}
	// the server sends these to the clients so they can figure
	// out which pk3s should be auto-downloaded
	p = FS_ReferencedPakChecksums();
	Cvar_Set( "sv_referencedPaks", p );
	p = FS_ReferencedPakNames();
	Cvar_Set( "sv_referencedPakNames", p );

	// save systeminfo and serverinfo strings
	Q_strncpyz( systemInfo, Cvar_InfoString_Big( CVAR_SYSTEMINFO ), sizeof( systemInfo ) );
	cvar_modifiedFlags &= ~CVAR_SYSTEMINFO;
	SV_SetConfigstring( CS_SYSTEMINFO, systemInfo );

	SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) );
	cvar_modifiedFlags &= ~CVAR_SERVERINFO;

	// any media configstring setting now should issue a warning
	// and any configstring changes should be reliably transmitted
	// to all clients
	sv.state = SS_GAME;

	// send a heartbeat now so the master will get up to date info
	SV_Heartbeat_f();

	Hunk_SetMark();

	Com_Printf ("-----------------------------------\n");

	/* MrE: 2000-09-13: now called in CL_DownloadsComplete
	// don't call when running dedicated
	if ( !com_dedicated->integer ) {
		// note that this is called after setting the hunk mark with Hunk_SetMark
		CL_StartHunkUsers();
	}
	*/

	// shutdown webserver
	if (mgsrv && ((mv_httpdownloads->latchedString && !atoi(mv_httpdownloads->latchedString)) || mv_httpserverport->latchedString)) {
		SV_MV_Websrv_Shutdown();
	}

	// here because latched
	mv_httpdownloads = Cvar_Get("mv_httpdownloads", "0", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_LATCH);
	mv_httpserverport = Cvar_Get("mv_httpserverport", "0", CVAR_ARCHIVE | CVAR_LATCH);

	// start webserver
	if (mv_httpdownloads->integer) {
		if (Q_stristr(mv_httpserverport->string, "http://")) {
			Com_Printf("HTTP Downloads: redirecting to %s\n", mv_httpserverport->string);
		} else if (!mgsrv) {
			const char *err = NULL;
			int port;

			mgsrv = mg_create_server(NULL, SV_MV_Websrv_Request_ExtThread);
			mg_set_option(mgsrv, "document_root", Cvar_Get("fs_basepath", "", 0)->string);

			if (mv_httpserverport->integer) {
				port = mv_httpserverport->integer;
				err = mg_set_option(mgsrv, "listening_port", va("%i", port));
			} else {
				for (port = HTTPSRV_STDPORT; port <= HTTPSRV_STDPORT + 15; port++) {
					err = mg_set_option(mgsrv, "listening_port", va("%i", port));
					if (!err) {
						break;
					}
				}
			}

			if (!err) {
				sv.http_port = port;
				Com_Printf("HTTP Downloads: webserver running on port %i...\n", port);
			} else {
				Com_Error(ERR_DROP, "HTTP Downloads: webserver startup failed: %s", err);
			}

			mg_start_thread(SV_MV_Websrv_Loop_ExtThread, mgsrv);
		}
	}
}
Esempio n. 13
0
File: main.c Progetto: ceph/mongoose
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);
            TerminateThread(hThread, 0);
            mg_destroy_server(&server);
            start_mongoose(__argc, __argv);
            mg_start_thread(serving_thread_func, server);
          }
          EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
          break;
        case ID_RESET_DEFAULTS:
          for (i = 0; options[i * 2] != NULL; i++) {
            name = options[i * 2];
            value = options[i * 2 + 1] == NULL ? "" : options[i * 2 + 1];
            if (is_boolean_option(name)) {
              CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
                             BST_CHECKED : BST_UNCHECKED);
            } else {
              SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
            }
          }
          break;
      }

      for (i = 0; options[i * 2] != NULL; i++) {
        name = options[i * 2];
        if ((is_filename_option(name) || is_directory_option(name)) &&
            LOWORD(wParam) == ID_CONTROLS + i + 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(server, "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), 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 * 2] != NULL; i++) {
        name = options[i * 2];
        value = mg_get_option(server, name);
        if (is_boolean_option(name)) {
          CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
                         BST_CHECKED : BST_UNCHECKED);
        } else {
          SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
        }
      }
      break;
    default:
      break;
  }

  return FALSE;
}