Exemplo n.º 1
0
void end_aktion (void)
{
	if (akt_handle > 0)
	{
		int	msg[8], d, event = 0;

		wind_close(akt_handle);
		wind_delete(akt_handle);
		akt_handle = -1;

		/*
		 * Alle auflaufenden Redraw-Messages abarbeiten, damit
		 * alle Fenster sauber sind, wenn der Dialog beendet ist.
		*/
		while (event != MU_TIMER)
		{
			event = evnt_multi(MU_MESAG|MU_TIMER, 1, 1, 1, 
									0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
									msg, 1, &d, &d, &d, &d, &d, &d);
			if ((event & MU_MESAG) && (msg[0] == WM_REDRAW))
				handle_msg(msg);
		}

		/* Men� wieder an */
		enable_menu();
	}
}
Exemplo n.º 2
0
void handle_recvmsg (struct process *process, ssize_t ret, int sockfd, struct msghdr *msg, int flags)
{
  if (ret < 0)
    return;

  (void) msg;
  (void) flags;

  struct descriptor *descriptor;

  if (!(descriptor = get_netlink_descriptor (process, sockfd)))
    return;

  unsigned char *data = NULL;

  if (!(data = malloc (ret)))
  {
    perror ("malloc");
    goto end;
  }

  if (handle_msg (data, ret, process, msg) == -1)
  {
    fprintf (stderr, "handle_msg FAILED\n");
    goto end;
  }

  descriptor_handle_recv (descriptor, data, ret);
  /* was already handled/freed */
  data = NULL;

end:
  free (data);
}
Exemplo n.º 3
0
void handle_sendmsg (struct process *process, ssize_t ret, int sockfd, const struct msghdr *msg, int flags)
{
  if (ret < 0)
    return;

  (void) msg;
  (void) flags;

  struct descriptor *descriptor;

  if (!(descriptor = get_netlink_descriptor (process, sockfd)))
    return;

  unsigned char *data = NULL;

  // TODO: we must detect total length of original message (!)
  if (!(data = malloc (ret)))
  {
    perror ("malloc");
    goto end;
  }

  if (handle_msg (data, ret, process, msg) == -1)
  {
    fprintf (stderr, "handle_msg FAILED\n");
    goto end;
  }

  descriptor_handle_send (descriptor, data, ret);
/* was already handled/freed */
  data = NULL;
end:
  free (data);

}
Exemplo n.º 4
0
static int handle_enter(int x, int y)
{
	char *line = NULL;

	/* Handle when a user presses enter.
	   - Save the contents of the line.
	   - Set the prompt to nothing.
	   - Blank the line.
	   - pass the message to the message handler
	   - rl_copy_text returns malloc'd mem, so free it
	   - restore the prompt
	   - tell readline we're done mucking
	*/
	line = rl_copy_text(0, rl_end);
	rl_set_prompt("");
	rl_replace_line("", 1);
	rl_redisplay();

	handle_msg(line);

	free(line);

	rl_set_prompt(PROMPT);
	rl_redisplay();

	rl_done = 1;
	return 0;
}
Exemplo n.º 5
0
int mysql_dissector(struct tcp_stream* tcp, void** no_need_param){
    struct half_stream* stream;
    int msg_type;
    int ret = 0;

    if(tcp->client.count_new){
        stream = &tcp->client;
        /* the msg is sent by server so the message is server type*/
        msg_type = MYSQL_SERVER_MSG;
    }else{
        stream = &tcp->server;
        msg_type = MYSQL_CLIENT_MSG;
    }

    mysql_session* sess = get_mysql_session(&tcp->addr); 
    /* FIXME: it shouldn't be null, but it can be null in some case.*/
    //DEBUG_ASSERT(sess != NULL);
    if(sess != NULL){
        ret = handle_resume_state(sess, msg_type);
        if(ret == SESSION_STATE_PROCESS_CONTINUE){
            ret = handle_msg(stream, msg_type, sess);
            if(ret == STREAM_DISCARD){
                /* leave the data we have received but not unhandled to next call */
                nids_discard(tcp, sess->handled_len);
                sess->handled_len = 0;
            }
        }else{
            log_runtime_error("handle canceled due to resume state");
        }
    }else{
        log_runtime_error("Cannot get a session");
    }
    return ret;
}
Exemplo n.º 6
0
void read_serial(int fd) {
  int bytes, total, proc;

  // Data on the serial port
  ioctl(fd, FIONREAD, &bytes);
  if (bytes < 0) return;

  bytes = read(fd, &serial_buffer[in_buffer], BUFFER_SIZE - in_buffer);
  if (bytes == -1) {
    ERROR(1, "Error reading from serial port: %d (%s)\n", errno, strerror(errno));
  } else {
    fwrite(&serial_buffer[in_buffer], 1, bytes, stdout);
    fflush(stdout);

    in_buffer += bytes;
  }

  if (in_buffer > 0) {
    for (total = 0, proc = 1; proc && in_buffer > 0 && total < in_buffer; total += proc) {
      proc = handle_msg(&serial_buffer[total], in_buffer - total);
    }

    if (total && in_buffer > 0) {
      if (total >= in_buffer) {
        in_buffer = 0;
      } else {
        memmove(serial_buffer, &(serial_buffer[total]), in_buffer - total);
        in_buffer -= total;
      }
    }
  }
}
Exemplo n.º 7
0
bool
No1ServerSession::recv_msg()
{
	while (true)
	{
		if (static_cast<int>(kBufferLen) - m_recv_len < static_cast<int>(kPerReadSize))
		{
			char* buffer = new char [2 * m_recv_len];
			memcpy(buffer, m_recv_buffer, m_recv_len);
			delete[] m_recv_buffer;
			m_recv_buffer = buffer;
		}

		int size = ::read(m_sock_fd, m_recv_buffer + m_recv_len, static_cast<int>(kPerReadSize));
		if (size  == -1)
		{
			if (errno == EAGAIN)
			{
				handle_msg();
				return true;
			} else {
				disconnect();
				return false;
			}
		}else if (size == 0){
			disconnect();
		} else {
			m_recv_len += size;
			continue;
		}
	}
	return false;
}
Exemplo n.º 8
0
static int
handle_buffer(struct rev_server *revsrv, struct rev_client *cl)
{
	struct FIFOBUF *inbuf = INBUF(cl);

	if (fifo_len(inbuf) < 3)
		return 0; /* not enough data */

	int msg_size = *((uint16_t*)inbuf->data);
	int msg_id = *((uint8_t*)(inbuf->data+2));

	ASSERT(msg_size <= MAX_MSG_SIZE, "invalid msg size")

	if (fifo_len(inbuf) < 3 + msg_size)
		return 0; /* not enough data */

	/* skip size & id */
	fifo_read(inbuf, NULL, 3);

	char buf[MAX_MSG_SIZE];
	struct netmsg msg;

	msg.id = msg_id;
	msg.size = msg_size;
	msg.data = buf;

	//printf("got msg id %d size %d\n", msg_id, msg_size);
	/* read and handle message */
	fifo_read(inbuf, buf, msg_size);
	ASSERT(handle_msg(revsrv, cl, &msg) == 0, "invalid msg");

	if (fifo_len(inbuf) > 0)
		return 1; /* there is data left */
	return 0;
}
Exemplo n.º 9
0
Arquivo: mu-cmd.c Projeto: antono/mu
MuError
mu_cmd_view (MuConfig *opts, GError **err)
{
	int i;
	gboolean rv;

	g_return_val_if_fail (opts, MU_ERROR_INTERNAL);
	g_return_val_if_fail (opts->cmd == MU_CONFIG_CMD_VIEW,
			      MU_ERROR_INTERNAL);

	rv = view_params_valid(opts, err);
	if (!rv)
		goto leave;

	for (i = 1; opts->params[i]; ++i) {

		rv = handle_msg (opts->params[i], opts, err);
		if (!rv)
			break;

		/* add a separator between two messages? */
		if (opts->terminator)
			g_print ("%c", VIEW_TERMINATOR);
	}

leave:
	if (!rv)
		return err && *err ? (*err)->code : MU_ERROR;

	return MU_OK;
}
Exemplo n.º 10
0
static int read_msg(bano_list_item_t* li, void* p)
{
  bano_socket_t* const socket = li->data;
  const int fd = bano_socket_get_fd(socket);
  struct prw_msg_data* const prwmd = p;
  int err;
#ifdef BANO_CONFIG_HTTPD
  bano_httpd_msg_t httpd_msg;
#endif /* BANO_CONFIG_HTTPD */
  bano_msg_t bano_msg;
  void* msg;
  msg_handler_t handle_msg;

  if (FD_ISSET(fd, prwmd->fds) == 0) return 0;

  /* TODO: use while loop instead of if. doing so */
  /* TODO: requires to retrieve the exact errno */
  /* TODO: code from sub layer and differentiate */
  /* TODO: between end of file, wouldblock ... */
  /* TODO: for now, assume closed on error */

  if (socket->type == BANO_SOCKET_TYPE_SNRF)
  {
    msg = &bano_msg;
    handle_msg = handle_bano_msg;
  }
#ifdef BANO_CONFIG_HTTPD
  else if (socket->type == BANO_SOCKET_TYPE_HTTPD)
  {
    msg = &httpd_msg;
    handle_msg = handle_httpd_msg;
  }
#endif /* BANO_CONFIG_HTTPD */
  else
  {
    BANO_PERROR();
    return 0;
  }

  err = bano_socket_read(socket, msg);
  if (err == -2)
  {
    /* msg partially filled, redo select */
    return 0;
  }

  if (err)
  {
    BANO_PERROR();
    bano_socket_free(socket, prwmd->base);
    bano_list_del(&prwmd->base->sockets, li);
    return 0;
  }

  handle_msg(prwmd, socket, msg);

  return 0;
}
Exemplo n.º 11
0
int
loop()
{
	/* receive events */
	while(1) {
		il_octet_string_t *msg;
		long offset;
		int ret;

		do_handle_signal();
		if(killflg)
			return (0);

		clear_error();
		if((ret = input_queue_get(&msg, &offset, INPUT_TIMEOUT)) < 0)
		{
			if(error_get_maj() == IL_PROTO) {
				glite_common_log(IL_LOG_CATEGORY, LOG_PRIORITY_DEBUG, 
						 "  premature EOF while receiving event");
				/* problems with socket input, try to catch up from files */
#ifndef PERF_EMPTY
				event_store_recover_all();
#endif
				continue;
			} else
				return(-1);
		}
		else if(ret == 0) {
			continue;
		}

#ifdef PERF_EMPTY
		glite_wll_perftest_consumeEventString(msg->data);
		free(msg->data);
		continue;
#endif

#ifdef INTERLOGD_HANDLE_CMD
		ret = handle_cmd(msg, offset);
		if(ret == 0)
#endif
			ret = handle_msg(msg, offset);
		if(msg->data) free(msg->data);
		if(ret < 0)
			switch (error_get_maj()) {
				case IL_SYS:
				case IL_NOMEM:
					return (ret);
					break;
				default:
    					glite_common_log(IL_LOG_CATEGORY, LOG_PRIORITY_ERROR, 
							 "Error: %s", 
							 error_get_msg());
					break;
			}
	} /* while */
}
Exemplo n.º 12
0
static ssize_t read_data(struct qmi_device *qmid){
    ssize_t numbytes;
    qmux_hdr_t *qmux_hdr;

    //First, read a qmux header then read the data
    //TODO: Consider something more efficient than two reads. A circular buffer
    //for example.
    if(!qmid->cur_qmux_length){
        numbytes = read(qmid->qmi_fd, qmid->buf + qmid->qmux_progress,
                sizeof(qmux_hdr_t));

        if(numbytes == -1){
            if(qmid_verbose_logging >= QMID_LOG_LEVEL_1)
                QMID_DEBUG_PRINT(stderr, "Read from device failed\n");

            return numbytes;
        } else if(numbytes != sizeof(qmux_hdr_t)){
            if(qmid_verbose_logging >= QMID_LOG_LEVEL_3)
                QMID_DEBUG_PRINT(stderr, "Parial QMUX, length %zd\n", numbytes);

            qmid->qmux_progress += numbytes;
        } else {
            qmux_hdr = (qmux_hdr_t*) qmid->buf;
            qmid->qmux_progress = sizeof(qmux_hdr_t);
            //+1 is for the marker, which is also part of the data I want to
            //read
            qmid->cur_qmux_length = le16toh(qmux_hdr->length) + 1;

            //Add check for too large qmux length
        }
    } 

    //If I have received a full header, try to read data. This might happen
    //immediatly 
    if(qmid->cur_qmux_length){
        numbytes = read(qmid->qmi_fd, qmid->buf + qmid->qmux_progress,
                qmid->cur_qmux_length - qmid->qmux_progress);

        if(numbytes == -1){
            if(qmid_verbose_logging >= QMID_LOG_LEVEL_1)
                QMID_DEBUG_PRINT(stderr, "Read from device failed\n");

            return numbytes;
        }

        qmid->qmux_progress += numbytes;

        if(qmid->qmux_progress == qmid->cur_qmux_length){
            handle_msg(qmid);
            qmid->qmux_progress = 0;
            qmid->cur_qmux_length = 0;
        }
    }

    return numbytes;
}
Exemplo n.º 13
0
//���������������������������������������������������������������������������
// TurnerClassic - receive
//���������������������������������������������������������������������������
int TurnerClassic::receive ()
{
    DPID    from, to;
    HRESULT res;
    DWORD   size;

    if (!pIDP)
        return DPERR_UNAVAILABLE;

    if (!rbuffer)
    {
        rbuffer = new char[TURNER_INIT_BUFFER];
        if (!rbuffer)
            return DPERR_OUTOFMEMORY;

        rbsize = TURNER_INIT_BUFFER;
    }

    for(;;)
    {
        Sleep(0);
        res = pIDP->Receive (&from, &to,
                             DPRECEIVE_ALL,
                             rbuffer, (LPDWORD)&size);

        switch (res)
        {
            case DPERR_BUFFERTOOSMALL:
                if (size > TURNER_MAX_BUFFER)
                    return DPERR_SENDTOOBIG;

                delete [] rbuffer;

                while (rbsize < size)
                    rbsize *= 2;

                rbuffer = new char[rbsize];
                if (!rbuffer)
                    return DPERR_OUTOFMEMORY;
                break;

            case DP_OK:
                if (!from)
                    handle_sysmsg (to, (DPMSG_GENERIC *)rbuffer, size);
                else
                    handle_msg (from, to, rbuffer, size);
                return DP_OK;

            default:
                return res;
        }
    }
}
Exemplo n.º 14
0
bool DataFlashFileReader::update(char type[5])
{
    uint8_t hdr[3];
    if (read_input(hdr, 3) != 3) {
        return false;
    }
    if (hdr[0] != HEAD_BYTE1 || hdr[1] != HEAD_BYTE2) {
        printf("bad log header\n");
        return false;
    }

    if (hdr[2] == LOG_FORMAT_MSG) {
        struct log_Format f;
        memcpy(&f, hdr, 3);
        if (read_input(&f.type, sizeof(f)-3) != sizeof(f)-3) {
            return false;
        }
        memcpy(&formats[f.type], &f, sizeof(formats[f.type]));
        strncpy(type, "FMT", 3);
        type[3] = 0;

        message_count++;
        return handle_log_format_msg(f);
    }

    if (!done_format_msgs) {
        done_format_msgs = true;
        end_format_msgs();
    }

    const struct log_Format &f = formats[hdr[2]];
    if (f.length == 0) {
        // can't just throw these away as the format specifies the
        // number of bytes in the message
        ::printf("No format defined for type (%d)\n", hdr[2]);
        exit(1);
    }

    uint8_t msg[f.length];

    memcpy(msg, hdr, 3);
    if (read_input(&msg[3], f.length-3) != f.length-3) {
        return false;
    }

    strncpy(type, f.name, 4);
    type[4] = 0;

    message_count++;
    return handle_msg(f,msg);
}
Exemplo n.º 15
0
int main(int argc, char* argv[]){

	//printf("argc:%d arg1:%s\n", argc, argv[1]);
	clr_connections(srv_state);
	clr_connections(dirty_state);

	int cont =1;
	next_fid =0;
	
	struct sigaction act;
	act.sa_handler = (update_clients_handler);
	if(sigaction(SIGALRM, &act, NULL)){
		printf("error setting alarm handler\n");
	}
	struct timeval tv;
	//kill(getpid(), SIGVTALRM);
	tv.tv_sec=0;
	tv.tv_usec = TIC_RATE;
	const struct itimerval it_update = {tv, tv};
	if(setitimer(ITIMER_REAL, &it_update, NULL)) perror("setitimer failure");

	openfd = socket(AF_INET, SOCK_DGRAM, 0);

	struct sockaddr_in server_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(HOST_PORT);
	bind(openfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr_in));

	while(cont){
		struct client_data new_client;
		int socklen = sizeof(struct sockaddr_in);
		if(recvfrom(openfd, &new_client, sizeof(struct client_data), 0, (struct sockaddr*)&new_client.destaddr, &socklen)!=0){
			printf("recieved msg. client_id=%d, address=%s\n", new_client.client_id, inet_ntoa(new_client.destaddr.sin_addr));
			if(new_client.client_id>-1){
				if(handle_msg(&new_client, dirty_state, openfd)){
					printf("error handle_msg()\n");
					return -1;
					}
			}
			else{
				if(handle_new_client(&new_client, dirty_state, openfd)){
					printf("error handle_msg()\n");
					return -1;
				}
			}
		}
	}
	return 0;
}
Exemplo n.º 16
0
	void do_read_body(Header header){
		auto self(shared_from_this());
		buf_ptr buf_ptr_(new EasyBuffer);
		buf_ptr_->prepare(sizeof(Header) + header.body_size);
		memcpy(buf_ptr_->get_buffer(), &header, sizeof(Header));
		boost::asio::async_read(socket_, boost::asio::buffer(buf_ptr_->get_buffer(sizeof(Header)), header.body_size),
				[this, self, &buf_ptr_](boost::system::error_code ec, std::size_t){
					if(!ec){
						handle_msg(buf_ptr_);
						do_read_header();
					}
				}
		);
	}
Exemplo n.º 17
0
void ClientConnection::on_read(const boost::system::error_code &err, size_t bytes) {
	if (err) {
		BOOST_LOG_TRIVIAL(error) << "on_read error: " << err << " client id=" << _id;
		throw server_exception("on_read error", shared_from_this());
	}
	std::string msg(_read_buffer, bytes);
	BOOST_LOG_TRIVIAL(info) << "Received from client id=" << _id << " msg: " << msg;
	if (_need_stop) {
		_need_stop = false;
		do_write("stop\n", boost::bind(&ClientConnection::on_write_disconnected, shared_from_this(), _1, _2));
	}
	else {
		handle_msg(msg);
	}
}
Exemplo n.º 18
0
int MsgTask::svc (void)
{
    Message  *  m  =0 ; 
    while (!stop_) 
    {
        if ( get_msg(m) == 0)
        {
            assert(m);
            (void) handle_msg(*m);
            delete m;
        }
    }

    return 0;
}
Exemplo n.º 19
0
void on_receive(struct moag *m, ENetEvent *ev)
{
    struct chunk_header *chunk;

    chunk = receive_chunk(ev->packet);
    intptr_t id = (intptr_t)ev->peer->data;

    switch (chunk->type)
    {
        case INPUT_CHUNK:
        {
            struct input_chunk *input = (void *)chunk;
            switch (input->key)
            {
                case KLEFT_PRESSED:   m->players[id].kleft = true; break;
                case KLEFT_RELEASED:  m->players[id].kleft = false; break;
                case KRIGHT_PRESSED:  m->players[id].kright = true; break;
                case KRIGHT_RELEASED: m->players[id].kright = false; break;
                case KUP_PRESSED:     m->players[id].kup = true; break;
                case KUP_RELEASED:    m->players[id].kup = false; break;
                case KDOWN_PRESSED:   m->players[id].kdown = true; break;
                case KDOWN_RELEASED:  m->players[id].kdown = false; break;
                case KFIRE_PRESSED:   m->players[id].kfire = true; break;
                case KFIRE_RELEASED:
                {
                    uint16_t power = input->ms;
                    m->players[id].kfire = false;
                    m->players[id].tank.power = power / 2;
                    m->players[id].tank.power = CLAMP(0, 1000, m->players[id].tank.power);
                    break;
                }
            }
            break;
        }

        case CLIENT_MSG_CHUNK:
        {
            struct client_msg_chunk *client_msg = (void *)chunk;
            handle_msg(m, id, (char *)client_msg->data, ev->packet->dataLength - 1);
            break;
        }

        default: break;
    }

    free(chunk);
}
Exemplo n.º 20
0
void NativeChannel::handle_read_body(const boost::system::error_code& error)
{
	if (!error)
	{
		handle_msg(read_msg_);
		boost::asio::async_read(serverSocket,
			boost::asio::buffer(read_msg_.data(), Message::header_length),
			boost::bind(&NativeChannel::handle_read_header, this,
				boost::asio::placeholders::error));
	}
	else
	{
		Logger::log("Channel( " + me.to_log_string() + "error when reading message body: " + error.message());
		m_IsConnected = false;
		do_close();
	}
}
Exemplo n.º 21
0
int main(int cgc_argc, char *cgc_argv[])
{
    uint8_t *data = NULL;
    cgc_init_vault();
    cgc_store_in_vault(0, (void *)cgc_handlers, sizeof(cgc_handlers));
    while (1)
    {
        uint8_t msg[6], *newdata;
        uint16_t id;
        uint32_t len;

        if (cgc_read_bytes(&msg[0], 4) == 0)
            break;

        id = betoh16(*(uint16_t *)&msg[0]);
        len = betoh16(*(uint16_t *)&msg[2]);
        if (len & 0x8000)
        {
            if (cgc_read_bytes(&msg[4], 2) == 0)
                break;
            len = betoh32(*(uint32_t *)&msg[2]) & 0x7fffffff;
        }

        if (!is_supported(id))
        {
ignore:
            if (consume_bytes(len) == 0)
                break;
            continue;
        }

        newdata = cgc_realloc(data, len);
        if (newdata == NULL)
            goto ignore;
        data = newdata;

        if (cgc_read_bytes(data, len) == 0)
            break;

        handle_msg(id, data, len);
    }

    cgc_free(data);
    return 0;
}
Exemplo n.º 22
0
int main(int argc, char**argv)
{
    int sockfd,n_bytes;
    struct sockaddr_in servaddr,cliaddr;
    char recvline[MAX_RX_BUF];
    int quit = 0, flag = 1;

    if (argc != 2)
    {
      printf("usage:  robot <IP address>\n");
      exit(1);
    }

    sockfd=socket(AF_INET,SOCK_STREAM,0);
    setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)); // disable Naggle algorithm

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(argv[1]);
    servaddr.sin_port=htons(10000);

    connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    while(!quit) {
        n_bytes = recv(sockfd, recvline, sizeof(recvline) - 1, 0);

        if (n_bytes == -1) {
            // Socket in error state
            return 0;
        } else if (n_bytes == 0) {
            // Socket has been closed
            fprintf (stderr, "Socket %d closed", sockfd);
            close(sockfd);
            return 0;
        } else {
            // let's process it
            recvline[n_bytes] = '\0';
            printf ("Received %s\n", recvline);
            quit = handle_msg(recvline, sockfd);
        }
    }
    return 0;
}
Exemplo n.º 23
0
int handle_proc_req(int socket)
{
	int ret;
	struct timeval timeout;
	unix_domain_msg *msg = NULL;
	char msg_buf[MAX_BUF_SIZE] = { 0 };

	msg = (unix_domain_msg *)msg_buf;
	timeout.tv_sec = 3;
	timeout.tv_usec = 0;

	ret = unix_domain_recv_msg(socket, msg, MAX_BUF_SIZE, &timeout);
	if (ret != 0) {
		fprintf(std_err, "recv_msg() failed.\n");
		goto done;
	}

	ret = handle_msg((tl_timer_t *)msg->data);
	if (ret != 0) {
		fprintf(std_err, "handle_msg() failed.\n");
	}
	
	msg->size = sizeof(tl_timer_t);
	ret = unix_domain_send_msg(socket, (void *)msg, sizeof(unix_domain_msg) + msg->size, &timeout);
	if (ret != 0) {
		fprintf(std_err, "send_msg() failed.\n");
	}

done:

	if ((void *)msg != (void *)msg_buf) {
		free(msg);
		msg = NULL;
	}
	
	if (socket >= 0) {
		close(socket);
	}

	return (ret);

}
Exemplo n.º 24
0
static void
nub_rcv( int fd, int dummy_events ) 
{
	struct pollfd ufds;
	mol_dgram_t *dg;
	int err, events;

	/* the events parameter can not be trusted since a queued async events can
	 * be stolen by a debugger_nub_poll() call.
	 */
	ufds.fd = fd;
	ufds.events = POLLHUP | POLLIN | POLLERR;
	if( poll(&ufds, 1, 0) <= 0 )
		return;
	events = ufds.revents;
	
	if( events & POLLHUP ) {
		if( sv.hup_count++ > 0 ) {
			sv.hup_count = 0;
			printm("Debugger connection lost\n");
			close_sock();
		}
		return;
	}

	if( events & ~POLLIN ) {
		fprintf(stderr, "nub_rcv events %x\n", events );
		return;
	}

	if( sv.dgram_receiver ) {
		if( (dg=receive_dgram(sv.dgram_receiver, &err)) ) {
			handle_msg(dg);
			free(dg);
		} else if( err ) {
			printm("nub_rcv: an error occured\n");
		}
	} else {
		printm("Unexpected nub_rcv\n");
	}
}
Exemplo n.º 25
0
/*
 *              RUN()
 * run() to start the epoll_server
 * param time_out is to wait running epoll_wait once
 * determine what the m_epoll_events[i].data.fd equals
 * 1. if it equals listen sock fd, then do accept_new_client()
 * 2. if it equals client sock fd, and the property is EPOLLIN,
 *    then recv_data() from client
 * 3. if it equals client sock fd, and the property is EPOLLOUT,
 *    then send_data() to client
 */
void epoll_server::run(int time_out)
{
    while (1) {
        int ret = epoll_server_wait(time_out);

        if (ret == 0) {
            continue;
        } else if (ret == -1) {
            cout << "epoll wait error: " << strerror(errno)
                 << "(errno: " << errno << ")" << endl;
            continue;
        } else {
            for (int i = 0; i < ret; ++i) {
                if (m_epoll_events[i].data.fd == m_listen_sock) {
                        accept_new_client();
                } else {
                    handle_msg(m_epoll_events[i].data.fd);
                }
            }
        }
    }
}
Exemplo n.º 26
0
static int peek_msg(bano_list_item_t* li, void* p)
{
  bano_socket_t* const socket = li->data;
  struct prw_msg_data* const prwmd = p;
#ifdef BANO_CONFIG_HTTPD
  bano_httpd_msg_t httpd_msg;
#endif /* BANO_CONFIG_HTTPD */
  bano_msg_t bano_msg;
  void* msg;
  msg_handler_t handle_msg;

  if (socket->type == BANO_SOCKET_TYPE_SNRF)
  {
    msg = &bano_msg;
    handle_msg = handle_bano_msg;
  }
#ifdef BANO_CONFIG_HTTPD
  else if (socket->type == BANO_SOCKET_TYPE_HTTPD)
  {
    msg = &httpd_msg;
    handle_msg = handle_httpd_msg;
  }
#endif /* BANO_CONFIG_HTTPD */
  else
  {
    BANO_PERROR();
    return 0;
  }

  while (bano_socket_peek(socket, msg) == 0)
  {
    handle_msg(prwmd, socket, msg);
  }

  return 0;
}
Exemplo n.º 27
0
int16 main(void)
{
    GRECT		n = {0,0,0,0};
    GRECT		r1;
    EVNTDATA	ev;
    int16		bclicks, bmask, bstate;
    boolean	leave;
    quit = FALSE;

    debug_init("MControl", null, NULL);

    init_app("mcontrol.rsc");
    init_rsrc();
    init_conf();
    init_dial();
    init_comm();
    init_beta();

    /* Callback f�r modale Fensterdialoge, Fenster-Alerts usw. */
    set_mdial_wincb(handle_msg);

    graf_mkstate( &ev );
    wdial_hover( ev.x, ev.y, &r1, &leave );

    while (!quit)
    {
        mbutton = 0;

        if( !((ev.bstate) & 3) )
            bclicks = 258;
        else
            bclicks = 0;

        bmask = 3;
        bstate = 0;

        event = evnt_multi( MU_BUTTON|MU_M1|MU_MESAG|MU_KEYBD,
                            bclicks, bmask, bstate,
                            leave, &r1, 0, &n,
                            msg,
                            0l,
                            &ev,
                            &kreturn, &mclick );
        msx = ev.x;
        msy = ev.y;
        mbutton = ev.bstate;
        kstate = ev.kstate;

        if (event & MU_MESAG)
        {
            if( msg[0] == WM_MOVED )
                wdial_hover( msx, msy, &r1, &leave );

            handle_msg(msg);
        }

        if (event & MU_BUTTON)
        {
            if( mbutton == 2 )
                menu_context( msx, msy );
            else if (!click_wdial(mclick, msx, msy, kstate, mbutton))
                ;
        }

        if (event & MU_M1)
            wdial_hover( msx, msy, &r1, &leave );

        if (event & MU_KEYBD)
        {
            int16	title, item;

            if (is_menu_key(kreturn, kstate, &title, &item))
                handle_menu(title, item);
            else
            {
                key_wdial(kreturn, kstate);
                key_sdial(kreturn, kstate);
            }
        }
    }

    exit_comm();
    exit_dial();
    exit_rsrc();
    debug_exit();
    exit_app(0);
    return 0;
}
Exemplo n.º 28
0
int main(int argc, char *argv[]) {
	char *str;
	int i = 0, day = 0, hour = 4;

	umask(027);

	lockfd = open(MY_BBS_HOME "/friends.lock", O_CREAT | O_RDONLY, 0660);
	if (flock(lockfd, LOCK_EX | LOCK_NB) < 0)
		exit(1);
	
	if(argc == 2) {
		if(!strcmp(argv[1], "-d")) { //run as daemon
			if (fork())
				return 0;
			setsid();
			if (fork())
				return 0;
			close(0);
			close(1);
			close(2);
		}
	}
	
	msqid = initFriendsMSQ();
	if (msqid < 0)
		exit(1);
	
	fidx = ght_create(MAXUSERS + 3);
	if (fidx == NULL)
		exit(1);

	mkdir(FRIENDS_TMPDIR, 0770);	//try making tmp dir
	if(load_friends() == -1)
		exit(1);	
	div_friends();
	friends_top10();
	
	signal(SIGHUP, set_sync_flag);	//sync if disconnected
	signal(SIGTERM, write_back_all);
	signal(SIGCHLD, sig_child);
	while (1) {
		while ((str = rcvlog(msqid, 1))) {
		//	printf("%s\n", str);
			handle_msg(str);
		}
		sleep(5);
		i++;
		if (i == hour*12*60 || sync_flag) { //write back from time to time
			system("rm -f " FRIENDS_TMPDIR "/*");
			if(++day == 24/hour) {//daily
				day = 0;
				estrange_by_time();
			}
			save_friends();
			div_friends();
			friends_top10();
			i = 0;
			sync_flag = 0;
		}
	}
	return 0;
}
Exemplo n.º 29
0
void IRC::handle(const string& oline) {
    string line = trim(oline);
    printf("%s\n", line.c_str());

    //We are pinged, respond!
    if(line.compare(0, 4, "PING") == 0) {
        onServerPing(line.substr(5));
        return;
    }

    char* cstr = new char[line.size() + 1];
    strcpy(cstr, line.c_str());

    string sender, nick, login, host;

    bool nickOnly = false;
    size_t tokn = 0;
    char *tok = strtok(cstr, " ");
    while(tok != NULL) {
        //For each token, check
        string tmp = tok;
        if(tokn == 0) {
            sender = tmp;
            if(sender[0] == ':')
                sender = sender.substr(1);

            size_t exp = sender.find("!");
            size_t at = sender.find("@");

            //TODO: Add checks for 'exp' and 'at' being string::npos
            //  to avoid calling these when there are (no ill effects
            //  have been seen from not doing so yet, however for sanity sake)
            if(exp == string::npos || at == string::npos) {
                nick = trim(sender);
                login = "";
                host = "";
                nickOnly = true;
            } else {
                nick = trim(sender.substr(0, exp));
                login = trim(sender.substr(exp + 1, at));
                host = trim(sender.substr(at + 1));
            }
        }

        if(tokn == 1) {
            tok = strtok(NULL, " ");
            string target(tok); //AKA channel

            uint32_t code = 0;
            if(tmp.length() == 3 && (code = (uint32_t) atoi(tmp.c_str())) != 0 && code < 1000) {
                string response = line.substr(sender.length()+5+target.length()+1);
                handle_numeric(code,target,response);
                onNumeric(sender,code,target,response);
            } else if(tmp.compare("PRIVMSG") == 0) {
                handle_msg(target, nick, login, host, line.substr(line.find(" :") + 2));
            } else if(tmp.compare("NOTICE") == 0) {
                onNotice(target, nick, login, host, line.substr(line.find(" :") + 2));
            } else if(tmp.compare("JOIN") == 0) {
                //TODO: Add this user to the channel.
                onJoin(target, nick, login, host);
            } else if(tmp.compare("PART") == 0) {
                //TODO: Remove this user from the channel.
                onPart(target, nick, login, host);
            } else if(tmp.compare("TOPIC") == 0) {
                onTopic(target, line.substr(line.find(" :") + 2), nick, time(NULL), true);
            } else if(tmp.compare("KICK") == 0) {
                tok = strtok(NULL, " ");
                string recipient(tok);
                onKick(target, nick, login, host, recipient, line.substr(line.find(" :") + 2));
            } else if(tmp.compare("QUIT") == 0) {
                onQuit(nick, login, host, line.substr(line.find(" :") + 2));
            } else if(tmp.compare("MODE") == 0) {
                tok = strtok(NULL, " ");
                string mode = tok;
                if(mode[0] == ':')
                    mode = mode.substr(1);
                handle_mode(nick, login, host, target, mode);
            }
            //TODO: Add mode handler here
            else {
                onUnknown(line);
            }

            break;
        }

        tok = strtok(NULL, " ");
        ++tokn;
    }

    delete[] cstr;
}
Exemplo n.º 30
0
Arquivo: main.c Projeto: Drooids/nrf
static uint8_t do_uart(void)
{
  /* return 0 if no msg processed, 1 otherwise */

  /* note: commands comming from the host always */
  /* require a form of ack, which implies that */
  /* there wont be a uart rx burst from the dev */
  /* point of view. thus, this routine can be */
  /* slow to handle message without missing */
  /* bytes, until the reply is sent. */

  /* no need to disable interrupts. cf USART_RX_vect comment. */
  const uint8_t pos = uart_pos;

  uint8_t x;

  if (pos != sizeof(snrf_msg_t))
  {
    /* not a full message available */
    return 0;
  }

  /* synchronization procedure */
  if (uart_buf[offsetof(snrf_msg_t, sync)] == SNRF_SYNC_BYTE)
  {
    /* disable interrupts before setting uart_pos */
    /* with interrupts disabled, wait for SYNC_END */
    cli();
    uart_pos = 0;
    while (1)
    {
      /* do not stop on error during sync */
      if (uart_read_uint8(&x)) continue ;
      if (x == SNRF_SYNC_END) break ;
    }
    sei();

    /* set state to conf */
    if (snrf_state != SNRF_STATE_CONF)
    {
      snrf_state = SNRF_STATE_CONF;
      nrf_set_powerdown_mode();
    }

    return 1;
  }

  /* handle new message */
  handle_msg((snrf_msg_t*)uart_buf);

  /* warning: set uart_pos to 0 before sending */
  /* the reply, since the host will start sending */
  /* new packets and we do not want the interrupt */
  /* handler to see uart_buf full */
  uart_pos = 0;

  /* send completion */
  uart_write((uint8_t*)uart_buf, sizeof(snrf_msg_t));

  /* a message has been handled */
  return 1;
}