Esempio n. 1
0
static int
connection_init(PyObject *obj, PyObject *args, PyObject *kwds)
{
    const char *dsn;

    if (!PyArg_ParseTuple(args, "s", &dsn))
        return -1;

    return connection_setup((connectionObject *)obj, dsn);
}
Esempio n. 2
0
/*
 * Setup a phase 2 connection.
 * XXX Maybe phase 1 works too, but teardown won't work then, fix?
 */
static void
ui_connect(char *cmd)
{
	char	name[201];

	if (sscanf(cmd, "c %200s", name) != 1) {
		log_print("ui_connect: command \"%s\" malformed", cmd);
		return;
	}
	LOG_DBG((LOG_UI, 10, "ui_connect: setup connection \"%s\"", name));
	connection_setup(name);
}
Esempio n. 3
0
static int
connection_init(PyObject *obj, PyObject *args, PyObject *kwds)
{
    const char *dsn;
    long int async = 0;
    static char *kwlist[] = {"dsn", "async", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|l", kwlist, &dsn, &async))
        return -1;

    return connection_setup((connectionObject *)obj, dsn, async);
}
Esempio n. 4
0
    void connect( const std::wstring &address )
    {
        HANDLE pipe = CreateFileW( address.c_str( ),
                                   GENERIC_WRITE | GENERIC_READ,
                                   0,
                                   NULL, OPEN_EXISTING,
                                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                                   NULL);

        if(INVALID_HANDLE_VALUE == pipe) {
            throw vtrc::common::exception( GetLastError( ),
                                           rpc::errors::CATEGORY_SYSTEM );
        } else {
            get_socket( ).assign( pipe );
        }
        connection_setup( );
        start_reading( );
    }
Esempio n. 5
0
int main(int argc, char **argv)
{

  int n,sockfd, on=1,i,j,maxfdp,optval=1;
  char recvline[LINE_MAX], in_packet[PACKET_LEN];	
  client_config_t config;
  int num_ifi = 0;
  pthread_t tid;
  thread_arg* arg;
  bool done = FALSE, is_probe = FALSE, is_error = FALSE;
  unsigned int ack_seq, seq, timestamp;
  unsigned short curr_win;

  circ_buffer_t rcv_buffer;

  ifi_t *ifi_array[IFI_MAX];

  read_client_config("client.in", &config);
  print_client_config(&config);

  num_ifi = get_ifi(ifi_array);
  print_ifi(ifi_array, num_ifi);

  srand(config.seed);
  init_circular_buffer(&rcv_buffer, config.window_size);
  
  rtt_init(&rttinfo);

  if (connection_setup(&sockfd, ifi_array, num_ifi, &rcv_buffer, &config) < 0)
    err_sys("[Error] Connection Setup Error, Terminating..\n");

  /* TODO: Recv ACK and connect to the new port */

  arg = (thread_arg*)calloc(1, sizeof(thread_arg));
  arg->rcv_buf = &rcv_buffer;
  arg->config = &config;
  arg->sockfd = sockfd;
  Pthread_create(&tid, NULL, &consumer_thread, arg);

  /* Below is the Producer Logic which reads from the socket and fills 
   * up the receive Buffer.
   */
  while (!done)
  {
    if ((n = read(sockfd, in_packet, PACKET_LEN)) < 0)
    {
      if (errno == EINTR) 
        continue;
      else
        err_sys("[Error] Unknown Read Error");
    }

    packet_info_t *pkt_info = get_packet_info(in_packet, n);

    if (!IS_DATA(pkt_info) && !(is_probe = IS_PROBE(pkt_info))
          && !(is_error = IS_ERR(pkt_info)))
    {
      free_pkt_info(pkt_info);
      continue;
    }

    if (consume_random_packet(pkt_info, config.prob_loss, TRUE))
    {
      free_pkt_info(pkt_info);
      continue;
    }

    if(IS_EOF(pkt_info) || is_error)
      done = TRUE;

    Pthread_mutex_lock(&buf_mutex);
    /* Special Handling for Probes & Errors, send an ACK, don't store in buffer */
    if(!is_probe && !is_error)
    {
      write_to_buffer(&rcv_buffer , pkt_info);
    }
    /* Save off these values as we are releasing the lock below */
    curr_win = window_size(&rcv_buffer); 
    ack_seq = NEXT_ACK(&rcv_buffer);
    seq = pkt_info->seq;
    timestamp = pkt_info->timestamp;

    Pthread_mutex_unlock(&buf_mutex);

    if(is_probe)
      printf("[Info] Persist Timer Response [Ack:%u] [Window Size:%hu]\n", ack_seq, curr_win);
    else
      printf("[Info] Received [Seq: %u] Responding with [Ack:%u] [Window Size:%hu]\n", 
          seq, ack_seq, curr_win);

    send_ack(sockfd, curr_win, seq, ack_seq, timestamp, config.prob_loss);

  }
  pthread_exit(NULL);
}
Esempio n. 6
0
File: main.cpp Progetto: dai-vdr/uim
int
main(int argc, char **argv)
{
    const char *locale;

    printf("uim <-> XIM bridge. Supporting multiple locales.\n");

    get_runtime_env();

    parse_args(argc, argv);

    if (g_option_mask & OPT_ON_DEMAND_SYNC)
	printf("Using on-demand-synchronous XIM event flow (not safe for Tcl/TK)\n");
    else
	printf("Using full-synchronous XIM event flow\n");

    signal(SIGPIPE, SIG_IGN);
    signal(SIGUSR1, reload_uim);

    check_helper_connection();

    XimServer::gDpy = XOpenDisplay(NULL);
    if (!XimServer::gDpy) {
	printf("failed to open display!\n");
	return 1;
    }
    if (!pretrans_register()) {
	printf("pretrans_register failed\n");
	return 1;
    }

    get_uim_info();
    print_uim_info();

    locale = setlocale(LC_CTYPE, "");
    if (!locale)
	locale = setlocale(LC_CTYPE, "C");

    check_default_engine(locale);
    init_supported_locales();
    init_modifier_keys();

    std::list<UIMInfo>::iterator it;
    bool res = false;

    // First, setup conversion engine selected by cmdline option or
    // "default-im-name" on ~/.uim.
    for (it = uim_info.begin(); it != uim_info.end(); ++it) {
	if (strcmp(it->name, default_engine) == 0) {
	    XimServer *xs = new XimServer(it->name, it->lang);
	    res = xs->setupConnection(true);
	    if (res)
		printf("XMODIFIERS=@im=uim registered, selecting %s (%s) as default conversion engine\n", it->name, it->lang);
	    else
		delete xs;
	    break;
	}
    }

    if (!res) {
	printf("aborting...\n");
	return 1;
    }

    connection_setup();
    error_handler_setup();
    if (pretrans_setup() == -1)
	return 0;

#if HAVE_XFT_UTF8_STRING
    if (uim_scm_symbol_value_bool("uim-xim-use-xft-font?"))
	init_default_xftfont(); // setup Xft fonts for Ov/Rw preedit
#endif
    check_candwin_style();
    check_candwin_pos_type();

    // Handle pending events to prevent hang just after startup
    check_pending_xevent();

    main_loop();
    return 0;
}
/*
 * The definition of the process.
 */
PROCESS_THREAD(twamp_tcp_control_server, ev, data)
{
  /*
   * The process begins here.
   */
  uip_ipaddr_t *ipaddr;
  
  PROCESS_BEGIN();
  set_global_address();
  /*
   * We start with setting up a listening TCP port. Note how we're
   * using the UIP_HTONS() macro to convert the port number (862) to
   * network byte order as required by the tcp_listen() function.
   */
  tcp_listen(UIP_HTONS(862));

  /*
   * We loop for ever, accepting new connections.
   */
  while(1) {

    /*
     * We wait until we get the first TCP/IP event, which probably
     * comes because someone connected to us.
     */
    PROCESS_WAIT_EVENT_UNTIL(ev == tcpip_event);

    /*
     * If a peer connected with us, we'll initialize the protosocket
     * with PSOCK_INIT().
     */
    if(uip_connected()) {
      
      /*
       * The PSOCK_INIT() function initializes the protosocket and
       * binds the input buffer to the protosocket.
       */
      PSOCK_INIT(&ps, buffer, sizeof(buffer));
      printf("Someone connected!\n");
      
      /*
       * We loop until the connection is aborted, closed, or times out.
       */
      while(!(uip_aborted() || uip_closed() || uip_timedout())) {
	/*
	 * We wait until we get a TCP/IP event. Remember that we
	 * always need to wait for events inside a process, to let
	 * other processes run while we are waiting.
	 */
	PROCESS_WAIT_EVENT_UNTIL(ev == tcpip_event);
	/*
	 * Here is where the real work is taking place: we call the
	 * handle_connection() protothread that we defined above. This
	 * protothread uses the protosocket to receive the data that
	 * we want it to.
	 */
	if(state == 1){
          connection_setup(&ps);
        }
        if(state == 2){
          create_test_session(&ps);
        }
        if(state == 3){
          timesynch(&ps);
        }
        if(state == 4){
          //PT_INIT(&pthread);
          //run_test_session(&ps);
          process_start(&run_test_session,NULL);
          PROCESS_YIELD_UNTIL(!process_is_running(&run_test_session));
        }
      }
    }
  }
  
  /*
   * We must always declare the end of a process.
   */
  PROCESS_END();
}
Esempio n. 8
0
int main(int argc, char *argv[]) {
    
    if ( argc == 2 ) {
	port = strtol(argv[1], &endptr, 0);
	if ( *endptr ) {
	    fprintf(stderr, "Invalid port number.\n");
	    exit(EXIT_FAILURE);
	}
    }
    else if ( argc < 2 ) {
            port = ecPort;
    }

    else {
	fprintf(stderr, "Invalid arguments\n");
	exit(EXIT_FAILURE);
    }

    fileSystemInit();
    connection_setup();

    if ( (connS = accept(listS, NULL, NULL) ) < 0 ) {
	    fprintf(stderr, "Error!!\n");
	    exit(EXIT_FAILURE);
    }
    header = (char *)malloc(2 * sizeof(int));
    elreadmos = (char *)malloc(10000);
    myLStable = (char *)malloc(100);
    while ( 1 ) {
	recieveing(connS, recEI, 2 * sizeof(int));
	memcpy(&recvReq, recEI, sizeof(int));
	memcpy(&recvSize, recEI +sizeof(int), sizeof(int));
	switch (recvReq) {

		case 1:
			printf("root directory\n");
			LStableAdd = sfs_ls();
			strcpy(myLStable, LStableAdd);
			size = strlen(myLStable);
			DataSend = (char *)malloc(size);
			memcpy(header, &lsCom, sizeof(int));
			memcpy(header+sizeof(int), &size, sizeof(int)); 
			memcpy(DataSend, myLStable, size);
			Sending(connS, header, (2 * sizeof(int)));
			Sending(connS, DataSend, size);
			free(DataSend);
			break;
		case 2:
			printf("open file\n");
			recData = (char *)malloc(recvSize);
			recieveing(connS, recData, recvSize);
			memcpy(openReq, recData, recvSize);
			openReq[recvSize] = 0;
			remID = sfs_open(openReq);
			DataSend = (char *)malloc(sizeof(int));
			size = sizeof(int);
			memcpy(header, &opCom, sizeof(int));
			memcpy(header+sizeof(int), &size, sizeof(int));
			memcpy(DataSend, &remID, size);
			Sending(connS, header, (2 * sizeof(int)));
			Sending(connS, DataSend, size);
			free(recData);
			free(DataSend);
			break;
		case 3:
			printf("close file\n");
			recData = (char *)malloc(recvSize);
			recieveing(connS, recData, recvSize);
			memcpy(&elremote, recData, sizeof(int));
			sfs_close(elremote);
			memcpy(header, &closeCom, sizeof(int));
			memcpy(header+sizeof(int), &size, sizeof(int)); 
			Sending(connS, header, (2 * sizeof(int)));
                        free(recData);
			break;
		case 4:
			printf("write file\n");
			recData = (char *)malloc(recvSize);
			elWritBuf = (char *)malloc(recvSize);
			recieveing(connS, recData, recvSize - 8);
			memcpy(elWritBuf, recData, recvSize -8);
			elWritBuf[recvSize - 8] = 0;
			recieveing(connS, recData, sizeof(int));
			memcpy(&remID, recData, sizeof(int));
			recieveing(connS, recData, sizeof(int));
			memcpy(&my_len, recData, sizeof(int));
                        sfs_write(remID, elWritBuf, my_len);
			size = 0;
                        memcpy(header, &writCom, sizeof(int));
			memcpy(header+sizeof(int), &size, sizeof(int)); 
			Sending(connS, header, (2 * sizeof(int)));
                        free(recData);
			free(elWritBuf);
                        break;

		case 5:

			printf("read file\n");
			recData = (char *)malloc(recvSize);
                        recieveing(connS, recData, sizeof(int));
			memcpy(&remID, recData, sizeof(int));
			recieveing(connS, recData, sizeof(int));
			memcpy(&my_len, recData, sizeof(int));
                        sfs_read(remID, elreadmos, my_len);
                        size = strlen(elreadmos);
                        memcpy(header, &readCom, sizeof(int));
			memcpy(header+sizeof(int), &size, sizeof(int));
			Sending(connS, header, (2 * sizeof(int)));
                        DataSend = (char *)malloc(size);
			memcpy(DataSend, elreadmos, size);
			DataSend[size] = 0;
			puts(DataSend);
                        Sending(connS, DataSend, size);
                        break;

		case 6:
			printf("remove file\n");
			recData = (char *)malloc(recvSize);
                        recieveing(connS, recData, recvSize);
			memcpy(remReq, recData, recvSize);
			remReq[recvSize] = 0;
			printf("file to remove = %s\n",remReq);
                        if (sfs_remove(remReq) == -1){
				size = strlen("Error: file doesnot exist\n");
				DataSend = (char *)malloc(size);
				strcpy(DataSend, "Error: file doesnt exist\n");
			}

			else{
				size = strlen("file removed successfully\n");
				DataSend = (char *)malloc(size);
				strcpy(DataSend, "file remove successfull\n");

			}
                        memcpy(header, &remCom, sizeof(int));
			memcpy(header+sizeof(int), &size, sizeof(int)); 
			Sending(connS, header, (2 * sizeof(int)));
                        Sending(connS, DataSend, size);
                        free(recData);
			free(DataSend);
                        break;
               default:
			printf("Invalid input\n");
                        break;
	}

    }

}
Esempio n. 9
0
static int worker_server(worker *info) {
	/* server worker */
	int nfds, fd, i;
	worker *w;

	int num = info->num;
	master_server *master_srv = info->master_srv;

	/* attach the shared mem */	
	int shmid;
	key_t key = master_srv->pid + num;

	if ((shmid = shmget(key, sizeof(worker), 0666)) < 0) {
		perror ("ERROR shmget");
		exit (1);
	}
	
	/* attach it */
	if ((w = shmat(shmid, NULL, 0)) == (char*) -1) {
		perror ("ERROR shmat");
		exit (1);
	}
	
	/* process id */
	w->pid = getpid();
	
	/* worker process started */
	printf (" * Worker process #%d is started.\n", num+1);
	
	/* pre-setup worker connections */
	w->conns = connection_setup(master_srv);
	
	/* create a new event handler for this worker */
	event_handler *ev_handler = events_create(master_srv->config->max_clients);

	/* share the event fd */
	w->ev_handler.fd = ev_handler->fd;
	
	/* starting keep-alive clean-up thread */
	printf (" * Starting keep-alive clean-up thread for worker #%d.\n", num+1);
	pthread_t thread_keep_alive;
	int rc_cleanup = pthread_create(&thread_keep_alive, NULL, worker_keep_alive_cleanup, w);
	
	/* starting heartbeat thread */
	printf (" * Starting heartbeat thread for worker #%d.\n", num+1);
	pthread_t thread_heartbeat;
	int rc_heartbeat = pthread_create(&thread_heartbeat, NULL, worker_heartbeat, w);
	
	/* entering main loop... */
	while (master_srv->running) {
		/* check for new data */
		if ((nfds = events_wait(ev_handler, master_srv)) == -1) {
			perror ("ERROR epoll_pwait");
		}

		for (i = 0; i < nfds; ++i) {
			/* data received */
			fd = events_get_fd(ev_handler, i);
			connection *conn = w->conns[fd];
			
			if (events_closed(ev_handler, i)) {
				/* the other end closed the connection */
				conn->status = CONN_INACTIVE;
				printf (" * Other end closed the connection\n");
			} else if (conn->status == CONN_INACTIVE) {
				/* this connection is inactive, initiate a new connection */
				connection_start (master_srv, conn);
			}
			
			connection_handle (w, conn);
			
			/* closing */
			if (conn->status == CONN_INACTIVE) {
				if (events_del_event(ev_handler, fd) == -1) {
					perror ("ERROR events_del_event");
				}
				close (fd);
			}
		}
	}
	
	printf (" * Shutting down worker process #%d...\n", num+1);
	
	/* free event handler */
	events_free (ev_handler, master_srv->config->max_clients);

	/* TODO: free all connections */
	free (w->conns);

	/* free this workers memory */
	worker_free (w);

	exit (0);
}
static MODULE_HANDLE Outprocess_Create(BROKER_HANDLE broker, const void* configuration)
{
	OUTPROCESS_HANDLE_DATA * module;
	if (
		(broker == NULL) ||
		(configuration == NULL)
		)
	{
		/*Codes_SRS_OUTPROCESS_MODULE_17_005: [ If broker or configuration are NULL, this function shall return NULL. ]*/
		LogError("invalid arguments for outprcess module. broker=[%p], configuration = [%p]", broker, configuration);
		module = NULL;
	}
	else
	{
		OUTPROCESS_MODULE_CONFIG * config = (OUTPROCESS_MODULE_CONFIG*)configuration;
		/*Codes_SRS_OUTPROCESS_MODULE_17_006: [ This function shall allocate memory for the MODULE_HANDLE. ]*/
		module = (OUTPROCESS_HANDLE_DATA*)malloc(sizeof(OUTPROCESS_HANDLE_DATA));
		if (module == NULL)
		{
			/*Codes_SRS_OUTPROCESS_MODULE_17_016: [ If any step in the creation fails, this function shall deallocate all resources and return NULL. ]*/
			LogError("allocation for module failed.");
		}
		else
		{
			/*Codes_SRS_OUTPROCESS_MODULE_17_007: [ This function shall intialize a lock for exclusive access to handle data. ]*/
			module->handle_lock = Lock_Init();
			if (module->handle_lock == NULL)
			{
				/*Codes_SRS_OUTPROCESS_MODULE_17_016: [ If any step in the creation fails, this function shall deallocate all resources and return NULL. ]*/
				LogError("unable to intialize module lock");
				free(module);
				module = NULL;
			}
			else
			{
				/*Codes_SRS_OUTPROCESS_MODULE_17_042: [ This function shall initialize a queue for outgoing gateway messages. ]*/
				module->outgoing_messages = MESSAGE_QUEUE_create();
				if (module->outgoing_messages == NULL)
				{
					LogError("unable to create outgoing message queue");
					Lock_Deinit(module->handle_lock);
					free(module);
					module = NULL;
				}
				else
				{
					if (connection_setup(module, config) < 0)
					{
						/*Codes_SRS_OUTPROCESS_MODULE_17_016: [ If any step in the creation fails, this function shall deallocate all resources and return NULL. ]*/
						LogError("unable to set up connections");
						connection_teardown(module);
						MESSAGE_QUEUE_destroy(module->outgoing_messages);
						Lock_Deinit(module->handle_lock);
						free(module);
						module = NULL;
					}
					else
					{
						THREAD_CONTROL default_thread =
						{
							NULL,
							NULL,
							0
						};
						module->broker = broker;
						module->remote_message_wait = config->remote_message_wait;
						module->message_receive_thread = default_thread;
						module->message_send_thread = default_thread;
						module->control_thread = default_thread;
						module->async_create_thread = default_thread;
						module->lifecyle_model = config->lifecycle_model;

						/*Codes_SRS_OUTPROCESS_MODULE_17_041: [ This function shall intitialize a lock for each thread for thread management. ]*/
						if ((module->message_receive_thread.thread_lock = Lock_Init()) == NULL)
						{
							connection_teardown(module);
							MESSAGE_QUEUE_destroy(module->outgoing_messages);
							Lock_Deinit(module->handle_lock);
							free(module);
							module = NULL;
						}
						else if ((module->control_thread.thread_lock = Lock_Init()) == NULL)
						{
							connection_teardown(module);
							MESSAGE_QUEUE_destroy(module->outgoing_messages);
							Lock_Deinit(module->message_receive_thread.thread_lock);
							Lock_Deinit(module->handle_lock);
							free(module);
							module = NULL;
						}
						else if ((module->async_create_thread.thread_lock = Lock_Init()) == NULL)
						{
							connection_teardown(module);
							MESSAGE_QUEUE_destroy(module->outgoing_messages);
							Lock_Deinit(module->control_thread.thread_lock);
							Lock_Deinit(module->message_receive_thread.thread_lock);
							Lock_Deinit(module->handle_lock);
							free(module);
							module = NULL;
						}
						else if ((module->message_send_thread.thread_lock = Lock_Init()) == NULL)
						{
							connection_teardown(module);
							MESSAGE_QUEUE_destroy(module->outgoing_messages);
							Lock_Deinit(module->async_create_thread.thread_lock);
							Lock_Deinit(module->control_thread.thread_lock);
							Lock_Deinit(module->message_receive_thread.thread_lock);
							Lock_Deinit(module->handle_lock);
							free(module);
							module = NULL;
						}
						else if (save_strings(module, config) != 0)
						{
							connection_teardown(module);
							MESSAGE_QUEUE_destroy(module->outgoing_messages);
							Lock_Deinit(module->async_create_thread.thread_lock);
							Lock_Deinit(module->control_thread.thread_lock);
							Lock_Deinit(module->message_receive_thread.thread_lock);
							Lock_Deinit(module->message_send_thread.thread_lock);
							Lock_Deinit(module->handle_lock);
							free(module);
							module = NULL;
						}
						else
						{
							/*Codes_SRS_OUTPROCESS_MODULE_17_014: [ This function shall wait for a Create Response on the control channel. ]*/
							if (ThreadAPI_Create(&(module->async_create_thread.thread_handle), outprocessCreate, module) != THREADAPI_OK)
							{
								/*Codes_SRS_OUTPROCESS_MODULE_17_016: [ If any step in the creation fails, this function shall deallocate all resources and return NULL. ]*/

								LogError("failed to spawn a thread");
								module->async_create_thread.thread_handle = NULL;
								connection_teardown(module);
								delete_strings(module);
								MESSAGE_QUEUE_destroy(module->outgoing_messages);
								Lock_Deinit(module->async_create_thread.thread_lock);
								Lock_Deinit(module->control_thread.thread_lock);
								Lock_Deinit(module->message_receive_thread.thread_lock);
								Lock_Deinit(module->message_send_thread.thread_lock);
								Lock_Deinit(module->handle_lock);
								free(module);
								module = NULL;
							}
							else
							{
								int thread_result = -1;
								if (module->lifecyle_model == OUTPROCESS_LIFECYCLE_SYNC)
								{
									if (ThreadAPI_Join(module->async_create_thread.thread_handle, &thread_result) != THREADAPI_OK)
									{
										/*Codes_SRS_OUTPROCESS_MODULE_17_016: [ If any step in the creation fails, this function shall deallocate all resources and return NULL. ]*/
										LogError("Async create thread failed result=[%d]", thread_result);
										thread_result = -1;
									}
									else
									{
										/*Codes_SRS_OUTPROCESS_MODULE_17_015: [ This function shall expect a successful result from the Create Response to consider the module creation a success. ]*/
										// async thread is done.
									}
									module->async_create_thread.thread_handle = NULL;
								}
								else
								{
									thread_result = 1;
								}
								if (thread_result < 0)
								{
									/*Codes_SRS_OUTPROCESS_MODULE_17_016: [ If any step in the creation fails, this function shall deallocate all resources and return NULL. ]*/
									connection_teardown(module);
									delete_strings(module);
									MESSAGE_QUEUE_destroy(module->outgoing_messages);
									Lock_Deinit(module->async_create_thread.thread_lock);
									Lock_Deinit(module->control_thread.thread_lock);
									Lock_Deinit(module->message_receive_thread.thread_lock);
									Lock_Deinit(module->message_send_thread.thread_lock);
									Lock_Deinit(module->handle_lock);
									free(module);
									module = NULL;
								}
							}
						}
					}
				}
			}
		}
	}
	return module;
}