void *janus_source_keepalive(void *data) {
	JANUS_LOG(LOG_INFO, "SourcePlugin keepalive started\n");

	CURL *curl = curl_init();
	gchar *body_str = g_strdup_printf("{\"pid\": \"%s\", \"dly\": \"%lu\"}", PID, (uint64_t)(keepalive_interval/G_USEC_PER_SEC));
	json_t *res_json_object = NULL;	

	while (g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
		janus_mutex_lock(&keepalive_mutex);
		
		gboolean retCode = curl_request(curl, keepalive_service_url, body_str, "POST", &res_json_object);
		if (retCode != TRUE) {
			JANUS_LOG(LOG_ERR, "Could not send the request to the server.\n");
		}else{
			if (json_is_object(res_json_object)) json_decref(res_json_object);
			else JANUS_LOG(LOG_ERR, "Not valid json object.\n");
		}

		janus_mutex_unlock(&keepalive_mutex);
		g_usleep(keepalive_interval);
	}

	if (body_str) {
		g_free(body_str);
	}

	curl_cleanup(curl);

	JANUS_LOG(LOG_INFO, "SourcePlugin keepalive stopped\n");
	return NULL;
}
Exemple #2
0
static int initialize() {
    int retval;

    if (!cc_config.allow_multiple_clients) {
        retval = wait_client_mutex(".", 10);
        if (retval) {
            log_message_error("Another instance of BOINC is running.");
            return ERR_EXEC;
        }
    }


    // Initialize WinSock
#if defined(_WIN32) && defined(USE_WINSOCK)
    if (WinsockInitialize() != 0) {
        log_message_error("Failed to initialize the Windows Sockets interface.");
        return ERR_IO;
    }
#endif

    curl_init();

#ifdef _WIN32
    if(!startup_idle_monitor()) {
        log_message_error(
            "Failed to initialize the BOINC idle monitor interface."
            "BOINC will not be able to determine if the user is idle or not...\n"
        );
    }
#endif

    return 0;
}
int main(int argc, char* argv[]) {
    std::vector<std::string> args(argv, argv+argc);

    std::string url;
    size_t iterations = 1000;
    try {
        url = args.at(1);
        if (args.size() > 2)
            iterations = atoi(args.at(2).c_str());
    } catch (std::exception& e) {
        std::cerr << "exception: " << e.what() << std::endl;
        std::cerr << "usage: " << args.at(0) << " url iterations" << std::endl;
        return 1;
    }

    curl_init();

    CURL* curl = curl_easy_init();
    if (!curl) {
        logError("curl_easy_init");
        return 1;
    }

    setopt(curl, CURLOPT_URL, url.c_str());
    setopt(curl, CURLOPT_TIMEOUT, 5L);
    setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);
    setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    setopt(curl, CURLOPT_HEADER, 1L);
    setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

    char send_data[] = "words, words, words";

    for (size_t i = 0; i < iterations; i++) {
        ReadState read_state(send_data, strlen(send_data));
        setopt(curl, CURLOPT_POST, 1L);
        setopt(curl, CURLOPT_READFUNCTION, read_callback);
        setopt(curl, CURLOPT_READDATA, &read_state);
        setopt(curl, CURLOPT_POSTFIELDSIZE, read_state.remains);

        bool sent = false;
        for (size_t i = 0; i < 3; i++) {
            if (perform(curl)) {
                std::cout << "^";
                sent = true;
                break;
            }
            std::cout << ".";
        }
        if (!sent) {
            std::cout << "!";
        }
    }

    curl_easy_cleanup(curl);
    curl_cleanup();

    return 0;
}
Exemple #4
0
static CURL* curl_request(lua_State* L, CurlCallbackState* state, FILE* fp, int progressFnIndex)
{
	CURL* curl;
	struct curl_slist* headers = NULL;
	const char* url = luaL_checkstring(L, 1);

	/* if the second argument is a lua function, then we save it
		to call it later as the http progress callback */
	if (lua_type(L, progressFnIndex) == LUA_TFUNCTION)
	{
		state->L = L;
		state->RefIndex = luaL_ref(L, LUA_REGISTRYINDEX);
	}

	curl_init();
	curl = curl_easy_init();

	if (!curl)
		return NULL;

	curl_easy_setopt(curl, CURLOPT_URL, url);
	curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, state->errorBuffer);

	get_headers(L, &headers);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, state);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_cb);

	if (fp)
	{
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_file_cb);
	}

	if (state->L != 0)
	{
		curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
		curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, state);
		curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, curl_progress_cb);
	}

	// clear error buffer.
	state->errorBuffer[0] = 0;

	return curl;
}
Exemple #5
0
void streambuf::open( char const *uri ) {
  if ( !curl_ ) {
    curl_ = create();
    try {
      curl_init();
    }
    catch ( ... ) {
      curl_destroy();
      throw;
    }
    curlm_init();
  }
  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_URL, uri ) );
}
Exemple #6
0
int main(int argc, char **argv) {
  long cookie_expire;
  int ret = 1;

  config = config_new();

  if (curl_init() != 0) {
    fprintf(stderr, "Error: An error occurred while initializing curl\n");
    goto finish;
  }

  ret = parseargs(argc, argv);
  if (ret != 0) {
    return 1;
  }

  if (config->category) {
    config->catnum = category_is_valid(config->category);
    if (config->catnum < 0) {
      usage_categories();
      goto finish;
    }
  } else {
    config->catnum = 1;
  }

  if (optind == argc) {
    fprintf(stderr, "error: no packages specified (use -h for help)\n");
    goto finish;
  }

  /* We can't read the config file without having verbosity set, but the
   * command line options need to take precedence over the config.  file.
   * Therefore, if ((user && pass) || cookie file) is supplied on the command
   * line, we won't read the config file.
   */
  if (!(config->user || config->cookie_file)) {
    read_config_file();
  }

  if (cookie_setup() != 0) {
    goto finish;
  }

  cookie_expire = cookie_expire_time(config->cookie_file, AUR_DOMAIN, AUR_COOKIE_NAME);
  if (cookie_expire > 0) {
    if (time(NULL) < cookie_expire) {
      config->cookie_valid = 1;
    } else {
      fprintf(stderr, "Your cookie has expired. Gathering user and password...\n");
    }
  }

  if (!config->cookie_valid) {
    if (!config->cmdline_user && !config->user) {
      config->user = read_stdin("Enter username", AUR_USER_MAX, 1);
      if (!config->user || !strlen(config->user)) {
        fprintf(stderr, "error: invalid username supplied\n");
        goto finish;
      }
    }

    if (!config->password || (config->cmdline_user && !config->cmdline_passwd)) {
      printf("[%s] ", config->user);
      config->password = read_stdin("Enter password", AUR_PASSWORD_MAX, 0);
    }
  }

  if (config->cookie_valid || aur_login() == 0) {
    char *csrf_token;

    /* booo, stupid hacks. curl doesn't prime curl_slist of cookies
     * we want via CURLINFO_COOKIELIST until we call perform at least
     * once. */
    prime_cookielist();

    csrf_token = get_csrf_token();
    if (csrf_token == NULL) {
      fprintf(stderr, "failed to obtain CSRF token for uploading\n");
      goto finish;
    }

    ret = 0;

    while (optind < argc) {
      int r = aur_upload(argv[optind++], csrf_token);
      if (r != 0) {
        ret = r;
      }
    }
    free(csrf_token);
  }

finish:
  if (config->cookie_file && !config->cookie_persist) {
    debug("Deleting file %s\n", config->cookie_file);
    unlink(config->cookie_file);
  }

  config_free(config);
  curl_cleanup();

  return ret;
}
Exemple #7
0
static int send_request(struct session *session)
{
	char endpoint[500];
	char user_password[500];
	char data[500];
	struct bti_curl_buffer *curl_buf;
	CURL *curl = NULL;
	CURLcode res;
	struct curl_httppost *formpost = NULL;
	struct curl_httppost *lastptr = NULL;
	struct curl_slist *slist = NULL;
	char *req_url = NULL;
	char *reply = NULL;
	char *postarg = NULL;
	char *escaped_tweet = NULL;
	int is_post = 0;

	if (!session)
		return -EINVAL;

	if (!session->hosturl)
		session->hosturl = strdup(twitter_host);

	if (session->no_oauth || session->guest) {
		curl_buf = bti_curl_buffer_alloc(session->action);
		if (!curl_buf)
			return -ENOMEM;
		curl_buf->session = session;

		curl = curl_init();
		if (!curl)
			return -EINVAL;

		if (!session->hosturl)
			session->hosturl = strdup(twitter_host);

		switch (session->action) {
		case ACTION_UPDATE:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			snprintf(data, sizeof(data), "status=\"%s\"",
				 session->tweet);
			curl_formadd(&formpost, &lastptr,
				     CURLFORM_COPYNAME, "status",
				     CURLFORM_COPYCONTENTS, session->tweet,
				     CURLFORM_END);

			curl_formadd(&formpost, &lastptr,
				     CURLFORM_COPYNAME, "source",
				     CURLFORM_COPYCONTENTS, "bti",
				     CURLFORM_END);

			if (session->replyto)
				curl_formadd(&formpost, &lastptr,
					     CURLFORM_COPYNAME,
					     "in_reply_to_status_id",
					     CURLFORM_COPYCONTENTS,
					     session->replyto,
					     CURLFORM_END);

			curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
			slist = curl_slist_append(slist, "Expect:");
			curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

			sprintf(endpoint, "%s%s", session->hosturl, update_uri);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_FRIENDS:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
					friends_uri, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_USER:
			sprintf(endpoint, "%s%s%s.xml?page=%d", session->hosturl,
				user_uri, session->user, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			break;

		case ACTION_REPLIES:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				replies_uri, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_PUBLIC:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				public_uri, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			break;

		case ACTION_GROUP:
			sprintf(endpoint, "%s%s%s.xml?page=%d",
				session->hosturl, group_uri, session->group,
				session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			break;

		default:
			break;
		}

		if (session->proxy)
			curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);

		if (debug)
			curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);

		dbg("user_password = %s\n", user_password);
		dbg("data = %s\n", data);
		dbg("proxy = %s\n", session->proxy);

		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
		if (!session->dry_run) {
			res = curl_easy_perform(curl);
			if (!session->background) {
				xmlDocPtr doc;
				xmlNodePtr current;

				if (res) {
					fprintf(stderr, "error(%d) trying to "
						"perform operation\n", res);
					return -EINVAL;
				}

				doc = xmlReadMemory(curl_buf->data,
						    curl_buf->length,
						    "response.xml", NULL,
						    XML_PARSE_NOERROR);
				if (doc == NULL)
					return -EINVAL;

				current = xmlDocGetRootElement(doc);
				if (current == NULL) {
					fprintf(stderr, "empty document\n");
					xmlFreeDoc(doc);
					return -EINVAL;
				}

				if (xmlStrcmp(current->name, (const xmlChar *)"status")) {
					fprintf(stderr, "unexpected document type\n");
					xmlFreeDoc(doc);
					return -EINVAL;
				}

				xmlFreeDoc(doc);
			}
		}

		curl_easy_cleanup(curl);
		if (session->action == ACTION_UPDATE)
			curl_formfree(formpost);
		bti_curl_buffer_free(curl_buf);
	} else {
		switch (session->action) {
		case ACTION_UPDATE:
			escaped_tweet = oauth_url_escape(session->tweet);
			if (session->replyto) {
				sprintf(endpoint,
					"%s%s?status=%s&in_reply_to_status_id=%s",
					session->hosturl, update_uri,
					escaped_tweet, session->replyto);
			} else {
				sprintf(endpoint, "%s%s?status=%s",
					session->hosturl, update_uri,
					escaped_tweet);
			}

			is_post = 1;
			break;
		case ACTION_USER:
			sprintf(endpoint, "%s%s%s.xml?page=%d",
				session->hosturl, user_uri, session->user,
				session->page);
			break;
		case ACTION_REPLIES:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				mentions_uri, session->page);
			break;
		case ACTION_PUBLIC:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				public_uri, session->page);
			break;
		case ACTION_GROUP:
			sprintf(endpoint, "%s%s%s.xml?page=%d",
				session->hosturl, group_uri, session->group,
				session->page);
			break;
		case ACTION_FRIENDS:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				friends_uri, session->page);
			break;
		case ACTION_RETWEET:
			sprintf(endpoint, "%s%s%s.xml", session->hosturl,
				retweet_uri, session->retweet);
			is_post = 1;
			break;
		default:
			break;
		}

		dbg("%s\n", endpoint);
		if (!session->dry_run) {
			if (is_post) {
				req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
							  NULL, session->consumer_key,
							  session->consumer_secret,
							  session->access_token_key,
							  session->access_token_secret);
				reply = oauth_http_post(req_url, postarg);
			} else {
				req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
							  session->consumer_key,
							  session->consumer_secret,
							  session->access_token_key,
							  session->access_token_secret);
				reply = oauth_http_get(req_url, postarg);
			}

			dbg("%s\n", req_url);
			dbg("%s\n", reply);
			if (req_url)
				free(req_url);
		}

		if (!reply) {
			fprintf(stderr, "Error retrieving from URL (%s)\n", endpoint);
			return -EIO;
		}

		if ((session->action != ACTION_UPDATE) &&
				(session->action != ACTION_RETWEET))
			parse_timeline(reply, session);
	}
	return 0;
}
Exemple #8
0
streambuf::streambuf( CURL *curl ) {
  init();
  curl_ = curl;
  curl_init();
  curlm_init();
}
Exemple #9
0
int
main(int argc, char *argv[])
{
	int cflag = 0, ch;
	int pp = 0;	/* items per page */
	int p = 0;	/* page number */
	enum {
		PLAY,
		SEARCH,
		QUERY
	} cmd = PLAY;

	quitflag = 0;
	setlocale(LC_ALL, "");
	signal(SIGINT, signalhandler);

	while ((ch = getopt(argc, argv, "PcSp:i:Q")) != -1) {
		switch (ch) {
		default:
		case 'P':
			cmd = PLAY;
			break;
		case 'c':
			if (cmd != PLAY)
				usage();
			cflag = 1;
			break;
		case 'S':
			cmd = SEARCH;
			break;
		case 'i':
			pp = atoi(optarg);
			break;
		case 'p':
			p = atoi(optarg);
			break;
		case 'Q':
			cmd = QUERY;
			break;
		}
	}
	argc -= optind;
	argv += optind;

	curl_init();
	switch (cmd) {
	case PLAY:
		if (argc < 1)
			usage();
		play(argv[0], cflag);
		break;
	case SEARCH:
		if (argc < 1)
			usage();
		search(argv[0], p, pp);
		break;
	case QUERY:
		if (argc < 1)
			usage();
		query(argv[0]);
		break;
	default:
		usage();
		/* NOTREACHED */
	}
	curl_exit();
	return 0;
}
/* Plugin implementation */
int janus_source_init(janus_callbacks *callback, const char *config_path) {
	if (g_atomic_int_get(&stopping)) {
		/* Still stopping from before */
		return -1;
	}
	if (callback == NULL || config_path == NULL) {
		/* Invalid arguments */
		return -1;
	}

	/* Read configuration */
	char filename[255];
	g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SOURCE_PACKAGE);
	JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
	janus_config *config = janus_config_parse(filename);
	if (config != NULL)
		janus_config_print(config);

	/* Parse configuration */
	if (config != NULL)
	{
		GList *cl = janus_config_get_categories(config);
		while (cl != NULL)
		{
			janus_config_category *cat = (janus_config_category *)cl->data;
			if (cat->name == NULL)
			{
				cl = cl->next;
				continue;
			}
			JANUS_LOG(LOG_VERB, "Parsing category '%s'\n", cat->name);
			janus_source_parse_ports_range(janus_config_get_item(cat, "udp_port_range"), &udp_min_port, &udp_max_port);
			janus_source_parse_keepalive_interval(janus_config_get_item(cat, "keepalive_interval"), &keepalive_interval);
			janus_source_parse_status_service_url(janus_config_get_item(cat, "keepalive_service_url"), &keepalive_service_url);
			janus_source_parse_status_service_url(janus_config_get_item(cat,"status_service_url"),&status_service_url);
			
			janus_source_parse_video_codec_priority(janus_config_get_item(cat, "video_codec_priority"));
			janus_source_parse_rtsp_interface_ip(janus_config_get_item(cat, "interface"),&rtsp_interface_ip);
			
			cl = cl->next;
		}
		janus_config_destroy(config);
		config = NULL;
	}

	if (udp_min_port <= 0 || udp_max_port <= 0) {
		udp_min_port = 4000;
		udp_max_port = 5000;
		JANUS_LOG(LOG_WARN, "Using default port range: %d-%d\n", udp_min_port, udp_max_port);
	}

	sessions = g_hash_table_new(NULL, NULL);
	janus_mutex_init(&sessions_mutex);
	messages = g_async_queue_new_full((GDestroyNotify)janus_source_message_free);
	/* This is the callback we'll need to invoke to contact the gateway */
	gateway = callback;
	g_atomic_int_set(&initialized, 1);

	GError *error = NULL;
	/* Start the sessions watchdog */
	watchdog = g_thread_try_new("source watchdog", &janus_source_watchdog, NULL, &error);
	if (error != NULL) {
		g_atomic_int_set(&initialized, 0);
		JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SourcePlugin watchdog thread...\n", error->code, error->message ? error->message : "??");
		return -1;
	}

	gst_init(NULL, NULL);
	gst_debug_set_threshold_from_string(gst_debug_str, FALSE);

	curl_handle = curl_init();
	
	socket_utils_init(udp_min_port, udp_max_port);
	
	/* Launch the thread that will handle incoming messages */
	handler_thread = g_thread_try_new("janus source handler", janus_source_handler, NULL, &error);
	if (error != NULL) {
		g_atomic_int_set(&initialized, 0);
		JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Source handler thread...\n", error->code, error->message ? error->message : "??");
		return -1;
	}
	
	/* Launch the thread that will handle rtsp clients */
	handler_rtsp_thread = g_thread_try_new("rtsp server", janus_source_rtsp_server_thread, NULL, &error); 
	if (error != NULL) {
		g_atomic_int_set(&initialized, 0);
		JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the Source rtsp server thread...\n", error->code, error->message ? error->message : "??");
		return -1;
	}

	/* Set PID */
	memset(&PID, 0, JANUS_PID_SIZE);	
	if (0 > janus_set_pid()) {
		g_atomic_int_set(&initialized, 0);
		JANUS_LOG(LOG_ERR, "Got an error while plugin id initialize.");
		return -1;
	}

	/*Start the keepalive thread */
	keepalive = g_thread_try_new("source keepalive", &janus_source_keepalive, NULL, &error);
	if (error != NULL) {
		g_atomic_int_set(&initialized, 0);
		JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SourcePlugin keepalive thread...\n", error->code, error->message ? error->message : "??");
		return -1;
	}

	JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SOURCE_NAME);
	return 0;
}
Exemple #11
0
static CURL* curl_request(lua_State* L, curl_state* state, int optionsIndex, int progressFnIndex, int headersIndex)
{
	CURL* curl;

	state->L = 0;
	state->RefIndex = 0;
	state->S.ptr = NULL;
	state->S.len = 0;
	state->errorBuffer[0] = '\0';
	state->headers = NULL;

	curl_init();
	curl = curl_easy_init();

	if (!curl)
		return NULL;

	curl_easy_setopt(curl, CURLOPT_URL, luaL_checkstring(L, 1));
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, state->errorBuffer);
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "Premake/" PREMAKE_VERSION);

	if (optionsIndex && lua_istable(L, optionsIndex))
	{
		lua_pushnil(L);
		while (lua_next(L, optionsIndex) != 0)
		{
			const char* key = luaL_checkstring(L, -2);

			if (!strcmp(key, "headers") && lua_istable(L, -1))
			{
				get_headers(L, lua_gettop(L), &state->headers);
				curl_easy_setopt(curl, CURLOPT_HTTPHEADER, state->headers);
			}
			else if (!strcmp(key, "progress") && lua_isfunction(L, -1))
			{
				state->L = L;
				lua_pushvalue(L, -1);
				state->RefIndex = luaL_ref(L, LUA_REGISTRYINDEX);
			}
			else if (!strcmp(key, "userpwd") && lua_isstring(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_USERPWD, luaL_checkstring(L, -1));
			}
			else if (!strcmp(key, "username") && lua_isstring(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_USERNAME, luaL_checkstring(L, -1));
			}
			else if (!strcmp(key, "password") && lua_isstring(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_PASSWORD, luaL_checkstring(L, -1));
			}
			else if (!strcmp(key, "timeout") && lua_isnumber(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long)luaL_checknumber(L, -1));
			}
			else if (!strcmp(key, "timeoutms") && lua_isnumber(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, (long)luaL_checknumber(L, -1));
			}
			else if (!strcmp(key, "sslverifyhost") && lua_isnumber(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, (long)luaL_checknumber(L, -1));
			}
			else if (!strcmp(key, "sslverifypeer") && lua_isnumber(L, -1))
			{
				curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, (long)luaL_checknumber(L, -1));
			}

			// pop the value, leave the key for lua_next
			lua_pop(L, 1);
		}
	}
	else
	{
		if (progressFnIndex && lua_type(L, progressFnIndex) == LUA_TFUNCTION)
		{
			state->L = L;
			lua_pushvalue(L, progressFnIndex);
			state->RefIndex = luaL_ref(L, LUA_REGISTRYINDEX);
		}

		if (headersIndex && lua_istable(L, headersIndex))
		{
			get_headers(L, headersIndex, &state->headers);
			curl_easy_setopt(curl, CURLOPT_HTTPHEADER, state->headers);
		}
	}

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, state);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_cb);

	if (state->L != 0)
	{
		curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
		curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, state);
		curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, curl_progress_cb);
	}

	// clear error buffer.
	state->errorBuffer[0] = 0;

	return curl;
}
Exemple #12
0
static int send_request(struct session *session)
{
	char endpoint[500];
	char user_password[500];
	char data[500];
	struct bti_curl_buffer *curl_buf;
	CURL *curl = NULL;
	CURLcode res;
	struct curl_httppost *formpost = NULL;
	struct curl_httppost *lastptr = NULL;
	struct curl_slist *slist = NULL;
	char *req_url = NULL;
	char *reply = NULL;
	char *postarg = NULL;
	char *escaped_tweet = NULL;
	int is_post = 0;

	if (!session)
		return -EINVAL;

	if (!session->hosturl)
		session->hosturl = strdup(twitter_host);

	if (session->no_oauth) {
		curl_buf = bti_curl_buffer_alloc(session->action);
		if (!curl_buf)
			return -ENOMEM;

		curl = curl_init();
		if (!curl)
			return -EINVAL;

		if (!session->hosturl)
			session->hosturl = strdup(twitter_host);

		switch (session->action) {
		case ACTION_UPDATE:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			snprintf(data, sizeof(data), "status=\"%s\"",
				 session->tweet);
			curl_formadd(&formpost, &lastptr,
				     CURLFORM_COPYNAME, "status",
				     CURLFORM_COPYCONTENTS, session->tweet,
				     CURLFORM_END);

			curl_formadd(&formpost, &lastptr,
				     CURLFORM_COPYNAME, "source",
				     CURLFORM_COPYCONTENTS, "bti",
				     CURLFORM_END);

			if (session->replyto)
				curl_formadd(&formpost, &lastptr,
					     CURLFORM_COPYNAME, "in_reply_to_status_id",
					     CURLFORM_COPYCONTENTS, session->replyto,
					     CURLFORM_END);

			curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
			slist = curl_slist_append(slist, "Expect:");
			curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

			sprintf(endpoint, "%s%s", session->hosturl, update_uri);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_FRIENDS:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
					friends_uri, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_USER:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s?screen_name=%s&page=%d", session->hosturl,
				user_uri, session->user, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_REPLIES:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				replies_uri, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_PUBLIC:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				public_uri, session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		case ACTION_GROUP:
			snprintf(user_password, sizeof(user_password), "%s:%s",
				 session->account, session->password);
			sprintf(endpoint, "%s%s%s.xml?page=%d",
				session->hosturl, group_uri, session->group,
				session->page);
			curl_easy_setopt(curl, CURLOPT_URL, endpoint);
			curl_easy_setopt(curl, CURLOPT_USERPWD, user_password);
			break;

		default:
			break;
		}

		if (session->proxy)
			curl_easy_setopt(curl, CURLOPT_PROXY, session->proxy);

		if (debug)
			curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);

		dbg("user_password = %s\n", user_password);
		dbg("data = %s\n", data);
		dbg("proxy = %s\n", session->proxy);

		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_buf);
		if (!session->dry_run) {
			res = curl_easy_perform(curl);
			if (res && !session->background) {
				fprintf(stderr, "error(%d) trying to perform "
						"operation\n", res);
				return -EINVAL;
			}
		}

		curl_easy_cleanup(curl);
		if (session->action == ACTION_UPDATE)
			curl_formfree(formpost);
		bti_curl_buffer_free(curl_buf);
	} else {
		switch (session->action) {
		case ACTION_UPDATE:
			escaped_tweet = oauth_url_escape(session->tweet);
			sprintf(endpoint, "%s%s?status=%s", session->hosturl,
				update_uri, escaped_tweet);
			is_post = 1;
			break;
		case ACTION_USER:
			sprintf(endpoint, "%s%s%s.xml?page=%d",
				session->hosturl, user_uri, session->user,
				session->page);
			break;
		case ACTION_REPLIES:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				mentions_uri, session->page);
			break;
		case ACTION_PUBLIC:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				public_uri, session->page);
			break;
		case ACTION_GROUP:
			sprintf(endpoint, "%s%s%s.xml?page=%d",
				session->hosturl, group_uri, session->group,
				session->page);
			break;
		case ACTION_FRIENDS:
			sprintf(endpoint, "%s%s?page=%d", session->hosturl,
				friends_uri, session->page);
			break;
		default:
			break;
		}

		if (is_post) {
			req_url = oauth_sign_url2(endpoint, &postarg, OA_HMAC,
						  NULL, session->consumer_key,
						  session->consumer_secret,
						  session->access_token_key,
						  session->access_token_secret);
			reply = oauth_http_post(req_url, postarg);
		} else {
			req_url = oauth_sign_url2(endpoint, NULL, OA_HMAC, NULL,
						  session->consumer_key,
						  session->consumer_secret,
						  session->access_token_key,
						  session->access_token_secret);
			reply = oauth_http_get(req_url, postarg);
		}

		dbg("%s\n", req_url);
		dbg("%s\n", reply);
		if (req_url)
			free(req_url);

		if (session->action != ACTION_UPDATE)
			parse_timeline(reply);
	}
	return 0;
}
Exemple #13
0
interface void lt_init(void)
{
    curl_init();
}