Beispiel #1
0
/*---------------------------Main function -----------------------------*/
int main()
{
 ub4 rownum;

 /* Initialize the environment and allocate handles */
 if (init_env_handle()) 
 {
   printf("FAILED: init_env_handle()!\n");
   return OCI_ERROR;
 }

 /* Log on to the server and begin a session */
 if (connect_server()) 
 {
   printf("FAILED: connect_server()!\n");
   cleanup();
   return OCI_ERROR;
 }

 /* Initialize the demo table */
 if (init_table())
 {
   printf("FAILED: init_table()\n");
   disconnect_server();
   return OCI_ERROR;
 }

 rownum = 1;
 /* Insertion */
 if (insert_xml(rownum))
 {
   printf("FAILED: insert_xml()!\n");
   disconnect_server();
   return OCI_ERROR;
 }

 /* Selection */
 if (select_xml(rownum))
 {
   printf("FAILED: select_xml()!\n");
   disconnect_server();
   return OCI_ERROR;
 }

 /* Detach from a server and clean up the environment */
 disconnect_server();

 return OCI_SUCCESS;
}
Beispiel #2
0
/******************************************************************************
 *                                                                            *
 * Function: host_availability_sender                                         *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	host_availability_sender(struct zbx_json *j)
{
	const char	*__function_name = "host_availability_sender";
	zbx_sock_t	sock;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	zbx_json_clean(j);
	zbx_json_addstring(j, ZBX_PROTO_TAG_REQUEST, ZBX_PROTO_VALUE_HOST_AVAILABILITY, ZBX_JSON_TYPE_STRING);
	zbx_json_addstring(j, ZBX_PROTO_TAG_HOST, CONFIG_HOSTNAME, ZBX_JSON_TYPE_STRING);

	if (SUCCEED == get_host_availability_data(j))
	{
		char	*error = NULL;

		connect_to_server(&sock, 600, CONFIG_PROXYDATA_FREQUENCY); /* retry till have a connection */

		if (SUCCEED != put_data_to_server(&sock, j, &error))
			zabbix_log(LOG_LEVEL_WARNING, "sending host availability data to server failed: %s", error);

		zbx_free(error);
		disconnect_server(&sock);
	}

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
/******************************************************************************
 *                                                                            *
 * Function: process_configuration_sync                                       *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	process_configuration_sync()
{
	const char	*__function_name = "process_configuration_sync";

	zbx_sock_t	sock;
	char		*data;
	struct		zbx_json_parse jp;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	connect_to_server(&sock, 600, CONFIG_PROXYCONFIG_RETRY); /* retry till have a connection */

	if (FAIL == get_data_from_server(&sock, ZBX_PROTO_VALUE_PROXY_CONFIG, &data))
		goto exit;

	if ('\0' != *data)
		zabbix_log(LOG_LEVEL_WARNING, "Received configuration data from server. Datalen " ZBX_FS_SIZE_T,
				(zbx_fs_size_t)strlen(data));
	else
		zabbix_log(LOG_LEVEL_WARNING, "Cannot obtain configuration data from server. "
				"Proxy host name might not be matching that on the server.");

	if (FAIL == zbx_json_open(data, &jp))
		goto exit;

	process_proxyconfig(&jp);
exit:
	disconnect_server(&sock);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Beispiel #4
0
/******************************************************************************
 *                                                                            *
 * Function: send_heartbeat                                                   *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static int	send_heartbeat(void)
{
	zbx_sock_t	sock;
	struct zbx_json	j;
	int		ret = SUCCEED;
	char		*error = NULL;

	zabbix_log(LOG_LEVEL_DEBUG, "In send_heartbeat()");

	zbx_json_init(&j, 128);
	zbx_json_addstring(&j, "request", ZBX_PROTO_VALUE_PROXY_HEARTBEAT, ZBX_JSON_TYPE_STRING);
	zbx_json_addstring(&j, "host", CONFIG_HOSTNAME, ZBX_JSON_TYPE_STRING);

	if (FAIL == connect_to_server(&sock, CONFIG_HEARTBEAT_FREQUENCY, 0)) /* do not retry */
		return FAIL;

	if (SUCCEED != put_data_to_server(&sock, &j, &error))
	{
		zabbix_log(LOG_LEVEL_WARNING, "sending heartbeat message to server failed: %s", error);
		ret = FAIL;
	}

	zbx_free(error);
	disconnect_server(&sock);

	return ret;
}
Beispiel #5
0
static void start_auth_request(PgSocket *client, const char *username)
{
	int res;
	char quoted_username[64], query[128];

	client->auth_user = client->db->auth_user;
	/* have to fetch user info from db */
	client->pool = get_pool(client->db, client->db->auth_user);
	if (!find_server(client)) {
		client->wait_for_user_conn = true;
		return;
	}
	slog_noise(client, "Doing auth_conn query");
	client->wait_for_user_conn = false;
	client->wait_for_user = true;
	if (!sbuf_pause(&client->sbuf)) {
		release_server(client->link);
		disconnect_client(client, true, "pause failed");
		return;
	}
	client->link->ready = 0;

	pg_quote_literal(quoted_username, username, sizeof(quoted_username));
	snprintf(query, sizeof(query), "SELECT usename, passwd FROM pg_shadow WHERE usename=%s", quoted_username);
	SEND_generic(res, client->link, 'Q', "s", query);
	if (!res)
		disconnect_server(client->link, false, "unable to send login query");
}
Beispiel #6
0
static void timeout_server(int idx)
{
  putlog(LOG_SERV, "*", "Timeout: connect to %s", dcc[idx].host);
  disconnect_server(idx);
  check_tcl_event("fail-server");
  lostdcc(idx);
}
Beispiel #7
0
/*
 * Look for duplicate IP addresses.  This is done very inoften, so we do
 * not use a particularly efficient algorithm.
 *
 * Only reconnect a client which has not done its initial poll.
 */
void
client_check_duplicate_ips(struct server_info **info_ary, int count)
{
    server_info_t info1;
    server_info_t info2;
    int tries;
    int i;
    int j;

    for (i = 0; i < count; ++i) {
	info1 = info_ary[i];
	if (info1->fd < 0 || info1->server_state != 0)
	    continue;
	for (tries = 0; tries < 10; ++tries) {
	    for (j = 0; j < count; ++j) {
		info2 = info_ary[j];
		if (i == j || info2->fd < 0)
		    continue;
		if (info1->fd < 0 || /* info1 was lost in previous reconnect */
		    strcmp(info1->ipstr, info2->ipstr) == 0) {
		    reconnect_server(info1);
		    break;
		}
	    }
	    if (j == count)
		break;
	}
	if (tries == 10) {
	    disconnect_server(info1);
	    client_setserverstate(info1, -2,
				  "permanently disabling duplicate server");
	}
    }
}
Beispiel #8
0
PROTO void client_quit(void)
{
        if ( client->connected == 1 )
        {
                closegroup();
                disconnect_server(client);
        }
}
Beispiel #9
0
/* close all sockets in server list */
static void close_server_list(struct StatList *sk_list, const char *reason)
{
	struct List *item, *tmp;
	PgSocket *server;

	statlist_for_each_safe(item, sk_list, tmp) {
		server = container_of(item, PgSocket, head);
		disconnect_server(server, true, "%s", reason);
	}
Beispiel #10
0
/* Close the current server connection.
 */
static void nuke_server(char *reason)
{
  if (serv >= 0) {
    int servidx = findanyidx(serv);

    if (reason && (servidx > 0))
      dprintf(servidx, "QUIT :%s\n", reason);
    disconnect_server(servidx);
    lostdcc(servidx);
  }
}
Beispiel #11
0
/******************************************************************************
 *                                                                            *
 * Function: history_sender                                                   *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	history_sender(struct zbx_json *j, int *records, const char *tag,
		int (*f_get_data)(), void (*f_set_lastid)())
{
	const char	*__function_name = "history_sender";

	zbx_sock_t	sock;
	zbx_uint64_t	lastid;
	zbx_timespec_t	ts;
	int		ret = SUCCEED;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	zbx_json_clean(j);
	zbx_json_addstring(j, ZBX_PROTO_TAG_REQUEST, tag, ZBX_JSON_TYPE_STRING);
	zbx_json_addstring(j, ZBX_PROTO_TAG_HOST, CONFIG_HOSTNAME, ZBX_JSON_TYPE_STRING);

	zbx_json_addarray(j, ZBX_PROTO_TAG_DATA);

	*records = f_get_data(j, &lastid);

	zbx_json_close(j);

	if (*records > 0)
	{
		char	*error = NULL;

		connect_to_server(&sock, 600, CONFIG_PROXYDATA_FREQUENCY); /* retry till have a connection */

		zbx_timespec(&ts);
		zbx_json_adduint64(j, ZBX_PROTO_TAG_CLOCK, ts.sec);
		zbx_json_adduint64(j, ZBX_PROTO_TAG_NS, ts.ns);

		if (SUCCEED != (ret = put_data_to_server(&sock, j, &error)))
		{
			*records = 0;
			zabbix_log(LOG_LEVEL_WARNING, "sending data to server failed: %s", error);
		}

		zbx_free(error);
		disconnect_server(&sock);
	}

	if (SUCCEED == ret && 0 != lastid)
	{
		DBbegin();
		f_set_lastid(lastid);
		DBcommit();
	}

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Beispiel #12
0
static void kill_server(int idx, void *x)
{
  module_entry *me;

  disconnect_server(idx);
  if ((me = module_find("channels", 0, 0)) && me->funcs) {
    struct chanset_t *chan;

    for (chan = chanset; chan; chan = chan->next)
      (me->funcs[CHANNEL_CLEAR]) (chan, 1);
  }
  /* A new server connection will be automatically initiated in
   * about 2 seconds. */
}
/******************************************************************************
 *                                                                            *
 * Function: send_heartbeat                                                   *
 *                                                                            *
 * Purpose:                                                                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	send_heartbeat()
{
    zbx_sock_t	sock;
    struct zbx_json	j;

    zabbix_log(LOG_LEVEL_DEBUG, "In send_heartbeat()");

    zbx_json_init(&j, 128);
    zbx_json_addstring(&j, "request", ZBX_PROTO_VALUE_PROXY_HEARTBEAT, ZBX_JSON_TYPE_STRING);
    zbx_json_addstring(&j, "host", CONFIG_HOSTNAME, ZBX_JSON_TYPE_STRING);

    if (FAIL == connect_to_server(&sock, CONFIG_HEARTBEAT_FREQUENCY, 0)) /* do not retry */
        return;

    if (FAIL == put_data_to_server(&sock, &j))
        zabbix_log(LOG_LEVEL_WARNING, "Heartbeat message failed");

    disconnect_server(&sock);
}
Beispiel #14
0
int main(int argc, char *argv[])
{
    int sockfd;

    if (argc < 3) {
       usage();
       exit(0);
    }

    if( (sockfd = open_connection_to( argv[1], atoi(argv[2]))) == 0) {
      report_error( "couldn't open connection to destination" );
      return -1;
    }

    recv_message( sockfd );
    read_one_line( sockfd );

    disconnect_server( sockfd );
    return 0;
}
void
on_cb_disconnect_clicked               (GtkButton       *button,
                                        gpointer         user_data)
{
  GtkWidget *widget;

  disconnect_server();
  widget=lookup_widget( mainwindow, "cb_disconnect" );
  gtk_widget_set_sensitive( widget, FALSE );
  widget=lookup_widget( mainwindow, "cb_connect" );
  gtk_widget_set_sensitive( widget, TRUE );
  widget=lookup_widget( mainwindow, "tb_footpsat" );
  gtk_widget_set_sensitive( widget, FALSE );
  widget=lookup_widget( mainwindow, "tb_footpqth" );
  gtk_widget_set_sensitive( widget, FALSE );
  widget=lookup_widget( mainwindow, "tb_track" );
  gtk_widget_set_sensitive( widget, FALSE );
  widget=lookup_widget( mainwindow, "tb_autofreq" );
  gtk_widget_set_sensitive( widget, FALSE );
  widget=lookup_widget( mainwindow, "bt_azelgraph" );
  gtk_widget_set_sensitive( widget, FALSE );
}
Beispiel #16
0
static void main_loop(void)
{
#ifdef CONFIG_AMBARELLA_IMAGE_SERVER_DAEMON
	if (start_server() < 0) {
		APP_ERROR("start_server");
		return;
	}
#endif
	while (1) {
		if (connect_server() < 0)
			break;

		while (1) {
			Request req;
			if (receive_text((u8 *)&req, sizeof(req)) < 0)
				break;

			process_request(&req);
		}

		disconnect_server();
	}
}
Beispiel #17
0
static void start_auth_request(PgSocket *client, const char *username)
{
	int res;
	PktBuf *buf;

	client->auth_user = client->db->auth_user;
	/* have to fetch user info from db */
	client->pool = get_pool(client->db, client->db->auth_user);
	if (!find_server(client)) {
		client->wait_for_user_conn = true;
		return;
	}
	slog_noise(client, "Doing auth_conn query");
	client->wait_for_user_conn = false;
	client->wait_for_user = true;
	if (!sbuf_pause(&client->sbuf)) {
		release_server(client->link);
		disconnect_client(client, true, "pause failed");
		return;
	}
	client->link->ready = 0;

	res = 0;
	buf = pktbuf_dynamic(512);
	if (buf) {
		pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
		res = pktbuf_send_immediate(buf, client->link);
		pktbuf_free(buf);
		/*
		 * Should do instead:
		 *   res = pktbuf_send_queued(buf, client->link);
		 * but that needs better integration with SBuf.
		 */
	}
	if (!res)
		disconnect_server(client->link, false, "unable to send login query");
}
Beispiel #18
0
static void
meta_command(struct sockaddr_in *from, char *command)
{
    Server	*s;
    char	*cmd, *name, *dummy;

    parse_connect(command, &cmd, &name, &dummy);
    s = serv_name2server(name); 
    if (!strcmp(cmd + 1, "connect")) {
	char		buf[128];
	Server	       *local;

	if (!s) {
	    s = promiscuous_connect(from, name);
	    if (!s) {
		return;
	    }
	} else if (verify_servers && !verify_server(s, from)) {
	    return;
	}
	s->connected = 1;
	s->last_msgid = -1;
	writelog();
	fprintf(stderr, "Server %s (%s %d) connected\n", s->name, s->hostname,
		s->port);
	local = serv_id2server(0);
	sprintf(buf, "*connectok %s\n", local->name);
	sendto(yo_sock, buf, strlen(buf), 0, (struct sockaddr *) from,
		sizeof(*from));
	connect_server(s->id);
    } else if (!strcmp(cmd + 1, "connectok")) {
	if (!s) {
	    s = promiscuous_connect(from, name);
	    if (!s) {
		return;
	    }
	} else if (verify_servers && !verify_server(s, from)) {
	    return;
	}
	s->connected = 1;
	s->last_msgid = -1;
	writelog();
	fprintf(stderr, "Server %s (%s %d) connected ok\n", s->name,
		s->hostname, s->port);
	connect_server(s->id);
    } else if (!strcmp(cmd + 1, "disconnect")) {
	if (!s) {
	    return;
	}
	s->connected = 0;
	writelog();
	fprintf(stderr, "Server %s (%s %d) disconnected\n", s->name,
		s->hostname, s->port);
	disconnect_server(s->id);
    } else {
	if (!s) {
	    return;
	}
	writelog();
	fprintf(stderr, "Unknown metacommand \"%s\" from server %s\n",
		command, s->name);
    }
}
Beispiel #19
0
static void timeout_server(int idx)
{
  putlog(LOG_SERV, "*", "Timeout: connect to %s", dcc[idx].host);
  disconnect_server(idx);
  lostdcc(idx);
}
Beispiel #20
0
static void eof_server(int idx)
{
  putlog(LOG_SERV, "*", "%s %s", IRC_DISCONNECTED, dcc[idx].host);
  disconnect_server(idx);
  lostdcc(idx);
}
Beispiel #21
0
PROTO int passcmd(char *command, char *args, CMDINFO *cmd)
{
        int     i = 1;
        char    chkbuf[5];
        ssize_t bread = 0;
        int     ret;
        CLEARBUF

        if ( ! writeserver(client, "%s %s\r\n", command, args) ) goto sdown;
        if ( (readserverline(client->bbuf, cfg.BufSize)) == NULL ) goto sdown;

        /* logic to retry command if article not found */
        int j=0;
        while ( ( cmd->num == cmd_body || cmd->num == cmd_article ) 
                && ( atoi(client->bbuf) == 423 || atoi(client->bbuf) == 430 )
                && j++ < cfg.NoSuchArticleRetries)
        {
                if ( ! writeserver(client, "%s %s\r\n", command, args) ) goto sdown;
                if ( (readserverline(client->bbuf, cfg.BufSize)) == NULL ) goto sdown;
                if ( atoi(client->bbuf) < 400 )
                {
                        if ( client->group == NULL )
                                syslog(LOG_ERR, "No such article, found in %d retries on server %s msgid %s",
                                                j,
                                                client->groupserver->Name,
                                                args);
                        else
                                syslog(LOG_ERR, "No such article, found in %d retries on server %s group %s msgid %s",
                                                j,
                                                client->groupserver->Name,
                                                client->group->newsgroup,
                                                args);
                }
        }

        if ( swriteclient(client, client->bbuf) ) goto sdown;

        ret = atoi(client->bbuf);
        if ( ret == 0 ) {
                syslog(LOG_ERR, "ret==0 cmd=%s args=%s server=%s", command, args, client->currserver->Name);
        }
        if ( ret > 399 ) i=0;

        if ( ret == 430 && cfg.LogMissing )
                syslog(LOG_ERR, "missing_article: %s %s", client->hostname, args);
        if ( ret == 423 && cfg.LogMissing )
                syslog(LOG_ERR, "missing_article: %s %s:%s", client->hostname, client->group->newsgroup, args);

        checkbuf_init(chkbuf);
        while (i && ! client->error)
        {
                if ( (bread = nreadserver(client, client->bbuf, cfg.BufSize)) == 0 )
                        goto sdown;

                if ( checkbuf_isend(chkbuf, client->bbuf, bread) )
                        i = 0;

                if ( slwriteclient(client, client->bbuf, bread, cmd->limit) )
                        return -1;

                if ( cmd->acct == 1 ) {
                        client->bytes += (ulong64)bread;
                        client->rbytes += (ulong64)bread;
                }

                if ( cmd->acct == 1 && client->user->bytesleft > 0 )
                        client->user->bytesleft -= (ulong64)bread;

                client->groupbytes  += (ulong64)bread;
        }

        return 0;

sdown:
        syslog(LOG_ERR, "Server down during passcmd, sending MSG_SERVER_DOWN");
        swriteclient(client, MSG_SERVER_DOWN);
        disconnect_server(client);
        return 0;
}
Beispiel #22
0
/* callback from SBuf */
bool client_proto(SBuf *sbuf, SBufEvent evtype, struct MBuf *data)
{
	bool res = false;
	PgSocket *client = container_of(sbuf, PgSocket, sbuf);
	PktHdr pkt;


	Assert(!is_server_socket(client));
	Assert(client->sbuf.sock);
	Assert(client->state != CL_FREE);

	/* may happen if close failed */
	if (client->state == CL_JUSTFREE)
		return false;

	switch (evtype) {
	case SBUF_EV_CONNECT_OK:
	case SBUF_EV_CONNECT_FAILED:
		/* ^ those should not happen */
	case SBUF_EV_RECV_FAILED:
		disconnect_client(client, false, "client unexpected eof");
		break;
	case SBUF_EV_SEND_FAILED:
		disconnect_server(client->link, false, "Server connection closed");
		break;
	case SBUF_EV_READ:
		if (mbuf_avail_for_read(data) < NEW_HEADER_LEN && client->state != CL_LOGIN) {
			slog_noise(client, "C: got partial header, trying to wait a bit");
			return false;
		}

		if (!get_header(data, &pkt)) {
			char hex[8*2 + 1];
			disconnect_client(client, true, "bad packet header: '%s'",
					  hdr2hex(data, hex, sizeof(hex)));
			return false;
		}
		slog_noise(client, "pkt='%c' len=%d", pkt_desc(&pkt), pkt.len);

		client->request_time = get_cached_time();
		switch (client->state) {
		case CL_LOGIN:
			res = handle_client_startup(client, &pkt);
			break;
		case CL_ACTIVE:
			if (client->wait_for_welcome)
				res = handle_client_startup(client, &pkt);
			else
				res = handle_client_work(client, &pkt);
			break;
		case CL_WAITING:
			fatal("why waiting client in client_proto()");
		default:
			fatal("bad client state: %d", client->state);
		}
		break;
	case SBUF_EV_FLUSH:
		/* client is not interested in it */
		break;
	case SBUF_EV_PKT_CALLBACK:
		/* unused ATM */
		break;
	}
	return res;
}
Beispiel #23
0
PROTO int group(const char *group, char nogroupecho)
{
        char b[MAX_SERVERRSP];
        ACTIVE *newgroup;
        SERVER *svr;
        CLEARBUF

        if ( nullstr(group) )
        {
                swriteclient(client,"500 You must select a group\r\n");
                return 1;
        }
  
        /* only change group if it has changed */
        if ( client->group == NULL || strcmp(client->group->newsgroup, group) != 0 ) 
        {
                /* check for read permission */
                if ( ! match_expression((unsigned char *)group
                                        , (unsigned char *)getwildmat(client->user->readpat)
                                        , 0) ) 
                {
                        if ( ! nogroupecho )
                                swriteclient(client, MSG_NOSUCHGROUP);
                        return 1;
                }

                /* find and load our new group */
                if ( (newgroup = getgroup(group)) == NULL ) 
                {
                        if ( ! nogroupecho )
                                swriteclient(client, MSG_NOSUCHGROUP);
                        return 1;
                }

                if ( (svr=getserver(newgroup->server)) == NULL )
                        return swriteclient(client, "500 Cant find server for group\r\n");

                /* disconnect first if we have to change server */
                if ( client->groupserver != NULL &&
                        client->connected == 1 &&
                        strcmp(svr->Groups, client->groupserver->Groups) != 0 )
                {
                        disconnect_server(client);
                }

                /* close group and reconnect */
                closegroup();
                client->group = newgroup;

                switch ( connect_groupserver(client, svr->Name) )
                {
                        case CONNECT_ERR:
                                return swriteclient(client, "500 Error selecting server\r\n");

                        case CONNECT_DOWN:
                                sleep(cfg.DownDelay);
                                return writeclient(client, MSG_SERVER_DOWN);

                        default:
                                break;
                }

                /* reset by connect_groupserver (via disconnect_server FIXME) */
                client->group = newgroup;

                client->groups++;
        }

        if ( ! writeserver(client, "GROUP %s\r\n", group) ) return -1;
        if ( ! readserver(client, b, MAX_SERVERRSP-1) ) return -1;

        syslog(LOG_NOTICE, "%s: group %s", client->hostname, group);

        if ( ! nogroupecho ) return swriteclient(client,b);
        return 0;
}
Beispiel #24
0
errr report_score(void)
{
#ifdef MACINTOSH
	OSStatus err;
#else
	errr err = 0;
#endif

#ifdef WINDOWS
	WSADATA wsaData;
	WORD wVersionRequested =(WORD) (( 1) |  ( 1 << 8));
#endif

	BUF *score;
	int sd;
	char seikakutmp[128];

	score = buf_new();

	sprintf(seikakutmp, "%s ", ap_ptr->title);

	buf_sprintf(score, "name: %s\n", player_name);
	buf_sprintf(score, "version: Hengband %d.%d.%d\n",
		    FAKE_VER_MAJOR-10, FAKE_VER_MINOR, FAKE_VER_PATCH);
	buf_sprintf(score, "score: %d\n", total_points());
	buf_sprintf(score, "level: %d\n", p_ptr->lev);
	buf_sprintf(score, "depth: %d\n", dun_level);
	buf_sprintf(score, "maxlv: %d\n", p_ptr->max_plv);
	buf_sprintf(score, "maxdp: %d\n", max_dlv[DUNGEON_ANGBAND]);
	buf_sprintf(score, "au: %d\n", p_ptr->au);
	buf_sprintf(score, "turns: %d\n", turn_real(turn));
	buf_sprintf(score, "sex: %d\n", p_ptr->psex);
	buf_sprintf(score, "race: %s\n", rp_ptr->title);
	buf_sprintf(score, "class: %s\n", cp_ptr->title);
	buf_sprintf(score, "seikaku: %s\n", seikakutmp);
	buf_sprintf(score, "realm1: %s\n", realm_names[p_ptr->realm1]);
	buf_sprintf(score, "realm2: %s\n", realm_names[p_ptr->realm2]);
	buf_sprintf(score, "killer: %s\n", p_ptr->died_from);
	buf_sprintf(score, "-----charcter dump-----\n");

	make_dump(score);

	if (screen_dump)
	{
		buf_sprintf(score, "-----screen shot-----\n");
		buf_append(score, screen_dump, strlen(screen_dump));
	}
	
#ifdef WINDOWS
	if (WSAStartup(wVersionRequested, &wsaData))
	{
		msg_print("Report: WSAStartup failed.");
		goto report_end;
	}
#endif

#ifdef MACINTOSH
#if TARGET_API_MAC_CARBON
	err = InitOpenTransportInContext(kInitOTForApplicationMask, NULL);
#else
	err = InitOpenTransport();
#endif
	if (err != noErr)
	{
		msg_print("Report: OpenTransport failed.");
		return 1;
	}
#endif

	Term_clear();

	while (1)
	{
		char buff[160];
		prt("connecting...", 0, 0);
		Term_fresh();
		
		/* プロキシを設定する */
		set_proxy(HTTP_PROXY, HTTP_PROXY_PORT);

		/* Connect to the score server */
		sd = connect_server(HTTP_TIMEOUT, SCORE_SERVER, SCORE_PORT);


		if (!(sd < 0)) break;
		sprintf(buff, "Failed to connect to the score server.(%s)", soc_err());
		prt(buff, 0, 0);
		(void)inkey();
		
		if (!get_check_strict("Try again? ", CHECK_NO_HISTORY))
		{
			err = 1;
			goto report_end;
		}
	}
	prt("Sending the score...", 0, 0);
	Term_fresh();
	http_post(sd, SCORE_PATH, score);

	disconnect_server(sd);
 report_end:
#ifdef WINDOWS
	WSACleanup();
#endif

#ifdef MACINTOSH
#if TARGET_API_MAC_CARBON
	CloseOpenTransportInContext(NULL);
#else
	CloseOpenTransport();
#endif
#endif

	return err;
}
Beispiel #25
0
bool handle_auth_response(PgSocket *client, PktHdr *pkt) {
	uint16_t columns;
	uint32_t length;
	const char *username, *password;
	PgUser user;
	PgSocket *server = client->link;

	switch(pkt->type) {
	case 'T':	/* RowDescription */
		if (!mbuf_get_uint16be(&pkt->data, &columns)) {
			disconnect_server(server, false, "bad packet");
			return false;
		}
		if (columns != 2u) {
			disconnect_server(server, false, "expected 1 column from login query, not %hu", columns);
			return false;
		}
		break;
	case 'D':	/* DataRow */
		memset(&user, 0, sizeof(user));
		if (!mbuf_get_uint16be(&pkt->data, &columns)) {
			disconnect_server(server, false, "bad packet");
			return false;
		}
		if (columns != 2u) {
			disconnect_server(server, false, "expected 1 column from login query, not %hu", columns);
			return false;
		}
		if (!mbuf_get_uint32be(&pkt->data, &length)) {
			disconnect_server(server, false, "bad packet");
			return false;
		}
		if (!mbuf_get_chars(&pkt->data, length, &username)) {
			disconnect_server(server, false, "bad packet");
			return false;
		}
		if (sizeof(user.name) - 1 < length)
			length = sizeof(user.name) - 1;
		memcpy(user.name, username, length);
		if (!mbuf_get_uint32be(&pkt->data, &length)) {
			disconnect_server(server, false, "bad packet");
			return false;
		}
		if (length == (uint32_t)-1) {
			// NULL - set an md5 password with an impossible value,
			// so that nothing will ever match
			password = "******";
			length = 3;
		} else {
			if (!mbuf_get_chars(&pkt->data, length, &password)) {
				disconnect_server(server, false, "bad packet");
				return false;
			}
		}
		if (sizeof(user.passwd)  - 1 < length)
			length = sizeof(user.passwd) - 1;
		memcpy(user.passwd, password, length);

		client->auth_user = add_db_user(client->db, user.name, user.passwd);
		if (!client->auth_user) {
			disconnect_server(server, false, "unable to allocate new user for auth");
			return false;
		}
		break;
	case 'C':	/* CommandComplete */
		break;
	case 'Z':	/* ReadyForQuery */
		sbuf_prepare_skip(&client->link->sbuf, pkt->len);
		if (!client->auth_user) {
			if (cf_log_connections)
				slog_info(client, "login failed: db=%s", client->db->name);
			disconnect_client(client, true, "No such user");
		} else {
			slog_noise(client, "auth query complete");
			client->link->resetting = true;
			sbuf_continue(&client->sbuf);
		}
		// either sbuf_continue or disconnect_client could disconnect the server
		// way down in their bowels of other callbacks. so check that, and
		// return appropriately (similar to reuse_on_release)
		if (server->state == SV_FREE || server->state == SV_JUSTFREE)
			return false;
		return true;
	default:
		disconnect_server(server, false, "unexpected response from login query");
		return false;
	}
	sbuf_prepare_skip(&server->sbuf, pkt->len);
	return true;
}
Beispiel #26
0
/*
 * Actively manage the polling interval.  Note that the poll_* fields are
 * always transfered to the alternate regression when the check code replaces
 * the current regression with a new one.
 *
 * This routine is called from the main loop for each base info structure.
 * The polling mode applies to all alternates so we do not have to iterate
 * through the alt's.
 */
void
client_manage_polling_mode(struct server_info *info, int *didreconnect)
{
    /*
     * Permanently failed servers are ignored.
     */
    if (info->server_state == -2)
	return;

    /*
     * Our polling interval has not yet passed.
     */
    if (info->poll_sleep)
	return;

    /*
     * Standard polling mode progression
     */
    switch(info->poll_mode) {
    case POLL_FIXED:
	/*
	 * Initial state after connect or when a reconnect is required.
	 */
	if (info->fd < 0) {
	    logdebuginfo(info, 2, "polling mode INIT, relookup & reconnect\n");
	    reconnect_server(info);
	    *didreconnect = 1;
	    if (info->fd < 0) {
		if (info->poll_failed >= POLL_RECOVERY_RESTART * 5)
		    info->poll_sleep = max_sleep_opt;
		else if (info->poll_failed >= POLL_RECOVERY_RESTART)
		    info->poll_sleep = nom_sleep_opt;
		else
		    info->poll_sleep = min_sleep_opt;
		break;
	    }

	    /*
	     * Transition the server to the DNS lookup successful state.
	     * Note that the server state does not transition out of
	     * lookup successful if we relookup after a packet failure
	     * so the message is printed only once, usually.
	     */
	    client_setserverstate(info, 0, "DNS lookup success");

	    /*
	     * If we've failed many times switch to the startup state but
	     * do not fall through into it.  break the switch and a single
	     * poll will be made after the nominal polling interval.
	     */
	    if (info->poll_failed >= POLL_RECOVERY_RESTART * 5) {
		logdebuginfo(info, 2, "polling mode INIT->STARTUP (very slow)\n");
		info->poll_mode = POLL_STARTUP;
		info->poll_sleep = max_sleep_opt;
		info->poll_count = 0;
		break;
	    } else if (info->poll_failed >= POLL_RECOVERY_RESTART) {
		logdebuginfo(info, 2, "polling mode INIT->STARTUP (slow)\n");
		info->poll_mode = POLL_STARTUP;
		info->poll_count = 0;
		break;
	    }
	}

	/*
	 * Fall through to the startup state.
	 */
	info->poll_mode = POLL_STARTUP;
	logdebuginfo(info, 2, "polling mode INIT->STARTUP (normal)\n");
	/* fall through */
    case POLL_STARTUP:
	/*
	 * Transition to a FAILED state if too many poll failures occured.
	 */
	if (info->poll_failed >= POLL_FAIL_RESET) {
	    logdebuginfo(info, 2, "polling mode STARTUP->FAILED\n");
	    info->poll_mode = POLL_FAILED;
	    info->poll_count = 0;
	    break;
	}

	/*
	 * Transition the server to operational.  Do a number of minimum
	 * interval polls to try to get a good offset calculation quickly.
	 */
	if (info->poll_count)
	    client_setserverstate(info, 1, "connected ok");
	if (info->poll_count < POLL_STARTUP_MAX) {
	    info->poll_sleep = min_sleep_opt;
	    break;
	}

	/*
	 * Once we've got our polls fall through to aquisition mode to
	 * do aquisition processing.
	 */
	info->poll_mode = POLL_ACQUIRE;
	info->poll_count = 0;
	logdebuginfo(info, 2, "polling mode STARTUP->ACQUIRE\n");
	/* fall through */
    case POLL_ACQUIRE:
	/*
	 * Transition to a FAILED state if too many poll failures occured.
	 */
	if (info->poll_failed >= POLL_FAIL_RESET) {
	    logdebuginfo(info, 2, "polling mode STARTUP->FAILED\n");
	    info->poll_mode = POLL_FAILED;
	    info->poll_count = 0;
	    break;
	}

	/*
	 * Acquisition mode using the nominal timeout.  We do not shift
	 * to maintainance mode unless the correlation is at least 0.90
	 */
	if (info->poll_count < POLL_ACQUIRE_MAX ||
	    info->lin_count < 8 ||
	    fabs(info->lin_cache_corr) < 0.85
	) {
	    if (info->poll_count >= POLL_ACQUIRE_MAX && 
		info->lin_count == LIN_RESTART - 2
	    ) {
		logdebuginfo(info, 2, 
		    "WARNING: Unable to shift this source to "
		    "maintenance mode.  Target correlation is aweful\n");
	    }
	    break;
	}
	info->poll_mode = POLL_MAINTAIN;
	info->poll_count = 0;
	logdebuginfo(info, 2, "polling mode ACQUIRE->MAINTAIN\n");
	/* fall through */
    case POLL_MAINTAIN:
	/*
	 * Transition to a FAILED state if too many poll failures occured.
	 */
	if (info->poll_failed >= POLL_FAIL_RESET) {
	    logdebuginfo(info, 2, "polling mode STARTUP->FAILED\n");
	    info->poll_mode = POLL_FAILED;
	    info->poll_count = 0;
	    break;
	}

	/*
	 * Maintaince mode, max polling interval.
	 *
	 * Transition back to acquisition mode if we are unable to maintain
	 * this mode due to the correlation going bad.
	 */
	if (info->lin_count >= LIN_RESTART / 2 && 
	    fabs(info->lin_cache_corr) < 0.70
	) {
	    logdebuginfo(info, 2, 
		"polling mode MAINTAIN->ACQUIRE.  Unable to maintain\n"
		"the maintenance mode because the correlation went"
		" bad!\n");
	    info->poll_mode = POLL_ACQUIRE;
	    info->poll_count = 0;
	    break;
	}
	info->poll_sleep = max_sleep_opt;
	break;
    case POLL_FAILED:
	/*
	 * We have a communications failure.  A late recovery is possible 
	 * if we enter this state with a good poll.
	 */
	if (info->poll_count != 0) {
	    logdebuginfo(info, 2, "polling mode FAILED->ACQUIRE\n");
	    if (info->poll_failed >= POLL_FAIL_RESET)
		info->poll_mode = POLL_STARTUP;
	    else
		info->poll_mode = POLL_ACQUIRE;
	    /* do not reset poll_count */
	    break;
	}

	/*
	 * If we have been failed too long, disconnect from the server
	 * and start us all over again.  Note that the failed count is not
	 * reset to 0.
	 */
	if (info->poll_failed >= POLL_RECOVERY_RESTART) {
	    logdebuginfo(info, 2, "polling mode FAILED->INIT\n");
	    client_setserverstate(info, 0, "FAILED");
	    disconnect_server(info);
	    info->poll_mode = POLL_FIXED;
	    break;
	}
	break;
    }

    /*
     * If the above state machine has not set a polling interval, set a
     * nominal polling interval.
     */
    if (info->poll_sleep == 0)
	info->poll_sleep = nom_sleep_opt;
}
Beispiel #27
0
int main(int argc, const char** argv) {
    struct timeb t;
    ftime(&t);
    srand(1000*t.time+t.millitm);

    unsigned tries = 1, playouts = 0;
    int average = 0;
    strategy strategy = s_up;
    const char* server = NULL;

    // parse command line options
    while (argc>1)
        if (!strcmp(argv[argc-1], "-v")) {
            argc--, verbose = 1;
        } else if (!strcmp(argv[argc-1], "--average")) {
            argc--, average = 1;
        } else if (!strcmp(argv[argc-1], "--highscore")) {
            argc--, tries = ~0;
        } else if (!strcmp(argv[argc-1], "--up")) {
            argc--, strategy = s_up;
        } else if (!strcmp(argv[argc-1], "--score")) {
            argc--, strategy = s_score;
        } else if (!strcmp(argv[argc-1], "--lr")) {
            argc--, strategy = s_lr;
        } else if (argc>2 && !strcmp(argv[argc-2], "--server")) {
            server = argv[argc-1];
            argc -= 2;
        } else {
            if (!strcmp(argv[argc-1], "-h"))
                argc--;
            else
                printf("%s: unknown option %s\n", basename((char*) argv[0]), argv[argc-1]);

            printf("usage: %s [--average] [--highscore] [--lr|--score|--up] [--server <ip-address>] [-v]\n", basename((char*) argv[0]));
            return argc-1;
        }

    board b; // board
    dir d = (dir) -1; // last move
    unsigned hs = 0; // highscore
    unsigned as = 0, an = 0; // average score
    while (tries--) {
        unsigned s = 0;
        int moved;
        playouts++;

        if (server) {
            // connect to server
            if (connect_server(server)) {
                printf("failure to communicate %s\n", server);
                return -1;
            }
        } else {
            // create a board
            memset(b, 0, sizeof(b));
            drop(b);
            drop(b);
        }

        // move until the board is full
        do {
            if (server &&
                ((d<last && !send_server(dirs[d])) ||
                 parse_notation(send_server("board"), b))) {
                printf("failure to communicate %s\n", server);
                return -1;
            }

            if (verbose)
                print_board(b);
        } while (
            // simple strategy: move up, left, right or down, whatever works
            (strategy==s_up && (
                ((s += move(b, d = up,    &moved)), (moved && drop(b))) ||
                ((s += move(b, d = left,  &moved)), (moved && drop(b))) ||
                ((s += move(b, d = right, &moved)), (moved && drop(b))) ||
                ((s += move(b, d = down,  &moved)), (moved && drop(b))))) ||
            // other strategies: evaluate moves
            (strategy!=s_up && (
                ((s += move(b, d = evaluate(b, strategy), &moved)), (moved && drop(b))))));

        // calculate the average score
        as += s;
        an++;

        // print the score/board
        if (s>hs) {
            printf("score %u (%u)\n", s, playouts);
            print_board(b);
            hs = s;
        } else if (average && tries%16384==0) {
            printf("avg.  %u\n", as/an);
        }

        // disconnect the server, if any
        if (server)
            send_server("gameover");
        disconnect_server();
    }

    return 0;
}