Пример #1
0
int mrp_get_domain(struct mrp_listener_ctx *ctx, struct mrp_domain_attr *class_a, struct mrp_domain_attr *class_b)
{
	char *msgbuf;
	int ret;

	/* we may not get a notification if we are joining late,
	 * so query for what is already there ...
	 */
	msgbuf = malloc(1500);
	if (NULL == msgbuf)
		return -1;
	memset(msgbuf, 0, 1500);
	sprintf(msgbuf, "S??");
	ret = send_msg(msgbuf, 1500, ctx);
	free(msgbuf);
	if (ret != 1500)
		return -1;
	while (!ctx->halt_tx && (ctx->domain_a_valid == 0) && (ctx->domain_b_valid == 0))
		usleep(20000);
	class_a->id = 0;
	class_a->priority = 0;
	class_a->vid = 0;
	class_b->id = 0;
	class_b->priority = 0;
	class_b->vid = 0;
	if (ctx->domain_a_valid) {
		class_a->id = ctx->domain_class_a_id;
		class_a->priority = ctx->domain_class_a_priority;
		class_a->vid = ctx->domain_class_a_vid;
	}
	if (ctx->domain_b_valid) {
		class_b->id = ctx->domain_class_b_id;
		class_b->priority = ctx->domain_class_b_priority;
		class_b->vid = ctx->domain_class_b_vid;
	}
	return 0;
}
Пример #2
0
/* Send a request to get the slave ID of the device (only available in serial
   communication). */
int modbus_report_slave_id(modbus_t *ctx, uint8_t *dest)
{
    int rc;
    int req_length;
    uint8_t req[_MIN_REQ_LENGTH];

    req_length = ctx->backend->build_request_basis(ctx, _FC_REPORT_SLAVE_ID,
                                                   0, 0, req);

    /* HACKISH, addr and count are not used */
    req_length -= 4;

    rc = send_msg(ctx, req, req_length);
    if (rc > 0) {
        int i;
        int offset;
        uint8_t rsp[MAX_MESSAGE_LENGTH];

        rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
        if (rc == -1)
            return -1;

        rc = check_confirmation(ctx, req, rsp, rc);
        if (rc == -1)
            return -1;

        offset = ctx->backend->header_length + 2;

        /* Byte count, slave id, run indicator status,
           additional data */
        for (i=0; i < rc; i++) {
            dest[i] = rsp[offset + i];
        }
    }

    return rc;
}
Пример #3
0
static void test_ctx_send_cb(struct pomp_ctx *ctx,
		struct pomp_conn *conn,
		struct pomp_buffer *buf,
		uint32_t status,
		void *cookie,
		void *userdata)
{
	int res = 0;
	struct test_data *data = userdata;
	struct test_peer *src = NULL;
	struct test_peer *dst = NULL;
	CU_ASSERT_PTR_NOT_NULL(ctx);
	CU_ASSERT_PTR_NOT_NULL(conn);
	CU_ASSERT_PTR_NOT_NULL(buf);
	data->sendcount++;
	CU_ASSERT_PTR_NULL(cookie);

	/* Internal function invalid arguments checks */
	res = pomp_ctx_notify_send(NULL, conn, buf, 0);
	CU_ASSERT_EQUAL(res, -EINVAL);
	res = pomp_ctx_notify_send(ctx, NULL, buf, 0);
	CU_ASSERT_EQUAL(res, -EINVAL);
	res = pomp_ctx_notify_send(ctx, conn, NULL, 0);
	CU_ASSERT_EQUAL(res, -EINVAL);

	/* Get source and destination */
	src = (ctx == data->srv.ctx) ? &data->srv : &data->cli;
	dst = (ctx == data->srv.ctx) ? &data->cli : &data->srv;

	if (src->recurs_send_enabled) {
		/* Disable recursive send. */
		src->recurs_send_enabled = 0;

		/* Exchange some message */
		send_msg(data, src, dst, "recursive_msg");
	}
}
Пример #4
0
int
main()
{
	uint16_t	num_trackers;
	in_addr_t	trackers[MAX_TRACKERS];
	uint16_t	maxpeers;
	uint16_t	num_pkg_servers;
	in_addr_t	pkg_servers[MAX_PKG_SERVERS];
	int		i;
	int		sockfd;
	char		trackers_url[256];
	char		pkg_servers_url[256];

	sprintf(trackers_url,"127.0.0.1");

	sprintf(pkg_servers_url,"127.0.0.1");

	fprintf(stderr, "main:trackers_url (%s)\n", trackers_url);
	fprintf(stderr, "main:pkg_servers_url (%s)\n", pkg_servers_url);
	
	if (init(&num_trackers, trackers_url, trackers, &maxpeers,
			pkg_servers_url, &num_pkg_servers, pkg_servers) != 0) {
		fprintf(stderr, "main:init failed\n");
		return(-1);
	}

	if ((sockfd = init_tracker_comm(0)) < 0) {
		fprintf(stderr, "main:init_tracker_comm failed\n");
		return(-1);
	}

	for (i = 0 ; i < num_trackers; ++i) {
		send_msg(sockfd, &trackers[i], DUMP_TABLES);
	}

	return(0);
}
Пример #5
0
static int on_host_init(VSCMsgHeader *mhHeader, VSCMsgInit *incoming)
{
    uint32_t *capabilities = (incoming->capabilities);
    int num_capabilities =
        1 + ((mhHeader->length - sizeof(VSCMsgInit)) / sizeof(uint32_t));
    int i;
    int rv;
    pthread_t thread_id;

    incoming->version = ntohl(incoming->version);
    if (incoming->version != VSCARD_VERSION) {
        if (verbose > 0) {
            printf("warning: host has version %d, we have %d\n",
                verbose, VSCARD_VERSION);
        }
    }
    if (incoming->magic != VSCARD_MAGIC) {
        printf("unexpected magic: got %d, expected %d\n",
            incoming->magic, VSCARD_MAGIC);
        return -1;
    }
    for (i = 0 ; i < num_capabilities; ++i) {
        capabilities[i] = ntohl(capabilities[i]);
    }
    /* Future: check capabilities */
    /* remove whatever reader might be left in qemu,
     * in case of an unclean previous exit. */
    send_msg(VSC_ReaderRemove, VSCARD_MINIMAL_READER_ID, NULL, 0);
    /* launch the event_thread. This will trigger reader adds for all the
     * existing readers */
    rv = pthread_create(&thread_id, NULL, event_thread, NULL);
    if (rv < 0) {
        perror("pthread_create");
        return rv;
    }
    return 0;
}
Пример #6
0
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  long pid = long (ACE_OS::getpid ());

  ACE_Typed_SV_Message_Queue<Message_Data> msgque (key_t (SRV_KEY));

  Message_Data msg_data (pid,
                         ACE_OS::cuserid (static_cast<char *> (0)),
                         "did you get this?");

  ACE_Typed_SV_Message<Message_Data> send_msg (msg_data,
					       SRV_ID,
					       msg_data.length ()),
					       recv_msg (pid);

  if (msgque.send (send_msg) < 0)
    ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
                       ACE_TEXT ("msgque.send")), 1);

  if (msgque.recv (recv_msg) < 0)
    ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
                       ACE_TEXT ("msgque.recv")), 1);

  Message_Data &recv_msg_data = recv_msg.data ();

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("a message of length %d")
              ACE_TEXT (" received from server %d")
              ACE_TEXT (" (user %C): %C\n"),
              recv_msg_data.length (),
              recv_msg_data.pid (),
              recv_msg_data.user (),
              recv_msg_data.text ()));

  return 0;
}
Пример #7
0
int init_draw_graph_u(sym_environment *env)
{
   if (env->par.do_draw_graph){ /*start up the graphics window*/
      int s_bufid;
      if (env->par.dg_machine_set){
	 spawn(env->par.dg_exe, (char **)NULL, env->par.dg_debug | TaskHost,
	       env->par.dg_machine, 1, &env->dg_tid);
      }else{
	 spawn(env->par.dg_exe, (char **)NULL, env->par.dg_debug, (char *)NULL, 1,
	       &env->dg_tid);
      }
      s_bufid = init_send(DataInPlace);
      send_char_array((char *)&env->par.dg_par, sizeof(dg_params));
      send_msg(env->dg_tid, DG_DATA);
      freebuf(s_bufid);

#ifdef USE_SYM_APPLICATION
      if (env->dg_tid)
	 CALL_USER_FUNCTION( user_init_draw_graph(env->user, env->dg_tid) );
#endif
   }

   return(FUNCTION_TERMINATED_NORMALLY);
}
Пример #8
0
bool gdbr_kill_pid(libgdbr_t *g, int pid) {
	char *cmd;
	int ret;
	size_t buffer_size;

	if (!g || !g->sock || !g->stub_features.multiprocess) {
		return false;
	}
	reg_cache.valid = false;
	g->stop_reason.is_valid = false;

	buffer_size = strlen (CMD_KILL_MP) + (sizeof (pid) * 2) + 1;
	cmd = calloc (buffer_size, sizeof (char));
	if (!cmd) {
		return false;
	}

	if ((snprintf (cmd, buffer_size, "%s%x", CMD_KILL_MP, g->pid)) < 0) {
		free(cmd);
		return false;
	}
	ret = send_msg (g, cmd);
	free(cmd);
	if (ret < 0) {
		return false;
	}

	read_packet (g, false);
	if ((ret = send_ack (g)) < 0) {
		return false;
	}
	if (strncmp (g->data, "OK", 2)) {
		return false;
	}
	return true;
}
Пример #9
0
/* Called from VM Monitor */
int NodeManager_notify_vm_started(
    char        *node_addr,
    char        *vmmon_addr,
    char        *theater )
{
    int retval = 0;
    NodeMessage *msg;

    Dbg_printf( NODE, INFO, "node_addr=%s, vmmon_addr=%s, theater=%s\n",
                node_addr, vmmon_addr, theater );

    msg = node_alloc_msg( NodeMessageID_NOTIFY_VM_STARTED );
    node_set_notify_vm_started_msg( msg, vmmon_addr, theater );

    if (send_msg( node_addr, NULL, msg ) < 0) {
        Dbg_printf( NODE, ERROR, "node_send_msg, node_addr=%s, msg=%s failed\n", 
                    node_addr, node_msgid2str( msg->msgid ) );
        retval = -1;
    }

    node_dealloc_msg( msg );

    return retval;
}
int UnixSocketAdapter::send(const AmSipRequest &req, string &src, string &dst)
{
  if (! isComplete(req)) {
    ERROR("can not send request: not complete.\n");
    return -1;
  }

  string rplAddr;
  string msg;
  int timeout;
  if (req.method == "CANCEL") {
    rplAddr = "/tmp/" + AmSession::getNewId();
    msg = serialize_cancel(req, rplAddr);
    timeout = 50000; /*TODO: WTF's with this value?!*/
  } else {
    rplAddr = src;//AmConfig::ReplySocketName;
    msg = serialize(req, rplAddr);
    /* timeout: don't wait for reply [comes through other, 
     * dedicated socket] */
    timeout = 0;
  }

  return send_msg(msg, rplAddr, dst, timeout);
}
Пример #11
0
int NodeManager_destroy_vm_req(
    char        *node_addr,
    char        *return_cos_addr,
    char        *vm_name )
{
    int retval = 0;
    NodeMessage *msg;

    Dbg_printf( NODE, INFO, "node_addr=%s, return_cos_addr=%s, vm_name=%s\n", 
                node_addr, return_cos_addr, vm_name );

    msg = node_alloc_msg( NodeMessageID_DESTROY_VM_REQ );
    node_set_destroy_vm_req_msg( msg, vm_name );

    if (send_msg( node_addr, return_cos_addr, msg ) < 0) {
        Dbg_printf( NODE, ERROR, "node_send_msg, node_addr=%s, return_cos_addr=%s, msg=%s failed\n", 
                    node_addr, return_cos_addr, node_msgid2str( msg->msgid ) );
        retval = -1;
    }

    node_dealloc_msg( msg );

    return retval;
}
Пример #12
0
/*
 *    Test2b
 *
 *    Sending thread of test2b
 */
static void Test2b( void ) {

	pthread_t t1;
	char * msg = "Test2b Burst Send Non-Blocking / Receive Blocking";
	int recv_count = 0;
	int send_count = 0;

	TEST_INTRO( "Send Blocking Test" );

	if (pthread_create ( &t1, NULL, &test2b_thread, NULL ) != 0) {
		printf("Failed to create test2b_thread t1!\n");
		FAILURE_EXIT();
	}

	usleep(100000);

	burst_send( msg, MAX_QUEUE_SIZE, MBX_NON_BLOCKING, NOISY, ON_FAILURE_EXIT );
	send_count += MAX_QUEUE_SIZE;

	usleep(10000);

	send_msg( msg, MBX_BLOCK, NOISY, ON_FAILURE_EXIT );
	send_count += 1;

	pthread_join( t1, (void*)&recv_count );

	printf("Thread 0 sent %d messages\n",send_count);
	printf("Thread 1 received %d messages\n",recv_count);

	if (recv_count != send_count) {
		FAILURE_EXIT();
	}

	TEST_CLOSING();

}
Пример #13
0
bool campareGameMoney(Hero *hero,long _gameMoney)		//判断游戏币是否够用
{
	Money *money=hero->getMoney();
	if (money==NULL)								//money类为空 返回false;
	{
		return false;
	}
	if (_gameMoney<0)								//使用的游戏币为负数,返回false
	{
		cout<<"jolly:you can increase a negative number money_operator 228"<<endl;
		return false;
	}
	
	if ((money->money_getGameMoney()-_gameMoney)<0)
	{
		msg_error(g_out_buf,1);
		send_msg(hero->getFd(),g_out_buf);
		return false;
	}
	else
	{
		return true;
	}
}
Пример #14
0
bool increaseGameMoney(Hero *hero,long _gameMoney)	//增加游戏币
{	
	Money *money=hero->getMoney();
	if (money==NULL)								//money类为空 返回false;
	{
		return false;
	}
	if (_gameMoney<0)								//增加的游戏币为负数,返回false
	{
		cout<<"jolly:you can increase a negative number money_operator 210"<<endl;
		return false;
	}
	
	money->money_increaseGameMoney(_gameMoney);
	money->money_inform(g_out_buf,sizeof(g_out_buf));
	send_msg(hero->getFd(),g_out_buf);				//发送增加游戏币之后的金币状态	
	
	// 增加获得货币写日志功能,jolly 2012 12 17 start
	char account_msg[1024]={'\0'};
	sprintf(account_msg,"%d,%d,%s,%d,%s,%s,%ld,%ld",3,0,server_name,(int)myTime.tv_sec,hero->getIdentity(),hero->getNickName(),money->money_getGameMoney(),_gameMoney);
	write_log(account_msg);	
	// 增加获得货币写日志功能,jolly 2012 12 17 end
	return true;
}
Пример #15
0
bool campareGold(Hero *hero,long _gold)		//判定元宝是否够用
{
	Money *money=hero->getMoney();
	if (money==NULL)							//money类为空 返回false;
	{
		return false;
	}
	if (_gold<0)								//比较的元宝为负数,返回false
	{
		cout<<"jolly:you can increase a negative number money_operator 177"<<endl;
		return false;
	}	

	if (_gold>money->money_getGold())				//比较的元宝大于了自身的元宝,则提示充值
	{
		snprintf(g_out_buf,sizeof(g_out_buf),"%d,%d,%ld",9,MONEY_NOT_ENOUGH,_gold-money->money_getGold());
		send_msg(hero->getFd(),g_out_buf);
		return false;
	}
	else
	{
		return true;
	}	
}
Пример #16
0
int client_init(void)
{
/*
    if(argc<2)
    {
    
         printf("\n");
         printf("sorry,your type is wrong\n");    
         printf("usage: %s x.x.x.x(server ip)\n",argv[0]);
         exit(EXIT_FAILURE);
    }
*/
    if((client_sock = socket(AF_INET, SOCK_DGRAM, 0))< 0)
    {
       fprintf(stderr,"%s\n",strerror(errno)) ;
       exit(EXIT_FAILURE);
    
    }
    else
    {
         printf("create socket ok !\n");
    }



    bzero(&server, sizeof(server));

    server.sin_family = AF_INET;
    server.sin_port = htons(SERVER_PORD);
    server.sin_addr.s_addr = inet_addr("10.1.14.39");

    server_len = sizeof(server);
    send_msg(0,0);
    return 0;

}
Пример #17
0
void ctrl_g_defence_original()
{
	char buf[200];
	if (RINFO.turn==mypos&& (PINFO(mypos).flag & PEOPLE_ALIVE))
	{
		if (PINFO(mypos).flag & PEOPLE_BAD)
		{
			if (RINFO.voted[mypos]!=-2)
			{
				sprintf (buf, "\33[31m你想崩溃了\33[m");
				RINFO.voted[mypos]=-2;
			}
			else
			{
				sprintf(buf,"\33[31m你不想崩溃了\33[m");
				RINFO.voted[mypos]=-1;
			}
		}
		else
			sprintf(buf,"不能崩溃");
		send_msg(mypos,buf);
		kill_msg(mypos);
	}
}
Пример #18
0
void mu_signal_process(char *command, int signal)
{
	unsigned short	slen;
	int		len, toprocess_id, save_errno;
	char		buff[256];
	error_def(ERR_MUPCLIERR);
	error_def(ERR_MUPIPSIG);

	slen = sizeof(buff);
	if (!cli_get_str("ID", buff, &slen))
		mupip_exit(ERR_MUPCLIERR);
	len = slen;
	toprocess_id = asc2i((uchar_ptr_t)buff, len);
	if (toprocess_id < 0)
	{
		util_out_print("Error converting !AD to a number", FLUSH, len, buff);
		mupip_exit(ERR_MUPCLIERR);
	} else
	{
		if (-1 == kill(toprocess_id, signal))
		{
			save_errno = errno;
			util_out_print("Error issuing !AD to process !UL: !AZ", FLUSH,
				       LEN_AND_STR(command), toprocess_id, STRERROR(errno));
		} else
		{
			util_out_print("!AD issued to process !UL", FLUSH, LEN_AND_STR(command), toprocess_id);
			if (!MEMCMP_LIT(command, STOP_STR))
			{
				send_msg(VARLSTCNT(9) ERR_MUPIPSIG, 7, LEN_AND_STR(command), signal, process_id, process_id,
					 toprocess_id, toprocess_id);
			}
		}
	}
	return;
}
Пример #19
0
void		soon(int cs)
{
	char				buf[1024];
	int					r;
	char				*home;

	home = get_pwd();
	while ((r = read(cs, buf, 1023)) > 0)
	{
		buf[r - 1] = '\0';
		ft_printf("received %d bytes: [%s]\n", r, buf);
		if (!ft_strcmp(buf, "ls"))
			ft_ls(cs);
		else if (!ft_strcmp(buf, "pwd"))
			send_msg(cs, get_pwd(), 0);
		else if (!ft_strncmp(buf, "cd ", 3) || !ft_strcmp(buf, "cd"))
			ft_cd(cs, buf, home);
		else if (!ft_strcmp(buf, "quit"))
			break ;
		else
			send_error(cs, "invalid_cmd");
		ft_bzero(buf, 1024);
	}
}
Пример #20
0
int NodeManager_notify_low_cpu_usage(
    char        *node_addr,
    char        *vmmon_addr,
    double      cpu_usage_history[CPU_USAGE_HISTORY_LEN] )
{
    int retval = 0;
    NodeMessage *msg;

    Dbg_printf( NODE, INFO, "vmmon_addr=%s, cpu_usage_history[0]=%lf\n",
                vmmon_addr, cpu_usage_history[0] );

    msg = node_alloc_msg( NodeMessageID_NOTIFY_LOW_CPU_USAGE );
    node_set_notify_cpu_usage_msg( msg, vmmon_addr, cpu_usage_history );

    if (send_msg( node_addr, vmmon_addr, msg ) < 0) {
        Dbg_printf( NODE, ERROR, "send_msg, node_addr=%s, msg=%s failed\n", 
                    node_addr, node_msgid2str( msg->msgid ) );
        retval = -1;
    }

    node_dealloc_msg( msg );

    return retval;
}
Пример #21
0
void CacheQuorum::handle_push_local_ack() {
#ifdef DEBUG
   printf("CACHE_NODE handle_push_local_ack\n");
   print_msg_info(&(node->msg_info));
#endif
   int result;

   result = recv_msg(buf, msg_info->count, MPI_UINT8_T, msg_info->src,
         PUSH_LOCAL_ACK, msg_info->comm, status);
   MPI_ASSERT(result == MPI_SUCCESS);

   PutAckTemplate *put_ack = (PutAckTemplate *)buf;

   put_ack->result = SUCCESS;
   uint32_t job_num = put_ack->job_num;
   uint32_t job_node = put_ack->job_node;

   MPI_Comm job_comm = node->job_to_comms[job_num].job;

   // Reply back to original job node with outcome.
   result = send_msg(buf, sizeof(PushAckTemplate), MPI_UINT8_T, job_node,
         PUSH_LOCAL_ACK, job_comm, &request);
   MPI_ASSERT(result == MPI_SUCCESS);
}
void proc_comm_connector(struct task_struct *task)
{
	struct cn_msg *msg;
	struct proc_event *ev;
	__u8 buffer[CN_PROC_MSG_SIZE] __aligned(8);

	if (atomic_read(&proc_event_num_listeners) < 1)
		return;

	msg = buffer_to_cn_msg(buffer);
	ev = (struct proc_event *)msg->data;
	memset(&ev->event_data, 0, sizeof(ev->event_data));
	ev->timestamp_ns = ktime_get_ns();
	ev->what = PROC_EVENT_COMM;
	ev->event_data.comm.process_pid  = task->pid;
	ev->event_data.comm.process_tgid = task->tgid;
	get_task_comm(ev->event_data.comm.comm, task);

	memcpy(&msg->id, &cn_proc_event_id, sizeof(msg->id));
	msg->ack = 0; /* not used */
	msg->len = sizeof(*ev);
	msg->flags = 0; /* not used */
	send_msg(msg);
}
Пример #23
0
int
run_big_request_test (Test::Hello_ptr hello)
{
  const int length = 40000;
  Test::Octet_Seq send_msg(length);
  send_msg.length (length);

  for (int i= 0; i<length; ++i)
    {
      send_msg[i]= static_cast<CORBA::Octet> (i & 0xff);
    }

  ACE_DEBUG((LM_DEBUG,
              ACE_TEXT("run_big_request_test, send = %d bytes\n"), length));

  if (test == 2)
    {
      ACE_DEBUG((LM_DEBUG,
                 ACE_TEXT("*** NOTE TestCompressor is EXPECTED to throw IDL:omg.org/Compression/CompressionException ***\n")));
    }

  hello->big_request(send_msg);
  return 0;
}
Пример #24
0
/*
 * A MSG_STOP_LOCKSPACE message has been received.
 */
static void
proto_stop_lockspace(struct node *node, const char *name)
{
	struct lockspace *ls;

	ls = find_lockspace(name);
	if (!ls)
		ls = new_lockspace(name);
	/*
	 * The lockspace will not be restarted until all bits in ls->stopping
	 * (one for each peer node) have been cleared again.
	 */
	ls->stopping |= node_mask(node);
	/*
	 * The ls->stopped bit for the local node indicates whether the
	 * lockspace is active or stopped locally; new lockspaces start out
	 * stopped.  The ls->stopping bit for the local node indicates whether
	 * we have already requested the kernel to stop the lockspace locally.
	 */
	if (ls->stopped & node_mask(local_node))
		send_msg(node, MSG_LOCKSPACE_STOPPED, ls->name);
	else if (!(ls->stopping & node_mask(local_node)))
		stop_lockspace(ls);
}
Пример #25
0
static int
pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
    int padding)
{
	Key key;
	u_char *blob, *signature = NULL;
	u_int blen, slen = 0;
	int ret = -1;
	Buffer msg;

	if (padding != RSA_PKCS1_PADDING)
		return (-1);
	key.type = KEY_RSA;
	key.rsa = rsa;
	if (key_to_blob(&key, &blob, &blen) == 0)
		return -1;
	buffer_init(&msg);
	buffer_put_char(&msg, SSH2_AGENTC_SIGN_REQUEST);
	buffer_put_string(&msg, blob, blen);
	buffer_put_string(&msg, from, flen);
	buffer_put_int(&msg, 0);
	free(blob);
	send_msg(&msg);
	buffer_clear(&msg);

	if (recv_msg(&msg) == SSH2_AGENT_SIGN_RESPONSE) {
		signature = buffer_get_string(&msg, &slen);
		if (slen <= (u_int)RSA_size(rsa)) {
			memcpy(to, signature, slen);
			ret = slen;
		}
		free(signature);
	}
	buffer_free(&msg);
	return (ret);
}
Пример #26
0
int
pkcs11_add_provider(char *name, char *pin, Key ***keysp)
{
	Key *k;
	int i, nkeys;
	u_char *blob;
	u_int blen;
	Buffer msg;

	if (fd < 0 && pkcs11_start_helper() < 0)
		return (-1);

	buffer_init(&msg);
	buffer_put_char(&msg, SSH_AGENTC_ADD_SMARTCARD_KEY);
	buffer_put_cstring(&msg, name);
	buffer_put_cstring(&msg, pin);
	send_msg(&msg);
	buffer_clear(&msg);

	if (recv_msg(&msg) == SSH2_AGENT_IDENTITIES_ANSWER) {
		nkeys = buffer_get_int(&msg);
		*keysp = xcalloc(nkeys, sizeof(Key *));
		for (i = 0; i < nkeys; i++) {
			blob = buffer_get_string(&msg, &blen);
			free(buffer_get_string(&msg, NULL));
			k = key_from_blob(blob, blen);
			wrap_key(k->rsa);
			(*keysp)[i] = k;
			free(blob);
		}
	} else {
		nkeys = -1;
	}
	buffer_free(&msg);
	return (nkeys);
}
Пример #27
0
static int _server_handle_vCont(libgdbr_t *g, gdbr_server_cmd_cb cmd_cb, void *core_ptr) {
	char *action = NULL;
	if (send_ack (g) < 0) {
		return -1;
	}
	g->data[g->data_len] = '\0';
	if (g->data[5] == '?') {
		// Query about everything we support
		return send_msg (g, "vCont;c;s");
	}
	if (!(action = strtok (g->data, ";"))) {
		return send_msg (g, "E01");
	}
	while ((action = strtok (NULL, ";"))) {
		eprintf ("action: %s\n", action);
		switch (action[0]) {
		case 's':
			// TODO handle thread selections
			if (cmd_cb (g, core_ptr, "ds", NULL, 0) < 0) {
				send_msg (g, "E01");
				return -1;
			}
			return send_msg (g, "OK");
		case 'c':
			// TODO handle thread selections
			if (cmd_cb (g, core_ptr, "dc", NULL, 0) < 0) {
				send_msg (g, "E01");
				return -1;
			}
			return send_msg (g, "OK");
		default:
			// TODO support others
			return send_msg (g, "E01");
		}
	}
	return -1;
}
Пример #28
0
int main(int argc, char **argv)
{
	struct mrpc_conn_set *sset;
	struct mrpc_conn_set *cset;
	struct mrpc_connection *conn;
	struct sockaddr_in addr;
	socklen_t addrlen;
	char *set_port;
	char skt_port[8];
	int cfd;
	int lfd;
	int sfd;
	unsigned seq;
	mrpc_status_t expected;
	int expected_ioerrs=0;

	if (sem_init(&cb_complete, 0, 0))
		die("Couldn't initialize semaphore");
	sset=spawn_server(&set_port, proto_server, sync_server_accept, NULL,
				1);
	mrpc_set_disconnect_func(sset, disconnect_normal);
	mrpc_set_ioerr_func(sset, handle_ioerr);
	if (mrpc_conn_set_create(&cset, proto_client, NULL))
		die("Couldn't create client conn set");
	mrpc_set_disconnect_func(cset, disconnect_normal);
	mrpc_set_ioerr_func(cset, handle_ioerr);
	start_monitored_dispatcher(cset);

	cfd=socket(PF_INET, SOCK_STREAM, 0);
	if (cfd == -1)
		die("Couldn't create socket");
	addr.sin_family=AF_INET;
	addr.sin_port=htons(atoi(set_port));
	addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
	if (connect(cfd, (struct sockaddr *)&addr, sizeof(addr)))
		die("Couldn't connect socket");
	free(set_port);
	lfd=socket(PF_INET, SOCK_STREAM, 0);
	if (lfd == -1)
		die("Couldn't create socket");
	addr.sin_port=0;
	if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)))
		die("Couldn't bind socket");
	if (listen(lfd, 16))
		die("Couldn't listen on socket");
	addrlen=sizeof(addr);
	if (getsockname(lfd, (struct sockaddr *)&addr, &addrlen))
		die("Couldn't get socket name");
	snprintf(skt_port, sizeof(skt_port), "%u", ntohs(addr.sin_port));
	if (mrpc_conn_create(&conn, cset, NULL))
		die("Couldn't create conn handle");
	if (mrpc_connect(conn, AF_INET, NULL, skt_port))
		die("Couldn't connect to listening socket");
	sfd=accept(lfd, NULL, NULL);
	if (sfd == -1)
		die("Couldn't accept incoming connection");
	close(lfd);

	/* Successful ping on raw client */
	send_msg(cfd, 0, MINIRPC_PENDING, nr_proto_ping, 0);
	recv_msg(cfd, &seq, MINIRPC_OK, nr_proto_ping, 0);
	expect(seq, 0);

	/* Successful ping on raw server */
	expected=0;
	expect(proto_ping_async(conn, cb_ping, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_ping, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_ping, 0);
	sem_wait(&cb_complete);

	/* Request payload too short */
	send_msg(cfd, 1, MINIRPC_PENDING, nr_proto_send_buffer, 500);
	recv_msg(cfd, &seq, MINIRPC_ENCODING_ERR, nr_proto_send_buffer, 0);
	expect(seq, 1);
	expected_ioerrs++;

	/* Request payload too long */
	send_msg(cfd, 2, MINIRPC_PENDING, nr_proto_send_buffer, 2000);
	recv_msg(cfd, &seq, MINIRPC_ENCODING_ERR, nr_proto_send_buffer, 0);
	expect(seq, 2);
	expected_ioerrs++;

	/* Zero-length request payload when expecting non-zero */
	send_msg(cfd, 3, MINIRPC_PENDING, nr_proto_send_buffer, 0);
	recv_msg(cfd, &seq, MINIRPC_ENCODING_ERR, nr_proto_send_buffer, 0);
	expect(seq, 3);
	expected_ioerrs++;

	/* Bogus procedure */
	send_msg(cfd, 4, MINIRPC_PENDING, 12345, 500);
	recv_msg(cfd, &seq, MINIRPC_PROCEDURE_UNAVAIL, 12345, 0);
	expect(seq, 4);

	/* Procedure call against NULL operations pointer */
	send_msg(sfd, 5, MINIRPC_PENDING, nr_proto_client_check_int, 4);
	recv_msg(sfd, &seq, MINIRPC_PROCEDURE_UNAVAIL,
				nr_proto_client_check_int, 0);
	expect(seq, 5);

	/* Call against procedure zero */
	send_msg(cfd, 6, MINIRPC_PENDING, 0, 0);
	recv_msg(cfd, &seq, MINIRPC_PROCEDURE_UNAVAIL, 0, 0);
	expect(seq, 6);

	/* Reply payload too short */
	expected=MINIRPC_ENCODING_ERR;
	expect(proto_recv_buffer_async(conn, cb_recv, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_recv_buffer, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_recv_buffer, 500);
	sem_wait(&cb_complete);
	expected_ioerrs++;

	/* Reply payload too long */
	expected=MINIRPC_ENCODING_ERR;
	expect(proto_recv_buffer_async(conn, cb_recv, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_recv_buffer, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_recv_buffer, 2000);
	sem_wait(&cb_complete);
	expected_ioerrs++;

	/* Zero-length reply payload when expecting nonzero */
	expected=MINIRPC_ENCODING_ERR;
	expect(proto_recv_buffer_async(conn, cb_recv, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_recv_buffer, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_recv_buffer, 0);
	sem_wait(&cb_complete);
	expected_ioerrs++;

	/* Successful recv_buffer call (sanity check) */
	expected=MINIRPC_OK;
	expect(proto_recv_buffer_async(conn, cb_recv, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_recv_buffer, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_recv_buffer, 1024);
	sem_wait(&cb_complete);

	/* Reply with both error code and payload */
	expected=MINIRPC_ENCODING_ERR;
	expect(proto_recv_buffer_async(conn, cb_recv, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_recv_buffer, 0);
	send_msg(sfd, seq, 25, nr_proto_recv_buffer, 1024);
	sem_wait(&cb_complete);
	expected_ioerrs++;

	/* Reply with command not matching request command */
	expected=MINIRPC_ENCODING_ERR;
	expect(proto_ping_async(conn, cb_ping, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_ping, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_send_buffer, 0);
	sem_wait(&cb_complete);
	expected_ioerrs++;

	/* Unmatched reply */
	send_msg(cfd, 7, MINIRPC_OK, nr_proto_ping, 0);
	expected_ioerrs++;

	/* Unidirectional message with error code */
	send_msg(cfd, 8, MINIRPC_OK, nr_proto_msg_buffer, 1024);
	expected_ioerrs++;

	/* Empty event queues before closing, to make sure that no ioerr
	   events are squashed */
	send_msg(cfd, 0, MINIRPC_PENDING, nr_proto_ping, 0);
	recv_msg(cfd, &seq, MINIRPC_OK, nr_proto_ping, 0);
	expect(seq, 0);
	expected=0;
	expect(proto_ping_async(conn, cb_ping, &expected), 0);
	recv_msg(sfd, &seq, MINIRPC_PENDING, nr_proto_ping, 0);
	send_msg(sfd, seq, MINIRPC_OK, nr_proto_ping, 0);
	sem_wait(&cb_complete);

	close(cfd);
	close(sfd);
	mrpc_listen_close(sset);
	mrpc_conn_set_unref(sset);
	mrpc_conn_set_unref(cset);
	expect_disconnects(0, 2, 0);
	expect_ioerrs(expected_ioerrs);
	sem_destroy(&cb_complete);
	return 0;
}
Пример #29
0
/* this is the underlying (unformatted) rsync debugging function. Call
 * it with FINFO, FERROR_*, FWARNING, FLOG, or FCLIENT.  Note: recursion
 * can happen with certain fatal conditions. */
void rwrite(enum logcode code, const char *buf, int len, int is_utf8)
{
	int trailing_CR_or_NL;
	FILE *f = msgs2stderr ? stderr : stdout;
#ifdef ICONV_OPTION
	iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck;
#else
#ifdef ICONV_CONST
	iconv_t ic = ic_chck;
#endif
#endif

	if (len < 0)
		exit_cleanup(RERR_MESSAGEIO);

	if (msgs2stderr) {
		if (!am_daemon) {
			if (code == FLOG)
				return;
			goto output_msg;
		}
		if (code == FCLIENT)
			return;
		code = FLOG;
	} else if (send_msgs_to_gen) {
		assert(!is_utf8);
		/* Pass the message to our sibling in native charset. */
		send_msg((enum msgcode)code, buf, len, 0);
		return;
	}

	if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */
		code = FERROR;
	else if (code == FERROR_UTF8) {
		is_utf8 = 1;
		code = FERROR;
	}

	if (code == FCLIENT)
		code = FINFO;
	else if (am_daemon || logfile_name) {
		static int in_block;
		char msg[2048];
		int priority = code == FINFO || code == FLOG ? LOG_INFO :  LOG_WARNING;

		if (in_block)
			return;
		in_block = 1;
		if (!log_initialised)
			log_init(0);
		strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
		logit(priority, msg);
		in_block = 0;

		if (code == FLOG || (am_daemon && !am_server))
			return;
	} else if (code == FLOG)
		return;

	if (quiet && code == FINFO)
		return;

	if (am_server) {
		enum msgcode msg = (enum msgcode)code;
		if (protocol_version < 30) {
			if (msg == MSG_ERROR)
				msg = MSG_ERROR_XFER;
			else if (msg == MSG_WARNING)
				msg = MSG_INFO;
		}
		/* Pass the message to the non-server side. */
		if (send_msg(msg, buf, len, !is_utf8))
			return;
		if (am_daemon) {
			/* TODO: can we send the error to the user somehow? */
			return;
		}
		f = stderr;
	}

output_msg:
	switch (code) {
	case FERROR_XFER:
		got_xfer_error = 1;
		/* FALL THROUGH */
	case FERROR:
	case FERROR_UTF8:
	case FERROR_SOCKET:
	case FWARNING:
		f = stderr;
		break;
	case FLOG:
	case FINFO:
	case FCLIENT:
		break;
	default:
		fprintf(stderr, "Unknown logcode in rwrite(): %d [%s]\n", (int)code, who_am_i());
		exit_cleanup(RERR_MESSAGEIO);
	}

	if (output_needs_newline) {
		fputc('\n', f);
		output_needs_newline = 0;
	}

	trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
			  ? buf[--len] : 0;

	if (len && buf[0] == '\r') {
		fputc('\r', f);
		buf++;
		len--;
	}

#ifdef ICONV_CONST
	if (ic != (iconv_t)-1) {
		xbuf outbuf, inbuf;
		char convbuf[1024];
		int ierrno;

		INIT_CONST_XBUF(outbuf, convbuf);
		INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);

		while (inbuf.len) {
			iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT);
			ierrno = errno;
			if (outbuf.len) {
				filtered_fwrite(f, convbuf, outbuf.len, 0);
				outbuf.len = 0;
			}
			if (!ierrno || ierrno == E2BIG)
				continue;
			fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
			inbuf.len--;
		}
	} else
#endif
		filtered_fwrite(f, buf, len, !allow_8bit_chars);

	if (trailing_CR_or_NL) {
		fputc(trailing_CR_or_NL, f);
		fflush(f);
	}
}
Пример #30
0
/* Main loop to listen for packets on a wireless card in monitor mode. */
enum wps_result do_wps_exchange() {
    struct pcap_pkthdr header;
    const u_char *packet = NULL;
    enum wps_type packet_type = UNKNOWN, last_msg = UNKNOWN;
    enum wps_result ret_val = KEY_ACCEPTED;
    int premature_timeout = 0, terminated = 0, got_nack = 0;
    int id_response_sent = 0, tx_type = 0;
    int m2_sent = 0, m4_sent = 0, m6_sent = 0;

    /* Initialize settings for this WPS exchange */
    set_last_wps_state(0);
    set_eap_id(0);

    /* Initiate an EAP session */
    send_eapol_start();

    /* 
     * Loop until:
     *
     * 	o The pin has been cracked
     * 	o An EAP_FAIL packet is received
     * 	o We receive a NACK message
     *	o We hit an unrecoverable receive timeout
     */
    while ((get_key_status() != KEY_DONE) &&
            !terminated &&
            !got_nack &&
            !premature_timeout) {
        tx_type = 0;

        if (packet_type > last_msg) {
            last_msg = packet_type;
        }

        packet = next_packet(&header);
        if (packet == NULL) {
            break;
        }

        packet_type = process_packet(packet, &header);
        memset((void *) packet, 0, header.len);

        switch (packet_type) {
            case IDENTITY_REQUEST:
                cprintf(VERBOSE, "[+] Received identity request\n");
                tx_type = IDENTITY_RESPONSE;
                id_response_sent = 1;
                break;
            case M1:
                cprintf(VERBOSE, "[+] Received \033[1;35mM1\033[0m message\n");
                if (id_response_sent && !m2_sent) {
                    tx_type = SEND_M2;
                    m2_sent = 1;
                } else if (get_oo_send_nack()) {
                    tx_type = SEND_WSC_NACK;
                    terminated = 1;
                }
                break;
            case M3:
                cprintf(VERBOSE, "[+] Received \033[1;35mM3\033[0m  message\n");
                if (m2_sent && !m4_sent) {
                    if (globule->pixie_loop == 1) {
                        tx_type = SEND_WSC_NACK;
                        terminated = 1;
                    } else if (globule->pixie_loop == 0) {
                        tx_type = SEND_M4;
                        m4_sent = 1;
                    }
                    //tx_type = SEND_M4;
                    //m4_sent = 1;
                } else if (get_oo_send_nack()) {
                    tx_type = SEND_WSC_NACK;
                    terminated = 1;
                }
                break;
            case M5:
                cprintf(VERBOSE, "[+] Received \033[1;35mM5\033[0m  message\n");
                if (get_key_status() == KEY1_WIP) {
                    set_key_status(KEY2_WIP);
                }
                if (m4_sent && !m6_sent) {
                    tx_type = SEND_M6;
                    m6_sent = 1;
                } else if (get_oo_send_nack()) {
                    tx_type = SEND_WSC_NACK;
                    terminated = 1;
                }
                break;
            case M7:
                cprintf(VERBOSE, "[+] Received \033[1;35mM7\033[0m  message\n");
                //bug fix made by flatr0ze
                if (!m6_sent) {
                    tx_type = SEND_WSC_NACK;
                    terminated = 1;
                }
                /* Fall through */
            case DONE:
                if (get_key_status() == KEY2_WIP) {
                    set_key_status(KEY_DONE);
                }
                tx_type = SEND_WSC_NACK;
                break;
            case NACK:
                cprintf(VERBOSE, "[+] Received WSC NACK (reason: 0x%04X)\n", get_nack_reason());
                got_nack = 1;
                break;
            case TERMINATE:
                terminated = 1;
                break;
            default:
                if (packet_type != 0) {
                    cprintf(VERBOSE, "[!] WARNING: Unexpected packet received (0x%.02X), terminating transaction\n", packet_type);
                    terminated = 1;
                }
                break;
        }

        if (tx_type == IDENTITY_RESPONSE) {
            send_identity_response();
        } else if (tx_type) {
            send_msg(tx_type);
        }            /* 
         * If get_oo_send_nack is 0, then when out of order packets come, we don't
         * NACK them. However, this also means that we wait infinitely for the expected
         * packet, since the timer is started by send_msg. Manually start the timer to
         * prevent infinite loops.
         */
        else if (packet_type != 0) {
            start_timer();
        }

        /* Check to see if our receive timeout has expired */
        if (get_out_of_time()) {
            /* If we have not sent an identity response, try to initiate an EAP session again */
            if (!id_response_sent) {
                /* Notify the user after EAPOL_START_MAX_TRIES eap start failures */
                if (get_eapol_start_count() == EAPOL_START_MAX_TRIES) {
                    cprintf(WARNING, "[!] WARNING: %d successive start failures\n", EAPOL_START_MAX_TRIES);
                    set_eapol_start_count(0);
                    premature_timeout = 1;
                }

                send_eapol_start();
            } else {
                /* Treat all other time outs as unexpected errors */
                premature_timeout = 1;
            }
        }
    }

    /*
     * There are four states that can signify a pin failure:
     *
     * 	o Got NACK instead of an M5 message				(first half of pin wrong)
     * 	o Got NACK instead of an M5 message, when cracking second half	(fake NACK)
     * 	o Got NACK instead of an M7 message				(second half of pin wrong)
     * 	o Got receive timeout while waiting for an M5 message		(first half of pin wrong)
     * 	o Got receive timeout while waiting for an M7 message		(second half of pin wrong)
     */
    if (got_nack) {
        /*
         * If a NACK message was received, then the current wps->state value will be
         * SEND_WSC_NACK, indicating that we need to reply with a NACK. So check the
         * previous state to see what state we were in when the NACK was received.
         */


        /* Warning the user about change of reason code for the received NACK message. */
        if (!get_ignore_nack_reason()) {
            if ((get_last_nack_reason() >= 0) && (get_nack_reason() != get_last_nack_reason())) {
                cprintf(WARNING, "[!] WARNING: The reason code for NACK has been changed. Potential FAKE NACK!\n");
            }
            set_last_nack_reason(get_nack_reason());
        }

        /* Check NACK reason code for */
        if ((get_fake_nack_reason() >= 0) && (get_nack_reason() == get_fake_nack_reason()) && (get_timeout_is_nack())) {
            ret_val = FAKE_NACK;
        } else {
            if ((last_msg == M3) || (last_msg == M5)) {
                /* The AP is properly sending WSC_NACKs, so don't treat future timeouts as pin failures. */
                set_timeout_is_nack(0);

                /* bug fix made by KokoSoft */
                ret_val = ((last_msg == M3) && (get_key_status() == KEY2_WIP) && (get_timeout_is_nack())) ? FAKE_NACK : KEY_REJECTED;
            } else {
                ret_val = UNKNOWN_ERROR;
            }
        }
    } else if (premature_timeout) {
        /* 
         * Some WPS implementations simply drop the connection on the floor instead of sending a NACK.
         * We need to be able to handle this, but at the same time using a timeout on the M5/M7 messages
         * can result in false negatives. Thus, treating M5/M7 receive timeouts as NACKs can be disabled.
         * Only treat the timeout as a NACK if this feature is enabled.
         */
        if (get_timeout_is_nack() &&
                //(last_msg == M3 || last_msg == M5))
                ((last_msg == M3 && (get_key_status() == KEY1_WIP)) || last_msg == M5)) //bug fix made by flatr0ze
        {
            ret_val = KEY_REJECTED;
        } else {
            /* If we timed out at any other point in the session, then we need to try the pin again */
            ret_val = RX_TIMEOUT;
        }
    }        /*
     * If we got an EAP FAIL message without a preceeding NACK, then something went wrong. 
     * This should be treated the same as a RX_TIMEOUT by the caller: try the pin again.
     */
    else if (terminated) {
        ret_val = EAP_FAIL;
    } else if (get_key_status() != KEY_DONE) {
        ret_val = UNKNOWN_ERROR;
    }

    /* 
     * Always completely terminate the WPS session, else some WPS state machines may
     * get stuck in their current state and won't accept new WPS registrar requests
     * until rebooted.
     *
     * Stop the receive timer that is started by the termination transmission.
     */
    send_wsc_nack();
    stop_timer();

    if (get_eap_terminate() || ret_val == EAP_FAIL) {
        send_termination();
        stop_timer();
    }

    return ret_val;
}