void on_new_connection(uv_stream_t *server, int status) { uv_tcp_t *client; if (status < 0) { fprintf(stderr, "New connection error %s\n", uv_strerror(status)); return; } client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, client); if (uv_accept(server, (uv_stream_t*)client) == 0) { uv_read_start((uv_stream_t*)client, alloc_buffer, echo_read); } else { uv_close((uv_handle_t*)client, NULL); } }
static void response_error(uv_handle_t* handle, int status_code, const char* status, const char* message) { char bufline[1024]; const char* ptr = message ? message : status; int nbuf = sprintf(bufline, "HTTP/1.0 %d %s\r\n" "Content-Length: %d\r\n" "Content-Type: text/plain; charset=UTF-8;\r\n" "\r\n" "%s", status_code, status, (int) strlen(ptr), ptr); uv_write_t* write_req = malloc(sizeof(uv_write_t)); if (write_req == NULL) { fprintf(stderr, "Allocate error: %s\n", strerror(errno)); return; } uv_buf_t buf = uv_buf_init(bufline, nbuf); int r = uv_write(write_req, (uv_stream_t*) handle, &buf, 1, on_write_error); if (r) { fprintf(stderr, "Write error %s: %s\n", uv_err_name(r), uv_strerror(r)); } }
int Client::resolve(const char *host) { setState(HostLookupState); m_expire = 0; m_recvBufPos = 0; if (m_failures == -1) { m_failures = 0; } const int r = uv_getaddrinfo(uv_default_loop(), &m_resolver, Client::onResolved, host, nullptr, &m_hints); if (r) { if (!m_quiet) { LOG_ERR("[%s:%u] getaddrinfo error: \"%s\"", host, m_url.port(), uv_strerror(r)); } return 1; } return 0; }
static MVMObject * socket_accept(MVMThreadContext *tc, MVMOSHandle *h) { MVMIOSyncSocketData *data = (MVMIOSyncSocketData *)h->body.data; while (!data->accept_server) { if (tc->loop != data->ss.handle->loop) { MVM_exception_throw_adhoc(tc, "Tried to accept() on a socket from outside its originating thread"); } uv_ref((uv_handle_t *)data->ss.handle); MVM_gc_mark_thread_blocked(tc); uv_run(tc->loop, UV_RUN_DEFAULT); MVM_gc_mark_thread_unblocked(tc); } /* Check the accept worked out. */ if (data->accept_status < 0) { MVM_exception_throw_adhoc(tc, "Failed to listen: unknown error"); } else { uv_tcp_t *client = MVM_malloc(sizeof(uv_tcp_t)); uv_stream_t *server = data->accept_server; int r; uv_tcp_init(tc->loop, client); data->accept_server = NULL; if ((r = uv_accept(server, (uv_stream_t *)client)) == 0) { MVMOSHandle * const result = (MVMOSHandle *)MVM_repr_alloc_init(tc, tc->instance->boot_types.BOOTIO); MVMIOSyncSocketData * const data = MVM_calloc(1, sizeof(MVMIOSyncSocketData)); data->ss.handle = (uv_stream_t *)client; data->ss.encoding = MVM_encoding_type_utf8; MVM_string_decode_stream_sep_default(tc, &(data->ss.sep_spec)); result->body.ops = &op_table; result->body.data = data; return (MVMObject *)result; } else { uv_close((uv_handle_t*)client, NULL); MVM_free(client); MVM_exception_throw_adhoc(tc, "Failed to accept: %s", uv_strerror(r)); } } }
int rxs_sender_send(rxs_sender* net, uint8_t* buffer, uint32_t nbytes) { char* tmp = NULL; int r; uv_buf_t b; uv_udp_send_t* req = NULL; if (!net) { return -1; } if (!buffer) { return -2; } if (!nbytes) { return -3; } /* we should copy the buf here... */ tmp = (char*)malloc(nbytes); if (NULL == tmp) { printf("Error: cannot allocate BUF.\n"); return -4; } memcpy(tmp, buffer, nbytes); /* @todo - the tests of libuv use this, but I'm pretty sure we want to allocate on the heap here */ b = uv_buf_init((char*)tmp, nbytes); req = (uv_udp_send_t*)malloc(sizeof(uv_udp_send_t)); if (NULL == req) { printf("Error: cannot allocate REQ.\n"); return -4; } memset(req, 0x00, sizeof(uv_udp_send_t)); req->data = tmp; r = uv_udp_send(req, &net->send_sock, &b, 1, (const struct sockaddr*)&net->saddr, send_cb); if (r != 0) { printf("Error: cannot send udp: %s\n", uv_strerror(r)); /* @todo -> shouldn't we free the allocated buffer here? */ return -1; } return 0; }
static void remote_connect_cb(uv_connect_t *req, int status) { struct remote_context *remote = (struct remote_context *)req->data; struct client_context *client = remote->client; if (status == 0) { reset_timer(remote); client->stage = XSTAGE_FORWARD; remote->stage = XSTAGE_FORWARD; request_to_server(remote); receive_from_remote(remote); } else { if (status != UV_ECANCELED) { char addrbuf[INET6_ADDRSTRLEN + 1]; ip_name(&server_addr, addrbuf, sizeof(addrbuf)); logger_log(LOG_ERR, "connect to %s failed: %s", addrbuf, uv_strerror(status)); close_client(client); close_remote(remote); } } }
LUALIB_API int luaopen_luv (lua_State *L) { uv_loop_t* loop; int ret; // Setup the uv_loop meta table for a proper __gc luaL_newmetatable(L, "uv_loop.meta"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, loop_gc); lua_settable(L, -3); loop = lua_newuserdata(L, sizeof(*loop)); ret = uv_loop_init(loop); if (ret < 0) { return luaL_error(L, "%s: %s\n", uv_err_name(ret), uv_strerror(ret)); } // setup the metatable for __gc luaL_getmetatable(L, "uv_loop.meta"); lua_setmetatable(L, -2); // Tell the state how to find the loop. lua_pushstring(L, "uv_loop"); lua_insert(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); lua_pop(L, 1); // Tell the loop how to find the state. loop->data = L; luv_req_init(L); luv_handle_init(L); luv_thread_init(L); luv_work_init(L); luaL_newlib(L, luv_functions); luv_constants(L); lua_setfield(L, -2, "constants"); return 1; }
void UvTcpServerStream::HandleRead(ssize_t nread, const uv_buf_t* buf) { if (nread > 0) { std::vector<uint8_t> targetBuf(nread); memcpy(&targetBuf[0], buf->base, targetBuf.size()); if (GetReadCallback()) { GetReadCallback()(targetBuf); } } else if (nread < 0) { // hold a reference to ourselves while in this scope fwRefContainer<UvTcpServerStream> tempContainer = this; trace("read error: %s\n", uv_strerror(nread)); Close(); } }
int server_run(const server_config *cf, uv_loop_t *loop) { struct addrinfo hints; server_state state; int err; memset(&state, 0, sizeof(state)); state.servers = NULL; state.config = *cf; state.loop = loop; /* Resolve the address of the interface that we should bind to. * The getaddrinfo callback starts the server and everything else. */ memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; err = uv_getaddrinfo(loop, &state.getaddrinfo_req, do_bind, cf->bind_host, NULL, &hints); if (err != 0) { pr_err("getaddrinfo: %s", uv_strerror(err)); return err; } /* Start the event loop. Control continues in do_bind(). */ if (uv_run(loop, UV_RUN_DEFAULT)) { abort(); } /* Please Valgrind. */ uv_loop_delete(loop); free(state.servers); return 0; }
static void eventpool_update_poll(uv_poll_t *req) { struct uv_custom_poll_t *custom_poll_data = NULL; struct iobuf_t *send_io = NULL; int action = 0, r = 0; custom_poll_data = req->data; if(custom_poll_data == NULL || uv_is_closing((uv_handle_t *)req)) { return; } send_io = &custom_poll_data->send_iobuf; if(custom_poll_data->doread == 1) { action |= UV_READABLE; } if(custom_poll_data->dowrite == 1) { action |= UV_WRITABLE; } if(custom_poll_data->doclose == 1 && send_io->len == 0) { custom_poll_data->doclose = 2; if(custom_poll_data->close_cb != NULL) { custom_poll_data->close_cb(req); } if(!uv_is_closing((uv_handle_t *)req)) { uv_poll_stop(req); } } else if(custom_poll_data->action != action && action > 0) { uv_poll_start(req, action, uv_custom_poll_cb); if(r != 0) { /*LCOV_EXCL_START*/ logprintf(LOG_ERR, "uv_poll_start: %s", uv_strerror(r)); return; /*LCOV_EXCL_STOP*/ } custom_poll_data->action = action; } }
int main() { loop = uv_default_loop(); char* args[3]; args[0] = "sleep"; args[1] = "100"; args[2] = NULL; options.exit_cb = NULL; options.file = "sleep"; options.args = args; options.flags = UV_PROCESS_DETACHED; if (uv_spawn(loop, &child_req, options)) { fprintf(stderr, "%s\n", uv_strerror(uv_last_error(loop))); return 1; } fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid); uv_unref((uv_handle_t*) &child_req); return uv_run(loop, UV_RUN_DEFAULT); }
int DirWatcher::shutdown() { int r = 0; if (NULL == loop) { RX_WARNING("Asking to shutdown, but loop is NULL. Did you call init()?"); return -1; } /* stop listening for dir changes.*/ r = uv_fs_event_stop(&fs_event); if (0 != r) { RX_ERROR("Error while trying to stop the fs_event: %s", uv_strerror(r)); } directory.clear(); loop = NULL; user = NULL; on_rename = NULL; return 0; }
void send_head_request(uv_connect_t *req, int status) { if (status != 0) { printf("on connect failed: %s\n", uv_strerror(status)); return; } uv_read_start(req->handle, on_alloc, on_head_read); task *task = (struct task*)req->handle->data; http_request *request = task->head_request; http_set_on_header_field(request, on_header_field); http_set_on_header_value(request, on_header_value); http_set_on_headers_complete(request, on_headers_complete_close); http_request_set_method(request, HTTP_HEAD); http_send_request(request); uv_fs_t fs; task->fd = uv_fs_open(req->handle->loop, &fs, task->name, O_CREAT | O_RDWR, 0777, NULL); }
static int luv_stream_accept(lua_State *L) { luaL_checktype(L, 1, LUA_TUSERDATA); luv_object_t* self = (luv_object_t*)lua_touserdata(L, 1); luv_object_t* conn = (luv_object_t*)lua_touserdata(L, 2); luv_state_t* curr = luvL_state_self(L); if (self->count) { self->count--; int rv = uv_accept(&self->h.stream, &conn->h.stream); if (rv) { uv_err_t err = uv_last_error(self->h.stream.loop); lua_settop(L, 0); lua_pushnil(L); lua_pushstring(L, uv_strerror(err)); return 2; } return 1; } self->flags |= LUV_OWAITING; return luvL_cond_wait(&self->rouse, curr); }
int main(int argc, char **argv) { struct addrinfo hints; int err; uv_getaddrinfo_t getaddrinfo_req; if (argc != 2) { printf("UNKNOWN args\n"); return 1; } memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; err = uv_getaddrinfo(uv_default_loop(), &getaddrinfo_req, address_cb, argv[1], NULL, &hints); if (err != 0) { printf("getaddrinfo: %s", uv_strerror(err)); return err; } /* Start the event loop. Control continues in do_bind(). */ if (uv_run(uv_default_loop(), UV_RUN_DEFAULT)) { abort(); } /* Please Valgrind. */ uv_loop_delete(uv_default_loop()); return 0; }
void spawn_child(int detach) { uv_stdio_container_t stdio[3]; int i; options.stdio_count = 3; if (detach) { for (i = 0; i < options.stdio_count; i++) { stdio[i].flags = UV_IGNORE; } } else { for (i = 0; i < options.stdio_count; i++) { stdio[i].flags = UV_INHERIT_FD; stdio[i].data.fd = i; } } options.file = opts.child_args[0]; options.args = opts.child_args; options.stdio = stdio; options.env = environ; options.exit_cb = detach ? NULL : spawn_cb; if (detach) options.flags = UV_PROCESS_DETACHED; if (uv_spawn(loop, &child_req, options)) { fprintf(stderr, "Error %s\n", uv_err_name(uv_last_error(loop))); fprintf(stderr, "%s\n", uv_strerror(uv_last_error(loop))); } if (detach) { uv_unref((uv_handle_t*)&child_req); return; } if (opts.pidname != NULL) { write_pid_file(child_req.pid, opts.pidname); } }
static void on_connection(uv_stream_t* server, int status) { uv_stream_t* stream; int r; if (status != 0) { fprintf(stderr, "Connect error: %s: %s\n", uv_err_name(status), uv_strerror(status)); return; } stream = malloc(sizeof(uv_tcp_t)); if (stream == NULL) { fprintf(stderr, "Allocate error: %s\n", strerror(errno)); return; } r = uv_tcp_init(loop, (uv_tcp_t*) stream); if (r) { fprintf(stderr, "Socket creation error: %s: %s\n", uv_err_name(r), uv_strerror(r)); return; } r = uv_tcp_simultaneous_accepts((uv_tcp_t*) stream, 1); if (r) { fprintf(stderr, "Flag error: %s: %s\n", uv_err_name(r), uv_strerror(r)); return; } r = uv_accept(server, stream); if (r) { fprintf(stderr, "Accept error: %s: %s\n", uv_err_name(r), uv_strerror(r)); return; } r = uv_tcp_nodelay((uv_tcp_t*) stream, 1); if (r) { fprintf(stderr, "Flag error: %s: %s\n", uv_err_name(r), uv_strerror(r)); return; } r = uv_read_start(stream, on_alloc, on_read); if (r) { fprintf(stderr, "Read error: %s: %s\n", uv_err_name(r), uv_strerror(r)); uv_close((uv_handle_t*) stream, on_close); } }
void tcp_connection::on_uv_read(::ssize_t nread, const uv_buf_t* buf) { if (m_is_closing) return; if (nread == 0) return; // Data received. if (nread > 0) { // Update the buffer data length. m_buffer_data_len += (size_t)nread; // Notify the subclass. user_on_tcp_connection_read(); } // Client disconneted. else if (nread == UV_EOF || nread == UV_ECONNRESET) { osd_printf_verbose("connection closed by peer, closing server side\n"); m_is_closed_by_peer = true; // Close server side of the connection. close(); } // Some error. else { osd_printf_verbose("read error, closing the connection: %s\n", uv_strerror(nread)); m_has_error = true; // Close server side of the connection. close(); } }
/* Creates the allocator data structure with bins. */ MVMFixedSizeAlloc * MVM_fixed_size_create(MVMThreadContext *tc) { int init_stat; #ifdef MVM_VALGRIND_SUPPORT int bin_no; #endif MVMFixedSizeAlloc *al = MVM_malloc(sizeof(MVMFixedSizeAlloc)); al->size_classes = MVM_calloc(MVM_FSA_BINS, sizeof(MVMFixedSizeAllocSizeClass)); if ((init_stat = uv_mutex_init(&(al->complex_alloc_mutex))) < 0) MVM_exception_throw_adhoc(tc, "Failed to initialize mutex: %s", uv_strerror(init_stat)); al->freelist_spin = 0; al->free_at_next_safepoint_overflows = NULL; /* All other places where we use valgrind macros are very likely * thrown out by dead code elimination. Not 100% sure about this, * so we ifdef it out. */ #ifdef MVM_VALGRIND_SUPPORT for (bin_no = 0; bin_no < MVM_FSA_BINS; bin_no++) VALGRIND_CREATE_MEMPOOL(&al->size_classes[bin_no], MVM_FSA_REDZONE_BYTES, 0); #endif return al; }
static void read_cb(uv_stream_t *uv_stream, ssize_t len, const uv_buf_t *buf) { rig_pb_stream_t *stream = uv_stream->data; if (len < 0) { c_warning("stream error: %s", uv_strerror(len)); rig_pb_stream_disconnect(stream); return; } if (len == UV_EOF) { rig_pb_stream_disconnect(stream); return; } if (len > 0) stream->read_callback(stream, (uint8_t *)buf->base, len, stream->read_data); if (buf->base) c_free(buf->base); }
static int do_read_request(client_ctx *cx) { conn *incoming; size_t size; incoming = &cx->incoming; if (incoming->result < 0) { pr_err("read error: %s", uv_strerror(incoming->result)); return do_kill(cx); } size = (size_t)incoming->offset; if (size >= (size_t)incoming->req_size + 2) { return do_process_request(cx); } else { conn_read(incoming); } return s_read_request; }
void TcpConnection::Setup(Listener* listener, struct sockaddr_storage* localAddr, const std::string &localIP, uint16_t localPort) { MS_TRACE(); int err; // Set the UV handle. err = uv_tcp_init(DepLibUV::GetLoop(), this->uvHandle); if (err) { delete this->uvHandle; this->uvHandle = nullptr; MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err)); } // Set the listener. this->listener = listener; // Set the local address. this->localAddr = localAddr; this->localIP = localIP; this->localPort = localPort; }
LUALIB_API int luaopen_luv (lua_State *L) { uv_loop_t* loop; int ret; loop = lua_newuserdata(L, sizeof(*loop)); ret = uv_loop_init(loop); if (ret < 0) { return luaL_error(L, "%s: %s\n", uv_err_name(ret), uv_strerror(ret)); } // Tell the state how to find the loop. lua_pushstring(L, "uv_loop"); lua_insert(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); // Tell the loop how to find the state. loop->data = L; luv_req_init(L); luv_handle_init(L); luaL_newlib(L, luv_functions); return 1; }
void tun_to_tcp(uint8_t *buf, int len, uv_stream_t *stream) { uint8_t *hdr = malloc(HEADER_BYTES); write_size(hdr, len); uv_write_t *req = malloc(sizeof(*req) + sizeof(uv_buf_t) * 2); uv_buf_t *outbuf1 = (uv_buf_t *) (req + 1); uv_buf_t *outbuf2 = outbuf1 + 1; *outbuf1 = uv_buf_init((char *) hdr, HEADER_BYTES); *outbuf2 = uv_buf_init((char *) buf, len); uv_buf_t bufs[2] = { *outbuf1, *outbuf2, }; int rc = uv_write(req, stream, bufs, 2, send_cb); if (rc) { logger_log(LOG_ERR, "TCP Write error: %s", uv_strerror(rc)); free(buf); } }
/* lua call spec: Success: status(true), nil = timer:start(timeout) Failure: status(false), error message = timer:start(timeout) */ static int start_user_timer(lua_State* l_thread) { LUA_GET_TIMER_OR_ERROR(l_thread, 1, timer); if (timer->state != INIT) { /* Timer is already started by another lua thread */ return error_to_lua(l_thread, "Timer already in use by another thread"); } int timeout = lua_tointeger(l_thread, 2); if (timeout <= 0) { return error_to_lua(l_thread, "Invalid timeout value %d specified", timeout); } int rc = uv_timer_start(&timer->handle, on_user_timer_timeout, timeout, 0); if (rc) { close_timer(timer); return error_to_lua(l_thread, "Error starting timer: %s", uv_strerror(rc)); } timer->state = TICKING; lua_pushboolean(l_thread, 1); return 1; }
static void remote_connect_cb(uv_connect_t *req, int status) { struct remote_context *remote = (struct remote_context *)req->data; struct client_context *client = remote->client; if (status == 0) { reset_timer(remote); client->stage = XSTAGE_FORWARD; remote->stage = XSTAGE_FORWARD; receive_from_client(client); receive_from_remote(remote); } else { if (status != UV_ECANCELED) { // TODO: handle RST logger_log(LOG_ERR, "connect to %s failed: %s", client->target_addr, uv_strerror(status)); close_client(client); close_remote(remote); } } }
void MVM_file_delete(MVMThreadContext *tc, MVMString *f) { uv_fs_t req; char * const a = MVM_string_utf8_encode_C_string(tc, f); #ifdef _WIN32 const int r = MVM_platform_unlink(a); if( r < 0 && r != ENOENT) { MVM_free(a); MVM_exception_throw_adhoc(tc, "Failed to delete file: %d", errno); } #else const int r = uv_fs_unlink(tc->loop, &req, a, NULL); if( r < 0 && r != UV_ENOENT) { MVM_free(a); MVM_exception_throw_adhoc(tc, "Failed to delete file: %s", uv_strerror(req.result)); } #endif MVM_free(a); }
void on_read(uv_fs_t* req) { ssize_t size_read = req->result; read_write_op_t* read_write_op = req->data; uv_fs_req_cleanup(req); if (size_read < 0) { fprintf(stderr, "Error when reading: %s\n", uv_strerror(uv_last_error(uv_default_loop()))); } else if (size_read == 0) { uv_fs_t close_req; if (read_write_op && read_write_op->buff) { free(read_write_op->buff); read_write_op->buff = NULL; } uv_fs_close(uv_default_loop(), &close_req, read_write_op->read_fd, NULL); } else { uv_fs_t write_req; write_req.data = read_write_op; uv_fs_write(uv_default_loop(), &write_req, 1, read_write_op->buff, size_read, -1, on_write); } }
/* _http_conn_read_cb(): server read callback. */ static void _http_conn_read_cb(uv_stream_t* tcp_u, ssize_t siz_i, uv_buf_t buf_u) { u2_hcon* hon_u = (u2_hcon*)(void*) tcp_u; u2_lo_open(); { if ( siz_i < 0 ) { uv_err_t las_u = uv_last_error(u2L); if ( UV_EOF != las_u.code ) { uL(fprintf(uH, "http: read: %s\n", uv_strerror(las_u))); } _http_conn_dead(hon_u); } else { if ( !hon_u->ruc_u ) { hon_u->ruc_u = _http_req_new(hon_u); } if ( siz_i != http_parser_execute(hon_u->ruc_u->par_u, &_http_settings, (c3_c*)buf_u.base, siz_i) ) { uL(fprintf(uH, "http: parse error\n")); _http_conn_dead(hon_u); } } if ( buf_u.base ) { free(buf_u.base); } } u2_lo_shut(u2_yes); }
int luv_tcp_getpeername(lua_State* L) { int before = lua_gettop(L); uv_tcp_t* handle = (uv_tcp_t*)luv_checkudata(L, 1, "tcp"); int port = 0; char ip[INET6_ADDRSTRLEN]; int family; struct sockaddr_storage address; int addrlen = sizeof(address); if (uv_tcp_getpeername(handle, (struct sockaddr*)(&address), &addrlen)) { uv_err_t err = uv_last_error(luv_get_loop(L)); return luaL_error(L, "tcp_getpeername: %s", uv_strerror(err)); } family = address.ss_family; if (family == AF_INET) { struct sockaddr_in* addrin = (struct sockaddr_in*)&address; uv_inet_ntop(AF_INET, &(addrin->sin_addr), ip, INET6_ADDRSTRLEN); port = ntohs(addrin->sin_port); } else if (family == AF_INET6) { struct sockaddr_in6* addrin6 = (struct sockaddr_in6*)&address; uv_inet_ntop(AF_INET6, &(addrin6->sin6_addr), ip, INET6_ADDRSTRLEN); port = ntohs(addrin6->sin6_port); } lua_newtable(L); lua_pushnumber(L, port); lua_setfield(L, -2, "port"); lua_pushnumber(L, family); lua_setfield(L, -2, "family"); lua_pushstring(L, ip); lua_setfield(L, -2, "address"); assert(lua_gettop(L) == before + 1); return 1; }