コード例 #1
0
ファイル: resolve_address_uv.c プロジェクト: royalharsh/grpc
static int retry_named_port_failure(int status, request *r,
                                    uv_getaddrinfo_cb getaddrinfo_cb) {
  if (status != 0) {
    // This loop is copied from resolve_address_posix.c
    char *svc[][2] = {{"http", "80"}, {"https", "443"}};
    for (size_t i = 0; i < GPR_ARRAY_SIZE(svc); i++) {
      if (strcmp(r->port, svc[i][0]) == 0) {
        int retry_status;
        uv_getaddrinfo_t *req = gpr_malloc(sizeof(uv_getaddrinfo_t));
        req->data = r;
        retry_status = uv_getaddrinfo(uv_default_loop(), req, getaddrinfo_cb,
                                      r->host, svc[i][1], r->hints);
        if (retry_status < 0 || getaddrinfo_cb == NULL) {
          // The callback will not be called
          gpr_free(req);
        }
        return retry_status;
      }
    }
  }
  /* If this function calls uv_getaddrinfo, it will return that function's
     return value. That function only returns numbers <=0, so we can safely
     return 1 to indicate that we never retried */
  return 1;
}
コード例 #2
0
ファイル: resolve_address_uv.c プロジェクト: gnirodi/grpc
static grpc_error *blocking_resolve_address_impl(
    const char *name, const char *default_port,
    grpc_resolved_addresses **addresses) {
  char *host;
  char *port;
  struct addrinfo hints;
  uv_getaddrinfo_t req;
  int s;
  grpc_error *err;

  req.addrinfo = NULL;

  err = try_split_host_port(name, default_port, &host, &port);
  if (err != GRPC_ERROR_NONE) {
    goto done;
  }

  /* Call getaddrinfo */
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;     /* ipv4 or ipv6 */
  hints.ai_socktype = SOCK_STREAM; /* stream socket */
  hints.ai_flags = AI_PASSIVE;     /* for wildcard IP address */

  s = uv_getaddrinfo(uv_default_loop(), &req, NULL, host, port, &hints);
  err = handle_addrinfo_result(s, req.addrinfo, addresses);

done:
  gpr_free(host);
  gpr_free(port);
  if (req.addrinfo) {
    uv_freeaddrinfo(req.addrinfo);
  }
  return err;
}
コード例 #3
0
ファイル: client.c プロジェクト: yquant/ws-node
int wsn_client_start(wsn_client_ctx_t *client)
{
  int err = 0;
  
  if (wsn_is_pipe(client->conf)) {
    err = wsn_client_start_connect_(client);
    if (err) {
      uv_stop(client->loop);
    }
    return err;
  }
  
  struct addrinfo hints;

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

  connect_timer_reset_(client);

  err = uv_getaddrinfo(client->loop,
                       &client->getaddrinfo_req,
                       on_get_host_addrs_,
                       client->conf->host,
                       NULL,
                       &hints);
  if (err) {
    wsn_report_err(WSN_ERR_GET_ADDR_INFO,
                   "Failed to start client to (\"%s\"), getaddrinfo error: %s",
                   client->conf->host, uv_strerror(err));
    err = WSN_ERR_GET_ADDR_INFO;
  }
  return err;
}
コード例 #4
0
void
rig_pb_stream_set_tcp_transport(rig_pb_stream_t *stream,
                                const char *hostname,
                                const char *port)
{
    uv_loop_t *loop = rut_uv_shell_get_loop(stream->shell);
    struct addrinfo hints;

    c_return_if_fail(stream->type == STREAM_TYPE_DISCONNECTED);
    c_return_if_fail(stream->hostname == NULL);
    c_return_if_fail(stream->port == NULL);
    c_return_if_fail(stream->resolving == false);

    hints.ai_family = PF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;

    stream->hostname = c_strdup(hostname);
    stream->port = c_strdup(port);

    rut_object_ref(stream); /* keep alive during resolve request */
    stream->resolving = true;
    uv_getaddrinfo(loop, &stream->resolver, on_address_resolved,
                   hostname, port, &hints);
}
コード例 #5
0
bool HTTPRequest::send() {
    // CREATE HTTP REQUEST
    std::string request = getAsString();
    std::copy(request.begin(), request.end(), std::back_inserter(out_buffer));

    // HINTS FOR SOCKET
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;

    // SECURE CONNECTION?
    std::string port = "80";
    if(is_secure) {
        port = "443";
    }

    int r = uv_getaddrinfo(loop, &resolver_req, httpreq_on_resolved, host.c_str(), port.c_str(), &hints);
    if(r) {
        printf("ERROR: cannot resolve addres: %s\n", uv_err_name(uv_last_error(loop)));
        return false;
    }
    return true;
}
コード例 #6
0
ファイル: task.c プロジェクト: Marcus366/campus-downloader
struct task*
create_task(downloader *dler, const char *url, const char *fullname)
{
	struct task *task = (struct task*)malloc(sizeof(struct task));
	
	task->dler          = dler;
	task->next          = dler->tasks;
	dler->tasks         = task;

	task->head_request  = http_request_new(task);

	task->name          = strdup(fullname);
	task->cur_size      = 0;

	task->blocks        = NULL;

	task->start_time    = uv_now(dler->mainloop);
	task->consumed_time = 0;

	task->last_step_time = task->start_time;
	task->last_step_size = task->cur_size;

	if (strncmp(url, "http://", 7) == 0) {
		task->url = http_parse_url(url);
	} else {
		int   len     = strlen(url);
		char *new_url = (char*)calloc(1, len + 7 + 1);
		memcpy(new_url, "http://", 7);
		memcpy(new_url + 7, url, len);

		task->url = http_parse_url(new_url);

		free(new_url);
	}

	if (task->url == NULL) {
		printf("parse url failed\n");
		exit(-1);
	}

	/* change host to a zero-terminated string for uv_getaddrinfo() */
	uv_buf_t buf = http_url_get_field(task->url, UF_HOST);
	char *host = (char*)calloc(1, buf.len + 1);
	memcpy(host, buf.base, buf.len);

	struct addrinfo hints;
	hints.ai_family   = PF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags    = 0;

	uv_getaddrinfo_t *getaddrinfo = (uv_getaddrinfo_t*)malloc(sizeof(uv_getaddrinfo_t));
	getaddrinfo->data = task;

	uv_getaddrinfo(dler->mainloop, getaddrinfo, on_resolved, host, NULL, &hints);

	free(host);

	return task;
}
コード例 #7
0
ファイル: rust_uv.cpp プロジェクト: devmario/rust
extern  "C" int
rust_uv_getaddrinfo(uv_loop_t* loop, uv_getaddrinfo_t* handle,
                    uv_getaddrinfo_cb cb,
                    char* node, char* service,
                    addrinfo* hints) {
    return uv_getaddrinfo(loop, handle, cb, node, service, hints);
}
コード例 #8
0
bool HTTPConnection::connect(httpconnection_event_callback eventCB,  /* gets called when a socket event occurs */
                             void* eventUser)                        /* gets passed into eventCB */

 {

  int r = uv_tcp_init(loop, sock);
  if(r) {
    RX_ERROR("Cannot init socket");
    return false;
  }

  cb_event = eventCB;
  cb_event_user = eventUser;

  struct addrinfo hints;
  hints.ai_family = PF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_flags = 0;
 
  RX_VERBOSE("Connecting to: %s", host.c_str());
  r = uv_getaddrinfo(loop, &resolver_req, httpconnection_on_resolved, 
                     host.c_str(), port.c_str(), &hints);

  if(r) {
    RX_ERROR("cannot uv_tcp_init(): %s", uv_strerror(uv_last_error(loop)));
    return false;
  }
    
  return true;
}
コード例 #9
0
ファイル: net.c プロジェクト: flybird119/uv-mongo
int
net_resolve(net_t * net) {
  net_ai hints;
  int ret;
  char buf[6];

  snprintf(buf, sizeof(buf), "%d", net->port);
  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  net->resolver = malloc(sizeof(uv_getaddrinfo_t));
  if (!net->resolver) {
    /*
     * TODO(Yorkie): depent parital handles
     */
    return -1;
  }

  net->resolver->data = (void *) net;
  ret = uv_getaddrinfo(net->loop, net->resolver,
    net_resolve_cb, net->hostname, NULL, &hints);

  return ret;
}
コード例 #10
0
static void getaddrinfo_initiate(uv_getaddrinfo_t* handle) {
    int r;

    calls_initiated++;

    r = uv_getaddrinfo(loop, handle, &getaddrinfo_cb, name, NULL, NULL);
    ASSERT(r == 0);
}
コード例 #11
0
ファイル: test-thread.c プロジェクト: 1GHL/learn_libuv
static void getaddrinfo_do(struct getaddrinfo_req* req) {
  int r;

  r = uv_getaddrinfo(req->loop,
                     &req->handle,
                     getaddrinfo_cb,
                     "localhost",
                     NULL,
                     NULL);
  ASSERT(r == 0);
}
コード例 #12
0
int main() {
    loop = uv_default_loop();

    int r = uv_getaddrinfo(loop, handle, getaddrinfo_cb, name, "80", NULL);

    if (r) {
        printf("Error at dns request: %s.\n",
                uv_strerror(uv_last_error(loop)));
    }

    return 0;
}
コード例 #13
0
ファイル: jl_uv.c プロジェクト: jskDr/julia
DLLEXPORT int jl_getaddrinfo(uv_loop_t *loop, const char *host, const char *service, jl_function_t *cb)
{
    uv_getaddrinfo_t *req = (uv_getaddrinfo_t*)malloc(sizeof(uv_getaddrinfo_t));
    struct addrinfo hints;

    memset (&hints, 0, sizeof (hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags |= AI_CANONNAME;

    req->data = cb;

    return uv_getaddrinfo(loop,req,jl_uv_getaddrinfocb,host,service,&hints);
}
コード例 #14
0
ファイル: resolve_address_uv.c プロジェクト: royalharsh/grpc
static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name,
                                 const char *default_port,
                                 grpc_pollset_set *interested_parties,
                                 grpc_closure *on_done,
                                 grpc_resolved_addresses **addrs) {
  uv_getaddrinfo_t *req;
  request *r;
  struct addrinfo *hints;
  char *host;
  char *port;
  grpc_error *err;
  int s;
  err = try_split_host_port(name, default_port, &host, &port);
  if (err != GRPC_ERROR_NONE) {
    grpc_closure_sched(exec_ctx, on_done, err);
    return;
  }
  r = gpr_malloc(sizeof(request));
  r->on_done = on_done;
  r->addresses = addrs;
  r->host = host;
  r->port = port;
  req = gpr_malloc(sizeof(uv_getaddrinfo_t));
  req->data = r;

  /* Call getaddrinfo */
  hints = gpr_malloc(sizeof(struct addrinfo));
  memset(hints, 0, sizeof(struct addrinfo));
  hints->ai_family = AF_UNSPEC;     /* ipv4 or ipv6 */
  hints->ai_socktype = SOCK_STREAM; /* stream socket */
  hints->ai_flags = AI_PASSIVE;     /* for wildcard IP address */
  r->hints = hints;

  s = uv_getaddrinfo(uv_default_loop(), req, getaddrinfo_callback, host, port,
                     hints);

  if (s != 0) {
    *addrs = NULL;
    err = GRPC_ERROR_CREATE_FROM_STATIC_STRING("getaddrinfo failed");
    err = grpc_error_set_str(err, GRPC_ERROR_STR_OS_ERROR,
                             grpc_slice_from_static_string(uv_strerror(s)));
    grpc_closure_sched(exec_ctx, on_done, err);
    gpr_free(r);
    gpr_free(req);
    gpr_free(hints);
    gpr_free(host);
    gpr_free(port);
  }
}
コード例 #15
0
ファイル: resolver.hpp プロジェクト: robmccoll/cpp-driver
    static void resolve(uv_loop_t* loop, const std::string& host, int port,
                        void* data, Callback cb, struct addrinfo* hints = NULL) {
        Resolver* resolver = new Resolver(host, port, data, cb);

        std::ostringstream ss;
        ss << port;

        int rc = uv_getaddrinfo(loop, &resolver->req_, on_resolve, host.c_str(),
                                ss.str().c_str(), hints);

        if (rc != 0) {
            resolver->status_ = FAILED_BAD_PARAM;
            resolver->cb_(resolver);
            delete resolver;
        }
    }
コード例 #16
0
ファイル: resolver.hpp プロジェクト: bnbshenhui/uvpp11
 error resolve(const std::string& addr, ResolveCallback callback)
 {
   callbacks::store(get()->data, internal::uv_cid_resolve, callback);
   return error(uv_getaddrinfo(m_loop, get(),
                 [](uv_getaddrinfo_t* req, int status, struct addrinfo* res)
                 {
                   std::shared_ptr<addrinfo> res_holder(res, [](addrinfo* res)
                       {
                         uv_freeaddrinfo(res);
                       });
                   char addr[128] = {'\0'};
                   bool is_ip4;
                   error err = read_addr_info(status, res, addr, is_ip4);
                   callbacks::invoke<decltype(callback)>(req->data, internal::uv_cid_resolve, err, is_ip4, addr);
                 }, addr.c_str(), 0, 0));
 }
コード例 #17
0
ファイル: socksys.cpp プロジェクト: davidd2k/qminer
void TSockSys::GetAsyncSockHost(const TStr& HostNm, const PSockHost& SockHost) {
	// prepare address info request
	uv_getaddrinfo_t* Request = (uv_getaddrinfo_t*)malloc(sizeof(uv_getaddrinfo_t));
	// submit the request
	int ResCd = uv_getaddrinfo(Loop, Request, TSockSys::OnGetHost, HostNm.CStr(), NULL, NULL);
	// check submission went fine
	if (ResCd != 0) {
		// cleanup first
		free(Request);
		// and throw exception
		throw TExcept::New("TSockSys.GetAsyncSockHost: Error requestiong resolve of hostname " + HostNm);
	}
	// remember SockHost for the callback
	TUInt64 RequestHnd = (uint64)Request;
	HndToSockHostH.AddDat(RequestHnd, SockHost);
}
コード例 #18
0
ファイル: withssl.cpp プロジェクト: kapilash/dc
// --------------------
int main() {
  char client_key_file[1024];
  sprintf(client_key_file, "%s/%s", dirname(__FILE__), "client-key.pem");
 
  // Initialize SSL
  SSL_library_init();
  SSL_load_error_strings();

  BIO* bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
  SSL_CTX* ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  int rc = SSL_CTX_use_PrivateKey_file(ssl_ctx, client_key_file, SSL_FILETYPE_PEM);
  if(!rc) {
    EXIT("Could not load client key file.\n");
  }

  SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2); 
  SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, dummy_ssl_verify_callback); // our callback always returns true, so no validation
  SSL_CTX_set_info_callback(ssl_ctx, dummy_ssl_info_callback);  // for dibugging
  SSL_CTX_set_msg_callback(ssl_ctx, dummy_ssl_msg_callback);

  uv_loop_t* loop = uv_loop_new();

  // Client context
  Client c;
  c.loop = loop;
  c.connect_req.data = &c;
  c.socket.data = &c;
  c.ssl = NULL;
  c.ssl_ctx = ssl_ctx;

  sprintf(c.host, "%s", "test.localhost");
  sprintf(c.port, "%s", "443");
  sprintf(c.page, "%s", "/chunked.php");

  // Resolve host
  struct addrinfo hints;
  hints.ai_family = PF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_flags = 0;
  uv_getaddrinfo_t resolver;
  resolver.data = &c;
  int r = uv_getaddrinfo(loop, &resolver, on_resolved_callback, c.host, c.port, &hints);
  uv_run(loop, UV_RUN_DEFAULT);
  return 0;
}
コード例 #19
0
ファイル: main.c プロジェクト: JuliaLang/libuv
int main() {
    loop = uv_default_loop();

    struct addrinfo hints;
    hints.ai_family = PF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;

    uv_getaddrinfo_t resolver;
    fprintf(stderr, "irc.freenode.net is... ");
    int r = uv_getaddrinfo(loop, &resolver, on_resolved, "irc.freenode.net", "6667", &hints);

    if (r) {
        fprintf(stderr, "getaddrinfo call error %s\n", uv_err_name(r));
        return 1;
    }
    return uv_run(loop, UV_RUN_DEFAULT);
}
コード例 #20
0
ファイル: client.cpp プロジェクト: Bulliby/Reactive
    std::future<response> client::send(const request& req_)
    {
        return std::async(std::launch::async, [=]() -> response {
            response res;

            struct addrinfo hints;

            hints.ai_family     = PF_INET;
            hints.ai_socktype   = SOCK_STREAM;
            hints.ai_protocol   = IPPROTO_TCP;
            hints.ai_flags      = 0;

            uv_getaddrinfo_t resolver;

            data_t data;
            data.req    = &req_;
            data.res    = &res;
            data.loop   = uv_loop_new();

            resolver.data = &data;

            int r = uv_getaddrinfo(
                data.loop,
                &resolver,
                onResolved,
                req_.getUrl().getHost().c_str(),
                std::to_string(req_.getUrl().getPort()).c_str(),
                &hints
            );

            if (r)
            {
                throw std::runtime_error(uv_err_name(r));
            }

            uv_run(data.loop, UV_RUN_DEFAULT);

            uv_loop_delete(data.loop);

            return res;
        });
    }
コード例 #21
0
ファイル: Client.cpp プロジェクト: raiden017/xmrig-amd
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;
}
コード例 #22
0
ファイル: server.c プロジェクト: sjw7453584/Server
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;
}
コード例 #23
0
ファイル: uv_getaddr.c プロジェクト: ChangerR/CppUtils
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;
}
コード例 #24
0
ファイル: async.c プロジェクト: Ryezhang/stronglink
int async_getaddrinfo(char const *const node, char const *const service, struct addrinfo const *const hints, struct addrinfo **const res) {
// uv_getaddrinfo kind of sucks so we try to avoid it.
// TODO: We don't ever define __POSIX__ currently.
#if defined(__POSIX__) || defined(CORO_USE_VALGRIND)
	async_pool_enter(NULL);
	int rc = getaddrinfo(node, service, hints, res);
	async_pool_leave(NULL);
	return rc;
#else
	getaddrinfo_state state[1];
	uv_getaddrinfo_t req[1];
	req->data = state;
	uv_getaddrinfo_cb cb = NULL;
	if(async_main) {
		state->thread = async_active();
		cb = getaddrinfo_cb;
	}
	int rc = uv_getaddrinfo(async_loop, req, cb, node, service, hints);
	if(rc < 0) return rc;
	if(cb) async_yield();
	if(res) *res = state->res;
	return state->status;
#endif
}
コード例 #25
0
ファイル: dns.c プロジェクト: tarruda/luv
static int luv_getaddrinfo(lua_State* L) {
  const char* node;
  const char* service;
  uv_getaddrinfo_t* req;
  luv_callback_t* callback;
  struct addrinfo hints_s;
  struct addrinfo* hints = &hints_s;

  if (!lua_isnil(L, 1)) node = luaL_checkstring(L, 1);
  else node = NULL;
  if (!lua_isnil(L, 2)) service = luaL_checkstring(L, 2);
  else service = NULL;
  if (!lua_isnil(L, 3)) luaL_checktype(L, 3, LUA_TTABLE);
  else hints = NULL;
  luaL_checktype(L, 4, LUA_TFUNCTION);

  if (hints) {
    /* Initialize the hints */
    memset(hints, 0, sizeof(struct addrinfo));

    /* Process the `family` hint. */
    lua_getfield(L, 3, "family");
    switch (lua_tointeger(L, -1)) {
      case 0:
        hints->ai_family = AF_UNSPEC;
        break;
      case 4:
        hints->ai_family = AF_INET;
        break;
      case 6:
        hints->ai_family = AF_INET6;
        break;
      default:
        return luaL_error(L, "`family` must be integer 0 (any), 4 (IPv4), or 6 (IPv6)");
        break;
    }
    lua_pop(L, 1);

    /* Process `socktype` hint */
    lua_getfield(L, 3, "socktype");
    if (!lua_isnil(L, -1)) {
      const char* socktype = luaL_checkstring(L, -1);
      if (strcmp(socktype, "STREAM") == 0) {
        hints->ai_socktype = SOCK_STREAM;
      }
      else if (strcmp(socktype, "DGRAM") == 0) {
        hints->ai_socktype = SOCK_DGRAM;
      }
      else {
        return luaL_error(L, "`socktype` must be 'STREAM' or 'DGRAM' or nil");
      }
    }
    lua_pop(L, 1);

    /* Process the `protocol` hint */
    lua_getfield(L, 3, "protocol");
    if (!lua_isnil(L, -1)) {
      const char* protocol = luaL_checkstring(L, -1);
#ifdef AF_UNIX
      if (strcmp(protocol, "UNIX") == 0) {
        hints->ai_protocol = AF_UNIX;
      }
      else
#endif
#ifdef AF_INET
      if (strcmp(protocol, "INET") == 0) {
        hints->ai_protocol = AF_INET;
      }
      else
#endif
#ifdef AF_INET6
      if (strcmp(protocol, "INET6") == 0) {
        hints->ai_protocol = AF_INET6;
      }
      else
#endif
#ifdef AF_IPX
      if (strcmp(protocol, "IPX") == 0) {
        hints->ai_protocol = AF_IPX;
      }
      else
#endif
#ifdef AF_NETLINK
      if (strcmp(protocol, "NETLINK") == 0) {
        hints->ai_protocol = AF_NETLINK;
      }
      else
#endif
#ifdef AF_X25
      if (strcmp(protocol, "X25") == 0) {
        hints->ai_protocol = AF_X25;
      }
      else
#endif
#ifdef AF_AX25
      if (strcmp(protocol, "AX25") == 0) {
        hints->ai_protocol = AF_AX25;
      }
      else
#endif
#ifdef AF_ATMPVC
      if (strcmp(protocol, "ATMPVC") == 0) {
        hints->ai_protocol = AF_ATMPVC;
      }
      else
#endif
#ifdef AF_APPLETALK
      if (strcmp(protocol, "APPLETALK") == 0) {
        hints->ai_protocol = AF_APPLETALK;
      }
      else
#endif
#ifdef AF_PACKET
      if (strcmp(protocol, "PACKET") == 0) {
        hints->ai_protocol = AF_PACKET;
      }
      else
#endif
      {
        return luaL_error(L, "Unknown protocol");
      }
    }
    lua_pop(L, 1);

    lua_getfield(L, 3, "addrconfig");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_ADDRCONFIG;
    lua_pop(L, 1);

    lua_getfield(L, 3, "v4mapped");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_V4MAPPED;
    lua_pop(L, 1);

    lua_getfield(L, 3, "all");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_ALL;
    lua_pop(L, 1);

    lua_getfield(L, 3, "numerichost");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_NUMERICHOST;
    lua_pop(L, 1);

    lua_getfield(L, 3, "passive");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_PASSIVE;
    lua_pop(L, 1);

    lua_getfield(L, 3, "numericserv");
    if (lua_toboolean(L, -1)) {
        hints->ai_flags |=  AI_NUMERICSERV;
        /* On OS X upto at least OSX 10.9, getaddrinfo crashes
         * if AI_NUMERICSERV is set and the servname is NULL or "0".
         * This workaround avoids a segfault in libsystem.
         */
        if(NULL == service) service = "00";
    }
    lua_pop(L, 1);

    lua_getfield(L, 3, "canonname");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_CANONNAME;
    lua_pop(L, 1);
  }

  /* Store the callback */
  callback = malloc(sizeof(*callback));
  callback->L = L;
  lua_pushvalue(L, 4);
  callback->ref = luaL_ref(L, LUA_REGISTRYINDEX);

  /* Create the request */
  req = malloc(sizeof(*req));
  req->data = (void*)callback;

  /* Make the call */
  if (uv_getaddrinfo(uv_default_loop(), req, on_addrinfo, node, service, hints)) {
    uv_err_t err = uv_last_error(uv_default_loop());
    return luaL_error(L, "getaddrinfo: %s", uv_strerror(err));
  }

  return 0;
}
コード例 #26
0
ファイル: util.c プロジェクト: aventurella/pyuv
static PyObject *
Util_func_getaddrinfo(PyObject *obj, PyObject *args, PyObject *kwargs)
{
    char *name;
    char port_str[6];
    int port, family, socktype, protocol, flags, r;
    struct addrinfo hints;
    getaddrinfo_cb_data_t *cb_data = NULL;
    uv_getaddrinfo_t* req = NULL;
    Loop *loop;
    PyObject *callback;

    UNUSED_ARG(obj);

    static char *kwlist[] = {"loop", "callback", "name", "port", "family", "socktype", "protocol", "flags", NULL};

    port = socktype = protocol = flags = 0;
    family = AF_UNSPEC;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!sO|iiiii:getaddrinfo", kwlist, &LoopType, &loop, &name, &callback, &port, &family, &socktype, &protocol, &flags)) {
        return NULL;
    }

    if (!PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        return NULL;
    }

    if (port < 0 || port > 65536) {
        PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65536");
        return NULL;
    }
    snprintf(port_str, sizeof(port_str), "%d", port);

    req = PyMem_Malloc(sizeof(uv_getaddrinfo_t));
    if (!req) {
        PyErr_NoMemory();
        goto error;
    }

    cb_data = PyMem_Malloc(sizeof(getaddrinfo_cb_data_t));
    if (!cb_data) {
        PyErr_NoMemory();
        goto error;
    }

    Py_INCREF(loop);
    Py_INCREF(callback);
    cb_data->loop = loop;
    cb_data->cb = callback;
    req->data = (void *)cb_data;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_socktype = socktype;
    hints.ai_protocol = protocol;
    hints.ai_flags = flags;

    r = uv_getaddrinfo(loop->uv_loop, req, &getaddrinfo_cb, name, port_str, &hints);
    if (r != 0) {
        RAISE_UV_EXCEPTION(loop->uv_loop, PyExc_UVError);
        goto error;
    }

    Py_RETURN_NONE;

error:
    if (req) {
        PyMem_Free(req);
    }
    return NULL;
}
コード例 #27
0
static PyObject *
Util_func_getaddrinfo(PyObject *obj, PyObject *args, PyObject *kwargs)
{
    char *host_str;
    char port_str[6];
    int port, family, socktype, protocol, flags, r;
    struct addrinfo hints;
    uv_getaddrinfo_t* req = NULL;
    Loop *loop;
    PyObject *callback, *host, *idna;

    static char *kwlist[] = {"loop", "callback", "host", "port", "family", "socktype", "protocol", "flags", NULL};

    UNUSED_ARG(obj);
    port = socktype = protocol = flags = 0;
    family = AF_UNSPEC;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!OO|iiiii:getaddrinfo", kwlist, &LoopType, &loop, &host, &callback, &port, &family, &socktype, &protocol, &flags)) {
        return NULL;
    }

    if (host == Py_None) {
        host_str = NULL;
    } else if (PyUnicode_Check(host)) {
        idna = PyObject_CallMethod(host, "encode", "s", "idna");
        if (!idna)
            return NULL;
        host_str = PyBytes_AS_STRING(idna);
    } else if (PyBytes_Check(host)) {
        host_str = PyBytes_AsString(host);
    } else {
        PyErr_SetString(PyExc_TypeError, "getaddrinfo() argument 2 must be string or None");
        return NULL;
    }

    if (!PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        return NULL;
    }

    if (port < 0 || port > 65535) {
        PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65535");
        return NULL;
    }
    snprintf(port_str, sizeof(port_str), "%d", port);

    req = PyMem_Malloc(sizeof(uv_getaddrinfo_t));
    if (!req) {
        PyErr_NoMemory();
        goto error;
    }

    Py_INCREF(loop);
    Py_INCREF(callback);
    req->data = (void *)callback;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_socktype = socktype;
    hints.ai_protocol = protocol;
    hints.ai_flags = flags;

    r = uv_getaddrinfo(loop->uv_loop, req, &getaddrinfo_cb, host_str, port_str, &hints);
    if (r != 0) {
        RAISE_UV_EXCEPTION(loop->uv_loop, PyExc_UVError);
        goto error;
    }

    Py_RETURN_NONE;

error:
    if (req) {
        PyMem_Free(req);
    }
    return NULL;
}
コード例 #28
0
ファイル: dns.c プロジェクト: ikeikeikeike/pyuv
static PyObject *
DNSResolver_func_getaddrinfo(DNSResolver *self, PyObject *args, PyObject *kwargs)
{
    char *name;
    char port_str[6];
    int port, family, socktype, protocol, flags, r;
    struct addrinfo hints;
    ares_cb_data_t *cb_data = NULL;
    uv_getaddrinfo_t* handle = NULL;
    PyObject *callback;

    static char *kwlist[] = {"callback", "name", "port", "family", "socktype", "protocol", "flags", NULL};

    port = socktype = protocol = flags = 0;
    family = AF_UNSPEC;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|iiiii:getaddrinfo", kwlist, &name, &callback, &port, &family, &socktype, &protocol, &flags)) {
        return NULL;
    }

    if (!PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        return NULL;
    }

    if (port < 0 || port > 65536) {
        PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65536");
        return NULL;
    }
    snprintf(port_str, sizeof(port_str), "%d", port);

    handle = PyMem_Malloc(sizeof(uv_getaddrinfo_t));
    if (!handle) {
        PyErr_NoMemory();
        goto error;
    }

    cb_data = (ares_cb_data_t*) PyMem_Malloc(sizeof *cb_data);
    if (!cb_data) {
        PyErr_NoMemory();
        goto error;
    }

    Py_INCREF(callback);
    cb_data->resolver = self;
    cb_data->cb = callback;
    handle->data = (void *)cb_data;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_socktype = socktype;
    hints.ai_protocol = protocol;
    hints.ai_flags = flags;

    r = uv_getaddrinfo(UV_LOOP(self), handle, &getaddrinfo_cb, name, port_str, &hints);
    if (r != 0) {
        raise_uv_exception(self->loop, PyExc_DNSError);
        goto error;
    }

    Py_RETURN_NONE;

error:
    if (handle) {
        PyMem_Free(handle);
    }
    if (cb_data) {
        Py_DECREF(callback);
        PyMem_Free(cb_data);
    }
    return NULL;
}
コード例 #29
0
static int luv_getaddrinfo(lua_State* L) {
  uv_getaddrinfo_t* req;
  const char* node;
  const char* service;
  struct addrinfo hints_s;
  struct addrinfo* hints = &hints_s;
  int ret, ref;
  if (lua_isnoneornil(L, 1)) node = NULL;
  else node = luaL_checkstring(L, 1);
  if (lua_isnoneornil(L, 2)) service = NULL;
  else service = luaL_checkstring(L, 2);
  if (!lua_isnoneornil(L, 3)) luaL_checktype(L, 3, LUA_TTABLE);
  else hints = NULL;
  if (hints) {
    // Initialize the hints
    memset(hints, 0, sizeof(*hints));

    // Process the `family` hint.
    lua_getfield(L, 3, "family");
    if (lua_isnumber(L, -1)) {
      hints->ai_family = lua_tointeger(L, -1);
    }
    else if (lua_isstring(L, -1)) {
      hints->ai_family = luv_af_string_to_num(lua_tostring(L, -1));
    }
    else if (lua_isnil(L, -1)) {
      hints->ai_family = AF_UNSPEC;
    }
    else {
      luaL_argerror(L, 3, "family hint must be string if set");
    }
    lua_pop(L, 1);

    // Process `socktype` hint
    lua_getfield(L, 3, "socktype");
    if (lua_isnumber(L, -1)) {
      hints->ai_socktype = lua_tointeger(L, -1);
    }
    else if (lua_isstring(L, -1)) {
      hints->ai_socktype = luv_sock_string_to_num(lua_tostring(L, -1));
    }
    else if (!lua_isnil(L, -1)) {
      return luaL_argerror(L, 3, "socktype hint must be string if set");
    }
    lua_pop(L, 1);

    // Process the `protocol` hint
    lua_getfield(L, 3, "protocol");
    if (lua_isnumber(L, -1)) {
      hints->ai_protocol = lua_tointeger(L, -1);
    }
    else if (lua_isstring(L, -1)) {
      int protocol = luv_af_string_to_num(lua_tostring(L, -1));
      if (protocol) {
        hints->ai_protocol = protocol;
      }
      else {
        return luaL_argerror(L, 3, "Invalid protocol hint");
      }
    }
    else if (!lua_isnil(L, -1)) {
      return luaL_argerror(L, 3, "protocol hint must be string if set");
    }
    lua_pop(L, 1);

    lua_getfield(L, 3, "addrconfig");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_ADDRCONFIG;
    lua_pop(L, 1);

#ifdef AI_V4MAPPED
    lua_getfield(L, 3, "v4mapped");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_V4MAPPED;
    lua_pop(L, 1);
#endif

#ifdef AI_ALL
    lua_getfield(L, 3, "all");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_ALL;
    lua_pop(L, 1);
#endif

    lua_getfield(L, 3, "numerichost");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_NUMERICHOST;
    lua_pop(L, 1);

    lua_getfield(L, 3, "passive");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_PASSIVE;
    lua_pop(L, 1);

    lua_getfield(L, 3, "numericserv");
    if (lua_toboolean(L, -1)) {
        hints->ai_flags |=  AI_NUMERICSERV;
        /* On OS X upto at least OSX 10.9, getaddrinfo crashes
         * if AI_NUMERICSERV is set and the servname is NULL or "0".
         * This workaround avoids a segfault in libsystem.
         */
        if (NULL == service) service = "00";
    }
    lua_pop(L, 1);

    lua_getfield(L, 3, "canonname");
    if (lua_toboolean(L, -1)) hints->ai_flags |=  AI_CANONNAME;
    lua_pop(L, 1);
  }

  ref = luv_check_continuation(L, 4);
  req = (uv_getaddrinfo_t*)lua_newuserdata(L, sizeof(*req));
  req->data = luv_setup_req(L, ref);

  ret = uv_getaddrinfo(luv_loop(L), req, ref == LUA_NOREF ? NULL : luv_getaddrinfo_cb, node, service, hints);
  if (ret < 0) {
    luv_cleanup_req(L, (luv_req_t*)req->data);
    lua_pop(L, 1);
    return luv_error(L, ret);
  }
  if (ref == LUA_NOREF) {

    lua_pop(L, 1);
    luv_pushaddrinfo(L, req->addrinfo);
    uv_freeaddrinfo(req->addrinfo);
    luv_cleanup_req(L, (luv_req_t*)req->data);
  }
  return 1;
}
コード例 #30
0
ファイル: server.c プロジェクト: leecade/shadowsocks-libuv
static void client_handshake_read_cb(uv_stream_t* stream, ssize_t nread, uv_buf_t buf)
{
	int n;
	server_ctx *ctx = (server_ctx *)stream->data;

	if (nread < 0) {
		if (buf.len) // If buf is set, we need to free it
			free(buf.base);
		HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb); // Then close the connection
		return;
	} else if (!nread) {
		free(buf.base);
		return;
	}

	memcpy(ctx->handshake_buffer + ctx->buffer_len, buf.base, buf.len);
	shadow_decrypt(ctx->handshake_buffer + ctx->buffer_len, decrypt_table, buf.len);

	ctx->buffer_len += nread;

	if (!ctx->handshake_buffer) {
		FATAL("Should no call this anmore");
	}
	free(buf.base);

	if (!ctx->remote_ip) {
		if (ctx->buffer_len < 2) // Not interpretable
			return;
		uint8_t addrtype = ctx->handshake_buffer[0];
		if (addrtype == ADDRTYPE_IPV4) {
			if (ctx->buffer_len < 5)
				return;
			ctx->remote_ip = *((uint32_t *)(ctx->handshake_buffer + 1));
			SHIFT_BYTE_ARRAY_TO_LEFT(ctx->handshake_buffer, 5, HANDSHAKE_BUFFER_SIZE);
			ctx->buffer_len -= 5;
			// TODO: Print out
		} else if (addrtype == ADDRTYPE_DOMAIN) {
			uint8_t domain_len = ctx->handshake_buffer[1];
			if (!domain_len) { // Domain length is zero
				LOGE("Domain length is zero");
				HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
				return;
			}
			if (ctx->buffer_len < domain_len + 2)
				return;
			char domain[domain_len+1];
			domain[domain_len] = 0;
			memcpy(domain, ctx->handshake_buffer+2, domain_len);
			struct addrinfo hints;
    		hints.ai_family = AF_INET; // IPv4 Only
    		hints.ai_socktype = SOCK_STREAM;
    		hints.ai_protocol = IPPROTO_TCP;
    		hints.ai_flags = 0;
			uv_getaddrinfo_t *resolver = (uv_getaddrinfo_t *)malloc(sizeof(uv_getaddrinfo_t));
			if (!resolver) {
				HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
				FATAL("malloc() failed!");
			}
			resolver->data = ctx; // We need to locate back the stream
			LOGI("Domain is: %s", domain);
			n = uv_getaddrinfo(stream->loop, resolver, client_handshake_domain_resolved, domain, NULL, &hints);
			if (n) {
				SHOW_UV_ERROR(stream->loop);
				HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
				free(resolver);
				return;
			}
			SHIFT_BYTE_ARRAY_TO_LEFT(ctx->handshake_buffer, 2+domain_len, HANDSHAKE_BUFFER_SIZE);
			ctx->buffer_len -= 2 + domain_len;
			uv_read_stop(stream); // Pause the reading process, wait for resolve result
			return;
		} else { // Unsupported addrtype
			LOGI("addrtype unknown, closing");
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			return;
		}
	} // !ctx->remote_ip

	if (!ctx->remote_port) {
		if (ctx->buffer_len < 2) // Not interpretable
			return;
		ctx->remote_port = *((uint16_t *)ctx->handshake_buffer);
		if (!ctx->remote_port) {
			LOGE("Remote port is zero");
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			return;
		}
		SHIFT_BYTE_ARRAY_TO_LEFT(ctx->handshake_buffer, 2, HANDSHAKE_BUFFER_SIZE);
		ctx->buffer_len -= 2;
		// Try connect now
		n = uv_tcp_init(stream->loop, &ctx->remote);
		if (n)
			SHOW_UV_ERROR_AND_EXIT(stream->loop);
		uv_connect_t *req = (uv_connect_t *)malloc(sizeof(uv_connect_t));
		if (!req) {
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			FATAL("malloc() failed!");
		}
		req->data = ctx;
		struct sockaddr_in remote_addr;
		memset(&remote_addr, 0, sizeof(remote_addr));
		remote_addr.sin_family = AF_INET;
		remote_addr.sin_addr.s_addr = ctx->remote_ip;
		remote_addr.sin_port = ctx->remote_port;
		n = uv_tcp_connect(req, &ctx->remote, remote_addr, connect_to_remote_cb);
		if (n) {
			SHOW_UV_ERROR(stream->loop);
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			free(req);
			return;
		}
		uv_read_stop(stream); // We are done handshake
	}
}