Exemple #1
0
static void
connect_server()
{
    ne_session *sess;
    ne_server_capabilities caps;
    int ret;

    /* set up the connection */

    ne_sock_init();

    memset(&session, 0, sizeof session);
    session.uri.scheme = ne_strdup("http");
    session.uri.host = hc_host;
    session.uri.port = port; 
    session.uri.path = ne_strdup("/webdav/"); /* always '/'-terminate */

    session.sess = sess = ne_session_create(session.uri.scheme, 
                                     session.uri.host, 
                                     session.uri.port);

    /* make the connection */

    ne_set_useragent(sess, "hctest/");  /* needed? */
/*
not needed to connect
    ne_lockstore_register(session.locks, sess);
    ne_redirect_register(sess);
*/
    /* convenient status */
    ne_set_status(sess, connection_status, NULL);
    ne_set_progress(sess, transfer_progress, NULL);

    /* execute connect */
    ret = ne_options(sess, session.uri.path, &caps);
    
    switch (ret) {
    case NE_OK:
	session.connected = true;
/*
	if (set_path(session.uri.path)) {
	    close_connection();
	}
*/
	break;
    case NE_CONNECT:
        printf("got NE_CONNECT\n");
        quit(1);
	break;
    case NE_LOOKUP:
	puts(ne_get_error(sess));
        quit(1);
	break;
    default:
	printf("Could not open collection (default connect err):\n%s\n",
	       ne_get_error(sess));
        quit(1);
	break;
    }
}
Exemple #2
0
void s3_begin_session(S3 *s3)
{
	if(s3) {
		if(s3->session_count == 0) s3->session = ne_session_create("http",AWS_S3_URL,80);
		s3->session_count++;
	}
}
Exemple #3
0
static ne_session *session_open(int with_lock) {
    const char *scheme = NULL;
    ne_session *session;

    extern ne_lock_store *lock_store;

    if (!b_uri)
        return NULL;

    scheme = uri.scheme ? uri.scheme : "http";
    
    if (!(session = ne_session_create(scheme, uri.host, uri.port ? uri.port : ne_uri_defaultport(scheme)))) {
        fprintf(stderr, "Failed to create session\n");
        return NULL;
    }

    ne_ssl_set_verify(session, ssl_verify_cb, NULL);
    ne_set_server_auth(session, ne_auth_creds_cb, NULL);
    ne_redirect_register(session);

    if (with_lock && lock_store)
        ne_lockstore_register(lock_store, session);
    
    return session;
}
Exemple #4
0
ne_session *
opensession_common(const addr_info_t *addr_info,
		int connect_timeout, int read_timeout, GError **err)
{
	ne_session *session=NULL;
	gchar host[1024];
	guint16 port;

	if (!addr_info) {
		GSETERROR (err, "Invalid parameter");
		return NULL;
	}

	port = 0;
	memset(host, 0x00, sizeof(host));
	if (!addr_info_get_addr(addr_info, host, sizeof(host)-1, &port)) {
		GSETERROR(err, "AddrInfo printing error");
		return NULL;
	}

	session = ne_session_create ("http", host, port);
	if (!session) {
		GSETERROR(err,"cannot create a new WebDAV session");
		return NULL;
	}

	ne_set_connect_timeout (session, connect_timeout);
	ne_set_read_timeout (session, read_timeout);
	return session;
}
Exemple #5
0
void get(const StringSlice& url, WriteTarget out) {
    static int inited = ne_sock_init();
    if (inited != 0) {
        throw Exception("ne_sock_init()");
    }

    CString cstr(url);
    ne_uri  uri = {};
    if (ne_uri_parse(cstr.data(), &uri)) {
        throw Exception("ne_uri_parse()");
    }
    if (uri.port == 0) {
        uri.port = ne_uri_defaultport(uri.scheme);
    }
    unique_ptr<ne_uri, decltype(&ne_uri_free)>            uri_free(&uri, ne_uri_free);
    unique_ptr<ne_session, decltype(&ne_session_destroy)> sess(
            ne_session_create(uri.scheme, uri.host, uri.port), ne_session_destroy);

    unique_ptr<ne_request, decltype(&ne_request_destroy)> req(
            ne_request_create(sess.get(), "GET", uri.path), ne_request_destroy);

    ne_userdata userdata = {out};
    ne_add_response_body_reader(req.get(), accept, reader, &userdata);

    auto err = ne_request_dispatch(req.get());
    if (err != NE_OK) {
        throw Exception("ne_request_dispatch()");
    }
    auto* st = ne_get_status(req.get());
    if (st->code != 200) {
        throw Exception(st->code);
    }
}
Exemple #6
0
int session_server(ne_session **sess, server_fn fn, void *userdata)
{
    unsigned int port;
    
    CALL(new_spawn_server(1, fn, userdata, &port));
    
    *sess = ne_session_create("http", "localhost", port);

    return OK;
}
std::string Client::connect(const std::string& httpURL)
{
  auto colpos = httpURL.find_first_of("://");
  if (colpos < 4 || colpos > 5)
    return std::string();

  ctx = std::make_shared<ClientCtx>();
  ctx->scheme.fill(0x00);
  ::memcpy(ctx->scheme.data(), httpURL.data(), colpos);

  for(unsigned c = 0; c < 5; ++c)
    ctx->scheme[c] = std::tolower(ctx->scheme[c]);

  ctx->host_and_port = ExtractHostPortHttp(httpURL);
  ctx->port = ctx->isHttps() ? 443 : 80;
  ne_session* ne = nullptr;
  auto pos = ctx->host_and_port.find_first_of(':');
  if (std::string::npos != pos)
    {//case format host.com:443
      char* end = nullptr;
      ctx->port = ::strtol(ctx->host_and_port.data() + (1 + pos), &end, 10);
      std::array<char, 80> hostStr;
      hostStr.fill(0x00);
      ::memcpy(hostStr.data(), ctx->host_and_port.data(), pos);
      ne = ne_session_create(ctx->scheme.data(), hostStr.data(), ctx->port);
    }
  else
    {//case format  host.com (no port)
      ne = ne_session_create(ctx->scheme.data(), ctx->host_and_port.data(), ctx->port);
      std::array<char,8> temp; temp.fill(0);
      ::snprintf(temp.data(), temp.size(), ":%u", ctx->port);
      ctx->host_and_port.append(temp.data());
    }
  ctx->sess = ne;
  ne_set_useragent(ctx->sess, "libneon");
  if (ctx->isHttps())
    {
      ne_ssl_trust_default_ca(ne);
      ne_ssl_set_verify(ne, &AcceptAllSSL, nullptr);
    }
  return ctx->host_and_port;
}
Exemple #8
0
int proxied_session_server(ne_session **sess, const char *scheme,
                           const char *host, unsigned int fakeport,
                           server_fn fn, void *userdata)
{
    unsigned int port;
    
    CALL(new_spawn_server(1, fn, userdata, &port));
    
    *sess = ne_session_create(scheme, host, fakeport);

    ne_session_proxy(*sess, "localhost", port);

    return OK;
}
Exemple #9
0
rawx_session_t* rawx_client_create_session( addr_info_t *ai, GError **err )
{
	struct sockaddr_storage ss;
	gsize ss_size = sizeof(ss);
	gchar host[256], port[16];
	rawx_session_t *session;

	session = g_try_malloc0( sizeof(rawx_session_t) );
	if (!session) {
		GSETERROR(err,"Memory allocation failure");
		goto error_session;
	}

	memcpy( &(session->addr), ai, sizeof(addr_info_t) );

	if (!addrinfo_to_sockaddr( ai, (struct sockaddr*)&ss, &ss_size )) {
		GSETERROR(err,"addr_info_t conversion error");
		goto error_addr;
	}

	memset( host, 0x00, sizeof(host) );
	memset( port, 0x00, sizeof(port) );

	if (getnameinfo ( (struct sockaddr* )&ss, ss_size, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST|NI_NUMERICSERV)) {
		GSETERROR(err,"addr_info_t resolution error : %s", strerror(errno));
		goto error_addr;
	}

	session->neon_session = ne_session_create ("http", host, atoi(port));
	if (!session->neon_session) {
		GSETERROR(err,"neon session creation error");
		goto error_neon;
	}

	session->timeout.cnx = 60000;
	session->timeout.req = 60000;

	ne_set_connect_timeout (session->neon_session, session->timeout.cnx/1000);
	ne_set_read_timeout (session->neon_session, session->timeout.req/1000);

	return session;

error_neon:
error_addr:
	g_free(session);
error_session:
	return NULL;
}
Exemple #10
0
static gboolean _ne_request(const char *host, int port, const char *target,
		const char *method, GSList *headers, GError **err)
{
	GRID_TRACE("%s", __FUNCTION__);
	gboolean result = FALSE;
	ne_session* session = ne_session_create("http", host, port);
	ne_set_connect_timeout(session, 10);
	ne_set_read_timeout(session, 30);

	GRID_DEBUG("%s http://%s:%d%s", method, host, port, target);
	ne_request* req = ne_request_create(session, method, target);
	if (NULL != req) {
		for (GSList *l = headers; l; l = l->next) {
			gchar **toks = g_strsplit(l->data, ":", 2);
			ne_add_request_header(req, toks[0], toks[1]);
			g_strfreev(toks);
		}
		switch (ne_request_dispatch(req)) {
			case NE_OK:
				if (ne_get_status(req)->klass != 2) {
					*err = NEWERROR(0, "cannot %s '%s' (%s)", method, target,
							ne_get_error(session));
				} else {
					result = TRUE;
				}
				break;
			case NE_AUTH:
			case NE_CONNECT:
			case NE_TIMEOUT:
			case NE_ERROR:
			default:
				*err = NEWERROR(0,
						"unexpected error from the WebDAV server (%s)",
						ne_get_error(session));
				break;
		}
		ne_request_destroy(req);
	} else {
		// This should be an assertion
		*err = NEWERROR(0, "Failed to create request");
	}
	ne_session_destroy (session);
	return result;
}
Exemple #11
0
int fakeproxied_session_server(ne_session **sess, const char *scheme,
                               const char *host, unsigned int fakeport,
                               server_fn fn, void *userdata)
{
    unsigned int port;
    ne_inet_addr *addr;
    const ne_inet_addr *alist[1];
    
    CALL(new_spawn_server2(1, fn, userdata, &addr, &port));
    
    alist[0] = addr;

    *sess = ne_session_create(scheme, host, fakeport);

    ne_set_addrlist2(*sess, port, alist, 1);

    ne_hook_destroy_session(*sess, fakesess_destroy, addr);

    return OK;
}
Exemple #12
0
int begin(void)
{
    const char *scheme = use_secure?"https":"http";
    char *space;
    static const char blanks[] = "          ";
    static const char stars[] = "**********************************";
    

    i_session = ne_session_create(scheme, i_hostname, i_port);
    CALL(init_session(i_session));
    ne_hook_pre_send(i_session, i_pre_send, "X-Prestan");


    space = ne_concat(i_path, "davtest/", NULL);
    ne_delete(i_session, space);
    if (ne_mkcol(i_session, space)) {
	t_context("Could not create new collection `%s' for tests: %s\n"
	  "Server must allow `MKCOL %s' for tests to proceed", 
	  space, ne_get_error(i_session), space);
	return FAILHARD;
    }
    free(i_path);
    i_path = space;    
    
    warmup();

    printf("\nStart Testing %s:\n\n",pget_option.URL) ;
    printf("\n%s%s\n", blanks, stars);
    printf("\n%s* Number of Requests\t\t%d\n", blanks, pget_option.requests);
    printf("\n%s* Number of Dead Properties\t%d\n", 
    			blanks, pget_option.numprops);
    printf("\n%s* Depth of Collection\t\t%d\n", blanks, pget_option.depth);
    printf("\n%s* Width of Collection\t\t%d\n", blanks, pget_option.width);
    printf("\n%s* Type of Methods\t\t%s\n", blanks, pget_option.methods);
    printf("\n%s%s\n", blanks, stars);
    printf("\n\n");
    
    return OK;
}
Exemple #13
0
static char *
_check_chunk(const char *cid)
{
	ne_session *session=NULL;
	ne_request *request=NULL;

	GString *str = g_string_new("");

	char **split = g_strsplit(cid, "/", 0);
	char **addr_tok = g_strsplit(split[2], ":", 2);

	if(NULL != (session = ne_session_create("http", addr_tok[0], atoi(addr_tok[1])))) {
		ne_set_connect_timeout(session, 10);
		ne_set_read_timeout(session, 30);
		/* FIXME: I'm a little harder with strrchr success presumption */
		if(NULL != (request = ne_request_create (session, "HEAD", strrchr(cid, '/')))) {
			switch (ne_request_dispatch (request)) {
				case NE_OK:
					if (ne_get_status(request)->klass != 2) {
						g_string_append_printf(str, "(Chunk unavailable : %s)",
								ne_get_error(session));
					}
					break;
				default:
					g_string_append_printf(str, "(Chunk unavailable : %s)",
							ne_get_error(session));
			}
			ne_request_destroy (request);
		} 
		ne_session_destroy (session);
	}

	g_strfreev(addr_tok);
	g_strfreev(split);

	return g_string_free(str, FALSE);
}
Exemple #14
0
/* ensure that ne_redirect_location returns NULL when no redirect has
 * been encountered, or redirect hooks aren't registered. */
static int no_redirect(void)
{
    ne_session *sess = ne_session_create("http", "localhost", 7777);
    const ne_uri *loc;

    ONN("redirect non-NULL before register", ne_redirect_location(sess));
    ne_redirect_register(sess);
    ONN("initial redirect non-NULL", ne_redirect_location(sess));

    CALL(spawn_server(7777, single_serve_string,
                      "HTTP/1.0 200 OK\r\n\r\n\r\n"));
    ONREQ(any_request(sess, "/noredir"));
    CALL(await_server());

    ONN("redirect non-NULL after non-redir req", ne_redirect_location(sess));

    CALL(spawn_server(7777, single_serve_string, "HTTP/1.0 302 Get Ye Away\r\n"
                      "Location: /blah\r\n" "\r\n"));
    CALL(process_redir(sess, "/foo", &loc));
    CALL(await_server());

    ne_session_destroy(sess);
    return OK;
}
Exemple #15
0
/*
 * Connect to a DAV server
 * This function sets the flag _connected if the connection is established
 * and returns if the flag is set, so calling it frequently is save.
 */
static int dav_connect(const char *base_url) {
    int useSSL = 0;
    int rc;
    char protocol[6] = {'\0'};
    char uaBuf[256];
    char *path = NULL;
    char *scheme = NULL;
    char *host = NULL;
    unsigned int port = 0;
    int proxystate = -1;

    if (_connected) {
        return 0;
    }

    rc = c_parse_uri( base_url, &scheme, &dav_session.user, &dav_session.pwd, &host, &port, &path );
    if( rc < 0 ) {
        DEBUG_WEBDAV("Failed to parse uri %s", base_url );
        goto out;
    }

    DEBUG_WEBDAV("* scheme %s", scheme );
    DEBUG_WEBDAV("* host %s", host );
    DEBUG_WEBDAV("* port %u", port );
    DEBUG_WEBDAV("* path %s", path );

    if( strcmp( scheme, "owncloud" ) == 0 ) {
        strcpy( protocol, "http");
    } else if( strcmp( scheme, "ownclouds" ) == 0 ) {
        strcpy( protocol, "https");
        useSSL = 1;
    } else {
        DEBUG_WEBDAV("Invalid scheme %s, go outa here!", scheme );
        rc = -1;
        goto out;
    }

    DEBUG_WEBDAV("* user %s", dav_session.user ? dav_session.user : "");

    if (port == 0) {
        port = ne_uri_defaultport(protocol);
    }

#if 0
    rc = ne_sock_init();
    DEBUG_WEBDAV("ne_sock_init: %d", rc );
    if (rc < 0) {
        rc = -1;
        goto out;
    }
#endif

    dav_session.ctx = ne_session_create( protocol, host, port);

    if (dav_session.ctx == NULL) {
        DEBUG_WEBDAV("Session create with protocol %s failed", protocol );
        rc = -1;
        goto out;
    }

    if (dav_session.read_timeout == 0)
        dav_session.read_timeout = 300;  // set 300 seconds as default.

    ne_set_read_timeout(dav_session.ctx, dav_session.read_timeout);

    snprintf( uaBuf, sizeof(uaBuf), "Mozilla/5.0 (%s) csyncoC/%s",
              get_platform(), CSYNC_STRINGIFY( LIBCSYNC_VERSION ));
    ne_set_useragent( dav_session.ctx, uaBuf);
    ne_set_server_auth(dav_session.ctx, ne_auth, 0 );

    if( useSSL ) {
        if (!ne_has_support(NE_FEATURE_SSL)) {
            DEBUG_WEBDAV("Error: SSL is not enabled.");
            rc = -1;
            goto out;
        }

        ne_ssl_trust_default_ca( dav_session.ctx );
        ne_ssl_set_verify( dav_session.ctx, verify_sslcert, 0 );
    }

    /* Hook called when a request is created. It sets the proxy connection header. */
    ne_hook_create_request( dav_session.ctx, request_created_hook, NULL );
    /* Hook called after response headers are read. It gets the Session ID. */
    ne_hook_post_headers( dav_session.ctx, post_request_hook, NULL );
    /* Hook called before a request is sent. It sets the cookies. */
    ne_hook_pre_send( dav_session.ctx, pre_send_hook, NULL );
    /* Hook called after request is dispatched. Used for handling possible redirections. */
    ne_hook_post_send( dav_session.ctx, post_send_hook, NULL );

    /* Proxy support */
    proxystate = configureProxy( dav_session.ctx );
    if( proxystate < 0 ) {
        DEBUG_WEBDAV("Error: Proxy-Configuration failed.");
    } else if( proxystate > 0 ) {
        ne_set_proxy_auth( dav_session.ctx, ne_proxy_auth, 0 );
    }

    _connected = 1;
    rc = 0;
out:
    SAFE_FREE(path);
    SAFE_FREE(host);
    SAFE_FREE(scheme);
    return rc;
}
Exemple #16
0
int dav_startsessx(char *server, char *comment, int enable_ssl)
{
	FILE *p12 = NULL;
	const char *p12cert = "/tmp/usercert.p12";
	const char *userkey, *usercert, *userproxy;
  char buffer[128];

	/* Function to be executed once per thread, used to create the connection structure and set the server name */
	if(mutex == 0)
	{
		/* If no host specified, use the DPNS default one */
		if (!server)
			server = getenv("DPNS_HOST");

		/* Finish the function if the host is still NULL*/
		if (!server)
		{
			dav_error = SENOSHOST;
			return -1;
		}

		/* Trigger an error if the comment is too long */
		if(comment && (strlen(comment) > CA_MAXCOMMENTLEN))
		{
			dav_error = EINVAL;
			return -1;
		}

		pthread_once(&init_once, thread_init_once);

		connection = (struct dav_connection *)calloc(sizeof(struct dav_connection), 1);
		strcpy(connection->server, server);
		mutex = 1;
	}

	/* exit function if a session already exists */
	if(connection->session)
		return 0;	

	/* Retrieve userkey and usercert from environement variable */
	userkey   = getenv("X509_USER_KEY");
	usercert  = getenv("X509_USER_CERT");
  userproxy = getenv("X509_USER_PROXY");
  
  /* Use a proxy */
  if (enable_ssl) {
    if (userproxy) {
      userkey = usercert = userproxy;
    }
    /* Try default proxy location */
    else if (!userkey && !usercert) {
      struct stat stat_buf;

      snprintf(buffer, sizeof(buffer), "/tmp/x509up_u%d", getuid());
      /* No luck, try with host cert and key */
      if (stat(buffer, &stat_buf) != 0) {
        usercert = "/etc/grid-security/hostcert.pem";
        userkey  = "/etc/grid-security/hostkey.pem";
      }
    }

    debug_msg("User certificate: %s", usercert);
    debug_msg("User key:         %s", userkey);

    /* Try to open the certificate, create one if file does not exist yet */
    if ((p12 = fopen(p12cert, "r")) == NULL){
      if(convert_x509_to_p12(userkey, usercert, p12cert) == -1){
        fprintf(stderr, "An error occur in the certificate conversion\n");
        return -1;
      }
    }else {
      fclose(p12);
    }

    /* Try to open a session, return -1 and set the correct errno if it failed */
    if ((connection->session = ne_session_create("https", server, 443)) == NULL)
    {
      dav_error = ENSNACT;
      return -1;
    }
  }
  else {
    if ((connection->session = ne_session_create("http", server, 80)) == NULL)
    {
      dav_error = ENSNACT;
      return -1;
    }
  }

	/* manual checking for ssl credentials */
	ne_ssl_set_verify(connection->session, no_ssl_verification, NULL);

	/* Read the pkcs12 certificate */
  if (enable_ssl) {
    ne_ssl_client_cert *cert = ne_ssl_clicert_read(p12cert);
        if (cert == NULL) {
      ne_session_destroy(connection->session);
      dav_error = SECOMERR;
      return -1;
    }
    ne_ssl_set_clicert(connection->session, cert);
    ne_ssl_clicert_free(cert);
  }
	
	return 0;
}
Exemple #17
0
int
main_http_config(const gchar *hn, int fd)
{
	int rc;
	GError *error = NULL;
	GByteArray *gba_services = NULL;
	GByteArray *gba_files = NULL;
	ne_session *http_session;

	set_sighandlers();
	fd_out = fd;

	DEBUG("Starting a new configuration process");
	rc = -1;

	bzero(hostname, sizeof(hostname));
	if (!hn)
		gethostname(hostname,sizeof(hostname));
	else
		g_strlcpy(hostname, hn, sizeof(hostname)-1);

	http_session = ne_session_create("http", gridconf_host, gridconf_port);
	ne_set_connect_timeout(http_session, 1);
	ne_set_read_timeout(http_session, 4);

	/*downlaod each file*/
	if (!is_running)
		goto label_error;

	gba_files = download_file_list(http_session, &error);
	if (!gba_files) {
		ERROR("Failed to get the files list file : %s", gerror_get_message(error));
		goto label_error;
	}
	
	if (!is_running)
		goto label_error;
	
	gba_services = download_file_services(http_session, &error);
	if (!gba_services) {
		ERROR("Failed to get the services definition file : %s", gerror_get_message(error));
		goto label_error;
	}
	
	if (!is_running)
		goto label_error;
	
	if (!download_each_configuration_file(http_session, gba_files, &error)) {
		ERROR("Failed to download a configuration file : %s", gerror_get_message(error));
		goto label_error;
	}

	if (!is_running)
		goto label_error;

	if (!dump_gba(gba_services, fd_out, &error)) {
		ERROR("Failed to dump the configuration to fd=%d : %s", fd_out, gerror_get_message(error));
		goto label_error;
	}

	rc = 0;
label_error:
	ne_session_destroy(http_session);
	metautils_pclose(&fd_out);
	if (gba_services)
		g_byte_array_free(gba_services, TRUE);
	if (gba_files)
		g_byte_array_free(gba_files, TRUE);
	DEBUG("http_config child pid=%d exiting with rc=%d", getpid(), rc);
	return rc;
}
Exemple #18
0
static int open_handle (struct neon_handle * handle, uint64_t startbyte)
{
    int ret;
    char * proxy_host = NULL;
    int proxy_port = 0;

    bool_t use_proxy = aud_get_bool (NULL, "use_proxy");
    bool_t use_proxy_auth = aud_get_bool (NULL, "use_proxy_auth");

    if (use_proxy)
    {
        proxy_host = aud_get_str (NULL, "proxy_host");
        proxy_port = aud_get_int (NULL, "proxy_port");
    }

    handle->redircount = 0;

    _DEBUG ("<%p> Parsing URL", handle);

    if (ne_uri_parse (handle->url, handle->purl) != 0)
    {
        _ERROR ("<%p> Could not parse URL '%s'", (void *) handle, handle->url);
        return -1;
    }

    while (handle->redircount < 10)
    {
        if (! handle->purl->port)
            handle->purl->port = ne_uri_defaultport (handle->purl->scheme);

        _DEBUG ("<%p> Creating session to %s://%s:%d", handle,
         handle->purl->scheme, handle->purl->host, handle->purl->port);
        handle->session = ne_session_create (handle->purl->scheme,
         handle->purl->host, handle->purl->port);
        ne_redirect_register (handle->session);
        ne_add_server_auth (handle->session, NE_AUTH_BASIC, server_auth_callback, (void *) handle);
        ne_set_session_flag (handle->session, NE_SESSFLAG_ICYPROTO, 1);
        ne_set_session_flag (handle->session, NE_SESSFLAG_PERSIST, 0);

#ifdef HAVE_NE_SET_CONNECT_TIMEOUT
        ne_set_connect_timeout (handle->session, 10);
#endif

        ne_set_read_timeout (handle->session, 10);
        ne_set_useragent (handle->session, "Audacious/" PACKAGE_VERSION);

        if (use_proxy)
        {
            _DEBUG ("<%p> Using proxy: %s:%d", handle, proxy_host, proxy_port);
            ne_session_proxy (handle->session, proxy_host, proxy_port);

            if (use_proxy_auth)
            {
                _DEBUG ("<%p> Using proxy authentication", handle);
                ne_add_proxy_auth (handle->session, NE_AUTH_BASIC,
                 neon_proxy_auth_cb, (void *) handle);
            }
        }

        if (! strcmp ("https", handle->purl->scheme))
        {
            ne_ssl_trust_default_ca (handle->session);
            ne_ssl_set_verify (handle->session,
             neon_vfs_verify_environment_ssl_certs, handle->session);
        }

        _DEBUG ("<%p> Creating request", handle);
        ret = open_request (handle, startbyte);

        if (! ret)
        {
            str_unref (proxy_host);
            return 0;
        }

        if (ret == -1)
        {
            ne_session_destroy (handle->session);
            handle->session = NULL;
            str_unref (proxy_host);
            return -1;
        }

        _DEBUG ("<%p> Following redirect...", handle);
        ne_session_destroy (handle->session);
        handle->session = NULL;
    }

    /* If we get here, our redirect count exceeded */
    _ERROR ("<%p> Redirect count exceeded for URL %s", (void *) handle, handle->url);

    str_unref (proxy_host);
    return 1;
}
Exemple #19
0
/* FIXME: Leaky as a bucket */
void open_connection(const char *url)
{
    char *proxy_host = get_option(opt_proxy), *pnt;
    ne_server_capabilities caps;
    int ret, use_ssl = 0;
    ne_session *sess;

    if (session.connected) {
	close_connection();
    } else {
        ne_uri_free(&session.uri);
        if (session.lastwp) {
            ne_free(session.lastwp);
            session.lastwp = NULL;
        }
    }

    /* Single argument: see whether we have a path or scheme */
    if (strchr(url, '/') == NULL) {
	/* No path, no scheme -> just a hostname */
	pnt = strchr(url, ':');
	if (pnt != NULL) {
	    *pnt++ = '\0';
	    session.uri.port = atoi(pnt);
	} else {
	    session.uri.port = 80;
	}
	session.uri.host = ne_strdup(url);
	session.uri.scheme = ne_strdup("http");
    } else {
	/* Parse the URL */
	if (ne_uri_parse(url, &session.uri) || session.uri.host == NULL) {
	    printf(_("Could not parse URL `%s'\n"), url);
	    return;
	}

	if (session.uri.scheme == NULL)
	    session.uri.scheme = ne_strdup("http");

	if (!session.uri.port)
	    session.uri.port = ne_uri_defaultport(session.uri.scheme);

	if (strcasecmp(session.uri.scheme, "https") == 0) {
	    if (!ne_has_support(NE_FEATURE_SSL)) {
		printf(_("SSL is not enabled.\n"));
		return;
	    }
	    use_ssl = 1;
	}
    }

    session.sess = ne_session_create(session.uri.scheme, session.uri.host,
                                     session.uri.port);
    sess = session.sess;
    
    if (use_ssl && setup_ssl()) {
	return;
    }

    ne_lockstore_register(session.locks, sess);
    ne_redirect_register(sess);
    ne_set_notifier(sess, notifier, NULL);

    if (session.uri.path == NULL) {
	session.uri.path = ne_strdup("/");
    } else {
	if (!ne_path_has_trailing_slash(session.uri.path)) {
	    pnt = ne_concat(session.uri.path, "/", NULL);
	    free(session.uri.path);
	    session.uri.path = pnt;
	}
    }

    /* Get the proxy details */
    if (proxy_host != NULL) {
	if (get_option(opt_proxy_port) != NULL) {
	    proxy_port = atoi(get_option(opt_proxy_port));
	} else {
	    proxy_port = 8080;
	}
	proxy_hostname = proxy_host;
    }

#ifdef ENABLE_NETRC
    {
	netrc_entry *found;
	found = search_netrc(netrc_list, session.uri.host);
	if (found != NULL) {
	    if (found->account && found->password) {
		server_username = found->account;
		server_password = found->password;
	    }
	}
    }
#endif /* ENABLE_NETRC */
#ifdef NE_SESSFLAG_EXPECT100
	ne_set_session_flag(session.sess, NE_SESSFLAG_EXPECT100, get_bool_option(opt_expect100));
#endif /* NE_SESSFLAG_EXPECT100 */
    session.connected = 0;

    ne_set_useragent(session.sess, "cadaver/" PACKAGE_VERSION);
    ne_set_server_auth(session.sess, supply_creds_server, NULL);
    ne_set_proxy_auth(session.sess, supply_creds_proxy, NULL);
    
    if (proxy_host) {
	ne_session_proxy(session.sess, proxy_hostname, proxy_port);
    }

    ret = ne_options(session.sess, session.uri.path, &caps);
    
    switch (ret) {
    case NE_OK:
	session.connected = true;
	if (set_path(session.uri.path)) {
	    close_connection();
	}
	break;
    case NE_CONNECT:
	if (proxy_host) {
	    printf(_("Could not connect to `%s' on port %d:\n%s\n"),
		   proxy_hostname, proxy_port, ne_get_error(session.sess));
	} else {
	    printf(_("Could not connect to `%s' on port %d:\n%s\n"),
		   session.uri.host, session.uri.port, ne_get_error(session.sess));
	}
	break;
    case NE_LOOKUP:
	puts(ne_get_error(session.sess));
	break;
    default:
	printf(_("Could not open collection:\n%s\n"),
	       ne_get_error(session.sess));
	break;
    }

}
Exemple #20
0
static gboolean
_rawx_update_chunk_attrs(chunk_id_t *cid, GSList *attrs, GError **err)
{
	ne_session *s = NULL;
	ne_request *r = NULL;
	int ne_rc;
	gboolean result = FALSE;

	gchar dst[128];
	guint16 port = 0;
	GString *req_str = NULL;
	char idstr[65];

	if (!addr_info_get_addr(&(cid->addr), dst, sizeof(dst), &port))
		return result;

	s = ne_session_create("http", dst, port);
	if (!s) {
		GSETERROR(err, "Failed to create session to rawx %s:%d", dst, port);
		return result;
	}

	ne_set_connect_timeout(s, 10);
	ne_set_read_timeout(s, 30);

	req_str =g_string_new("/rawx/chunk/set/");
	bzero(idstr, sizeof(idstr));
	buffer2str(&(cid->id), sizeof(cid->id), idstr, sizeof(idstr));
	req_str = g_string_append(req_str, idstr);
	GRID_TRACE("Calling %s", req_str->str);

	r = ne_request_create (s, "GET", req_str->str);
	if (!r) {
		goto end_attr;
	}

	for (; attrs != NULL; attrs = attrs->next) {
		struct chunk_attr_s *attr = attrs->data;
		ne_add_request_header(r, attr->key, attr->val);
	}

	switch (ne_rc = ne_request_dispatch(r)) {
		case NE_OK:
			result = TRUE;
			break;
		case NE_ERROR:
			GSETCODE(err, 500, "Request NE_ERROR");
			break;
		case NE_TIMEOUT:
			GSETCODE(err, 500, "Request Timeout");
			break;
		case NE_CONNECT:
			GSETCODE(err, 500, "Request Connection timeout");
			break;
		default:
			GSETCODE(err, 500, "Request failed");
			break;
	}

end_attr:
	if (NULL != req_str)
		g_string_free(req_str, TRUE);
	if (NULL != r)
		ne_request_destroy (r);
	if (NULL != s)
		ne_session_destroy (s);

	return result;
}
Exemple #21
0
void upsdrv_initups(void)
{
	int	ret;
	char	*val;
	FILE	*fp;

#if HAVE_NE_SET_CONNECT_TIMEOUT && HAVE_NE_SOCK_CONNECT_TIMEOUT
	/* we don't need to use alarm() */
#else
	struct sigaction	sa;

	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;

	sa.sa_handler = netxml_alarm_handler;
	sigaction(SIGALRM, &sa, NULL);
#endif
	/* allow override of default network timeout value */
	val = getval("timeout");
	if (val) {
		timeout = atoi(val);

		if (timeout < 1) {
			fatalx(EXIT_FAILURE, "timeout must be greater than 0");
		}
	}

	val = getval("shutdown_duration");
	if (val) {
		shutdown_duration = atoi(val);

		if (shutdown_duration < 0) {
			fatalx(EXIT_FAILURE, "shutdown duration must be greater than or equal to 0");
		}
	}

	val = getval("shutdown_timer");
	if (val) {
		shutdown_timer = atoi(val);

		if (shutdown_timer < 0) {
			fatalx(EXIT_FAILURE, "shutdown timer must be greater than or equal to 0");
		}
	}

	if (nut_debug_level > 5) {
		ne_debug_init(stderr, NE_DBG_HTTP | NE_DBG_HTTPBODY);
	}

	if (ne_sock_init()) {
		fatalx(EXIT_FAILURE, "%s: failed to initialize socket libraries", progname);
	}

	if (ne_uri_parse(device_path, &uri) || uri.host == NULL) {
		fatalx(EXIT_FAILURE, "%s: invalid hostname '%s'", progname, device_path);
	}
/*
	if (uri.scheme == NULL) {
		uri.scheme = strdup("http");
	}
 
	if (uri.host == NULL) {
		uri.host = strdup(device_path);
	}
 */
	if (uri.port == 0) {
		uri.port = ne_uri_defaultport(uri.scheme);
	}

	upsdebugx(1, "using %s://%s port %d", uri.scheme, uri.host, uri.port);

	session = ne_session_create(uri.scheme, uri.host, uri.port);
	
	/* timeout if we can't (re)connect to the UPS */
#ifdef HAVE_NE_SET_CONNECT_TIMEOUT
	ne_set_connect_timeout(session, timeout);
#endif

	/* just wait for a couple of seconds */
	ne_set_read_timeout(session, timeout);

	ne_set_useragent(session, subdriver->version);

	if (strcasecmp(uri.scheme, "https") == 0) {
		ne_ssl_trust_default_ca(session);
	}

	ne_set_server_auth(session, netxml_authenticate, NULL);

	/* if debug level is set, direct output to stderr */
	if (!nut_debug_level) {
		fp = fopen("/dev/null", "w");
	} else {
		fp = stderr;
	}

	if (!fp) {
		fatal_with_errno(EXIT_FAILURE, "Connectivity test failed");
	}

	/* see if we have a connection */
	ret = ne_get(session, subdriver->initups, fileno(fp));

	if (!nut_debug_level) {
		fclose(fp);
	} else {
		fprintf(fp, "\n");
	}

	if (ret != NE_OK) {
		fatalx(EXIT_FAILURE, "Connectivity test: %s", ne_get_error(session));
	}

	upslogx(LOG_INFO, "Connectivity test: %s", ne_get_error(session));
}
Exemple #22
0
/*
 * Connect to a DAV server
 * This function sets the flag _connected if the connection is established
 * and returns if the flag is set, so calling it frequently is save.
 */
static int dav_connect(const char *base_url) {
    int timeout = 30;
    int useSSL = 0;
    int rc;
    char protocol[6];
    char uaBuf[256];
    char *path = NULL;
    char *scheme = NULL;
    char *host = NULL;
    unsigned int port = 0;

    if (_connected) {
        return 0;
    }

    rc = c_parse_uri( base_url, &scheme, &dav_session.user, &dav_session.pwd, &host, &port, &path );
    if( rc < 0 ) {
        DEBUG_WEBDAV("Failed to parse uri %s", base_url );
        goto out;
    }

    DEBUG_WEBDAV("* scheme %s", scheme ? scheme : "empty");
    DEBUG_WEBDAV("* host %s", host ? host : "empty");
    DEBUG_WEBDAV("* port %u", port );
    DEBUG_WEBDAV("* path %s", path ? path : "empty");

    if( strcmp( scheme, "owncloud" ) == 0 ) {
        strncpy( protocol, "http", 6);
    } else if( strcmp( scheme, "ownclouds" ) == 0 ) {
        strncpy( protocol, "https", 6 );
        useSSL = 1;
    } else {
        strncpy( protocol, "", 6 );
        DEBUG_WEBDAV("Invalid scheme %s, go outa here!", scheme );
        rc = -1;
        goto out;
    }

    DEBUG_WEBDAV("* user %s", dav_session.user ? dav_session.user : "");

    if (port == 0) {
        port = ne_uri_defaultport(protocol);
    }

    rc = ne_sock_init();
    DEBUG_WEBDAV("ne_sock_init: %d", rc );
    if (rc < 0) {
        rc = -1;
        goto out;
    }

    dav_session.ctx = ne_session_create( protocol, host, port);

    if (dav_session.ctx == NULL) {
        DEBUG_WEBDAV("Session create with protocol %s failed", protocol );
        rc = -1;
        goto out;
    }

    ne_set_read_timeout(dav_session.ctx, timeout);
    snprintf( uaBuf, sizeof(uaBuf), "csyncoC/%s",CSYNC_STRINGIFY( LIBCSYNC_VERSION ));
    ne_set_useragent( dav_session.ctx, c_strdup( uaBuf ));
    ne_set_server_auth(dav_session.ctx, ne_auth, 0 );

    if( useSSL ) {
        if (!ne_has_support(NE_FEATURE_SSL)) {
            DEBUG_WEBDAV("Error: SSL is not enabled.");
            rc = -1;
            goto out;
        }

        ne_ssl_trust_default_ca( dav_session.ctx );
        ne_ssl_set_verify( dav_session.ctx, verify_sslcert, 0 );
    }

    _connected = 1;
    rc = 0;
out:
    SAFE_FREE(path);
    SAFE_FREE(host);
    SAFE_FREE(scheme);

    return rc;
}
/* Try to send the HTTP request to the Icecast server, and if possible deals with
 * all the probable redirections (HTTP status code == 3xx)
 */
static gint
gst_neonhttp_src_send_request_and_redirect (GstNeonhttpSrc * src,
        ne_session ** ses, ne_request ** req, gint64 offset, gboolean do_redir)
{
    ne_session *session = NULL;
    ne_request *request = NULL;
    gchar **c;
    gint res;
    gint http_status = 0;
    guint request_count = 0;

    do {
        if (src->proxy.host && src->proxy.port) {
            session =
                ne_session_create (src->uri.scheme, src->uri.host, src->uri.port);
            ne_session_proxy (session, src->proxy.host, src->proxy.port);
        } else if (src->proxy.host || src->proxy.port) {
            /* both proxy host and port must be specified or none */
            return HTTP_REQUEST_WRONG_PROXY;
        } else {
            session =
                ne_session_create (src->uri.scheme, src->uri.host, src->uri.port);
        }

        if (src->connect_timeout > 0) {
            ne_set_connect_timeout (session, src->connect_timeout);
        }

        if (src->read_timeout > 0) {
            ne_set_read_timeout (session, src->read_timeout);
        }

        ne_set_session_flag (session, NE_SESSFLAG_ICYPROTO, 1);
        ne_ssl_set_verify (session, ssl_verify_callback, src);

        request = ne_request_create (session, "GET", src->query_string);

        if (src->user_agent) {
            ne_add_request_header (request, "User-Agent", src->user_agent);
        }

        for (c = src->cookies; c != NULL && *c != NULL; ++c) {
            GST_INFO ("Adding header Cookie : %s", *c);
            ne_add_request_header (request, "Cookies", *c);
        }

        if (src->iradio_mode)
            ne_add_request_header (request, "icy-metadata", "1");

        if (offset > 0) {
            ne_print_request_header (request, "Range",
                                     "bytes=%" G_GINT64_FORMAT "-", offset);
        }

        res = ne_begin_request (request);

        if (res == NE_OK) {
            /* When the HTTP status code is 3xx, it is not the SHOUTcast streaming content yet;
             * Reload the HTTP request with a new URI value */
            http_status = ne_get_status (request)->code;
            if (STATUS_IS_REDIRECTION (http_status) && do_redir) {
                const gchar *redir;

                /* the new URI value to go when redirecting can be found on the 'Location' HTTP header */
                redir = ne_get_response_header (request, "Location");
                if (redir != NULL) {
                    ne_uri_free (&src->uri);
                    gst_neonhttp_src_set_location (src, redir, NULL);
                    GST_LOG_OBJECT (src, "Got HTTP Status Code %d", http_status);
                    GST_LOG_OBJECT (src, "Using 'Location' header [%s]", src->uri.host);
                }
            }
        }

        if ((res != NE_OK) ||
                (offset == 0 && http_status != 200) ||
                (offset > 0 && http_status != 206 &&
                 !STATUS_IS_REDIRECTION (http_status))) {
            ne_request_destroy (request);
            request = NULL;
            ne_close_connection (session);
            ne_session_destroy (session);
            session = NULL;
            if (offset > 0 && http_status != 206 &&
                    !STATUS_IS_REDIRECTION (http_status)) {
                src->seekable = FALSE;
            }
        }

        /* if - NE_OK */
        if (STATUS_IS_REDIRECTION (http_status) && do_redir) {
            ++request_count;
            GST_LOG_OBJECT (src, "redirect request_count is now %d", request_count);
            if (request_count < MAX_HTTP_REDIRECTS_NUMBER && do_redir) {
                GST_INFO_OBJECT (src, "Redirecting to %s", src->uri.host);
            } else {
                GST_WARNING_OBJECT (src, "Will not redirect, try again with a "
                                    "different URI or redirect location %s", src->uri.host);
            }
            /* FIXME: when not redirecting automatically, shouldn't we post a
             * redirect element message on the bus? */
        }
        /* do the redirect, go back to send another HTTP request now using the 'Location' */
    } while (do_redir && (request_count < MAX_HTTP_REDIRECTS_NUMBER)
             && STATUS_IS_REDIRECTION (http_status));

    if (session) {
        *ses = session;
        *req = request;
    }

    return res;
}