Beispiel #1
0
int test(char *URL)
{
  CURL *c;
  CURLM *m;
  int res = 0;
  int running;
  char done = FALSE;
  struct timeval ml_start;
  struct timeval mp_start;
  char ml_timedout = FALSE;
  char mp_timedout = FALSE;

  if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    return TEST_ERR_MAJOR_BAD;
  }

  if ((c = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  curl_easy_setopt(c, CURLOPT_PROXY, libtest_arg2); /* set in first.c */
  curl_easy_setopt(c, CURLOPT_URL, URL);
  curl_easy_setopt(c, CURLOPT_USERPWD, "test:ing");
  curl_easy_setopt(c, CURLOPT_PROXYUSERPWD, "test:ing");
  curl_easy_setopt(c, CURLOPT_HTTPPROXYTUNNEL, 1L);
  curl_easy_setopt(c, CURLOPT_HEADER, 1L);

  if ((m = curl_multi_init()) == NULL) {
    fprintf(stderr, "curl_multi_init() failed\n");
    curl_easy_cleanup(c);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  if ((res = (int)curl_multi_add_handle(m, c)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", res);
    curl_multi_cleanup(m);
    curl_easy_cleanup(c);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  ml_timedout = FALSE;
  ml_start = tutil_tvnow();

  while(!done) {
    fd_set rd, wr, exc;
    int max_fd;
    struct timeval interval;

    interval.tv_sec = 1;
    interval.tv_usec = 0;

    if (tutil_tvdiff(tutil_tvnow(), ml_start) >
        MAIN_LOOP_HANG_TIMEOUT) {
      ml_timedout = TRUE;
      break;
    }
    mp_timedout = FALSE;
    mp_start = tutil_tvnow();

    while (res == CURLM_CALL_MULTI_PERFORM) {
      res = (int)curl_multi_perform(m, &running);
      if (tutil_tvdiff(tutil_tvnow(), mp_start) >
          MULTI_PERFORM_HANG_TIMEOUT) {
        mp_timedout = TRUE;
        break;
      }
      if (running <= 0) {
        done = TRUE;
        break;
      }
    }
    if (mp_timedout || done)
      break;

    if (res != CURLM_OK) {
      fprintf(stderr, "not okay???\n");
      break;
    }

    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&exc);
    max_fd = 0;

    if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) {
      fprintf(stderr, "unexpected failured of fdset.\n");
      res = 89;
      break;
    }

    if (select_test(max_fd+1, &rd, &wr, &exc, &interval) == -1) {
      fprintf(stderr, "bad select??\n");
      res = 95;
      break;
    }

    res = CURLM_CALL_MULTI_PERFORM;
  }

  if (ml_timedout || mp_timedout) {
    if (ml_timedout) fprintf(stderr, "ml_timedout\n");
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    res = TEST_ERR_RUNS_FOREVER;
  }

  curl_multi_remove_handle(m, c);
  curl_easy_cleanup(c);
  curl_multi_cleanup(m);
  curl_global_cleanup();

  return res;
}
static int
testMultithreadedPoolPut ()
{
    struct MHD_Daemon *d;
    CURL *c;
    struct CBC cbc;
    unsigned int pos = 0;
    int done_flag = 0;
    CURLcode errornum;
    char buf[2048];

    cbc.buf = buf;
    cbc.size = 2048;
    cbc.pos = 0;
    d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
                          1081,
                          NULL, NULL, &ahc_echo, &done_flag,
                          MHD_OPTION_THREAD_POOL_SIZE, 4,
                          MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (1024*1024),
                          MHD_OPTION_END);
    if (d == NULL)
        return 16;
    c = curl_easy_init ();
    curl_easy_setopt (c, CURLOPT_URL, "http://localhost:1081/hello_world");
    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
    if (oneone)
        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    else
        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L);
    // NOTE: use of CONNECTTIMEOUT without also
    //   setting NOSIGNAL results in really weird
    //   crashes on my system!
    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
    if (CURLE_OK != (errornum = curl_easy_perform (c)))
    {
        fprintf (stderr,
                 "curl_easy_perform failed: `%s'\n",
                 curl_easy_strerror (errornum));
        curl_easy_cleanup (c);
        MHD_stop_daemon (d);
        return 32;
    }
    curl_easy_cleanup (c);
    MHD_stop_daemon (d);
    if (cbc.pos != strlen ("/hello_world"))
    {
        fprintf (stderr, "Got invalid response `%.*s'\n", (int)cbc.pos, cbc.buf);
        return 64;
    }
    if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
        return 128;
    return 0;
}
Beispiel #3
0
int test(char *URL)
{
  int res;
  CURL *curl;
  int counter=0;
  CURLM *m = NULL;
  int running=1;
  struct timeval mp_start;
  char mp_timedout = FALSE;

  if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    return TEST_ERR_MAJOR_BAD;
  }

  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  test_setopt(curl, CURLOPT_URL, URL);
  test_setopt(curl, CURLOPT_VERBOSE, 1L);
  test_setopt(curl, CURLOPT_HEADER, 1L);

  /* read the POST data from a callback */
  test_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctlcallback);
  test_setopt(curl, CURLOPT_IOCTLDATA, &counter);
  test_setopt(curl, CURLOPT_READFUNCTION, readcallback);
  test_setopt(curl, CURLOPT_READDATA, &counter);
  /* We CANNOT do the POST fine without setting the size (or choose chunked)! */
  test_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(UPLOADTHIS));

  test_setopt(curl, CURLOPT_POST, 1L);
#ifdef CURL_DOES_CONVERSIONS
  /* Convert the POST data to ASCII. */
  test_setopt(curl, CURLOPT_TRANSFERTEXT, 1L);
#endif
  test_setopt(curl, CURLOPT_PROXY, libtest_arg2);
  test_setopt(curl, CURLOPT_PROXYUSERPWD, libtest_arg3);
  test_setopt(curl, CURLOPT_PROXYAUTH,
                   (long) (CURLAUTH_NTLM | CURLAUTH_DIGEST | CURLAUTH_BASIC) );

  if ((m = curl_multi_init()) == NULL) {
    fprintf(stderr, "curl_multi_init() failed\n");
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  if ((res = (int)curl_multi_add_handle(m, curl)) != CURLM_OK) {
    fprintf(stderr, "curl_multi_add_handle() failed, "
            "with code %d\n", res);
    curl_multi_cleanup(m);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  mp_timedout = FALSE;
  mp_start = tutil_tvnow();

  while (running) {
    res = (int)curl_multi_perform(m, &running);
    if (tutil_tvdiff(tutil_tvnow(), mp_start) >
        MULTI_PERFORM_HANG_TIMEOUT) {
      mp_timedout = TRUE;
      break;
    }
#ifdef TPF
    sleep(1); /* avoid ctl-10 dump */
#endif
    if (running <= 0) {
      fprintf(stderr, "nothing left running.\n");
      break;
    }
  }

  if (mp_timedout) {
    if (mp_timedout) fprintf(stderr, "mp_timedout\n");
    fprintf(stderr, "ABORTING TEST, since it seems "
            "that it would have run forever.\n");
    res = TEST_ERR_RUNS_FOREVER;
  }

test_cleanup:

  if(m) {
    curl_multi_remove_handle(m, curl);
    curl_multi_cleanup(m);
  }
  curl_easy_cleanup(curl);
  curl_global_cleanup();

  return res;
}
// Process POST Request
KDint processPostTask ( CCHttpRequest* pRequest, write_callback pCallback, KDvoid* pStream, KDint* pResponseCode )
{
    CURLcode  eCode = CURL_LAST;
    CURL*     pCurl = curl_easy_init ( );
    
    do 
	{
        if ( !configureCURL ( pCurl ) )
		{
            break;
        }
        
        // handle custom header data 
        // create curl linked list 
        struct curl_slist*  pHeaders = KD_NULL;
        // get custom header data (if set) 
  		std::vector<std::string>  aHeaders = pRequest->getHeaders ( );
  		if ( !aHeaders.empty ( ) )
  		{      			
    		for ( std::vector<std::string>::iterator it = aHeaders.begin ( ); it != aHeaders.end ( ); it++ )
    		{
				// append custom headers one by one 
      			pHeaders = curl_slist_append ( pHeaders, it->c_str ( ) );
    		}
			
			// set custom headers for curl 
    		eCode = curl_easy_setopt ( pCurl, CURLOPT_HTTPHEADER, pHeaders );
    		if ( eCode != CURLE_OK )
			{
      			break;
    		}
  		}
              
        eCode = curl_easy_setopt ( pCurl, CURLOPT_URL, pRequest->getUrl ( ) );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }

        eCode = curl_easy_setopt ( pCurl, CURLOPT_WRITEFUNCTION, pCallback );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }

        eCode = curl_easy_setopt ( pCurl, CURLOPT_WRITEDATA, pStream );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }

        eCode = curl_easy_setopt ( pCurl, CURLOPT_POST, 1 );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }

        eCode = curl_easy_setopt ( pCurl, CURLOPT_POSTFIELDS, pRequest->getRequestData ( ) );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }

        eCode = curl_easy_setopt ( pCurl, CURLOPT_POSTFIELDSIZE, pRequest->getRequestDataSize ( ) );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }

        eCode = curl_easy_perform ( pCurl );
        if ( eCode != CURLE_OK ) 
		{
            break;
        }
        
        // free the linked list for header data 
        curl_slist_free_all ( pHeaders );

        eCode = curl_easy_getinfo ( pCurl, CURLINFO_RESPONSE_CODE, pResponseCode ); 
        if ( eCode != CURLE_OK || *pResponseCode != 200 ) 
		{
            eCode = CURLE_HTTP_RETURNED_ERROR;
        }

    } while ( 0 );

    if ( pCurl )
	{
        curl_easy_cleanup ( pCurl );
    }
    
    return ( eCode == CURLE_OK ? 0 : 1 );    
}
Beispiel #5
0
int test(char *URL)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  FILE *hd_src ;
  int hd ;
  struct_stat file_info;
  struct curl_slist *hl;
  int error;

  struct curl_slist *headerlist=NULL;
  const char *buf_1 = "RNFR 505";
  const char *buf_2 = "RNTO 505-forreal";

  if (!libtest_arg2) {
    fprintf(stderr, "Usage: <url> <file-to-upload>\n");
    return -1;
  }

  hd_src = fopen(libtest_arg2, "rb");
  if(NULL == hd_src) {
    error = ERRNO;
    fprintf(stderr, "fopen() failed with error: %d %s\n",
            error, strerror(error));
    fprintf(stderr, "Error opening file: %s\n", libtest_arg2);
    return -2; /* if this happens things are major weird */
  }

  /* get the file size of the local file */
  hd = fstat(fileno(hd_src), &file_info);
  if(hd == -1) {
    /* can't open file, bail out */
    error = ERRNO;
    fprintf(stderr, "fstat() failed with error: %d %s\n",
            error, strerror(error));
    fprintf(stderr, "ERROR: cannot open file %s\n", libtest_arg2);
    fclose(hd_src);
    return -1;
  }

  if(! file_info.st_size) {
    fprintf(stderr, "ERROR: file %s has zero size!\n", libtest_arg2);
    fclose(hd_src);
    return -4;
  }

  if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  /* get a curl handle */
  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }

  /* build a list of commands to pass to libcurl */

  if ((hl = curl_slist_append(headerlist, buf_1)) == NULL) {
    fprintf(stderr, "curl_slist_append() failed\n");
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }
  if ((headerlist = curl_slist_append(hl, buf_2)) == NULL) {
    fprintf(stderr, "curl_slist_append() failed\n");
    curl_slist_free_all(hl);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    fclose(hd_src);
    return TEST_ERR_MAJOR_BAD;
  }
  headerlist = hl;

  /* enable uploading */
  test_setopt(curl, CURLOPT_UPLOAD, 1L);

  /* enable verbose */
  test_setopt(curl, CURLOPT_VERBOSE, 1L);

  /* specify target */
  test_setopt(curl,CURLOPT_URL, URL);

  /* pass in that last of FTP commands to run after the transfer */
  test_setopt(curl, CURLOPT_POSTQUOTE, headerlist);

  /* now specify which file to upload */
  test_setopt(curl, CURLOPT_INFILE, hd_src);

  /* and give the size of the upload (optional) */
  test_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                   (curl_off_t)file_info.st_size);

  /* Now run off and do what you've been told! */
  res = curl_easy_perform(curl);

test_cleanup:

  /* clean up the FTP commands list */
  curl_slist_free_all(headerlist);

  /* close the local file */
  fclose(hd_src);

  curl_easy_cleanup(curl);
  curl_global_cleanup();

  return res;
}
Beispiel #6
0
/******************************************************************************
 *                                                                            *
 * Function: send_ez_texting                                                  *
 *                                                                            *
 * Purpose: send SMS using Ez Texting API                                     *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value: SUCCEED if message has been sent successfully                *
 *               FAIL otherwise                                               *
 *                                                                            *
 * Author: Aleksandrs Saveljevs                                               *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
int	send_ez_texting(const char *username, const char *password, const char *sendto,
		const char *message, const char *limit, char *error, int max_error_len)
{
#ifdef HAVE_LIBCURL

	const char	*__function_name = "send_ez_texting";

	int		ret = FAIL;
	int		max_message_len;
	int		i, len, opt, err;
	char		*sendto_digits = NULL, *message_ascii = NULL;
	char		*username_esc = NULL, *password_esc = NULL, *sendto_esc = NULL, *message_esc = NULL;
	char		postfields[MAX_STRING_LEN];
	CURL		*easy_handle = NULL;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() sendto:'%s' message:'%s'", __function_name, sendto, message);

	assert(error);
	*error = '\0';

	memset(&page, 0, sizeof(page));

	/* replace UTF-8 and invalid ASCII characters, and make sure the message is not too long */

	switch (atoi(limit))
	{
		case EZ_TEXTING_LIMIT_USA:
			max_message_len = EZ_TEXTING_LENGTH_USA;
			break;
		case EZ_TEXTING_LIMIT_CANADA:
			max_message_len = EZ_TEXTING_LENGTH_CANADA;
			break;
		default:
			THIS_SHOULD_NEVER_HAPPEN;
			zbx_snprintf(error, max_error_len, "Could not determine proper length limit: [%s]", limit);
			goto clean;
	}

	if (NULL == (message_ascii = zbx_replace_utf8(message)))
	{
		zbx_snprintf(error, max_error_len, "Could not replace UTF-8 characters: [%s]", message);
		goto clean;
	}

	for (i = 0, len = 0; '\0' != message_ascii[i] && len < max_message_len; i++, len++)
	{
		if (' ' == message_ascii[i])
			continue;
		if ('a' <= message_ascii[i] && message_ascii[i] <= 'z')
			continue;
		if ('A' <= message_ascii[i] && message_ascii[i] <= 'Z')
			continue;
		if ('0' <= message_ascii[i] && message_ascii[i] <= '9')
			continue;

		if ('\t' == message_ascii[i])	/* \t is not part of GSM character set */
		{
			message_ascii[i] = ' ';
			continue;
		}
		if ('\r' == message_ascii[i])	/* line end counts as two, regardless of... */
		{
			if ('\n' != message_ascii[i + 1])
				len++;
			continue;
		}
		if ('\n' == message_ascii[i])	/* ... how it is specified: \r, \n, or \r\n */
		{
			if (0 < i && '\r' != message_ascii[i - 1])
				len++;
			continue;
		}
		if (NULL == (strchr(EZ_TEXTING_VALID_CHARS, message_ascii[i])))
		{
			message_ascii[i] = '?';
			continue;
		}
		if (NULL != (strchr(EZ_TEXTING_DOUBLE_CHARS, message_ascii[i])))
		{
			len++;
			continue;
		}
	}

	if (len > max_message_len)
		i--;

	message_ascii[i] = '\0';

	/* prepare and make cURL request to Ez Texting API */

	if (NULL == (easy_handle = curl_easy_init()))
	{
		zbx_snprintf(error, max_error_len, "Could not initialize cURL");
		goto clean;
	}

	sendto_digits = strdup(sendto);
	zbx_remove_chars(sendto_digits, "() -"); /* allow phone numbers to be specified like "(123) 456-7890" */

	if (NULL == (username_esc = curl_easy_escape(easy_handle, username, strlen(username))) ||
			NULL == (password_esc = curl_easy_escape(easy_handle, password, strlen(password))) ||
			NULL == (sendto_esc = curl_easy_escape(easy_handle, sendto_digits, strlen(sendto_digits))) ||
			NULL == (message_esc = curl_easy_escape(easy_handle, message_ascii, strlen(message_ascii))))
	{
		zbx_snprintf(error, max_error_len, "Could not URL encode POST fields");
		goto clean;
	}

	zbx_snprintf(postfields, sizeof(postfields), "user=%s&pass=%s&phonenumber=%s&subject=&message=%s",
			username_esc, password_esc, sendto_esc, message_esc);

	if (CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_USERAGENT, "Zabbix " ZABBIX_VERSION)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_FOLLOWLOCATION, 1L)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_WRITEFUNCTION, WRITEFUNCTION2)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_HEADERFUNCTION, HEADERFUNCTION2)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_SSL_VERIFYPEER, 1L)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_SSL_VERIFYHOST, 2L)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_POSTFIELDS, postfields)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_POST, 1L)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_URL, EZ_TEXTING_API_URL)) ||
			CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_TIMEOUT, (long)EZ_TEXTING_TIMEOUT)))
	{
		zbx_snprintf(error, max_error_len, "Could not set cURL option %d: [%s]", opt, curl_easy_strerror(err));
		goto clean;
	}

	if (NULL != CONFIG_SOURCE_IP)
	{
		if (CURLE_OK != (err = curl_easy_setopt(easy_handle, opt = CURLOPT_INTERFACE, CONFIG_SOURCE_IP)))
		{
			zbx_snprintf(error, max_error_len, "Could not set cURL option %d: [%s]",
					opt, curl_easy_strerror(err));
			goto clean;
		}
	}

	if (CURLE_OK != (err = curl_easy_perform(easy_handle)))
	{
		zbx_snprintf(error, max_error_len, "Error doing curl_easy_perform(): [%s]", curl_easy_strerror(err));
		goto clean;
	}

	/* parse the response */

	if (NULL == page.data || FAIL == is_int_prefix(page.data))
	{
		zbx_snprintf(error, max_error_len, "Did not receive a proper response: [%s]", ZBX_NULL2STR(page.data));
		goto clean;
	}

	switch (atoi(page.data))
	{
		case 1:
			ret = SUCCEED;
			break;
		case -1:
			zbx_snprintf(error, max_error_len, "Invalid user and/or password or API is not allowed");
			break;
		case -2:
			zbx_snprintf(error, max_error_len, "Credit limit reached");
			break;
		case -5:
			zbx_snprintf(error, max_error_len, "Locally opted out phone number");
			break;
		case -7:
			zbx_snprintf(error, max_error_len, "Message too long or contains invalid characters");
			break;
		case -104:
			zbx_snprintf(error, max_error_len, "Globally opted out phone number");
			break;
		case -106:
			zbx_snprintf(error, max_error_len, "Incorrectly formatted phone number");
			break;
		case -10:
			zbx_snprintf(error, max_error_len, "Unknown error (please contact Ez Texting)");
			break;
		default:
			zbx_snprintf(error, max_error_len, "Unknown return value: [%s]", page.data);
			break;
	}
clean:
	if (NULL != message_ascii)
		zbx_free(message_ascii);
	if (NULL != sendto_digits)
		zbx_free(sendto_digits);
	if (NULL != username_esc)
		zbx_free(username_esc);
	if (NULL != password_esc)
		zbx_free(password_esc);
	if (NULL != sendto_esc)
		zbx_free(sendto_esc);
	if (NULL != message_esc)
		zbx_free(message_esc);
	if (NULL != page.data)
		zbx_free(page.data);
	if (NULL != easy_handle)
		curl_easy_cleanup(easy_handle);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;

#else
	zbx_snprintf(error, max_error_len, "cURL library is required for Ez Texting support");
	return FAIL;

#endif	/* HAVE_LIBCURL */
}
Beispiel #7
0
bool SMTPClient::SendEmail()
{
	if (m_From.size()==0)
		return false;
	if (m_Recipients.size()==0)
		return false;
	if (m_Server.size()==0)
		return false;

	const std::string rmessage=MakeMessage();

	CURLcode ret;
	struct curl_slist *slist1;

	smtp_upload_status smtp_ctx;
	smtp_ctx.bytes_read=0;

	slist1 = NULL;


	std::vector<std::string>::const_iterator itt;
	for (itt=m_Recipients.begin(); itt!=m_Recipients.end(); ++itt)
	{
		slist1 = curl_slist_append(slist1, (*itt).c_str());
	}

	std::stringstream sstr;
	sstr << "smtp://" << m_Server << ":" << m_Port;
	std::string szURL=sstr.str();//"smtp://"+MailServer;

	try
	{
		CURL *curl;
		curl = curl_easy_init();

		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);

		curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)177);
		curl_easy_setopt(curl, CURLOPT_URL, szURL.c_str());
		curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
		if (m_Username!="")
		{
			//std::string szUserPassword=MailUsername+":"+MailPassword;
			//curl_easy_setopt(curl, CURLOPT_USERPWD, szUserPassword.c_str());
			curl_easy_setopt(curl, CURLOPT_USERNAME, m_Username.c_str());
			curl_easy_setopt(curl, CURLOPT_PASSWORD, m_Password.c_str());
		}
		curl_easy_setopt(curl, CURLOPT_USERAGENT, "domoticz/7.26.0");
		curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
		curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);//CURLUSESSL_ALL);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
		curl_easy_setopt(curl, CURLOPT_SSLVERSION, 0L);
		curl_easy_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE, 0L);
		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

		//curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
		curl_easy_setopt(curl, CURLOPT_MAIL_FROM, m_From.c_str());
		curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, slist1);

		smtp_ctx.pDataBytes=new char[rmessage.size()];
		if (smtp_ctx.pDataBytes==NULL)
		{
			_log.Log(LOG_ERROR,"SMTP Mailer: Out of Memory!");

			curl_easy_cleanup(curl);
			curl_slist_free_all(slist1);
			return false;
		}
		smtp_ctx.sDataLength=rmessage.size();
		memcpy(smtp_ctx.pDataBytes,rmessage.c_str(),smtp_ctx.sDataLength);

		curl_easy_setopt(curl, CURLOPT_READFUNCTION, smtp_payload_reader);
		curl_easy_setopt(curl, CURLOPT_READDATA, &smtp_ctx);

		ret = curl_easy_perform(curl);

		curl_easy_cleanup(curl);
		curl_slist_free_all(slist1);
		delete [] smtp_ctx.pDataBytes;

		if (ret!=CURLE_OK)
		{
			_log.Log(LOG_ERROR,"SMTP Mailer: Error sending Email to: %s !",m_Recipients[0].c_str());
			return false;
		}
	}
	catch (...)
	{
		_log.Log(LOG_ERROR,"SMTP Mailer: Error sending Email to: %s !",m_Recipients[0].c_str());
		return false;
	}
	return true;
}
Beispiel #8
0
int curl_http_head(struct response_head *headinfo, const char * remotepath, const char * referer,const char * cookie)
{
	long timeout = 60;
	long connect_timeout = 30;
	headinfo->size = -1;
	headinfo->last_modified = -1;

	CURL *curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); // for thread safe
	curl_easy_setopt(curl, CURLOPT_URL, remotepath);
	if(referer) curl_easy_setopt(curl, CURLOPT_REFERER, referer);
	if(cookie)  curl_easy_setopt(curl, CURLOPT_COOKIE, cookie);
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "icache");
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connect_timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10L);
	curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
	curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
	CURLcode rc = curl_easy_perform(curl);
	long response_code;
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
	if ((rc==CURLE_OK && (response_code==405 || response_code==400 || response_code==403)) || rc==CURLE_GOT_NOTHING || rc==CURLE_OPERATION_TIMEDOUT){
		int last_head = 0;
		curl_easy_cleanup(curl);
        char temp_path[] = "/tmp/tmp_XXXXXX";
        int fd = mkstemp(temp_path);
        if (fd!=-1) close(fd);
		FILE *fp = fopen(temp_path, "w");
		curl = curl_easy_init();
		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); //for thread safe
		curl_easy_setopt(curl, CURLOPT_URL, remotepath);
		if(referer) curl_easy_setopt(curl, CURLOPT_REFERER, referer);
		if(cookie)  curl_easy_setopt(curl, CURLOPT_COOKIE, cookie);
		curl_easy_setopt(curl, CURLOPT_USERAGENT, "icache");
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connect_timeout);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10L);
		curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
		curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, curl_head);
		curl_easy_setopt(curl, CURLOPT_HEADERDATA, &last_head);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
		rc = curl_easy_perform(curl);
		fclose(fp);
		unlink(temp_path);
		curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
	}
	if ((rc==CURLE_OK || rc==CURLE_WRITE_ERROR) && response_code==200){
		double len;
		curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &len);
		headinfo->size = len;
		curl_easy_getinfo(curl, CURLINFO_FILETIME, &headinfo->last_modified);
	}
	curl_easy_cleanup(curl);
	if (headinfo->last_modified == -1) headinfo->last_modified = 0;
	if (headinfo->size!=-1){
		return 1;
	}else {
		return 0;
	}
}
Beispiel #9
0
//int curl_http_header(char *url_live, http_payload_t *http_payload, int *flag)
int curl_http_header(char *url_live, http_payload_t *host_url, http_payload_t *http_payload, int *flag)
{
	CURL *curl_handle;
	
	char *redirect_url;
	//int response_code;
	long response_code;

	//http_payload_t *chunk = http_payload;
	http_payload_t *chunk = host_url;

	/* FIXME  may cause memory lost
	 * if http_payload->memory already has a memory, the free job must 
	 * give to the pointer which it give to */
	chunk->memory = malloc(1);  	/* will be grown as needed by the realloc above */
	chunk->size = 0;    			/* no data at this point */
	
	//hls_dbg("[curl get request]===>%s\n", url_live);

	/* FIXME 
	 * QQTV's source do not support HTTP HEAD/ request, so we must request HTTP GET/
	 * but in curl_http_header(), we do not send http body out */
	//http_payload_t body_duty;
	//body_duty.memory = malloc(1);
	//body_duty.size = 0;
	http_payload_t *chunk1 = http_payload;
	chunk1->memory = malloc(1);
	chunk1->size = 0;	

	//curl_global_init(CURL_GLOBAL_ALL);

	/* init the curl session */
	curl_handle = curl_easy_init();

	/* specify URL to get */
	curl_easy_setopt(curl_handle, CURLOPT_URL, url_live);
	
	/* do not download body */
	//curl_easy_setopt(curl_handle, CURLOPT_NOBODY, 1);
	
	/* FIXME we need get the rederection url, so not do it here */
	//curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1);

	/* send all data to this function  */
	curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);

	/* we pass our 'chunk' struct to the callback function */
	//curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&body_duty);
	curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)chunk1);
	
	/* add http GET/ range context */
	curl_easy_setopt(curl_handle, CURLOPT_RANGE,"0-");
	
	/* some servers don't like requests that are made without a user-agent
     * field, so we provide one */
	curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
	
	//curl_easy_setopt(curl_handle, CURLOPT_FORBID_REUSE, 1);

	/* some servers don't like requests that are made without a user-agent
	   field, so we provide one */
	//curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");

	/* this fun will not return until the http payload is all download */
	curl_easy_perform(curl_handle);
	
	/* get http response code */
	curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &response_code);
	//hls_dbg("response_code = %d\n", response_code);
	
	/* for QQTV souct, release the body_duty.memory, do not send data out */
	//free(body_duty.memory);
	
	if (response_code == HLS_REDIRECT) {
		/* get redirect_url 2013-01-19 */
		curl_easy_getinfo(curl_handle, CURLINFO_REDIRECT_URL, &redirect_url);
		hls_dbg("redirect_url >>> %s\n", redirect_url);
		
		chunk->memory = realloc(chunk->memory, strlen(redirect_url) + 1);
		if (chunk->memory == NULL) {
			/* out of memory! */
			hls_err("not enough memory (realloc returned NULL)\n");
			exit(EXIT_FAILURE);
		}

		memcpy(&(chunk->memory[chunk->size]), redirect_url, strlen(redirect_url));
		chunk->size += strlen(redirect_url);
		chunk->memory[chunk->size] = 0;
		
		*flag = HLS_REDIRECT;
	} //else if (response_code != 200)
		//*flag = 0;

	/* cleanup curl stuff */
	curl_easy_cleanup(curl_handle);

	/*
	 * Now, our chunk.memory points to a memory block that is chunk.size
	 * bytes big and contains the remote file.
	 *
	 * Do something nice with it!
	 *
	 * You should be aware of the fact that at this point we might have an
	 * allocated data block, and nothing has yet deallocated that data. So when
	 * you're done with it, you should free() it as a nice application.
	 */

	//hls_dbg("%lu bytes retrieved\n", (long)chunk->size);

	/* FIXME
	 * modified by juguofeng
	 * do not free it here only in this project 
	 */
	//if(chunk->memory)
	//	free(chunk->memory);
	
	/* we're done with libcurl, so clean it up */
	//curl_global_cleanup();

	return 0;
}
Beispiel #10
0
char* curl_post_form(const char *url,\
	                 const char *postdata,\
	                 const char *proxy,\
	                 const char *cookie,\
	                 int flag_cookie)


{
   long timeout = 10800;
	long connect_timeout = 15;
	long low_speed_limit = 1024;
	long low_speed_time = 60;

	struct mem_node *mem_head = NULL;
	long response_code;
   CURL *curl = curl_easy_init();
   curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); // for thread safe
   curl_easy_setopt(curl,CURLOPT_URL,url); //url地址  
   curl_easy_setopt(curl,CURLOPT_POSTFIELDS,postdata); //post参数  
   curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connect_timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, low_speed_time);
   curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,&curl_read); //对返回的数据进行操作的函数地址  
   curl_easy_setopt(curl,CURLOPT_WRITEDATA,&mem_head); //这是write_data的第四个参数值  
   curl_easy_setopt(curl,CURLOPT_POST,1); //设置非0表示本次操作为post   
   curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应头信息location  
   if(flag_cookie)
   {
    curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"./cookie.txt");
     curl_easy_setopt(curl,CURLOPT_COOKIEJAR,"./cookie.txt");
 }
  // curl_easy_setopt(easy_handle, CURLOPT_PROXY,proxy);
   CURLcode rc = curl_easy_perform(curl); 
  	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
	curl_easy_cleanup(curl);
	if (rc!=CURLE_OK) {
		return NULL;
	}else if (response_code!=200 && response_code!=206){
		struct mem_node *p = mem_head;
		while(p){
			struct mem_node *q = p;
			p = p->next;
			free(q->buffer);
			free(q);
		}
		return NULL;
	}else{
		struct mem_node *p = mem_head;
		size_t size = 0;
		while(p){
			size += p->size;
			p = p->next;
		}
		char *content = (char*)malloc(size+1);
		p = mem_head;
		size = 0;
		while(p){
			memcpy(content+size, p->buffer, p->size);
			size += p->size;
			struct mem_node *q = p;
			p = p->next;
			free(q->buffer);
			free(q);
		}
		content[size] = 0;
		return content;
	}
  
}
Beispiel #11
0
char* curl_http_content(const char *uri ,int flag_cookie)
{
	long timeout = 10800;
	long connect_timeout = 15;
	long low_speed_limit = 1024;
	long low_speed_time = 60;

	struct mem_node *mem_head = NULL;
	long response_code;
	CURL *curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); // for thread safe
	curl_easy_setopt(curl, CURLOPT_URL, uri);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connect_timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, low_speed_time);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10L);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &curl_read);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &mem_head);
	if(flag_cookie)
	{
	 curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"./cookie.txt");
    curl_easy_setopt(curl,CURLOPT_COOKIEJAR,"./cookie.txt");
    }
	CURLcode rc = curl_easy_perform(curl);
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
	curl_easy_cleanup(curl);

	if (rc!=CURLE_OK) {
		return NULL;
	}else if (response_code!=200 && response_code!=206){
		struct mem_node *p = mem_head;
		while(p){
			struct mem_node *q = p;
			p = p->next;
			free(q->buffer);
			free(q);
		}
		return NULL;
	}else{
		struct mem_node *p = mem_head;
		size_t size = 0;
		while(p){
			size += p->size;
			p = p->next;
		}
		char *content = (char*)malloc(size+1);
		p = mem_head;
		size = 0;
		while(p){
			memcpy(content+size, p->buffer, p->size);
			size += p->size;
			struct mem_node *q = p;
			p = p->next;
			free(q->buffer);
			free(q);
		}
		content[size] = 0;
		return content;
	}
}
Beispiel #12
0
int curl_http_file(const char * localpath, const char * remotepath, const char * referer,const char *cookie)
{
	long timeout = 10800;
	long connect_timeout = 30;
	long low_speed_limit = 1024;
	long low_speed_time = 60;

	FILE *fp;
	if (!(fp=fopen(localpath, "wb"))){
		perror(localpath);
		return 0;
	}
	long response_code;
	CURL *curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); //for thread safe
	curl_easy_setopt(curl, CURLOPT_URL, remotepath);
	if(referer) curl_easy_setopt(curl, CURLOPT_REFERER, referer);
	if(cookie)  curl_easy_setopt(curl, CURLOPT_COOKIE, cookie);
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "icache");
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, connect_timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, low_speed_limit);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, low_speed_time);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10L);
	curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
	//curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip, deflate");
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
	CURLcode rc = curl_easy_perform(curl);
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
	double len = 0;
	long filesize = 0;
	time_t last_modified = 0;
	curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &len);
	filesize = len;
	curl_easy_getinfo(curl, CURLINFO_FILETIME, &last_modified);
	curl_easy_cleanup(curl);
	fclose(fp);

	int success = 1;
	if (rc!=CURLE_OK || response_code!=200) {
		success = 0;
	}else {
		if (filesize!=-1) {
			long localsize = 0;
			struct stat fileinfo;
			if (stat(localpath, &fileinfo) == 0) localsize =  fileinfo.st_size;
			if (filesize!=localsize) success = 0;
		}
	}

	if (success) {
		if (last_modified!=-1){
			struct utimbuf amtime;
			amtime.actime = amtime.modtime = last_modified;
			utime(localpath, &amtime);
		}
		return 1;
	}else{
		unlink(localpath);
		return 0;
	}
}
Beispiel #13
0
CURLcode check(char *response, size_t length, const char *username, const char* password, const char* proxy, int stype) {

	CURL *curl = curl_easy_init();
	if(!curl) {
		fdo_log(GENLOG, "cURL Init Error: (?!)");
		return CURLE_FAILED_INIT; //?!?!?!?!
	}

	struct memstruct CurlStruct;

	CurlStruct.memory = malloc(1);
	*CurlStruct.memory = 0;
	CurlStruct.size = 0;

	//Prepare custom headers.
	char *userenc = curl_easy_escape(curl, username, 0);
	if(!userenc) {
		free(CurlStruct.memory);
		return CURLE_FAILED_INIT;
	}
	char *passenc = curl_easy_escape(curl, password, 0);
	if(!passenc) {
		free(CurlStruct.memory);
		curl_free(passenc); passenc = NULL;
		return CURLE_FAILED_INIT;
	}
	size_t plen = snprintf(NULL, 0, "rem=on&username=%s&password=%s&submit=Log+In&mod=www&ssl=1&dest=account_settings.ws", userenc, passenc);
	plen += 1;
	char *post = malloc(plen);
	if(!post) {
		free(CurlStruct.memory);
		curl_free(userenc); userenc = NULL;
		curl_free(passenc); passenc = NULL;
		return CURLE_FAILED_INIT;
	}
	snprintf(post, plen, "rem=on&username=%s&password=%s&submit=Log+In&mod=www&ssl=1&dest=account_settings.ws", userenc, passenc);

	curl_free(userenc); userenc = NULL;
	curl_free(passenc); passenc = NULL;

	curl_easy_setopt(curl, CURLOPT_URL, "https://secure.runescape.com/m=weblogin/login.ws"); //This may change in the future.
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"); //Possibly change this in the future. They block useragents when they're old(Probably my fault)
	curl_easy_setopt(curl, CURLOPT_REFERER, "https://secure.runescape.com/m=weblogin/loginform.ws?mod=www&ssl=1&reauth=1&dest=account_settings.ws"); //Likewise, may be needed to change.
	curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1); //When followlocation takes place.
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(curl, CURLOPT_HEADER, 0);
	curl_easy_setopt(curl, CURLOPT_ENCODING, "identity");
	curl_easy_setopt(curl, CURLOPT_POST, 1);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);
	curl_easy_setopt(curl, CURLOPT_PROXYTYPE, stype);
	curl_easy_setopt(curl, CURLOPT_PROXY, proxy);

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, StoreCurl);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&CurlStruct);

	CURLcode res = curl_easy_perform(curl);

	if(res != CURLE_OK) {
		fdo_log(DBGLOG, "cURL Error: %s, Proxy: %s.(type: %d)", curl_easy_strerror(res), proxy, stype);
	} else {
		if(CurlStruct.memory != NULL) {
			strncpy(response, CurlStruct.memory, length);
			response[length-1] = '\0';
		} else {
			response = NULL;
		}
	}

	curl_easy_cleanup(curl);
	free(CurlStruct.memory); CurlStruct.memory = NULL;
	free(post); post = NULL;

	return res;
}
Beispiel #14
0
/* 
 * Performs http_query and saves possible result (first body line of reply)
 * to pvar.
 */
int http_query(struct sip_msg* _m, char* _url, char* _dst, char* _post)
{
    CURL *curl;
    CURLcode res;  
    str value, post_value;
    char *url, *at, *post;
    char* stream;
    long stat;
    pv_spec_t *dst;
    pv_value_t val;
    double download_size;

    if (fixup_get_svalue(_m, (gparam_p)_url, &value) != 0) {
	LM_ERR("cannot get page value\n");
	return -1;
    }

    curl = curl_easy_init();
    if (curl == NULL) {
	LM_ERR("failed to initialize curl\n");
	return -1;
    }

    url = pkg_malloc(value.len + 1);
    if (url == NULL) {
	curl_easy_cleanup(curl);
	LM_ERR("cannot allocate pkg memory for url\n");
	return -1;
    }
    memcpy(url, value.s, value.len);
    *(url + value.len) = (char)0;
    curl_easy_setopt(curl, CURLOPT_URL, url);

    if (_post) {
        /* Now specify we want to POST data */ 
	curl_easy_setopt(curl, CURLOPT_POST, 1L);

    	if (fixup_get_svalue(_m, (gparam_p)_post, &post_value) != 0) {
		LM_ERR("cannot get post value\n");
		pkg_free(url);
		return -1;
    	}
        post = pkg_malloc(post_value.len + 1);
        if (post == NULL) {
		curl_easy_cleanup(curl);
		pkg_free(url);
        	LM_ERR("cannot allocate pkg memory for post\n");
        	return -1;
	}
	memcpy(post, post_value.s, post_value.len);
	*(post + post_value.len) = (char)0;
 	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post);
    }
       

    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, (long)1);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long)http_query_timeout);

    stream = NULL;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_function);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);

    res = curl_easy_perform(curl);  
    pkg_free(url);
    if (_post) {
	pkg_free(post);
    }
    curl_easy_cleanup(curl);

    if (res != CURLE_OK) {
	LM_ERR("failed to perform curl\n");
	return -1;
    }

    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &stat);
    if ((stat >= 200) && (stat < 400)) {
	curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &download_size);
	LM_DBG("http_query download size: %u\n", (unsigned int)download_size);
	/* search for line feed */
	at = memchr(stream, (char)10, download_size);
	if (at == NULL) {
	    /* not found: use whole stream */
	    at = stream + (unsigned int)download_size;
	}
	val.rs.s = stream;
	val.rs.len = at - stream;
	LM_DBG("http)query result: %.*s\n", val.rs.len, val.rs.s);
	val.flags = PV_VAL_STR;
	dst = (pv_spec_t *)_dst;
	dst->setf(_m, &dst->pvp, (int)EQ_T, &val);
    }
	
    return stat;
}
Beispiel #15
0
void
loginhttp_cookieget(cearth_logindb *db, const char *user)
{
        int check = logindb_usercheck(db, user); /* You can't trust outside data! */
        switch(check) {
                case 1:
                        break;
                case 0:
                case 2:
                default:
                        return;
        }
        /* Obtain password from stdin */
        char prompt[128] = {0};
        char *password;
        sprintf(prompt, "Password for user '%s': ", user);
        password = getpass("Password: "******"r=/portal/&username="******"&password="******"/portal/sec/login");
        curl_easy_setopt(handle, CURLOPT_URL, loginurl);
        curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata);
        curl_easy_setopt(handle, CURLOPT_COOKIEJAR, LOGIN_COOKIEJAR);
        curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(handle, CURLOPT_NOBODY, 1);
        curl_easy_setopt(handle, CURLOPT_VERBOSE, 0);
        curl_easy_perform(handle);
        curl_easy_cleanup(handle);

        /* Read cookie if it exists. */
        FILE *fp = fopen(LOGIN_COOKIEJAR, "r");
        if (!fp) {
                perror("cearth_login");
                return;
        }
        char cookie[LOGIN_COOKIESIZE + 1] = {0};
        while(!feof(fp)) {
                char line[LOGINDB_MAXLINE];
                fgets(line, LOGINDB_MAXLINE, fp);
                sscanf(line, "www.havenandhearth.com\tFALSE\t/\tFALSE\t0\thsess\t%s", cookie);
        }

        fclose(fp);
        //remove(LOGIN_COOKIEJAR);

        logindb_cookieset(db, user, cookie);
}
Beispiel #16
0
/*
 * func for http downloading by libcurl
 */
int curl_http_download(char *url_live, http_payload_t *http_payload)
{
	CURL *curl_handle;
	
	//char *redirect_url;
	//int response_code;

	http_payload_t *chunk = http_payload;

	chunk->memory = malloc(1);  	/* will be grown as needed by the realloc above */
	chunk->size = 0;    			/* no data at this point */

	//curl_global_init(CURL_GLOBAL_ALL);

	/* init the curl session */
	curl_handle = curl_easy_init();

	/* specify URL to get */
	curl_easy_setopt(curl_handle, CURLOPT_URL, url_live);
	
	/* FIXME for LETV's relative url cast 
	 * rederection call curl_http_header(), this fun has rederection inside */
	curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1);

	/* send all data to this function  */
	curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);

	/* we pass our 'chunk' struct to the callback function */
	curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)chunk);
	
	/* add http GET/ range context */
	curl_easy_setopt(curl_handle, CURLOPT_RANGE,"0-");
	
	/* some servers don't like requests that are made without a user-agent
     * field, so we provide one */
	curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
	
	//curl_easy_setopt(curl_handle, CURLOPT_FORBID_REUSE, 1);

	/* some servers don't like requests that are made without a user-agent
	   field, so we provide one */
	//curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");

	/* this fun will not return until the http payload is all download */
	curl_easy_perform(curl_handle);

	/* cleanup curl stuff */
	curl_easy_cleanup(curl_handle);

	/*
	 * Now, our chunk.memory points to a memory block that is chunk.size
	 * bytes big and contains the remote file.
	 *
	 * Do something nice with it!
	 *
	 * You should be aware of the fact that at this point we might have an
	 * allocated data block, and nothing has yet deallocated that data. So when
	 * you're done with it, you should free() it as a nice application.
	 */

	//hls_dbg("%lu bytes retrieved\n", (long)chunk->size);

	/* FIXME
	 * modified by juguofeng
	 * do not free it here only in this project 
	 */
	//if(chunk->memory)
	//	free(chunk->memory);
	
	/* we're done with libcurl, so clean it up */
	//curl_global_cleanup();

	return 0;
}
Beispiel #17
0
/* Try to index job into elasticsearch */
static int _index_job(const char *jobcomp)
{
	CURL *curl_handle = NULL;
	CURLcode res;
	struct http_response chunk;
	int rc = SLURM_SUCCESS;

	if (log_url == NULL) {
		error("%s: JobCompLoc parameter not configured", plugin_type);
		return SLURM_ERROR;
	}

	if (curl_global_init(CURL_GLOBAL_ALL) != 0) {
		error("%s: curl_global_init: %m", plugin_type);
		rc = SLURM_ERROR;
	} else if ((curl_handle = curl_easy_init()) == NULL) {
		error("%s: curl_easy_init: %m", plugin_type);
		rc = SLURM_ERROR;
	}

	if (curl_handle) {
		char *url = xstrdup(log_url);
		xstrcat(url, index_type);

		chunk.message = xmalloc(1);
		chunk.size = 0;

		curl_easy_setopt(curl_handle, CURLOPT_URL, url);
		curl_easy_setopt(curl_handle, CURLOPT_POST, 1);
		curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, jobcomp);
		curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE,
				 strlen(jobcomp));
		curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1);
		curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,
				 _write_callback);
		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA,
				 (void *) &chunk);

		res = curl_easy_perform(curl_handle);
		if (res != CURLE_OK) {
			if (slurm_get_debug_flags() & DEBUG_FLAG_ESEARCH)
				info("%s: Could not connect to: %s , reason: %s"
				     , plugin_type, url,
				     curl_easy_strerror(res));
			rc = SLURM_ERROR;
		} else {
			char *token, *response;
			response = xstrdup(chunk.message);
			token = strtok(chunk.message, " ");
			if (token == NULL) {
				error("%s: Could not receive the HTTP response"
				      " status code from %s", plugin_type, 
					url);
				rc = SLURM_ERROR;
			} else {
				token = strtok(NULL, " ");
				if ((xstrcmp(token, "100") == 0)) {
					(void)  strtok(NULL, " ");
					token = strtok(NULL, " ");
				}
				if ((xstrcmp(token, "200") != 0)
				    && (xstrcmp(token, "201") != 0)) {
					if (slurm_get_debug_flags() &
					    DEBUG_FLAG_ESEARCH) {
						info("%s: HTTP status code %s "
						     "received from %s",
						     plugin_type, token, url);
						info("%s: HTTP response:\n%s",
						     plugin_type, response);
					}
					rc = SLURM_ERROR;
				} else {
					token = strtok((char *)jobcomp, ",");
					(void)  strtok(token, ":");
					token = strtok(NULL, ":");
					if (slurm_get_debug_flags() &
					    DEBUG_FLAG_ESEARCH) {
						info("%s: Job with jobid %s "
 						     "indexed into "
						     "elasticsearch",
						     plugin_type, token);
					}
				}
				xfree(response);
			}
		}
		xfree(chunk.message);
		curl_easy_cleanup(curl_handle);
		xfree(url);
	}
	curl_global_cleanup();

	return rc;
}
Beispiel #18
0
int webhdfs_req_exec (webhdfs_req_t *req, int type, char **error) {
    struct curl_slist *headers = NULL;
    CURLcode err;
    CURL *curl;

    if ((curl = curl_easy_init()) == NULL)
        return(1);

    curl_easy_setopt(curl, CURLOPT_URL, req->buffer.blob);
    DLOG(INFO) << "downloading url: " << req->buffer.blob;
    buffer_clear(&(req->buffer));

    curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, req->upload == NULL);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, __webhdfs_req_write);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, req);

    switch (type) {
      case WEBHDFS_REQ_GET:
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
        break;
      case WEBHDFS_REQ_PUT:
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
        break;
      case WEBHDFS_REQ_POST:
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
        break;
      case WEBHDFS_REQ_DELETE:
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
        break;
    }

    /* Upload Require two steps */
    if (req->upload != NULL) {
        char *url;

        if ((err = curl_easy_perform(curl))) {
            //fprintf(stderr, "%s\n", curl_easy_strerror(err));
            *error = (char *)malloc(512);
            if (*error != NULL) {
                snprintf(*error, 512, "%s (url: %s)", curl_easy_strerror(err), req->buffer.blob);
            }

            if (headers != NULL)
                curl_slist_free_all(headers);

            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &(req->rcode));
            curl_easy_cleanup(curl);

            return(err != 0);
        }

        curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &url);
        DLOG(INFO) << "downloading url: " << url;

        curl_easy_setopt(curl, CURLOPT_URL, url);

        headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_READFUNCTION, __webhdfs_req_read);
        curl_easy_setopt(curl, CURLOPT_READDATA, req);

        switch (type) {
          case WEBHDFS_REQ_PUT:
            curl_easy_setopt(curl, CURLOPT_PUT, 1);
            break;
          case WEBHDFS_REQ_POST:
            curl_easy_setopt(curl, CURLOPT_POST, 1);
            break;
        }
    }

    buffer_clear(&(req->buffer));
    if ((err = curl_easy_perform(curl))) {
        //fprintf(stderr, "%s\n", curl_easy_strerror(err));
        *error = (char *)malloc(512);
        if (*error != NULL) {
            snprintf(*error, 512, "%s (url: %s)", curl_easy_strerror(err), req->buffer.blob);
        }
    }

    if (headers != NULL)
        curl_slist_free_all(headers);

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &(req->rcode));
    curl_easy_cleanup(curl);

    return(err != 0);
}
Beispiel #19
0
int HttpClient::impl(const char *url, const char *data, int size,
                     StringBuffer &response, const HeaderMap *requestHeaders,
                     std::vector<String> *responseHeaders) {
  SlowTimer timer(RuntimeOption::HttpSlowQueryThreshold, "curl", url);

  m_response = &response;

  char error_str[CURL_ERROR_SIZE + 1];
  memset(error_str, 0, sizeof(error_str));

  CURL *cp = curl_easy_init();
  curl_easy_setopt(cp, CURLOPT_URL,               url);
  curl_easy_setopt(cp, CURLOPT_WRITEFUNCTION,     curl_write);
  curl_easy_setopt(cp, CURLOPT_WRITEDATA,         (void*)this);
  curl_easy_setopt(cp, CURLOPT_ERRORBUFFER,       error_str);
  curl_easy_setopt(cp, CURLOPT_NOPROGRESS,        1);
  curl_easy_setopt(cp, CURLOPT_VERBOSE,           0);
  curl_easy_setopt(cp, CURLOPT_NOSIGNAL,          1);
  curl_easy_setopt(cp, CURLOPT_DNS_USE_GLOBAL_CACHE, 0); // for thread-safe
  curl_easy_setopt(cp, CURLOPT_DNS_CACHE_TIMEOUT, 120);
  curl_easy_setopt(cp, CURLOPT_NOSIGNAL, 1); // for multithreading mode
  curl_easy_setopt(cp, CURLOPT_SSL_VERIFYPEER,    0);
  curl_easy_setopt(cp, CURLOPT_SSL_CTX_FUNCTION, curl_tls_workarounds_cb);

  curl_easy_setopt(cp, CURLOPT_TIMEOUT,           m_timeout);
  if (m_maxRedirect > 1) {
    curl_easy_setopt(cp, CURLOPT_FOLLOWLOCATION,    1);
    curl_easy_setopt(cp, CURLOPT_MAXREDIRS,         m_maxRedirect);
  } else {
    curl_easy_setopt(cp, CURLOPT_FOLLOWLOCATION,    0);
  }
  if (!m_use11) {
    curl_easy_setopt(cp, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  }
  if (m_decompress) {
    curl_easy_setopt(cp, CURLOPT_ENCODING, "");
  }

  if (!m_username.empty()) {
    curl_easy_setopt(cp, CURLOPT_HTTPAUTH,
                     m_basic ? CURLAUTH_BASIC : CURLAUTH_DIGEST);
    curl_easy_setopt(cp, CURLOPT_USERNAME, m_username.c_str());
    curl_easy_setopt(cp, CURLOPT_PASSWORD, m_password.c_str());
  }

  if (!m_proxyHost.empty() && m_proxyPort) {
    curl_easy_setopt(cp, CURLOPT_PROXY,     m_proxyHost.c_str());
    curl_easy_setopt(cp, CURLOPT_PROXYPORT, m_proxyPort);
    if (!m_proxyUsername.empty()) {
      curl_easy_setopt(cp, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
      curl_easy_setopt(cp, CURLOPT_PROXYUSERNAME, m_proxyUsername.c_str());
      curl_easy_setopt(cp, CURLOPT_PROXYPASSWORD, m_proxyPassword.c_str());
    }
  }

  std::vector<String> headers; // holding those temporary strings
  curl_slist *slist = nullptr;
  if (requestHeaders) {
    for (HeaderMap::const_iterator iter = requestHeaders->begin();
         iter != requestHeaders->end(); ++iter) {
      for (unsigned int i = 0; i < iter->second.size(); i++) {
        String header = iter->first + ": " + iter->second[i];
        headers.push_back(header);
        slist = curl_slist_append(slist, header.data());
      }
    }
    if (slist) {
      curl_easy_setopt(cp, CURLOPT_HTTPHEADER, slist);
    }
  }

  if (data && size) {
    curl_easy_setopt(cp, CURLOPT_POST,          1);
    curl_easy_setopt(cp, CURLOPT_POSTFIELDS,    data);
    curl_easy_setopt(cp, CURLOPT_POSTFIELDSIZE, size);
  }

  if (responseHeaders) {
    m_responseHeaders = responseHeaders;
    curl_easy_setopt(cp, CURLOPT_HEADERFUNCTION, curl_header);
    curl_easy_setopt(cp, CURLOPT_WRITEHEADER, (void*)this);
  }

  if (m_stream_context_options[s_ssl].isArray()) {
    const Array ssl = m_stream_context_options[s_ssl].toArray();
    if (ssl[s_verify_peer].toBoolean()) {
      curl_easy_setopt(cp, CURLOPT_SSL_VERIFYPEER, 1);
    }
    if (ssl.exists(s_capath)) {
      curl_easy_setopt(cp, CURLOPT_CAPATH,
                       ssl[s_capath].toString().data());
    }
    if (ssl.exists(s_cafile)) {
      curl_easy_setopt(cp, CURLOPT_CAINFO,
                       ssl[s_cafile].toString().data());
    }
    if (ssl.exists(s_local_cert)) {
      curl_easy_setopt(cp, CURLOPT_SSLKEY,
                       ssl[s_local_cert].toString().data());
      curl_easy_setopt(cp, CURLOPT_SSLKEYTYPE, "PEM");
    }
    if (ssl.exists(s_passphrase)) {
      curl_easy_setopt(cp, CURLOPT_KEYPASSWD,
                       ssl[s_passphrase].toString().data());
    }
  }

  long code = 0;
  {
    IOStatusHelper io("http", url);
    CURLcode error_no = curl_easy_perform(cp);
    if (error_no != CURLE_OK) {
      m_error = error_str;
    } else {
      curl_easy_getinfo(cp, CURLINFO_RESPONSE_CODE, &code);
    }
  }

  set_curl_statuses(cp, url);

  if (slist) {
    curl_slist_free_all(slist);
  }

  curl_easy_cleanup(cp);
  return code;
}
Beispiel #20
0
static void unit_stop(void)
{
  curl_easy_cleanup(easy);
  curl_global_cleanup();
}
Beispiel #21
0
void*
ProcessTransferQueues(
	void *socket
	                 )
{
	int                         i;
	struct DownloadSubscription *downloadSubscription;
	int                         transferer;
	struct DownloadStarter      *downloadStarter;
	sqlite3_int64               fileId;
	struct UploadStarter        *uploadStarter;
	pthread_t                   threadId;
	int                         socketHandle;

	socketHandle = * (int*) socket;

	/* Initialize transferers.  The S3COMM handle is not acquired via
	   s3_open( ), because for uploads and downloads, its contents are
	   file specific and would require us to open and close the s3comms
	   module for each file.  We can "fake" an S3COMM handle, however,
	   because we just use it for the s3BuildRequest function, which uses
	   it only for reading the region, the bucket, the keyId, and the
	   secretKey entries.  All we need to do is specify these values in
	   the handle for each upload or download. */
	curl_global_init( CURL_GLOBAL_ALL );
	for( i = 0; i < MAX_SIMULTANEOUS_TRANSFERS; i++ )
	{
		transferers[ i ].curl    = curl_easy_init( );
		transferers[ i ].s3Comm  = malloc( sizeof( S3COMM ) );
		transferers[ i ].isReady = true;
	}

	/* Main loop. */
	for( ; ; )
	{
		/* Prevent other threads from modifying the queue while we're
		   processing it. */
		pthread_mutex_lock( &mainLoop_mutex );

		/* Fill the transfer slots with uploads or downloads until either
		   all transfer slots are occupied or the queues are empty. */
		while( ( transferer = FindAvailableTransferer( ) ) != -1 )
		{
			/* Find an entry in the upload queue that isn't processed yet. */
			fileId = GetSubscriptionFromUploadQueue( );
			if( fileId != 0ll )
			{
				transferers[ transferer ].isReady = false;
				uploadStarter = malloc( sizeof( struct UploadStarter ) );
				uploadStarter->uploader     = transferer;
				uploadStarter->fileId       = fileId;
				uploadStarter->socket       = socketHandle;
				pthread_create( &threadId, NULL, BeginUpload, uploadStarter );
			}
			else
			{
				/* Find an entry in the download queue that isn't processed
				   yet. */
				downloadSubscription = GetSubscriptionFromDownloadQueue( );
				if( downloadSubscription != NULL )
				{
					downloadSubscription->downloadActive = true;
					transferers[ transferer ].isReady = false;
					downloadStarter = malloc(
						sizeof( struct DownloadStarter ) );
					downloadStarter->downloader   = transferer;
					downloadStarter->subscription = downloadSubscription;
					downloadStarter->socket       = socketHandle;
					pthread_create( &threadId, NULL, BeginDownload,
									downloadStarter );
				}
				else
				{
					/* Nothing waiting in either queue. */
					break;
				}
			}
		}

		/* If the queues are emptied or all transfer slots are occupied, then
		   wait until there are new entries in the queues or a transfer
		   finishes, whichever comes first.  (We still have the mutex lock,
		   so we won't receive any signals yet.  Any new entries will be
		   waiting for us to release the lock.) */
		if( ( transferer == -1 ) ||
			( ( downloadSubscription == NULL ) &&
			  ( fileId               == 0    ) ) )
		{
			pthread_cond_wait( &mainLoop_cond, &mainLoop_mutex );
		}
		/* Otherwise, process more entries until the queue is empty or all
		   download slots are taken. */
		pthread_mutex_unlock( &mainLoop_mutex );
	}


	/* Take down transferers. */
	for( i = 0; i < MAX_SIMULTANEOUS_TRANSFERS; i++ )
	{
		curl_easy_cleanup( transferers[ i ].curl );
	}
	curl_global_cleanup( );
}
	virtual ~activemq()
	{
		curl_easy_cleanup(m_curl);
		curl_global_cleanup();
	}
Beispiel #23
0
void Session::Impl::freeHolder(CurlHolder* holder) {
    curl_easy_cleanup(holder->handle);
    curl_slist_free_all(holder->chunk);
    delete holder;
}
Beispiel #24
0
int test(char *URL)
{
  CURLM *cm = NULL;
  CURLSH *sh = NULL;
  CURL *ch = NULL;
  int unfinished;

  cm = curl_multi_init();
  if(!cm)
    return 1;
  sh = curl_share_init();
  if(!sh)
    goto cleanup;

  curl_share_setopt(sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
  curl_share_setopt(sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

  ch = curl_easy_init();
  if(!ch)
    goto cleanup;

  curl_easy_setopt(ch, CURLOPT_SHARE, sh);
  curl_easy_setopt(ch, CURLOPT_URL, URL);
  curl_easy_setopt(ch, CURLOPT_COOKIEFILE, "log/cookies1905");
  curl_easy_setopt(ch, CURLOPT_COOKIEJAR, "log/cookies1905");

  curl_multi_add_handle(cm, ch);

  unfinished = 1;
  while(unfinished) {
    int MAX = 0;
    long max_tout;
    fd_set R, W, E;
    struct timeval timeout;

    FD_ZERO(&R);
    FD_ZERO(&W);
    FD_ZERO(&E);
    curl_multi_perform(cm, &unfinished);

    curl_multi_fdset(cm, &R, &W, &E, &MAX);
    curl_multi_timeout(cm, &max_tout);

    if(max_tout > 0) {
      timeout.tv_sec = max_tout / 1000;
      timeout.tv_usec = (max_tout % 1000) * 1000;
    }
    else {
      timeout.tv_sec = 0;
      timeout.tv_usec = 1000;
    }

    select(MAX + 1, &R, &W, &E, &timeout);
  }

  curl_easy_setopt(ch, CURLOPT_COOKIELIST, "FLUSH");
  curl_easy_setopt(ch, CURLOPT_SHARE, NULL);

  curl_multi_remove_handle(cm, ch);
  cleanup:
  curl_easy_cleanup(ch);
  curl_share_cleanup(sh);
  curl_multi_cleanup(cm);
  curl_global_cleanup();

  return 0;
}
Beispiel #25
0
int main(void)
{
  CURLM *cm;
  CURLMsg *msg;
  long L;
  unsigned int C = 0;
  int M, Q, U = -1;
  fd_set R, W, E;
  struct timeval T;
	CURL_data *resp=NULL;
	core();

	curl_global_init(CURL_GLOBAL_ALL);
	resp = (CURL_data *)malloc(sizeof(CURL_data));
	memset(resp,0,sizeof(CURL_data));

  curl_global_init(CURL_GLOBAL_ALL);

  cm = curl_multi_init();

  /* we can optionally limit the total amount of connections this multi handle
     uses */
  curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long)MAX);

  for(C = 0; C < MAX; ++C) {
    init(cm, C,resp);
  }

	while(U) {
		curl_multi_perform(cm, &U);
		if(U) {
			FD_ZERO(&R);
			FD_ZERO(&W);
			FD_ZERO(&E);

			if(curl_multi_fdset(cm, &R, &W, &E, &M)) {
				fprintf(stderr, "E: curl_multi_fdset\n");
				return EXIT_FAILURE;
			}

			if(curl_multi_timeout(cm, &L)) {
				fprintf(stderr, "E: curl_multi_timeout\n");
				return EXIT_FAILURE;
			}
			if(L == -1)
				L = 100;

			if(M == -1) {
#ifdef WIN32
				Sleep(L);
#else
				sleep((unsigned int)L / 1000);
#endif
			}
			else {
				T.tv_sec = L/1000;
				T.tv_usec = (L%1000)*1000;

				if(0 > select(M + 1, &R, &W, &E, &T)) {
					fprintf(stderr, "E: select(%i,,,,%li): %i: %s\n",
							M + 1, L, errno, strerror(errno));
					return EXIT_FAILURE;
				}else{
					fprintf(stderr,"Start!!! [%d]\n",U);
				}
			}
		}

		while((msg = curl_multi_info_read(cm, &Q))) {
			if(msg->msg == CURLMSG_DONE) {
				char *url;
				CURL *e = msg->easy_handle;
				curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &url);
				fprintf(stderr, "R: %d - %s <%s>\n",
						msg->data.result, curl_easy_strerror(msg->data.result), url);
				//fprintf(stderr,"%s\n",resp->body.memory);
				curl_multi_remove_handle(cm, e);
				curl_easy_cleanup(e);
			}
			else {
				fprintf(stderr, "E: CURLMsg (%d)\n", msg->msg);
			}
#if 0
			if(C < CNT) {
				init(cm, C++,resp);
				U++; /* just to prevent it from remaining at 0 if there are more
								URLs to get */
			}
#endif
		}
	}

  curl_multi_cleanup(cm);
  curl_global_cleanup();

  return EXIT_SUCCESS;
}
Beispiel #26
0
API::~API()
{
    curl_easy_cleanup(curlhandle);
}
Beispiel #27
0
static int
testExternalPut ()
{
    struct MHD_Daemon *d;
    CURL *c;
    struct CBC cbc;
    CURLM *multi;
    CURLMcode mret;
    fd_set rs;
    fd_set ws;
    fd_set es;
    int max;
    int running;
    struct CURLMsg *msg;
    time_t start;
    struct timeval tv;
    unsigned int pos = 0;
    int done_flag = 0;
    char buf[2048];

    cbc.buf = buf;
    cbc.size = 2048;
    cbc.pos = 0;
    multi = NULL;
    d = MHD_start_daemon (MHD_USE_DEBUG,
                          1082,
                          NULL, NULL, &ahc_echo, &done_flag,
                          MHD_OPTION_CONNECTION_MEMORY_LIMIT,
                          (size_t) (PUT_SIZE * 4), MHD_OPTION_END);
    if (d == NULL)
        return 256;
    c = curl_easy_init ();
    curl_easy_setopt (c, CURLOPT_URL, "http://localhost:1082/hello_world");
    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
    if (oneone)
        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    else
        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L);
    // NOTE: use of CONNECTTIMEOUT without also
    //   setting NOSIGNAL results in really weird
    //   crashes on my system!
    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);


    multi = curl_multi_init ();
    if (multi == NULL)
    {
        curl_easy_cleanup (c);
        MHD_stop_daemon (d);
        return 512;
    }
    mret = curl_multi_add_handle (multi, c);
    if (mret != CURLM_OK)
    {
        curl_multi_cleanup (multi);
        curl_easy_cleanup (c);
        MHD_stop_daemon (d);
        return 1024;
    }
    start = time (NULL);
    while ((time (NULL) - start < 5) && (multi != NULL))
    {
        max = 0;
        FD_ZERO (&rs);
        FD_ZERO (&ws);
        FD_ZERO (&es);
        curl_multi_perform (multi, &running);
        mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
        if (mret != CURLM_OK)
        {
            curl_multi_remove_handle (multi, c);
            curl_multi_cleanup (multi);
            curl_easy_cleanup (c);
            MHD_stop_daemon (d);
            return 2048;
        }
        if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
        {
            curl_multi_remove_handle (multi, c);
            curl_multi_cleanup (multi);
            curl_easy_cleanup (c);
            MHD_stop_daemon (d);
            return 4096;
        }
        tv.tv_sec = 0;
        tv.tv_usec = 1000;
        select (max + 1, &rs, &ws, &es, &tv);
        curl_multi_perform (multi, &running);
        if (running == 0)
        {
            msg = curl_multi_info_read (multi, &running);
            if (msg == NULL)
                break;
            if (msg->msg == CURLMSG_DONE)
            {
                if (msg->data.result != CURLE_OK)
                    printf ("%s failed at %s:%d: `%s'\n",
                            "curl_multi_perform",
                            __FILE__,
                            __LINE__, curl_easy_strerror (msg->data.result));
                curl_multi_remove_handle (multi, c);
                curl_multi_cleanup (multi);
                curl_easy_cleanup (c);
                c = NULL;
                multi = NULL;
            }
        }
        MHD_run (d);
    }
    if (multi != NULL)
    {
        curl_multi_remove_handle (multi, c);
        curl_easy_cleanup (c);
        curl_multi_cleanup (multi);
    }
    MHD_stop_daemon (d);
    if (cbc.pos != strlen ("/hello_world"))
    {
        fprintf (stderr, "Got invalid response `%.*s'\n", (int)cbc.pos, cbc.buf);
        return 8192;
    }
    if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
        return 16384;
    return 0;
}
void Com::cleanup(){
    curl_easy_cleanup(curl);
}
Beispiel #29
0
int IO::poll() {
  // Do some work and get number of handles in progress
  int num_handles;
  curl_multi_perform(m_mhandle, &num_handles);

  struct CURLMsg *msg = NULL;
  int msgs;

  // Get messages back out of CURL
  while ((msg = curl_multi_info_read(m_mhandle, &msgs)) != NULL) {

    DataStruct *ds = NULL;
    int err = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &ds);
    if (err != CURLE_OK) {
      // Do something on error
      fprintf(stderr, "Got some error on curl_easy_getinfo (%d)\n", err);
      continue;
    }

    bool failed = true; 
    std::string errormsg = "Unknown failure";
    switch (msg->msg) {
      case CURLMSG_DONE: {
        if (msg->data.result == CURLE_OK) {
          assert(ds != NULL);
          if (ds->expected_crc32 == 0L || 
              ds->expected_crc32 == ds->actual_crc32) {
            // Download success!
            failed = false;
            // Copy file to proper location
            if (copy_file(ds->fp, ds->path + "/" + ds->filename)) {
              errormsg = "Error copying file to target location.\n";
              failed = true;
            }

            // Set executable if required
            if (ds->executable) {
              os_set_executable(ds->path + "/" + ds->filename);
            }
          } else {
            // CRC32 check failed
            failed = true;
            errormsg = "CRC32 mismatch";
          }
        } else {
          // Error downloading file
          failed = true;
          errormsg = "There was an error downloading the requested file: "
                   + std::string(curl_easy_strerror(msg->data.result));
        }
        break;
      }
      default:
        // Something not too good with curl...
        failed = true;
        errormsg = "There was an unknown error downloading the requested file";
    }

    if (debug) printf("Removing Handle\n");

    // Close handle	
    curl_multi_remove_handle(m_mhandle, msg->easy_handle);

    // Clean up
    if (ds) {
      if (ds->fp) os_free_tmpfile(ds->fp);
      ds->fp = NULL;
      if (failed) {
        if (debug) printf("Download Failed\n");
        DownloadFailed.emit(ds->url, ds->filename, errormsg);
      } else {
        if (debug) printf("Download Complete\n");
        DownloadComplete.emit(ds->url, ds->filename);
      }
      m_files.erase(m_files.find(ds->url));
      curl_easy_cleanup(ds->handle);
      delete ds;
    }
  }

  // Spare capacity? Lets queue some more items.
  int diff = m_num_to_process - num_handles;
  if (diff > 0) {
    while (diff--) {

      if (!m_handles.empty()) {
        // This is where we tell curl about our downloads.
        curl_multi_add_handle(m_mhandle, m_handles.front());
        m_handles.pop_front();
        ++num_handles;
      }
    }
  }

  return num_handles;
}
Beispiel #30
0
bool stratum_connect(struct stratum_ctx *sctx, const char *url)
{
	CURL *curl;
	int rc;

	pthread_mutex_lock(&sctx->sock_lock);
	if (sctx->curl)
		curl_easy_cleanup(sctx->curl);
	sctx->curl = curl_easy_init();
	if (!sctx->curl) {
		applog(LOG_ERR, "CURL initialization failed");
		pthread_mutex_unlock(&sctx->sock_lock);
		return false;
	}
	curl = sctx->curl;
	if (!sctx->sockbuf) {
		sctx->sockbuf = (char*)calloc(RBUFSIZE, 1);
		sctx->sockbuf_size = RBUFSIZE;
	}
	sctx->sockbuf[0] = '\0';
	pthread_mutex_unlock(&sctx->sock_lock);

	if (url != sctx->url) {
		free(sctx->url);
		sctx->url = strdup(url);
	}
	free(sctx->curl_url);
	sctx->curl_url = (char*)malloc(strlen(url));
	sprintf(sctx->curl_url, "http%s", strstr(url, "://"));

	if (opt_protocol)
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
	curl_easy_setopt(curl, CURLOPT_URL, sctx->curl_url);
	curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, sctx->curl_err_str);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
	if (opt_proxy && opt_proxy_type != CURLPROXY_HTTP) {
		curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
		curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
	} else if (getenv("http_proxy")) {
		if (getenv("all_proxy"))
			curl_easy_setopt(curl, CURLOPT_PROXY, getenv("all_proxy"));
		else if (getenv("ALL_PROXY"))
			curl_easy_setopt(curl, CURLOPT_PROXY, getenv("ALL_PROXY"));
		else
			curl_easy_setopt(curl, CURLOPT_PROXY, "");
	}
#if LIBCURL_VERSION_NUM >= 0x070f06
	curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb);
#endif
#if LIBCURL_VERSION_NUM >= 0x071101
	curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_grab_cb);
	curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &sctx->sock);
#endif
	curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);

	rc = curl_easy_perform(curl);
	if (rc) {
		applog(LOG_ERR, "Stratum connection failed: %s", sctx->curl_err_str);
		curl_easy_cleanup(curl);
		sctx->curl = NULL;
		return false;
	}

#if LIBCURL_VERSION_NUM < 0x071101
	/* CURLINFO_LASTSOCKET is broken on Win64; only use it as a last resort */
	curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sctx->sock);
#endif

	return true;
}