Exemplo n.º 1
0
static void tell_emacs_to_resume(int sig)
{
	char buffer[GSERV_BUFSZ + 1];
	int sz;
	int s;			/* socket / msqid to server */
	int connect_type;	/* CONN_UNIX, CONN_INTERNET, or
				   ONN_IPC */

	/* Why is SYSV so retarded? */
	/* We want emacs to realize that we are resuming */
#ifdef SIGCONT
	signal(SIGCONT, tell_emacs_to_resume);
#endif

	connect_type = make_connection(NULL, 0, &s);

	SNPRINTF(sz, buffer, sizeof(buffer),
		 "(gnuserv-eval '(resume-pid-console %d))", (int)getpid());
	send_string(s, buffer);

#ifdef SYSV_IPC
	if (connect_type == (int)CONN_IPC)
		disconnect_from_ipc_server(s, msgp, FALSE);
#else				/* !SYSV_IPC */
	if (connect_type != (int)CONN_IPC)
		disconnect_from_server(s, FALSE);
#endif				/* !SYSV_IPC */
}
Exemplo n.º 2
0
static int
cmd_disconnect                      (int __argc, char **__argv)
{
  if (__argc!=1)
    console_log ("Usage: disconnect\n"); else
    disconnect_from_server ();

  return 0;
}
nvqrReturn_t nvqr_disconnect(NVQRConnection *connection)
{
    if (disconnect_from_server(*connection)) {
        close_client_connection(*connection);
        destroy_client(*connection);
        close_server_connection(connection->server_handle);
        free(connection->process_name);
        return NVQR_SUCCESS;
    }

    return NVQR_ERROR_UNKNOWN;
}
Exemplo n.º 4
0
static int
cmd_ipc                            (int __argc, char **__argv)
{
  char cmd[4096], dummy[1024];
  int sock=console_get_socket ();

  if (__argc!=2)
    {
      console_log ("Usage: ipc <ipc command>\n");
      return 0;
    }

  strcpy (cmd, __argv[1]);

  if (!strcmp (cmd, ""))
    return 0;

  if (sock>0)
    {
      char ans[65536];
      int a;
      if ((a=sock_answer (sock, "%s\n", cmd)))
        goto __fail_;

      if (sock_read (sock, 65536, ans)<0 || MSG_DISCONNECT (ans))
        goto __fail_;

      console_log ("%s", ans);
    } else
      console_log ("Not connected to server.\n");

  trim (cmd, dummy);
  if (!strcmp (dummy, "exit"))
    disconnect_from_server ();

  return 0;
__fail_:
  disconnect_from_server ();
  return 0;
}
Exemplo n.º 5
0
 bool Client::stop_client()
 {
     if(_V_is_running)
     {
         disconnect_from_server();
         clear();
         enet_host_destroy(_V_client_host);
         _V_client_host=nullptr;
         _V_is_running=false;
         return true;
     }
     return false;
 }
Exemplo n.º 6
0
int main(int argc, char **argv)
{
	static acs_cli_info_t ai;
	int rc;

	/* Initalise our context object */
	memset(&ai, 0, sizeof(ai));
	ai.wl_ifname	= DEFAULT_WL_IFNAME;
	ai.server_host	= DEFAULT_SERVER_HOST;
	ai.server_port	= DEFAULT_SERVER_PORT;
	ai.socket	= -1;
	for (rc = 0; rc < CMDARG_MAX; ++rc) {
		ai.cmdarg[rc] = "";
	}

	rc = parse_commandline(&ai, argc, argv);
	if (rc != BCME_OK) {
		return rc;
	}

	switch (ai.action) {

	case ACTION_SHOW_COMMANDS:
		rc = show_command_list();
		break;

	case ACTION_SHOW_USAGE:
		rc = BCME_OK;
		usage(argv[0]);
		break;

	case ACTION_REPORT_VARIABLES:
		rc = report_all_variables(&ai);
		break;

	case ACTION_REPORT_EVERYTHING:
		rc = report_everything(&ai);
		break;

	case ACTION_DO_COMMAND:
		rc = connect_to_server(&ai);
		if (rc == BCME_OK) {
			rc = do_command_response(&ai);
			disconnect_from_server(&ai);
		}
		break;
	}
	return rc;
}
Exemplo n.º 7
0
void
on_connect_toggled                 (GtkToggleButton *__self, gpointer __user_data)
{
  BOOL auth=gtk_toggle_button_get_active ((GtkToggleButton*)lookup_widget (main_window, "login_at_connect"));
  char *server   = (char*)gtk_entry_get_text ((GtkEntry*)lookup_widget (main_window, "server"));
  char *login    = (char*)gtk_entry_get_text ((GtkEntry*)lookup_widget (main_window, "login"));
  char *password = (char*)gtk_entry_get_text ((GtkEntry*)lookup_widget (main_window, "password"));

  if (gtk_toggle_button_get_active (__self))
    {
      if (!connect_to_server (server, auth, login, password))
        gtk_toggle_button_set_active (__self, FALSE);
    } else {
      disconnect_from_server ();
    }
}
Exemplo n.º 8
0
int
main(int argc, char* argv[])
{
    cout << "processing configuration options ..." << endl;

    // pointers to options we will create for the grid server program
    option_t* opt_server_host = 0;
    option_t* opt_connect_port = 0;

    const option_level_cnt = 3; 
    option_group_t options(option_level_cnt);

    W_COERCE(options.add_option("connect_port", "1024 < integer < 65535",
		     "1234", "port for connecting to grid server",
		     false, option_t::set_value_long,
		     opt_connect_port));

    W_COERCE(options.add_option("server_host", "host address",
		     "localhost", "address of host running server",
		     false, option_t::set_value_charstr,
		     opt_server_host));

    if (init_config_options(options, "client", argc, argv)) {
	usage(options);
	exit(1);
    }

    // there should not be any other command line arguments
    if (argc > 1) {
	usage(options);
	exit(1);
    }

    int port = strtol(opt_connect_port->value(), 0, 0);
    cout << "trying to connect to server at port " << port<< endl;
    if (!connect_to_server(opt_server_host->value(), port)) {
	cerr << "Shutting down due to connection failure" << endl;
	exit(1);
    }

    process_user_commands();

    disconnect_from_server();

    cout << "Finished!" << endl;
    return 0;
}
Exemplo n.º 9
0
/*
 * Each bot's entry point. 'arg' must be a dynamically allocated THREAD_ARG
 * pointer. The pointer is freed by the new thread.
 */
void*
BotEntryPoint(void *arg)
{
	THREAD_DATA *td = (THREAD_DATA*)arg;

	/* set the tls key */
	pthread_setspecific(g_tls_key, td);

	init_thread_data(td);

	db_instance_init();
	cmd_instance_init(td);
	player_instance_init(td);
	libman_instance_init(td);

	/* load the core pseudo-plugin */
	libman_load_library(td, NULL);

	/* load the bots libraries */
	int num_plugins = DelimCount(td->libstring, ' ') + 1;
	for (int i = 0; i < num_plugins; ++i) {
		char libname[64];
		DelimArgs(libname, 64, td->libstring, i, ' ', false);
		if (strlen(libname) > 0) {
			libman_load_library(td, libname);
		}
	}

	/* mainloop */
	mainloop(td);

	disconnect_from_server(td);

	libman_instance_shutdown(td);
	player_instance_shutdown(td);
	cmd_instance_shutdown(td);
	db_instance_shutdown();

	botman_bot_exiting(td->botman_handle);

	free_thread_data(td);

	free(td);

	return NULL;
}
Exemplo n.º 10
0
static int
report_all_dumps(acs_cli_info_t *ctx)
{
	int rc = BCME_OK;
	int i;

	ctx->cmdarg[CMDARG_COMMAND] = "dump";

	for (i = 0; (dump_table[i].option && (rc == 0)); ++i) {
		rc = connect_to_server(ctx);
		if (rc == BCME_OK) {
			printf( "[ %s: dump %s ]\n", ctx->wl_ifname, dump_table[i].option );
			ctx->cmdarg[CMDARG_PARAMETER] = dump_table[i].option;
			rc = do_command_response(ctx);
			disconnect_from_server(ctx);
		}
	}
	return rc;
}
Exemplo n.º 11
0
/** 
 * @brief  将发送缓冲中的数据发送出去,同时接收一次网络中的数据
 * @param   
 * @return  0success -1failed
 */
int c_net_client_impl::do_io()
{
    if(!m_inited)
    {
        return -1;
    }

    if(m_sock_fd < 0)
    {
        if(connect_to_server(m_timeout) != 0)
        {
            ERROR_LOG("can not connect now");
            return -1;
        }    
    }

    if(recv_data_from_server() < 0)
    {
        return -1;
    }

    if(m_send_buffer_len > 0)
    {
        int bytes_sent = send_to_server(m_sock_fd, m_send_buffer, m_send_buffer_len);
        if(bytes_sent > 0)
        {
            remove_data_from_send_buffer(bytes_sent);
        }
        else if(bytes_sent < 0)
        {/**< 连接遇到问题,关闭连接*/
           disconnect_from_server();
           return -1;
        }
        else
        {
            //nothing to do
        }
    }


    return 0;
}
Exemplo n.º 12
0
// Handle an incoming REJ( NME() ) message.
void BaseBot::process_rej_nme_message( TokenMessage &incoming_message, TokenMessage &message_parameters )
{
	bool attempt_reconnect;				// Whether to try and reconnect
	Token power_token = 0;				// The token for the power to reconnect as
	int passcode = 0;					// The passcode to reconnect as
	Token passcode_token;				// The passcode as a token

	attempt_reconnect = get_reconnect_details( power_token, passcode );

	if ( attempt_reconnect )
	{
		// Send an IAM message
		passcode_token.set_number( passcode );
		send_message_to_server( TOKEN_COMMAND_IAM & power_token & passcode_token );
	}
	else
	{
		// Disconnect
		disconnect_from_server();
	}
}
Exemplo n.º 13
0
static int
report_everything(acs_cli_info_t *ctx)
{
	int rc;

	rc = connect_to_server(ctx);
	if (rc == BCME_OK) {
		printf( "[ info ]\n" );
		ctx->cmdarg[CMDARG_COMMAND] = "info";
		rc = do_command_response(ctx);
		disconnect_from_server(ctx);
	}

	if (rc == BCME_OK) {
		rc = report_all_dumps(ctx);
		if (rc == BCME_OK) {
			rc = report_all_variables(ctx);
		}
	}
	return rc;
}
Exemplo n.º 14
0
static int
report_all_variables(acs_cli_info_t *ctx)
{
	int rc = BCME_OK;
	int i;

	ctx->cmdarg[CMDARG_COMMAND] = "get";

	printf( "[ %s: acsd variables ]\n", ctx->wl_ifname );

	for (i = 0; (acsd_variables[i] && (rc == BCME_OK)); ++i) {
		rc = connect_to_server(ctx);
		if (rc == BCME_OK) {
			printf( "%25s = ", acsd_variables[i] );
			fflush(stdout);
			ctx->cmdarg[CMDARG_PARAMETER] = acsd_variables[i];
			rc = do_command_response(ctx);
			disconnect_from_server(ctx);
		}
	}
	return rc;
}
Exemplo n.º 15
0
/** 
 * @brief  从服务端接收数据
 * @param   
 * @return  -1无法接收数据 >0 接收到的数据长度
 */
int c_net_client_impl::recv_data_from_server()
{
    if(m_recv_buffer_len >= (int)sizeof(m_recv_buffer))
    {/**< 检查是否有足够的空间接收继续数据*/
        return 0;
    }    

    int bytes_recved = recv_from_server(m_sock_fd, m_recv_buffer + m_recv_buffer_len, sizeof(m_recv_buffer) - m_recv_buffer_len);
    if(bytes_recved < 0)
    {
        disconnect_from_server();
        return -1;
    }
    else if(bytes_recved == 0)
    {
        //nothing to do
    }
    else
    {
        m_recv_buffer_len += bytes_recved;
    }

    return bytes_recved;
}
Exemplo n.º 16
0
static
void
mainloop(THREAD_DATA *td)
{
	THREAD_DATA::net_t *n = td->net;

	ticks_ms_t acc, ticks, lticks;	/* accumulator, current ticks, last iteration ticks */

	int	pktl;			/* packet length */
	uint8_t pkt[MAX_PACKET];	/* buffer space for a packet */

	if (connect_to_server(td) != 0) {
		free_thread_data(td);
		LogFmt(OP_MOD, "Error performing initial connect");
		return;
	}

	acc = 0;
	ticks = get_ticks_ms();
	lticks = ticks;
	ticks_ms_t last_botman_checkin = ticks;
	ticks_ms_t last_botman_stopcheck = ticks;
	ticks_ms_t last_config_mtime_check = ticks;
	while (td->running >= 0) {
		ticks = get_ticks_ms();
		acc += ticks - lticks;
		lticks = ticks;

		/* check in with the bot manager */
		if (ticks - last_botman_checkin >= BOTMAN_CHECKIN_INTERVAL) {
			botman_bot_checkin(td->botman_handle);
			last_botman_checkin = ticks;
		}
		if (ticks - last_botman_stopcheck >= BOTMAN_STOPCHECK_INTERVAL) {
			if (botman_bot_shouldstop(td->botman_handle)) {
				td->running = -1;
			}
			last_botman_stopcheck = ticks;
		}

		/* flush out tick events to bots */
		if (acc >= STEP_INTERVAL) { 
			libman_expire_timers(td);
			while(acc >= STEP_INTERVAL) {
				/* event_tick */
				libman_export_event(td, EVENT_TICK, NULL);
				acc -= STEP_INTERVAL;
			}
		}

		/* if the bot is disconnected, see if it is time to reconnect */
		if (n->state == NS_DISCONNECTED) {
			if (ticks - n->ticks->disconnected > 60000) {
				free_thread_data(td);
				init_thread_data(td);
				connect_to_server(td);
			} else {
				usleep(50000);	/* 50ms */
				continue;
			}
		}

		/* see if the config file has been modified and if so send a reread event */
		if (ticks - last_config_mtime_check >= CONFIG_MTIME_POLL_INTERVAL) {
			struct stat attr;
			memset(&attr, 0, sizeof(struct stat));
			if (stat(td->config->filename, &attr) == 0) {
				if (td->config->last_modified_time != attr.st_mtime) {
					libman_export_event(td, EVENT_CONFIG_CHANGE, NULL);
					td->config->last_modified_time = attr.st_mtime;
				}
			}
			last_config_mtime_check = ticks;
		}

		/* use up to STEP_INTERVAL ms for the db thread */
		ticks_ms_t ticks_taken = get_ticks_ms() - ticks;
		ticks_ms_t db_ticks = ticks_taken > STEP_INTERVAL ? STEP_INTERVAL : STEP_INTERVAL - ticks_taken;
		db_instance_export_events(db_ticks);

		/* read a packet or wait for a timeout */
		ticks_taken = get_ticks_ms() - ticks;
		ticks_ms_t timeout = ticks_taken > STEP_INTERVAL ? 0 : STEP_INTERVAL - ticks_taken;
		while (poll(n->pfd, 1, (int)timeout) > 0) {
			/* process incoming packet, data is waiting */
			pktl = (int)read(n->fd, pkt, MAX_PACKET);
			if (pktl >= 0) {
				++n->stats->packets_read;
				n->ticks->last_pkt_received = get_ticks_ms();

				if (n->encrypt->use_encryption) {
					if (pkt[0] == 0x00) {
						if (pktl >= 2) {
							decrypt_buffer(td, &pkt[2], pktl-2);
						}
					} else {
						decrypt_buffer(td, &pkt[1], pktl-1);
					}
				}

				if (td->debug->spew_packets) {
					spew_packet(pkt, pktl, DIR_INCOMING);
				}

				process_incoming_packet(td, pkt, pktl);
			}

			ticks_taken = get_ticks_ms() - ticks;
			timeout = timeout > ticks_taken ? timeout - ticks_taken : 0;
		}

		/* update the tick count after potential sleeping in poll() */
		ticks = get_ticks_ms();

		/* network state specfic actions */
		if (n->state == NS_CONNECTING) {
			/* retransmit connection request if it was lost */
			if (ticks - n->ticks->last_connection_request > 15000) {
				pkt_send_client_key(n->encrypt->client_key);
				n->ticks->last_connection_request = ticks;
			}
		} else if (ticks - n->ticks->last_pkt_received > 30*1000) {
			/* disconnect if no packets have been received for 30 seconds */
			Log(OP_MOD, "No data received for 30 seconds, reconnecting...");
			disconnect_from_server(td);
			continue;
		}

		/* transmit player position update if necessary */
		if (n->state == NS_CONNECTED && td->in_arena) {
			if ((ticks - n->ticks->last_pos_update_sent > 100
			    && td->bot_ship != SHIP_SPECTATOR)
			    || (ticks - n->ticks->last_pos_update_sent > 1000
			    && td->bot_ship == SHIP_SPECTATOR)) {
				pkt_send_position_update(td->bot_pos->x, td->bot_pos->y,
				    td->bot_vel->x, td->bot_vel->y);
				n->ticks->last_pos_update_sent = ticks;
			}
		}

		/* send periodic info/einfo */
		if (n->state == NS_CONNECTED) {
			// subtract 10000 to offset this by 10 seconds from *einfo to avoid filling buffers with commands/responses
			if (td->periodic->info && ticks - (td->periodic->last_info - 10000U) >= td->periodic->info) {
				int nhere = player_get_phere(td);
				PLAYER *parray = player_get_parray(td);
				for (int i = 0; i < nhere; ++i) {
					if (parray[i].here && td->enter->send_info) {
						PrivMessage(&parray[i], "*info");
					}
				}

				td->periodic->last_info = ticks;
			}

			if (td->periodic->einfo && ticks - td->periodic->last_einfo >= td->periodic->einfo) {
				int nhere = player_get_phere(td);
				PLAYER *parray = player_get_parray(td);
				for (int i = 0; i < nhere; ++i) {
					if (parray[i].here && td->enter->send_einfo) {
						PrivMessage(&parray[i], "*einfo");
					}
				}

				td->periodic->last_einfo = ticks;
			}
		}

		/* retransmit reliable packets that have not been acked */
		rpacket_list_t *l = n->rel_o->queue;
		rpacket_list_t::iterator iter = l->begin();
		while (iter != l->end()) {
			RPACKET *rp = *iter;
			if (ticks - rp->ticks > RELIABLE_RETRANSMIT_INTERVAL) {
				PACKET *p = allocate_packet(rp->len);
				memcpy(p->data, rp->data, rp->len);

				/* update packets retransmit tick */
				rp->ticks = ticks;

				queue_packet(p, SP_HIGH);
			}
			
			++iter;
		}

		/* free absent players if its time */
		ticks_ms_t flush_check_interval = 60 * 60 * 1000;
		if (ticks - td->arena->ticks->last_player_flush > flush_check_interval) {
			player_free_absent_players(td, flush_check_interval, true);
			td->arena->ticks->last_player_flush = ticks;
		}

		/* write packets generated during loop iteration */
		send_outgoing_packets(td);
	} /* while td->running != 0 */
}
Exemplo n.º 17
0
// Handle an incoming OFF message. Default disconnects from server and exits
void BaseBot::process_off_message( TokenMessage &incoming_message )
{
	disconnect_from_server();

	m_main_dlg->end_dialog();
}
Exemplo n.º 18
0
/*******************************************************************************
* The entry point to client. Builds a request packet, and then sends it. The
* way the packet is built depends on whether the URI and method have been
* specified in the command line arguments.
*******************************************************************************/
int main(int argc, char **argv)
{
	int num_bytes;
	socket_t sockfd;
	int port = 0;
	char hostname[MAXHOSTNAMESIZE + 1] = { 0 };
	char method[MAXMETHODSIZE + 1] = { 0 };
	int pot_number = 0;
	char additions[400] = { 0 };
	char message[80];
	char packet[MAXPACKETSIZE + 1] = { 0 };
	int i;

	/*check the arguments*/
	printf("\n");
	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-f") == 0) {
			++i;
			continue;
		}
		else if (strcmp(argv[i], "-u") == 0) {
			process_uri(argv[++i], &pot_number, additions, hostname, &port);
			continue;
		}
		else if (strcmp(argv[i], "-m") == 0) {
			strcpy(method, argv[++i]);
			continue;
		}
		else {
			printf("usage: %s [-f \"file\"] | [[-m \"method\"] [- u \"URI\"]]",
				argv[0]);
			exit(1);
		}
	}

	if (method[0] == '\0') {
		get_method(method);
	}

	/*allows the user to choose the message for a BREW/POST request*/
	if (strcmp(method, "BREW") == 0 || strcmp(method, "POST") == 0) {
		get_message(message);
	}
	else {
		strcpy(message, "Content-length:0\r\n\r\n");
	}

	if (strstr(message, "start") && additions[0] == '\0') {
		get_additions(additions);
	}

	if (pot_number == 0) {
		pot_number = get_pot_number();
	}

	if (hostname[0] == '\0') {
		get_hostname(hostname);
	}

	if (port == 0) {
		get_port(&port);
	}

	/*build the packet from the indivdual elements built up to now*/
	sprintf(packet, "%s pot-%d HTCPCP/1.0\r\n%s%s", method, pot_number,
		additions, message);

	sockfd = connect_to_server(hostname, port);

	/*send the packet*/
	num_bytes = send_message(sockfd, packet);
	if (num_bytes == 0) {
		printf("Failed to send message %s", packet);
	}

	/*wait for response*/
	do {
		num_bytes = receive_message(sockfd, packet, MAXPACKETSIZE);
		if (num_bytes != 0) {
			packet[num_bytes] = '\0';
			printf("received: %s\n", packet);
		}
	} while (packet[0] == '\0');

	disconnect_from_server(sockfd);
	return 0;
}
Exemplo n.º 19
0
static PyObject* python_disconnect_from_server(PyObject* self, PyObject* args) {
	if(PyArg_ParseTuple(args, "") == 0) return NULL;
	disconnect_from_server();
	return Py_BuildValue("i", 0);
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{
	int starting_line = 1;	/* line to start editing at */
	char command[MAXPATHLEN + 50];	/* emacs command buffer */
	char fullpath[MAXPATHLEN + 1];	/* full pathname to file */
	char *eval_form = NULL;	/* form to evaluate with `-eval' */
	char *eval_function = NULL;	/* function to evaluate with `-f' */
	char *load_library = NULL;	/* library to load */
	int quick = 0;		/* quick edit, don't wait for user to
				   finish */
	int batch = 0;		/* batch mode */
	int view = 0;		/* view only. */
	int nofiles = 0;
	int errflg = 0;		/* option error */
	int s;			/* socket / msqid to server */
	int connect_type;	/* CONN_UNIX, CONN_INTERNET, or
				 * CONN_IPC */
	int suppress_windows_system = 0;
	char *display = NULL;
#ifdef INTERNET_DOMAIN_SOCKETS
	char *hostarg = NULL;	/* remote hostname */
	char *remotearg;
	char thishost[HOSTNAMSZ];	/* this hostname */
	char remotepath[MAXPATHLEN + 1];	/* remote pathname */
	int rflg = 0;		/* pathname given on cmdline */
	char *portarg;
	unsigned short port = 0;	/* port to server */
#endif				/* INTERNET_DOMAIN_SOCKETS */
	char *path;		/* used indiscriminately */
#ifdef SYSV_IPC
	struct msgbuf *msgp;	/* message */
#endif				/* SYSV_IPC */
	char *tty = NULL;
	char buffer[GSERV_BUFSZ + 1];	/* buffer to read pid */
	char result[GSERV_BUFSZ + 1];
	int i;
	int sz;
	size_t msz;

#ifdef INTERNET_DOMAIN_SOCKETS
	memset(remotepath, 0, sizeof(remotepath));
#endif				/* INTERNET_DOMAIN_SOCKETS */

	progname = strrchr(argv[0], '/');
	if (progname)
		++progname;
	else
		progname = argv[0];

#ifdef USE_TMPDIR
	tmpdir = getenv("TMPDIR");
#endif
	if (!tmpdir)
		tmpdir = "/tmp";

	display = getenv("DISPLAY");
	if (display)
		display = my_strdup(display);
	else
		suppress_windows_system = 1;

	for (i = 1; argv[i] && !errflg; i++) {
		if (*argv[i] != '-')
			break;
		else if (*argv[i] == '-'
			 && (*(argv[i] + 1) == '\0'
			     || (*(argv[i] + 1) == '-'
				 && *(argv[i] + 2) == '\0'))) {
			/* `-' or `--' */
			++i;
			break;
		}

		if (!strcmp(argv[i], "-batch") || !strcmp(argv[i], "--batch"))
			batch = 1;
		else if (!strcmp(argv[i], "-eval")
			 || !strcmp(argv[i], "--eval")) {
			if (!argv[++i]) {
				fprintf(stderr,
					"%s: `-eval' must be followed by an argument\n",
					progname);
				exit(1);
			}
			eval_form = argv[i];
		} else if (!strcmp(argv[i], "-display")
			   || !strcmp(argv[i], "--display")) {
			suppress_windows_system = 0;
			if (!argv[++i]) {
				fprintf(stderr,
					"%s: `-display' must be followed by an argument\n",
					progname);
				exit(1);
			}
			if (display)
				free(display);
			/* no need to strdup. */
			display = argv[i];
		} else if (!strcmp(argv[i], "-nw"))
			suppress_windows_system = 1;
		else {
			/* Iterate over one-letter options. */
			char *p;
			int over = 0;
			for (p = argv[i] + 1; *p && !over; p++) {
				switch (*p) {
				case 'q':
					quick = 1;
					break;
				case 'v':
					view = 1;
					break;
				case 'f':
					GET_ARGUMENT(eval_function, "-f");
					break;
				case 'l':
					GET_ARGUMENT(load_library, "-l");
					break;
#ifdef INTERNET_DOMAIN_SOCKETS
				case 'h':
					GET_ARGUMENT(hostarg, "-h");
					break;
				case 'p':
					GET_ARGUMENT(portarg, "-p");
					port = atoi(portarg);
					break;
				case 'r':
					GET_ARGUMENT(remotearg, "-r");
					xstrncpy(remotepath, remotearg, sizeof(remotepath));
					remotepath[sizeof(remotepath)-1]='\0';
					rflg = 1;
					break;
#endif				/* INTERNET_DOMAIN_SOCKETS */
				default:
					errflg = 1;
				}
			}	/* for */
		}		/* else */
	}			/* for */

	if (errflg) {
		fprintf(stderr,
#ifdef INTERNET_DOMAIN_SOCKETS
			"Usage: %s [-nw] [-display display] [-q] [-v] [-l library]\n"
			"       [-batch] [-f function] [-eval form]\n"
			"       [-h host] [-p port] [-r remote-path] [[+line] file] ...\n",
#else				/* !INTERNET_DOMAIN_SOCKETS */
			"Usage: %s [-nw] [-q] [-v] [-l library] [-f function] [-eval form] "
			"[[+line] path] ...\n",
#endif				/* !INTERNET_DOMAIN_SOCKETS */
			progname);
		exit(1);
	}
	if (batch && argv[i]) {
		fprintf(stderr, "%s: Cannot specify `-batch' with file names\n",
			progname);
		exit(1);
	}
#if defined(INTERNET_DOMAIN_SOCKETS)
	if (suppress_windows_system && hostarg) {
		fprintf(stderr, "%s: Remote editing is available only on X\n",
			progname);
		exit(1);
	}
#endif
	*result = '\0';
	if (eval_function || eval_form || load_library) {
#if defined(INTERNET_DOMAIN_SOCKETS)
		connect_type = make_connection(hostarg, port, &s);
#else
		connect_type = make_connection(NULL, 0, &s);
#endif
		SNPRINTF(sz, command, sizeof(command),
			 "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
		send_string(s, command);
		if (load_library) {
			send_string(s, "(load-library ");
			send_string(s, clean_string(load_library));
			send_string(s, ") ");
		}
		if (eval_form) {
			send_string(s, eval_form);
		}
		if (eval_function) {
			send_string(s, "(");
			send_string(s, eval_function);
			send_string(s, ")");
		}
		send_string(s, "))");
		/* disconnect already sends EOT_STR */
#ifdef SYSV_IPC
		if (connect_type == (int)CONN_IPC)
			disconnect_from_ipc_server(s, msgp, batch && !quick);
#else				/* !SYSV_IPC */
		if (connect_type != (int)CONN_IPC)
			disconnect_from_server(s, batch && !quick);
#endif				/* !SYSV_IPC */
	} /* eval_function || eval_form || load_library */
	else if (batch) {
		/* no sexp on the command line, so read it from stdin */
		int nb;

#if defined(INTERNET_DOMAIN_SOCKETS)
		connect_type = make_connection(hostarg, port, &s);
#else
		connect_type = make_connection(NULL, 0, &s);
#endif
		SNPRINTF(sz, command, sizeof(command),
			 "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
		send_string(s, command);

		while ((nb = read(fileno(stdin), buffer, GSERV_BUFSZ - 1)) > 0) {
			buffer[nb] = '\0';
			send_string(s, buffer);
		}
		send_string(s, "))");
		/* disconnect already sends EOT_STR */
#ifdef SYSV_IPC
		if (connect_type == (int)CONN_IPC)
			disconnect_from_ipc_server(s, msgp, batch && !quick);
#else				/* !SYSV_IPC */
		if (connect_type != (int)CONN_IPC)
			disconnect_from_server(s, batch && !quick);
#endif				/* !SYSV_IPC */
	}

	if (!batch) {
		if (suppress_windows_system) {
			tty = ttyname(0);
			if (!tty) {
				fprintf(stderr, "%s: Not connected to a tty",
					progname);
				exit(1);
			}
#if defined(INTERNET_DOMAIN_SOCKETS)
			connect_type = make_connection(hostarg, port, &s);
#else
			connect_type = make_connection(NULL, 0, &s);
#endif
			send_string(s, "(gnuserv-eval '(emacs-pid))");
			send_string(s, EOT_STR);

			if (read_line(s, buffer) == 0) {
				fprintf(stderr,
					"%s: Could not establish Emacs process id\n",
					progname);
				exit(1);
			}
			/* Don't do disconnect_from_server because we have already read
			   data, and disconnect doesn't do anything else. */
#ifdef SYSV_IPC
			if (connect_type == (int)CONN_IPC)
				disconnect_from_ipc_server(s, msgp, FALSE);
#endif				/* !SYSV_IPC */

			emacs_pid = (pid_t) atol(buffer);
			initialize_signals();
		}
		/* suppress_windows_system */
#if defined(INTERNET_DOMAIN_SOCKETS)
		connect_type = make_connection(hostarg, port, &s);
#else
		connect_type = make_connection(NULL, 0, &s);
#endif

#ifdef INTERNET_DOMAIN_SOCKETS
		if (connect_type == (int)CONN_INTERNET) {
			char *ptr;
			gethostname(thishost, HOSTNAMSZ);
			if (!rflg) {	/* attempt to generate a path
					 * to this machine */
				if ((ptr = getenv("GNU_NODE")) != NULL) {
					/* user specified a path */
					xstrncpy(remotepath, ptr, sizeof(remotepath)-1);
					remotepath[sizeof(remotepath)-1]='\0';
				}
			}
#if 0				/* This is really bogus... re-enable it if you must have it! */
#if defined (hp9000s300) || defined (hp9000s800)
			else if (strcmp(thishost, hostarg)) {	/* try /net/thishost */
				strcpy(remotepath, "/net/");	/* (this fails using internet
								   addresses) */
				strcat(remotepath, thishost);
			}
#endif
#endif
		} else {	/* same machines, no need for path */
			remotepath[0] = '\0';	/* default is the empty path */
		}
#endif				/* INTERNET_DOMAIN_SOCKETS */

#ifdef SYSV_IPC
		if ((msgp = (struct msgbuf *)
		     malloc(sizeof *msgp + GSERV_BUFSZ)) == NULL) {
			fprintf(stderr,
				"%s: not enough memory for message buffer\n",
				progname);
			exit(1);
		}
		/* if */
		msgp->mtext[0] = '\0';	/* ready for later strcats */
#endif				/* SYSV_IPC */

		if (suppress_windows_system) {
			char *term = getenv("TERM");
			pid_t pid = getpid();

			if (!term) {
				fprintf(stderr, "%s: unknown terminal type\n",
					progname);
				exit(1);
			}
			SNPRINTF(sz, command, sizeof(command),
				 "(gnuserv-edit-files '(tty %s %s %d) '(",
				 clean_string(tty), clean_string(term),
				 (int)pid);
		} else {	/* !suppress_windows_system */

			if (0) ;
#ifdef HAVE_X_WINDOWS
			else if (display) {
				SNPRINTF(sz, command, sizeof(command),
					 "(gnuserv-edit-files '(x %s) '(",
					 clean_string(display));
			}
#endif
		}		/* !suppress_windows_system */
		send_string(s, command);

		if (!argv[i])
			nofiles = 1;

		for (; argv[i]; i++) {
			if (i < argc - 1 && *argv[i] == '+') {
				starting_line = atoi(argv[i++]);
			} else {
				starting_line = 1;
			}
			/* If the last argument is +something, treat it as a
			   file. */
			if (i == argc) {
				starting_line = 1;
				--i;
			}
			filename_expand(fullpath, argv[i], sizeof(fullpath));
#ifdef INTERNET_DOMAIN_SOCKETS
			msz = strlen(remotepath) + strlen(fullpath) + 1;
			path = (char*)malloc(msz);
			SNPRINTF(sz, path, msz, "%s%s", remotepath, fullpath);
#else  /* !INTERNET_DOMAIN_SOCKETS */
			path = my_strdup(fullpath);
#endif	/* INTERNET_DOMAIN_SOCKETS */
			SNPRINTF(sz, command, sizeof(command),
				"(%d . %s)", starting_line, clean_string(path));
			send_string(s, command);
			free(path);
		}

		SNPRINTF(sz, command, sizeof(command), ")%s%s",
			 (quick || (nofiles && !suppress_windows_system))
			 ? " 'quick"
			 : "",
			 view ? " 'view" : "");
		send_string(s, command);
		send_string(s, ")");

#ifdef SYSV_IPC
		if (connect_type == (int)CONN_IPC)
			disconnect_from_ipc_server(s, msgp, FALSE);
#else				/* !SYSV_IPC */
		if (connect_type != (int)CONN_IPC)
			disconnect_from_server(s, FALSE);
#endif				/* !SYSV_IPC */
	}

	/* not batch */
	return 0;

}
Exemplo n.º 21
0
/****************************************************************************
  Called when the ggz socket has data pending.
****************************************************************************/
void input_from_ggz(int socket)
{
  if (ggzmod_dispatch(ggzmod) < 0) {
    disconnect_from_server();
  }
}
Exemplo n.º 22
0
// usage: smp <IP address to connect to>
int main( int argc, char** argv )
{
    if ( argc != 2 ) /* argc should be 2 for correct execution */
    {
        printf( "usage:\n\tsmp <ipaddress>\n\tsmp server\n" );
        return EXIT_FAILURE;
    }
    
    int bServerMode = strstr( "server", argv[ 1 ] ) != 0;

    setup();
    
    unsigned char holder[ BUFFER_SIZE ];
    memset( holder, 0x00, BUFFER_SIZE );
    
    if ( !bServerMode )
    {
        // we are talking to the server at ip address argv[ 1 ]
        char input_string[ 256 ];
        printf( "Enter a shared secret: " );
        readLine( input_string, 256 );
        // TESTCODE: strcpy( input_string, "testme" );
        secret = binEncode( input_string, strlen( input_string ) );
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 1 and send to other side */
        /*****************************************************/
        /*****************************************************/
        int len = step1( holder, BUFFER_SIZE );
        
        int serverfd = connect_to_server( argv[ 1 ] );
        if ( serverfd == 1 )
            return EXIT_FAILURE;
        
        write_to_server( serverfd, holder, len );
        // dumpBuff( holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Get results from other side. */
        /*  Other side performed Step 2. */
        /*****************************************************/
        /*****************************************************/
        memset( holder, 0x00, BUFFER_SIZE );
        len = revc_from_server( serverfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 3 and send to the other side */
        /*****************************************************/
        /*****************************************************/
        step3( holder, BUFFER_SIZE );
        write_to_server( serverfd, holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Get bytes from other side and do Step 5 */
        /*****************************************************/
        /*****************************************************/
        memset( holder, 0x00, BUFFER_SIZE );
        len = revc_from_server( serverfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, len );
        
        step5( holder, len );
        
        disconnect_from_server( serverfd );
    }
    else    // we are in server mode, other side will send us data first
    {
        int listenfd = listen_server();
        /*if ( listenfd == 1 )
            return EXIT_FAILURE;
        TODO: error checking
        */
        
        char input_string[ 256 ];
        printf( "Enter a shared secret: " );
        readLine( input_string, 256 );
        // TESTCODE: strcpy( input_string, "testme" );
        secret = binEncode( input_string, strlen( input_string ) );
        
        int len = revc_from_server( listenfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, BUFFER_SIZE);
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 2 and send to other side */
        /*****************************************************/
        /*****************************************************/
        len = step2( holder, BUFFER_SIZE  );
        write_to_server( listenfd, holder, len );

        len = revc_from_server( listenfd, holder, BUFFER_SIZE );
        // dumpBuff( holder, len );
        
        /*****************************************************/
        /*****************************************************/
        /*  Do Step 4 and send to other side */
        /*****************************************************/
        /*****************************************************/
        len = step4( holder, BUFFER_SIZE );
        write_to_server( listenfd, holder, len );
        
        disconnect_from_server( listenfd );
    }
    
    
    if ( match == 1 )
        printf( "Secrets match\n" );
    else
        printf( "Secrets do not match\n");
    
    cleanup();
    return EXIT_SUCCESS;
}
Exemplo n.º 23
0
/** 
 * @brief  发送数据
 * @param   p_data 待发送的数据
 * @param   data_len 待发送的数据的长度
 * @return  0success -1failed
 */
int c_net_client_impl::send_data(char *p_data, int data_len)
{
    if(!m_inited)
    {
        return -1;
    }

    if(NULL == p_data || data_len < 0)
    {
        return -1;
    }

    if(m_sock_fd < 0)
    {
        if(connect_to_server(m_timeout) < 0)
        {
            ERROR_LOG("can not connect to server now.");
            return -1;
        }
    }

    if(m_send_buffer_len > 0)
    {/**< 发送缓冲中尚有数据,需首先将本次数据添加到发送缓冲中,然后再调用发送函数*/
        if(data_len > 0)
        {
            append_data_to_send_buffer(p_data, data_len);
        }
        
        int bytes_sent = send_to_server(m_sock_fd, m_send_buffer, m_send_buffer_len);
        if(bytes_sent > 0)
        {
            remove_data_from_send_buffer(bytes_sent);
        }
        else if(bytes_sent < 0)
        {/**< 连接遇到问题,关闭连接*/
           disconnect_from_server();
           return -1;
        }
        else
        {
            /**< 无法发送数据 nothing to do*/
        }
    }
    else
    {/**< 发送缓冲为空,直接调用发送函数*/
       if(data_len > 0)
       {
            int bytes_sent = send_to_server(m_sock_fd, p_data, data_len);
            if(bytes_sent >= 0)
            {
                if(bytes_sent < data_len)
                {
                    append_data_to_send_buffer(p_data + bytes_sent, data_len -bytes_sent);
                }
            }
            else
            {
                disconnect_from_server();
                return -1;
            }
       }
       else
       {
            //nothing to do
       }
    }

    return 0;
}