/**\brief 通过本地socket发送命令
 * \param fd socket
 * \param[in] cmd 命令字符串
 * \return
 *   - AM_SUCCESS 成功
 *   - 其他值 错误代码
 */
AM_ErrorCode_t AM_LocalSendCmd(int fd, const char *cmd)
{
	AM_ErrorCode_t ret;
	int len;
	
	assert(cmd);
	
	len = strlen(cmd)+1;
	
	ret = try_write(fd, (const char*)&len, sizeof(int));
	if(ret!=AM_SUCCESS)
	{
		AM_DEBUG(1, "write local socket failed");
		return ret;
	}
	
	ret = try_write(fd, cmd, len);
	if(ret!=AM_SUCCESS)
	{
		AM_DEBUG(1, "write local socket failed");
		return ret;
	}
	
	AM_DEBUG(2, "write cmd: %s", cmd);
	
	return AM_SUCCESS;
}
Beispiel #2
0
static void receive(int fd, const char* fd_path)
{
	unsigned char c;
	while ( true )
	{
		if ( !try_read(fd, fd_path, &c) )
			return;
		if ( c != 0xF7 )
			continue;
		if ( !try_read(fd, fd_path, &c) )
			return;
		if ( c == 0xFF )
			break;
	}
	while ( true )
	{
		if ( !try_read(fd, fd_path, &c) )
			return;
		if ( c == 0xF7 )
		{
			if ( !try_read(fd, fd_path, &c) )
				return;
			if ( c == 0xFE )
				break;
			if ( c == 0xFD )
				try_write(1, "stdout", 0xF7);
			continue;
		}
		try_write(1, "stdout", c);
	}
}
Beispiel #3
0
int
main (int argc UNUSED, char *argv[]) 
{
  msg ("begin");
  try_write ();
//printf("\nHERE\n");
  if (!isdigit (*argv[1]))
    fail ("bad command-line arguments");
  if (atoi (argv[1]) > 1) 
    {
      char cmd[128];
      int child;
      
      snprintf (cmd, sizeof cmd, "child-rox %d", atoi (argv[1]) - 1);
      CHECK ((child = exec (cmd)) != -1, "exec \"%s\"", cmd);
      quiet = true;
      CHECK (wait (child) == 12, "wait for \"child-rox\"");
      quiet = false;
    }

  try_write ();
  msg ("end");

  return 12;
}
Beispiel #4
0
int pump(thread_info_t *thread, pipe_info_t *pipe) {
    
    int res;
    
    if (pipe->out->pollfd->revents & POLLOUT) {
        
        res = try_write(thread, pipe);
        if (res < 0) return -1;
    }

    if (pipe->in->pollfd->revents & POLLIN && pipe->backup < BUFFER_SIZE) {
        
        ssize_t bytes_read = read(pipe->in->fd, pipe->buffer + pipe->backup, BUFFER_SIZE - pipe->backup);
        if (bytes_read < 0) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
                return 0;
            }
            fprintf(stderr, "Connection %d could not receive from %s: %s\n",
                thread->id, pipe->in->name, strerror(errno));
            return -1;
        }
        
        /* Put an entry into the log. When we write the log, we use blocking IO calls. We presume
        that the disk is faster than the network.
        
        Maybe it would be better to do this in try_write() so that the entry's timestamp is closer
        to the actual time that the data is sent to the server or client. */
        
        char count_buffer[20];
        sprintf(count_buffer, "%d", (int)bytes_read);
        res = write_log_entry(thread, pipe->in->name, count_buffer);
        if (res < 0) return -1;
        
        res = fwrite(pipe->buffer + pipe->backup, 1, bytes_read, thread->log);
        if (res != bytes_read) {
            fprintf(stderr, "Connection %d could not write to log: %s\n", thread->id, strerror(errno));
            return -1;
        }
        
        pipe->backup += bytes_read;
    }
    
    if (pipe->backup) {
        
        res = try_write(thread, pipe);
        if (res < 0) return -1;
    }
    
    if (pipe->backup)
        pipe->out->pollfd->events |= POLLOUT;
    else
        pipe->out->pollfd->events &= ~POLLOUT;
    
    return 0;
}
Beispiel #5
0
/*
 * Don't export this to libmount API -- utab is private library stuff.
 *
 * If the file does not exist and @writable argument is not NULL then it will
 * try to create the directory (e.g. /run/mount) and the file.
 *
 * Returns: 1 if utab is a regular file, and 0 in case of
 *          error (check errno for more details).
 */
int mnt_has_regular_utab(const char **utab, int *writable)
{
	struct stat st;
	int rc;
	const char *filename = utab && *utab ? *utab : mnt_get_utab_path();

	if (writable)
		*writable = 0;
	if (utab && !*utab)
		*utab = filename;

	DBG(UTILS, mnt_debug("utab: %s", filename));

	rc = lstat(filename, &st);

	if (rc == 0) {
		/* file exist */
		if (S_ISREG(st.st_mode)) {
			if (writable)
				*writable = !try_write(filename);
			return 1;
		}
		goto done;	/* it's not regular file */
	}

	if (writable) {
		char *dirname = strdup(filename);

		if (!dirname)
			goto done;

		stripoff_last_component(dirname);	/* remove filename */

		rc = mkdir(dirname, S_IWUSR|
				    S_IRUSR|S_IRGRP|S_IROTH|
				    S_IXUSR|S_IXGRP|S_IXOTH);
		free(dirname);
		if (rc && errno != EEXIST)
			goto done;			/* probably EACCES */

		*writable = !try_write(filename);
		if (*writable)
			return 1;
	}
done:
	DBG(UTILS, mnt_debug("%s: irregular/non-writable file", filename));
	return 0;
}
Beispiel #6
0
void otudp_old_write(OTUDP *x, Symbol *s, short argc, Atom *argv) {	
	
	// We want to discourage the old bad way of sending non-Max data to OTUDP,
	// but we provide the old interface for backwards-compatibility.
	
	if (!(x->o_complained_about_old_msgs)) {
		post("OTUDP: You shouldn't use old-style write+gimme messages.");
		post("You should upgrade the object that talks to OTUDP.");
		x->o_complained_about_old_msgs = 1;
	}
	
	if (!(x->o_writer)) {
		error("otudp read objects can't write!  Get a grip!");
		return;
	}
	
	if (!(x->o_ready)) {
		if (x->o_udp_ep == 0) {
			error("otudp: Can't send a packet yet; the endpoint hasn't been created yet.");
		} else {
			error("otudp: Can't send a packet yet; the endpoint hasn't been bound yet.");
		}
		return;
	}
	
	// Here's where we evily subvert Max's argc/argv
	try_write(x, argc, (void *) argv);
}
Beispiel #7
0
void TConnection::write() {
  while (1) {
    if (try_write() < 0) {
      break;
    }
  }
}
Beispiel #8
0
      bool SocketServer::Stream::process()
      {
        bool const can_read  = select_spec->read_out.find(fildes)  != select_spec->read_out.end();
        bool const can_write = select_spec->write_out.find(fildes) != select_spec->write_out.end();

        try
        {
          if(can_read)
          {
            if(can_write)
            {
              if(swap_order)
              {
                try_write();
                bool const wait = write_state == state_Wait;
                try_read();
                if(wait && write_state != state_Wait) { swap_order = false; cerr << "RESTORING READ/WRITE ORDER" << endl; }
              }
              else
              {
                try_read();
                bool const wait = read_state == state_Wait;
                try_write();
                if(wait && read_state != state_Wait) { swap_order = true; cerr << "REVERSING READ/WRITE ORDER" << endl; }
              }
            }
            else try_read();
          }
          else if(can_write) try_write();
        }
        catch(IOException &e)
        {
          cerr << "I/O error: "<<e.what() << endl;
          select_spec->read_in.erase(fildes);
          select_spec->write_in.erase(fildes);
          return false;
        }

        bool const close = write_state == state_Closed && read_state == state_Closed;
        if(!close && !async_resumption_enabled &&
           read_state != state_Ready && write_state != state_Ready)
          throw runtime_error("Connection implementation malfunction: Dead-locked");
        return !close;
      }
Beispiel #9
0
static gboolean
handle_stream (gpointer data)
{
  Stream *stream = data;

  if (!stream->started) {
    swfdec_playback_stream_start (stream);
    return TRUE;
  } else {
    return try_write (stream);
  }
}
bool connection_engine::process_nothrow(int flags) {
    if (closed()) return false;
    if (flags & WRITE) try_write();
    dispatch();
    if (flags & READ) try_read();
    dispatch();

    if (connection_.closed() && !closed()) {
        dispatch();
        while (can_write()) {
            try_write(); // Flush final data.
        }
        // no transport errors.
        close_transport(ctx_);
    }
    if (closed()) {
        pn_transport_unbind(ctx_->transport);
        dispatch();
        try { io_close(); } catch(const io_error&) {} // Tell the IO to close.
    }
    return !closed();
}
Beispiel #11
0
/**
 * mnt_has_regular_mtab:
 * @mtab: returns path to mtab
 * @writable: returns 1 if the file is writable
 *
 * If the file does not exist and @writable argument is not NULL then it will
 * try to create the file
 *
 * Returns: 1 if /etc/mtab is a regular file, and 0 in case of error (check
 *          errno for more details).
 */
int mnt_has_regular_mtab(const char **mtab, int *writable)
{
	struct stat st;
	int rc;
	const char *filename = mtab && *mtab ? *mtab : mnt_get_mtab_path();

	if (writable)
		*writable = 0;
	if (mtab && !*mtab)
		*mtab = filename;

	DBG(UTILS, mnt_debug("mtab: %s", filename));

	rc = lstat(filename, &st);

	if (rc == 0) {
		/* file exist */
		if (S_ISREG(st.st_mode)) {
			if (writable)
				*writable = !try_write(filename);
			return 1;
		}
		goto done;
	}

	/* try to create the file */
	if (writable) {
		*writable = !try_write(filename);
		if (*writable)
			return 1;
	}

done:
	DBG(UTILS, mnt_debug("%s: irregular/non-writable", filename));
	return 0;
}
Beispiel #12
0
	void async_write(const T& t, Handler handler)
	{
		boost::recursive_mutex::scoped_lock lck(wmtx_);

		buffer_ptr outbound_header_(new std::string);
		std::string outbound_data_;

		boost::iostreams::filtering_ostreambuf out;

		out.push(boost::iostreams::zlib_compressor());
		out.push(boost::iostreams::back_inserter(outbound_data_));

		{
			oar oa(out, archive_flags);
			oa << t;
		}// archive have to be closed before out.pop()

		out.pop ();

		// Format the header.
		std::ostringstream header_stream;
		header_stream << std::setw(header_length)
			<< std::hex << outbound_data_.size();
		if (!header_stream || header_stream.str().size() != header_length)
		{
			// Something went wrong, inform the caller.
			boost::system::error_code error(boost::asio::error::invalid_argument);
			handler(error);
			return;
		}

		//combine the header + data [size + actual data]
		header_stream << outbound_data_;
		*outbound_header_ = header_stream.str();

		wop_buf_.push_back(WOpElem(outbound_header_, handler));


		//尝试获得写锁。
		if ( writemtx_.try_lock() )
		{
			//如果获得了,说明没有在写数据。那么开始写。
			try_write();
		}
		//没有获得,说明已经有异步写操作了。这次放入的数据将会被已有的异步写操作写入连接中。

	}
Beispiel #13
0
static void _sock_dispatch(eventloop_t *loop, event_t *ev) {
	(void)loop;
	socket_t *sock = container_of(ev, socket_t, ev);
	stream.set_mask(sock->istm, 0);

	if ((ev->mask & (EVMASK_WRITE | EVMASK_ERROR)) == EVMASK_WRITE) {
		if (try_write(sock)) {
			ev->mask |= EVMASK_ERROR;
		}
	}
	if ((ev->mask & (EVMASK_READ | EVMASK_ERROR)) == EVMASK_READ) {
		if (try_read(sock)) {
			ev->mask |= EVMASK_ERROR;
		}
	}

	sock->cb(sock, ev->mask, ev->ud);
}
Beispiel #14
0
void otudp_write(OTUDP *x, long size, long bufferPointer) {
		
	if (!(x->o_writer)) {
		error("otudp read objects can't write!  Get a grip!");
		return;
	}
	
	if (!(x->o_ready)) {
		if (x->o_udp_ep == 0) {
			error("otudp: Can't send a packet yet; the endpoint hasn't been created yet.");
		} else {
			error("otudp: Can't send a packet yet; the endpoint hasn't been bound yet.");
		}
		return;
	}
	
	try_write(x, size, (void *) bufferPointer);	
}
Beispiel #15
0
static void transmit(int fd, const char* fd_path)
{
	try_write(fd, fd_path, 0xF7);
	try_write(fd, fd_path, 0xFF);
	unsigned char c;
	while ( try_read(0, "stdin", &c) )
	{
		if ( c == 0xF7 )
		{
			try_write(fd, fd_path, 0xF7);
			try_write(fd, fd_path, 0xFD);
			continue;
		}
		try_write(fd, fd_path, c);
	}
	try_write(fd, fd_path, 0xF7);
	try_write(fd, fd_path, 0xFE);
}
Beispiel #16
0
int net_recv_data(struct net_if *iface, struct net_buf *buf)
{
	struct net_buf *frag;

	SYS_LOG_DBG("Got data, buf %p, len %d frags->len %d",
		    buf, buf->len, net_buf_frags_len(buf));

	frag = net_buf_frag_last(buf);

	/**
	 * Add length 1 byte, do not forget to reserve it
	 */
	net_buf_push_u8(frag, net_buf_frags_len(buf) - 1);

	hexdump("<", frag->data, net_buf_frags_len(buf));

	try_write(WPANUSB_ENDP_BULK_IN, frag->data, net_buf_frags_len(buf));

	net_nbuf_unref(buf);

	return 0;
}
Beispiel #17
0
static int tx(struct net_buf *pkt)
{
	struct net_buf *buf = net_buf_frag_last(pkt);
	uint8_t seq = net_buf_pull_u8(buf);
	int retries = 3;
	int ret;

	SYS_LOG_DBG("len %d seq %u", buf->len, seq);

	do {
		ret = radio_api->tx(ieee802154_dev, pkt);
	} while (ret && retries--);

	if (ret) {
		SYS_LOG_ERR("Error sending data, seq %u", seq);
		/* Send seq = 0 for unsuccessful send */
		seq = 0;
	}

	try_write(WPANUSB_ENDP_BULK_IN, &seq, sizeof(seq));

	return ret;
}
Beispiel #18
0
int server_try_send(server* s, void const* data, unsigned size)
{
  return try_write(s->fd, data, size);
}
Beispiel #19
0
 /// write record at current offset
 void push_back(const data_t& a_data) {
     if (try_write(a_data)) return;
     base::flush();
     if (try_write(a_data)) return;
     throw runtime_error("encode error", "short buffer: ", base::capacity());
 }
Beispiel #20
0
void run() {
	long time, delta;
	int ret, cli_idx, cli;
	nfds_t nfds;

	if (allocate_mem() < 0) {
		free_mem();
		return;
	}

	cli_cnt = 0;

	nfds = 2;
	fd_all[0].fd = pcap_fd;
	fd_all[0].events = POLLIN;
	fd_all[1].fd = listenfd;
	fd_all[1].events = POLLIN;

	for (cli = 0; cli < max_client; ++cli)
		avai_no[cli] = max_client - cli - 1;
	avai_cnt = max_client;

	result.item[max_query - 1].next = -1;
	for (ret = max_query - 2; ret >= 0; --ret)
		result.item[ret].next = ret + 1;
	result.avai = 0;

	waiting.item[max_query - 1].next = -1;
	for (ret = max_query - 2; ret >= 0; --ret)
		waiting.item[ret].next = ret + 1;
	waiting.avai = 0;
	waiting.head = -1;

	for (cli = 0; cli < max_client; ++cli) {
		in_buffer[cli].len = 0;
		in_buffer[cli].newline = in_buffer[cli].buf;
		out_buffer[cli].head = 0;
		out_buffer[cli].tail = 0;
		out_buffer[cli].tot = 0;
		pending[cli].in = -1;
		pending[cli].out = -1;
	}

	fprintf(stderr, "max_client: %d, max_query: %d. Exceeded will be rejected.\n", max_client, max_query);
	time = -1;
	while (running) {
		pop_waiting();
		if (time == -1)
			delta = 1000;
		else
			delta = time - gettime();
		while (delta >= 0) {
			for (cli_idx = 0; cli_idx < cli_cnt; ++cli_idx) {
				cli = cli_no[cli_idx];
				push_waiting(cli);
				if ((fd_cli[cli_idx].events & POLLIN) == 0 && in_buffer[cli].len != GUK_MAX_QUERY_LEN)
					fd_cli[cli_idx].events |= POLLIN;
			}
			if ((ret = poll(fd_all, nfds, delta + 1)) > 0) {
				if (fd_all[0].revents == POLLIN)
					gk_cm_read_cap();

				ret = (fd_all[1].revents == POLLIN); // ret here stand for new connection available

				nfds -= 2;
				for (cli_idx = 0; cli_idx < cli_cnt; ++cli_idx) {
					if (fd_cli[cli_idx].revents & (POLLERR | POLLNVAL | POLLHUP)) {
						fprintf(stderr, "Connection closed or broken.");
						close_client(cli_idx);
						--nfds;
						continue;
					}
					cli = cli_no[cli_idx];
					if (fd_cli[cli_idx].revents & POLLOUT) {
						do {
							pop_result(cli);
						} while (try_write(cli));
						if (all_written(cli))
							fd_cli[cli_idx_of[cli]].events &= ~POLLOUT;
						last_act[cli] = gettime();
					}
					if (fd_cli[cli_idx].revents & POLLIN) {
						while (try_read(cli)) {
							push_waiting(cli);
						}
						if (in_buffer[cli].len == GUK_MAX_QUERY_LEN)
							fd_cli[cli_idx].events &= ~POLLIN;
						last_act[cli] = gettime();
					}
					else if (ret && is_idle(cli) && gettime() - last_act[cli] >= (GUK_SERV_TIMEOUT * 1000)) {
						fprintf(stderr, "Client timeout. ");
						close_client(cli_idx);
						--nfds;
					}
				}
				/* remove closed clients */
				for (cli_idx = 0; cli_cnt > (int)nfds; ) {
					while (cli_idx < (int)nfds && fd_cli[cli_idx].fd >= 0)
						++cli_idx;
					if (cli_idx == (int)nfds) {
						cli_cnt = cli_idx;
						break;
					}
					else {
						while (fd_cli[--cli_cnt].fd < 0);
						memcpy(fd_cli + cli_idx, fd_cli + cli_cnt, sizeof(struct pollfd));
						cli_idx_of[(cli_no[cli_idx] = cli_no[cli_cnt])] = cli_idx;
					}
				}
				nfds += 2;
				if (ret)
					while (cli_cnt < max_client && accept_client() == 0)
						++nfds;
			}
			else if (ret < 0)
				perror("poll");

			time = gk_cm_conn_next_time();
			if (time == -1)
				delta = 1000;
			else
				delta = time - gettime();
		}
		time = gk_cm_conn_step();
	}

	gk_cm_finalize();
	for (cli_idx = 0; cli_idx < cli_cnt; ++cli_idx) {
		cli = cli_no[cli_idx];
		do {
			pop_result(cli);
		} while (try_write(cli));
	}
	for (cli_idx = 0; cli_idx < cli_cnt; ++cli_idx)
		close_client(cli_idx);
	free_mem();
}