int main(int argc,char *argv[])
{
	int num_words,i;
	struct timeval t0,t1;
	char search_word[1001];

	// handle command line argument
	if (argc != 2) {
		printf("Syntax: %s num_words\n",argv[0]);
		exit(1);
	}
	num_words = atoi(argv[1]);

	// initialize search_word to 1, 1, ..., 101, a word which is not added
	for (i = 0; i < 1000; i++)
		search_word[i] = 1;
	search_word[999] = 101;
	search_word[1000] = '\0';

	// add words
	ws_init();
	add_words(num_words);

	// time a worst case find
	gettimeofday(&t0,NULL);
	ws_find_word(search_word); // entire list will be searched
	gettimeofday(&t1,NULL);

	// display the difference
	printf("After %d words loaded, find in %d microseconds.\n",
	 num_words,tv_diff(t0,t1));

	return 0;
}
Пример #2
0
/* Start the WebSocket server and initialize default options. */
static void
start_server (void *ptr_data)
{
  GWSWriter *writer = (GWSWriter *) ptr_data;

  if ((writer->server = ws_init ("0.0.0.0", "7890")) == NULL)
    return;

  ws_set_config_strict (1);
  if (conf.addr)
    ws_set_config_host (conf.addr);
  if (conf.fifo_in)
    ws_set_config_pipein (conf.fifo_in);
  if (conf.fifo_out)
    ws_set_config_pipeout (conf.fifo_out);
  if (conf.origin)
    ws_set_config_origin (conf.origin);
  if (conf.port)
    ws_set_config_port (conf.port);
  if (conf.sslcert)
    ws_set_config_sslcert (conf.sslcert);
  if (conf.sslkey)
    ws_set_config_sslkey (conf.sslkey);
  writer->server->onopen = onopen;
  set_self_pipe (writer->server->self_pipe);

  /* select(2) will block in here */
  ws_start (writer->server);
  fprintf (stderr, "Stopping WebSocket server...\n");
  ws_stop (writer->server);
}
Пример #3
0
/* Setup and start the WebSocket threads. */
int
setup_ws_server (GWSWriter * gwswriter, GWSReader * gwsreader)
{
  int id;
  pthread_t *thread;

  if (pthread_mutex_init (&gwswriter->mutex, NULL))
    FATAL ("Failed init gwswriter mutex");
  if (pthread_mutex_init (&gwsreader->mutex, NULL))
    FATAL ("Failed init gwsreader mutex");

  /* send WS data thread */
  thread = &gwswriter->thread;

  /* pre-init the websocket server, to ensure the FIFOs are created */
  if ((gwswriter->server = ws_init ("0.0.0.0", "7890", set_ws_opts)) == NULL)
    FATAL ("Failed init websocket");

  id = pthread_create (&(*thread), NULL, (void *) &start_server, gwswriter);
  if (id)
    FATAL ("Return code from pthread_create(): %d", id);

  /* read WS data thread */
  thread = &gwsreader->thread;
  id = pthread_create (&(*thread), NULL, (void *) &read_client, gwsreader);
  if (id)
    FATAL ("Return code from pthread_create(): %d", id);

  return 0;
}
/* Return entry from host data base for host with NAME.  */
struct hostent *__w32_gethostbyname (__const char *__name)
{
	struct hostent *ht;
	
	if (ws_init() == -1)
		return NULL;
	ht = gethostbyname (__name);
	if (ht == NULL)
		WSAErr;
	return ht;
}
Пример #5
0
int malloc_connect(ws_connect_t *&ptr, void *obj)
{
    ptr = new ws_connect_t;
    
    printf("malloc back\n");

	ws_init(ptr, uv_default_loop());
    
    ws_set_connect(ptr, con_cb, cb_error, NULL);
    
    return 0;
}
Пример #6
0
int main(int argc, char ** argv)
{
   char buf[8000];
   websocket_t ws;
   int fd, plen, len;

   fd = ws_connect();

   ws_init(&ws, fd, 1000, 1);

   for (int eof = 0; !eof;)
   {
      for (len = 0; !eof;)
      {
         if ((plen = read(0, buf + len, sizeof(buf) - len)) == -1)
            exit(1);

         // check for eof
         eof = plen == 0;

         len += plen;
         // check for "\n.\n" (single period on line)
         if (len > 2 && buf[len - 1] == '\n' &&
               buf[len - 3] == '\n' && buf[len - 2] == '.')
         {
            // remove it
            len -= 2;
            break;
         }
      }

      if ((ws_write(&ws, buf, len)) == -1)
         exit(1);

      if ((plen = ws_read(&ws, buf, sizeof(buf))) == -1)
         exit(1);

      if (!plen)
         break;

      write(1, buf, plen);
   }

   ws_free(&ws);

   close(fd);
   return 0;
}
int TEST_ws_generate_handshake_key(int argc, char *argv[])
{
	int ret = 0;
	ws_base_t base = NULL;
	ws_t ws = NULL;

	libws_test_HEADLINE("TEST_ws_generate_handshake_key");
	
	if (libws_test_init(argc, argv)) return -1;

	if (ws_global_init(&base))
	{
		libws_test_FAILURE("Failed to init global state");
		return -1;
	}

	if (ws_init(&ws, base))
	{
		libws_test_FAILURE("Failed to init websocket state");
		ret = -1;
		goto fail;
	}

	libws_test_STATUS("Run the same test twice to check for memory leaks");
	ret |= do_test(ws, 1);
	ret |= do_test(ws, 1);

	#ifndef WIN32
	libws_test_STATUS("Close file descriptor to random source and check fail");
	
	if (close(base->random_fd))
	{
		libws_test_FAILURE("Failed to close random source: %s (%d)", 
							strerror(errno), errno);
		ret |= -1;
	}
	else
	{
		ret |= do_test(ws, 0);
	}
	#endif

fail:
	ws_destroy(&ws);
	ws_global_destroy(&base);

	return ret;
}
Пример #8
0
int tport_ws_init_secondary(tport_t *self, int socket, int accepted,
			     char const **return_reason)
{
  int one = 1;
  tport_ws_primary_t *wspri = (tport_ws_primary_t *)self->tp_pri;
  tport_ws_t *wstp = (tport_ws_t *)self;

  self->tp_has_connection = 1;

  /* override the default 30 minute timeout on tport connections */
  self->tp_params->tpp_idle = UINT_MAX;

  if (setsockopt(socket, SOL_TCP, TCP_NODELAY, (void *)&one, sizeof one) == -1)
	  return *return_reason = "TCP_NODELAY", -1;

#if defined(SO_KEEPALIVE)
  setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, (void *)&one, sizeof one);
#endif
  one = 30;
#if defined(TCP_KEEPIDLE)
  setsockopt(socket, SOL_TCP, TCP_KEEPIDLE, (void *)&one, sizeof one);
#endif
#if defined(TCP_KEEPINTVL)
  setsockopt(socket, SOL_TCP, TCP_KEEPINTVL, (void *)&one, sizeof one);
#endif


  if (!accepted)
    tport_ws_setsndbuf(socket, 64 * 1024);

  if ( wspri->ws_secure ) wstp->ws_secure = 1;

  memset(&wstp->ws, 0, sizeof(wstp->ws));

  if (ws_init(&wstp->ws, socket, wstp->ws_secure ? wspri->ssl_ctx : NULL, 0) < 0) {
	  ws_destroy(&wstp->ws);
	  wstp->ws_initialized = -1;
	  return *return_reason = "WS_INIT", -1;
  }

  wstp->ws_initialized = 1;
  self->tp_pre_framed = 1;
  


  return 0;
}
Пример #9
0
int
main (int argc, char **argv)
{
  if ((server = ws_init ("0.0.0.0", "7890")) == NULL) {
    perror ("Error during ws_init.\n");
    exit (EXIT_FAILURE);
  }
  /* callbacks */
  server->onclose = onclose;
  server->onmessage = onmessage;
  server->onopen = onopen;

  set_self_pipe ();
  if (setup_signals () != 0)
    exit (EXIT_FAILURE);

  if (read_option_args (argc, argv) == 0)
    ws_start (server);
  ws_stop (server);

  return EXIT_SUCCESS;
}
Пример #10
0
int main()
{
    ws_server_t server;
    
    ws_listen(&server, uv_default_loop(), 8090, malloc_connect, NULL);
    
    //uv_run(uv_default_loop(), UV_RUN_DEFAULT);
    
    ws_connect_t connect;
    
    ws_init(&connect, uv_default_loop());
    
    ws_connect(&connect, "127.0.0.1", 8090, connect_cb, cb_error, NULL);
    
    printf("adfd");
    
    uv_run(uv_default_loop(), UV_RUN_DEFAULT);
    
    //ws_quit(&connect);
    
    return 0;
}
Пример #11
0
/*------------------------------------------------------------------------------
	main()
		Main
	Preconditions:
	Postconditions:
 *----------------------------------------------------------------------------*/
int  main(
	int argc,
	char **argv )
/*----------------------------------------------------------------------------*/
{
	int user_input;
	char user_str[128];

	ws_init();
	tty_init();
	// rmcpd_init_listener();

	printf("\nIPMI Exerciser -- %s\n", __DATE__); // say Hi

	process_command_line( argc, argv ); // process command line arguments
	// Get user keyboard input
	while( 1 )
	{
		main_menu();
		scanf( "%d", &user_input );
		fflush( stdin );

		switch ( user_input )
		{
			case KBD_APP_CMDS:
				kbd_app_cmds();
				break;
			case KBD_CHASSIS_CMDS:
				break;
			case KBD_EVENT_CMDS:
				break;
			case KBD_FIRMWARE_COMMANDS:
				break;
			case KBD_NVSTORE_CMDS:
				break;
			case KBD_MEDIA_SPECIFIC_CMDS:
				break;
			case KBD_PICMG_CMDS:
				kbd_atca_cmds();
				break;
			case KBD_RUN_UNIX:
				printf( "Enter command : " );
				scanf( "%s", user_str );
				//gets( user_str );
				fflush( stdin );
				if( system( user_str ) == -1 )
					printf( "\nError in command\n" );
				printf( "\n Press any key to continue\n" );
				getchar();
				fflush( stdin );
				break;
			case KBD_SETTINGS:
				kbd_settings();
				break;
			case KBD_QUIT:
				tty_restore();
				exit( EXIT_SUCCESS );
				break;
			default:
				printf( "Unknown option %d ignored.\n", user_input );
				break;
		} // end switch
		printf( "Press any key to continue\n" );
		getchar();
		fflush( stdin );

	}
}
int TEST_ws_read_server_handshake_reply(int argc, char *argv[])
{
	int ret = 0;
	ws_base_t base = NULL;
	ws_t ws = NULL;
	char key_hash[256];
	struct evbuffer *in = evbuffer_new();

	libws_test_HEADLINE("TEST_ws_read_server_handshake_reply");
	if (libws_test_init(argc, argv)) return -1;

	if (!in)
	{
		libws_test_FAILURE("Failed to init evbuffer");
		return -1;
	}

	if (ws_global_init(&base))
	{
		libws_test_FAILURE("Failed to init global state");
		return -1;
	}

	if (ws_init(&ws, base))
	{
		libws_test_FAILURE("Failed to init websocket state");
		ret = -1;
		goto fail;
	}

	if (ws_add_subprotocol(ws, "echo"))
	{
		libws_test_FAILURE("Failed to add sub protocol \"echo\"");
		ret = -1;
		goto fail;
	}

	if (_ws_generate_handshake_key(ws))
	{
		libws_test_FAILURE("Failed to generate handshake base64 key");
		ret = -1;
		goto fail;
	}
	else
	{
		libws_test_SUCCESS("Generated handshake base64 key: %s",
							ws->handshake_key_base64);
	}

	if (_ws_calculate_key_hash(ws->handshake_key_base64, 
								key_hash, sizeof(key_hash)))
	{
		libws_test_FAILURE("Failed to calculate key hash");
		ret = -1;
		goto fail;
	}
	else
	{
		libws_test_SUCCESS("Calculated key hash: %s", key_hash);
	}

	libws_test_STATUS("Test valid full response:");
	{
		// Emulate having sent a request.
		ws->connect_state = WS_CONNECT_STATE_SENT_REQ;
		evbuffer_drain(in, evbuffer_get_length(in));

		evbuffer_add_printf(in, 
							"HTTP/1.1 101\r\n"
							"Upgrade: websocket\r\n"
							"Connection: upgrade\r\n"
							"Sec-WebSocket-Accept: %s\r\n"
							"Sec-WebSocket-Protocol: echo\r\n"
							"\r\n", key_hash);
	
		ret |= run_header_test("  Valid full response", ws, in, 
							WS_PARSE_STATE_SUCCESS);
	}

	libws_test_STATUS("Test valid partial response:");
	{
		ws->connect_state = WS_CONNECT_STATE_SENT_REQ;
		evbuffer_drain(in, evbuffer_get_length(in));

		// Part 1.
		evbuffer_add_printf(in, 
							"HTTP/1.1 101\r\n"
							"Upgrade: websocket\r\n"
							"Connection: upg");

		libws_test_STATUS("	 Parse part 1:");
		ret |= run_header_test("  Valid partial response, part 1", ws, in, 
							WS_PARSE_STATE_NEED_MORE);
		// Part 2.
		evbuffer_add_printf(in,
							"rade\r\n"
							"Sec-WebSocket-Accept: %s\r\n"
							"Sec-WebSocket-Protocol: echo\r\n"
							"\r\n", key_hash);

		libws_test_STATUS("	 Parse part 2:");
		ret |= run_header_test("  Valid partial response, part 2", ws, in, 
							WS_PARSE_STATE_SUCCESS);
	}

	libws_test_STATUS("Test invalid HTTP version:");
	{
		// Emulate having sent a request.
		ws->connect_state = WS_CONNECT_STATE_SENT_REQ;
		evbuffer_drain(in, evbuffer_get_length(in));

		evbuffer_add_printf(in, 
							"HTTP/1.0 101\r\n"
							"Upgrade: websocket\r\n"
							"Connection: upgrade\r\n"
							"Sec-WebSocket-Accept: %s\r\n"
							"Sec-WebSocket-Protocol: echo\r\n"
							"\r\n", key_hash);
		
		ret |= run_header_test("Invalid HTTP version response", ws, in, 
						WS_PARSE_STATE_ERROR);
	}

	libws_test_STATUS("Test partial HTTP version:");
	{
		// Emulate having sent a request.
		ws->connect_state = WS_CONNECT_STATE_SENT_REQ;
		evbuffer_drain(in, evbuffer_get_length(in));

		evbuffer_add_printf(in, 
							"HTTP/1.");
		
		ret |= run_header_test("Partial HTTP version response", ws, in, 
						WS_PARSE_STATE_NEED_MORE);
	}

	libws_test_STATUS("Test invalid HTTP version line:");
	{
		// Emulate having sent a request.
		ws->connect_state = WS_CONNECT_STATE_SENT_REQ;
		evbuffer_drain(in, evbuffer_get_length(in));

		evbuffer_add_printf(in, 
							"HTTP/1.1 abc\r\n");
		
		ret |= run_header_test("Invalid HTTP version response", ws, in, 
						WS_PARSE_STATE_ERROR);
	}

	libws_test_STATUS("Test empty buffer");
	{
		// Emulate having sent a request.
		ws->connect_state = WS_CONNECT_STATE_SENT_REQ;
		evbuffer_drain(in, evbuffer_get_length(in));

		ret |= run_header_test("Partial HTTP version response", ws, in, 
						WS_PARSE_STATE_NEED_MORE);
	}

fail:
	evbuffer_free(in);
	ws_destroy(&ws);
	ws_global_destroy(&base);

	return ret;
}
Пример #13
0
abyss_bool websocket_hook(TSession *r)
{
	wsh_t *wsh;
	int ret;
	int i;
	ws_opcode_t opcode;
	uint8_t *data;
	switch_event_node_t *nodes[MAX_EVENT_BIND_SLOTS];
	int node_count = 0;
	char *p;
	char *key = NULL;
	char *version = NULL;
	char *proto = NULL;
	char *upgrade = NULL;

	for (i = 0; i < r->requestHeaderFields.size; i++) {
		TTableItem * const item = &r->requestHeaderFields.item[i];

		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "headers %s: %s\n", item->name, item->value);
	}

	key = RequestHeaderValue(r, "sec-websocket-key");
	version = RequestHeaderValue(r, "sec-websocket-version");
	proto = RequestHeaderValue(r, "sec-websocket-protocol");
	upgrade = RequestHeaderValue(r, "upgrade");

	if (!key || !version || !proto || !upgrade) return FALSE;
	if (strncasecmp(upgrade, "websocket", 9) || strncasecmp(proto, "websocket", 9)) return FALSE;

	wsh = ws_init(r);
	if (!wsh) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "websocket error %d\n", ret);
		return FALSE;
	}

	ret = ws_handshake_kvp(wsh, key, version, proto);
	if (ret < 0) wsh->down = 1;

	if (ret != 0) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "handshake error %d\n", ret);
		return FALSE;
	}

	if (switch_event_bind_removable("websocket", SWITCH_EVENT_CUSTOM, "websocket::stophook", stop_hook_event_handler, wsh, &nodes[node_count++]) != SWITCH_STATUS_SUCCESS) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't bind!\n");
		node_count--;
	}

	while (!wsh->down) {
		int bytes = ws_read_frame(wsh, &opcode, &data);

		if (bytes < 0) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "%d %s\n", opcode, (char *)data);
			switch_yield(100000);
			continue;
		}

		switch (opcode) {
			case WSOC_CLOSE:
				ws_close(wsh, 1000);
				break;
			case WSOC_CONTINUATION:
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "continue\n");
				continue;
			case WSOC_TEXT:
				p = data;
				if (!p) continue;
				if (!strncasecmp(data, "event ", 6)) {
					switch_event_types_t type;
					char *subclass;

					if (node_count == MAX_EVENT_BIND_SLOTS - 1) {
						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "cannot subscribe more than %d events\n", node_count);
						continue;
					}
					p += 6;
					if (p = strchr(p, ' ')) p++;
					if (!strncasecmp(p, "json ", 5)) {
						p += 5;
					} else if (!strncasecmp(p, "xml ", 4)) {
						p += 4;
					} else if (!strncasecmp(p, "plain ", 6)) {
						p += 6;
					}
					if (!*p) {
						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "missing event type in [%s]\n", data);
						break;
					} else {
					}
					if (subclass = strchr(p, ' ')) {
						*subclass++ = '\0';
						if (!*subclass) {
							switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "missing subclass\n");
							continue;
						}
					} else {
						subclass = SWITCH_EVENT_SUBCLASS_ANY;
					}

					if (switch_name_event(p, &type) != SWITCH_STATUS_SUCCESS) {
						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Unknown event %s\n", p);
						continue;
					}

					if (switch_event_bind_removable("websocket", type, subclass, event_handler, wsh, &nodes[node_count++]) != SWITCH_STATUS_SUCCESS) {
						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't bind!\n");
						node_count--;
						continue;
					} else {
						switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Bind %s\n", data);
					}

				}
				break;
			default:
				break;
		}
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "wsh->down = %d, node_count = %d\n", wsh->down, node_count);

	switch_yield(2000);
	while (--node_count >= 0) switch_event_unbind(&nodes[node_count]);

	switch_safe_free(wsh);

	return FALSE;
}
Пример #14
0
int main(int argc, char **argv)
{
	int ret = 0;
	int i;
	ws_base_t base = NULL;
	ws_t ws = NULL;
	int echo_count = 5;
	int ssl = 0;
	char *server = "localhost";

	for (i = 1; i < argc; i++)
	{
		if (!strcmp(argv[i], "--ssl"))
		{
			ssl = 1;
		}
		else
		{
			server = argv[i];
		}
	}

	ws_set_log_cb(ws_default_log_cb);
	ws_set_log_level(-1);

	printf("Echo client\n\n");

	if (ws_global_init(&base))
	{
		fprintf(stderr, "Failed to init global state.\n");
		return -1;
	}

	if (ws_init(&ws, base))
	{
		fprintf(stderr, "Failed to init websocket state.\n");
		ret = -1;
		goto fail;
	}

	ws_set_onmsg_cb(ws, onmsg, &echo_count);
	ws_set_onconnect_cb(ws, onconnect, NULL);
	ws_set_onclose_cb(ws, onclose, NULL);

	if (ssl)
	{
		ws_set_ssl_state(ws, LIBWS_SSL_SELFSIGNED);
	}

	printf("Connect to server %s\n", server);

	if (ws_connect(ws, server, 9500, ""))
	{
		ret = -1;
		goto fail;
	}

	ws_base_service_blocking(base);

fail:
	ws_destroy(&ws);
	ws_global_destroy(&base);
	printf("Bye bye!\n");
	return ret;
}
Пример #15
0
/**
 * Kick off the daap server and wait for events.
 *
 * This starts the initial db scan, sets up the signal
 * handling, starts the webserver, then sits back and waits
 * for events, as notified by the signal handler and the
 * web interface.  These events are communicated via flags
 * in the config structure.
 *
 * \param argc count of command line arguments
 * \param argv command line argument pointers
 * \returns 0 on success, -1 otherwise
 *
 * \todo split out a ws_init and ws_start, so that the
 * web space handlers can be registered before the webserver
 * starts.
 *
 */
int main(int argc, char *argv[]) {
    int option;
    char *configfile=CONFFILE;
    WSCONFIG ws_config;
    int reload=0;
    int start_time;
    int end_time;
    int rescan_counter=0;
    int old_song_count, song_count;
    int force_non_root=0;
    int skip_initial=1;
    int kill_server=0;
    int convert_conf=0;
    char *db_type,*db_parms,*web_root,*runas, *tmp;
    char **mp3_dir_array;
    char *servername, *iface;
    char *ffid = NULL;
    int appdir = 0;
    char *perr=NULL;
    char txtrecord[255];
    void *phandle;
    char *plugindir;

    int err;
    char *apppath;

    int debuglevel=0;
    int plugins_loaded = 0;

#ifdef ALPHA_CUSTOMIZE
    char *share_path;
    pthread_t thread1;
#endif

    config.use_mdns=1;
    err_setlevel(2);

    config.foreground=0;
    while((option=getopt(argc,argv,"D:d:c:P:mfrysiuvab:Vk")) != -1) {
        switch(option) {
        case 'a':
            appdir = 1;
            break;

        case 'b':
            ffid=optarg;
            break;

        case 'd':
            debuglevel = atoi(optarg);
            err_setlevel(debuglevel);
            break;

        case 'D':
            if(err_setdebugmask(optarg)) {
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            break;

        case 'f':
            config.foreground=1;
            err_setdest(err_getdest() | LOGDEST_STDERR);
            break;

        case 'c':
            configfile=optarg;
            break;

        case 'm':
            config.use_mdns=0;
            break;

#ifndef WIN32
        case 'P':
            os_set_pidfile(optarg);
            break;
#endif
        case 'r':
            reload=1;
            break;

        case 's':
            skip_initial=0;
            break;

        case 'y':
            force_non_root=1;
            break;

#ifdef WIN32
        case 'i':
            os_register();
            exit(EXIT_SUCCESS);
            break;

        case 'u':
            os_unregister();
            exit(EXIT_SUCCESS);
            break;
#endif
        case 'v':
            convert_conf=1;
            break;

        case 'k':
            kill_server=1;
            break;

        case 'V':
            fprintf(stderr,"Firefly Media Server: Version %s\n",VERSION);
            exit(EXIT_SUCCESS);
            break;

        default:
            usage(argv[0]);
            exit(EXIT_FAILURE);
            break;
        }
    }

    if((getuid()) && (!force_non_root) && (!convert_conf)) {
        fprintf(stderr,"You are not root.  This is almost certainly wrong.  "
                "If you are\nsure you want to do this, use the -y "
                "command-line switch\n");
        exit(EXIT_FAILURE);
    }


    if(kill_server) {
        os_signal_server(S_STOP);
        exit(0);
    }

    io_init();
    io_set_errhandler(main_io_errhandler);
    ws_set_errhandler(main_ws_errhandler);

    /* read the configfile, if specified, otherwise
     * try defaults */
    config.stats.start_time=start_time=(int)time(NULL);
    config.stop=0;

    /* set appdir first, that way config resolves relative to appdir */
    if(appdir) {
        apppath = os_apppath(argv[0]);
        DPRINTF(E_INF,L_MAIN,"Changing cwd to %s\n",apppath);
        chdir(apppath);
        free(apppath);
        configfile="mt-daapd.conf";
    }

    if(CONF_E_SUCCESS != conf_read(configfile)) {
        fprintf(stderr,"Error reading config file (%s)\n",configfile);
        exit(EXIT_FAILURE);
    }

    if(debuglevel) /* was specified, should override the config file */
        err_setlevel(debuglevel);

    if(convert_conf) {
        fprintf(stderr,"Converting config file...\n");
        if(CONF_E_SUCCESS != conf_write()) {
            fprintf(stderr,"Error writing config file.\n");
            exit(EXIT_FAILURE);
        }
        exit(EXIT_SUCCESS);
    }

    DPRINTF(E_LOG,L_MAIN,"Firefly Version %s: Starting with debuglevel %d\n",
            VERSION,err_getlevel());


    /* load plugins before we drop privs?  Maybe... let the
     * plugins do stuff they might need to */
    plugin_init();
    if((plugindir=conf_alloc_string("plugins","plugin_dir",NULL)) != NULL) {
        /* instead of specifying plugins, let's walk through the directory
         * and load each of them */
        if(!load_plugin_dir(plugindir)) {
            DPRINTF(E_LOG,L_MAIN,"Warning: Could not load plugins\n");
        } else {
            plugins_loaded = TRUE;
        }
        free(plugindir);
    }

    if(!plugins_loaded) {
        if((!load_plugin_dir("/usr/lib/firefly/plugins")) &&
           (!load_plugin_dir("/usr/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/opt/share/firefly/plugins")) &&
           (!load_plugin_dir("/opt/share/mt-daapd/plugins")) &&
           (!load_plugin_dir("/opt/lib/firefly/plugins")) &&
           (!load_plugin_dir("/opt/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("plugins/.libs"))) {
            DPRINTF(E_FATAL,L_MAIN,"plugins/plugin_dir not specified\n");
        }
    }

    phandle=NULL;
    while((phandle=plugin_enum(phandle))) {
        DPRINTF(E_LOG,L_MAIN,"Plugin loaded: %s\n",plugin_get_description(phandle));
    }

    runas = conf_alloc_string("general","runas","nobody");

#ifndef WITHOUT_MDNS
    if(config.use_mdns) {
        DPRINTF(E_LOG,L_MAIN,"Starting rendezvous daemon\n");
        if(rend_init(runas)) {
            DPRINTF(E_FATAL,L_MAIN|L_REND,"Error in rend_init: %s\n",
                    strerror(errno));
        }
    }
#endif

    if(!os_init(config.foreground,runas)) {
        DPRINTF(E_LOG,L_MAIN,"Could not initialize server\n");
        os_deinit();
        exit(EXIT_FAILURE);
    }

    free(runas);

#ifdef UPNP
    upnp_init();
#endif

    /* this will require that the db be readable by the runas user */
    db_type = conf_alloc_string("general","db_type","sqlite");
    db_parms = conf_alloc_string("general","db_parms","/var/cache/mt-daapd");
    err=db_open(&perr,db_type,db_parms);

    if(err) {
        DPRINTF(E_LOG,L_MAIN|L_DB,"Error opening db: %s\n",perr);
#ifndef WITHOUT_MDNS
        if(config.use_mdns) {
            rend_stop();
        }
#endif
        os_deinit();
        exit(EXIT_FAILURE);
    }

    free(db_type);
    free(db_parms);

    /* Initialize the database before starting */
    DPRINTF(E_LOG,L_MAIN|L_DB,"Initializing database\n");
    if(db_init(reload)) {
        DPRINTF(E_FATAL,L_MAIN|L_DB,"Error in db_init: %s\n",strerror(errno));
    }

    err=db_get_song_count(&perr,&song_count);
    if(err != DB_E_SUCCESS) {
        DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr);
    }
    /* do a full reload if the db is empty */
    if(!song_count)
        reload = 1;

    if(conf_get_array("general","mp3_dir",&mp3_dir_array)) {
        if((!skip_initial) || (reload)) {
            DPRINTF(E_LOG,L_MAIN|L_SCAN,"Starting mp3 scan\n");
	#ifdef ALPHA_CUSTOMIZE
	    share_path = conf_alloc_string("general", "mp3_dir", "AAA");
		printf("mp3_dir_array[0] = [%s]\n", mp3_dir_array[0]);
	    if (strlen(share_path) > 0)
	    {
		Cnt_total_file(mp3_dir_array[0]);
		pthread_create( &thread1, NULL, (void*)process_bar, NULL);
		free(share_path);
	    }
	#endif
            plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_START,0,NULL,0);
            start_time=(int) time(NULL);
            if(scan_init(mp3_dir_array)) {
                DPRINTF(E_LOG,L_MAIN|L_SCAN,"Error scanning MP3 files: %s\n",strerror(errno));
            }
            if(!config.stop) { /* don't send popup when shutting down */
                plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_END,0,NULL,0);
                err=db_get_song_count(&perr,&song_count);
                end_time=(int) time(NULL);
                DPRINTF(E_LOG,L_MAIN|L_SCAN,"Scanned %d songs in %d seconds\n",
                        song_count,end_time - start_time);
            }
        }
        conf_dispose_array(mp3_dir_array);
    }
    
#ifdef ALPHA_CUSTOMIZE
    thread_exit = 1;
#endif

    /* start up the web server */
    web_root = conf_alloc_string("general","web_root",NULL);
    ws_config.web_root=web_root;
    ws_config.port=conf_get_int("general","port",0);

    DPRINTF(E_LOG,L_MAIN|L_WS,"Starting web server from %s on port %d\n",
            ws_config.web_root, ws_config.port);

    config.server=ws_init(&ws_config);
    if(!config.server) {
        /* pthreads or malloc error */
        DPRINTF(E_FATAL,L_MAIN|L_WS,"Error initializing web server\n");
    }

    if(E_WS_SUCCESS != ws_start(config.server)) {
        /* listen or pthread error */
        DPRINTF(E_FATAL,L_MAIN|L_WS,"Error starting web server\n");
    }

    ws_registerhandler(config.server, "/",main_handler,main_auth,
                       0,1);

#ifndef WITHOUT_MDNS
    if(config.use_mdns) { /* register services */
        servername = conf_get_servername();

        memset(txtrecord,0,sizeof(txtrecord));
        txt_add(txtrecord,"txtvers=1");
        txt_add(txtrecord,"Database ID=%0X",util_djb_hash_str(servername));
        txt_add(txtrecord,"Machine ID=%0X",util_djb_hash_str(servername));
        txt_add(txtrecord,"Machine Name=%s",servername);
        txt_add(txtrecord,"mtd-version=" VERSION);
        txt_add(txtrecord,"iTSh Version=131073"); /* iTunes 6.0.4 */
        txt_add(txtrecord,"Version=196610");      /* iTunes 6.0.4 */
        tmp = conf_alloc_string("general","password",NULL);
        if(tmp && (strlen(tmp)==0)) tmp=NULL;

        txt_add(txtrecord,"Password=%s",tmp ? "true" : "false");
        if(tmp) free(tmp);

        srand((unsigned int)time(NULL));

        if(ffid) {
            txt_add(txtrecord,"ffid=%s",ffid);
        } else {
            txt_add(txtrecord,"ffid=%08x",rand());
        }

        DPRINTF(E_LOG,L_MAIN|L_REND,"Registering rendezvous names\n");
        iface = conf_alloc_string("general","interface","");

        rend_register(servername,"_http._tcp",ws_config.port,iface,txtrecord);

        plugin_rend_register(servername,ws_config.port,iface,txtrecord);

        free(servername);
        free(iface);
    }
#endif

    end_time=(int) time(NULL);

    err=db_get_song_count(&perr,&song_count);
    if(err != DB_E_SUCCESS) {
        DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr);
    }

    DPRINTF(E_LOG,L_MAIN,"Serving %d songs.  Startup complete in %d seconds\n",
            song_count,end_time-start_time);

    if(conf_get_int("general","rescan_interval",0) && (!reload) &&
       (!conf_get_int("scanning","skip_first",0)))
        config.reload = 1; /* force a reload on start */

    while(!config.stop) {
        if((conf_get_int("general","rescan_interval",0) &&
            (rescan_counter > conf_get_int("general","rescan_interval",0)))) {
            if((conf_get_int("general","always_scan",0)) ||
                (config_get_session_count())) {
                config.reload=1;
            } else {
                DPRINTF(E_DBG,L_MAIN|L_SCAN|L_DB,"Skipped bground scan... no users\n");
            }
            rescan_counter=0;
        }

        if(config.reload) {
            old_song_count = song_count;
            start_time=(int) time(NULL);

            DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Rescanning database\n");

            if(conf_get_array("general","mp3_dir",&mp3_dir_array)) {
                if(config.full_reload) {
                    config.full_reload=0;
                    db_force_rescan(NULL);
                }

                if(scan_init(mp3_dir_array)) {
                    DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Error rescanning... bad path?\n");
                }

                conf_dispose_array(mp3_dir_array);
            }
            config.reload=0;
            db_get_song_count(NULL,&song_count);
            DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Scanned %d songs (was %d) in "
                    "%d seconds\n",song_count,old_song_count,
                    time(NULL)-start_time);
        }

        os_wait(MAIN_SLEEP_INTERVAL);
        rescan_counter += MAIN_SLEEP_INTERVAL;
    }

    DPRINTF(E_LOG,L_MAIN,"Stopping gracefully\n");

#ifndef WITHOUT_MDNS
    if(config.use_mdns) {
        DPRINTF(E_LOG,L_MAIN|L_REND,"Stopping rendezvous daemon\n");
        rend_stop();
    }
#endif

#ifdef UPNP
    upnp_deinit();
#endif


    /* Got to find a cleaner way to stop the web server.
     * Closing the fd of the socking accepting doesn't necessarily
     * cause the accept to fail on some libcs.
     *
    DPRINTF(E_LOG,L_MAIN|L_WS,"Stopping web server\n");
    ws_stop(config.server);
    */
    free(web_root);
    conf_close();

    DPRINTF(E_LOG,L_MAIN|L_DB,"Closing database\n");
    db_deinit();

    DPRINTF(E_LOG,L_MAIN,"Done!\n");

    os_deinit();
    io_deinit();
    mem_dump();
    return EXIT_SUCCESS;
}
Пример #16
0
/*========================================================================
    Routine    Description:
        wifi state machine -- management the entry for each of wifi state
        because wifi_rx_proc() maybe no need to be called in some state or substate
        a bool param "b_doRx" is be used to declare it

    Arguments:
    Return Value:
    Note:
========================================================================*/
void wifi_state_machine(void)
{
#ifdef CONFIG_STATION
    bool b_doRx = FALSE;     /*not use and move wifi_rx_proc() before wifi_state_machine() to fix Dequeue fail*/

    switch (pIoTMlme->CurrentWifiState) {
        case WIFI_STATE_INIT:
            ws_init(&b_doRx);
            break;
            /*Smart Connection SM*/
        case WIFI_STATE_SMTCNT:
            ws_smt_conn(&b_doRx);
            break;
            /*Scan SM*/
        case WIFI_STATE_SCAN:
            /*send Probe req frame at first , then listen Probe response in each channel*/
            ws_scan(&b_doRx);
            break;
            /*Auth SM*/
        case WIFI_STATE_AUTH:
            ws_auth(&b_doRx);
            break;
            /*Assoc SM*/
        case WIFI_STATE_ASSOC:
            ws_assoc(&b_doRx);
            break;
            /*4 Way handshake SM*/
        case WIFI_STATE_4WAY:
            ws_4way(&b_doRx);
            break;
            /*Connected SM*/
        case WIFI_STATE_CONNED:
            ws_connected(&b_doRx);
#if CFG_SUPPORT_TCPIP
            if (pIoTMlme->TcpInit == FALSE) {
                /*pIoTMlme->TcpInit shall be set FALSE, once call 
                   wifi_state_chg(WIFI_STATE_INIT, 0) or iot_linkdown()*/
                tcpip_init();
                /*if user add their own tcp/udp connection in other place, but not in tcpip_init()
                   it need to initial such connection here*/
            }
            tcpip_periodic_timer();
#endif
            break;
        default:
            b_doRx = TRUE;
            break;
    }
#endif

#ifdef CONFIG_SOFTAP
#if CFG_SUPPORT_TCPIP
    if (pIoTMlme->TcpInit == FALSE) {
        tcpip_init();
        /*if user add their own tcp/udp connection in other place, but not in tcpip_init()
           it need to initial such connection here*/
    }
    tcpip_periodic_timer();
#endif
#endif

    return;
}