Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2012
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 9.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include <curl/curl.h>
  6. #include <event2\event.h>
  7. #include <fcntl.h>
  8. #include <sys/stat.h>
  9. #include <errno.h>
  10. #include "http.h"
  11. #include <string>
  12.  
  13. #define MSG_OUT stdout  
  14.  
  15. /* Global information, common to all connections */
  16. typedef struct _GlobalInfo {
  17.   struct event_base* base;
  18.   struct event* timer_event;
  19.   CURLM *multi;
  20.   int still_running;
  21.   http_handler_fn callback;
  22. } GlobalInfo;
  23.  
  24. /* Information associated with a specific easy handle */
  25. typedef struct _ConnInfo {
  26.   CURL *easy;
  27.   char *url;
  28.   GlobalInfo *global;
  29.   char error[CURL_ERROR_SIZE];
  30.   char* data;
  31.   int data_size;
  32.   int data_pos;
  33. //  std::string data;
  34. } ConnInfo;
  35.  
  36.  
  37. /* Information associated with a specific socket */
  38. typedef struct _SockInfo {
  39.   curl_socket_t sockfd;
  40.   CURL *easy;
  41.   int action;
  42.   long timeout;
  43.   struct event* ev;
  44.   int evset;
  45.   GlobalInfo *global;
  46. } SockInfo;
  47.  
  48. /* Update the event timer after curl_multi library calls */
  49. static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
  50. {
  51.   struct timeval timeout;
  52.   (void)multi; /* unused */
  53.  
  54.   timeout.tv_sec = timeout_ms/1000;
  55.   timeout.tv_usec = (timeout_ms%1000)*1000;
  56.   fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms);
  57.   evtimer_del(g->timer_event);
  58.   if( timeout_ms != -1 ) evtimer_add(g->timer_event, &timeout);
  59.   return 0;
  60. }
  61.  
  62. /* Die if we get a bad CURLMcode somewhere */
  63. static void mcode_or_die(const char *where, CURLMcode code, GlobalInfo *g)
  64. {
  65.   char error_str[256];
  66.   if ( CURLM_OK != code ) {
  67.     const char *s;
  68.     switch (code) {
  69.       case     CURLM_CALL_MULTI_PERFORM: s="CURLM_CALL_MULTI_PERFORM"; break;
  70.       case     CURLM_BAD_HANDLE:         s="CURLM_BAD_HANDLE";         break;
  71.       case     CURLM_BAD_EASY_HANDLE:    s="CURLM_BAD_EASY_HANDLE";    break;
  72.       case     CURLM_OUT_OF_MEMORY:      s="CURLM_OUT_OF_MEMORY";      break;
  73.       case     CURLM_INTERNAL_ERROR:     s="CURLM_INTERNAL_ERROR";     break;
  74.       case     CURLM_UNKNOWN_OPTION:     s="CURLM_UNKNOWN_OPTION";     break;
  75.       case     CURLM_LAST:               s="CURLM_LAST";               break;
  76.       default: s="CURLM_unknown";
  77.         break;
  78.     case     CURLM_BAD_SOCKET:         s="CURLM_BAD_SOCKET";
  79.       //sprintf(error_str, "ERROR: %s returns %s", where, s);
  80.       /* ignore this error */
  81.       return;
  82.     }
  83.     sprintf(error_str, "ERROR: %s returns %s", where, s);
  84.     g->callback(-1, 0, 0, error_str);
  85.   }
  86. }
  87.  
  88. /* Check for completed transfers, and remove their easy handles */
  89. static void check_multi_info(GlobalInfo *g)
  90. {
  91.   char *eff_url;
  92.   CURLMsg *msg;
  93.   int msgs_left;
  94.   ConnInfo *conn;
  95.   CURL *easy;
  96.   CURLcode res;
  97.   while ((msg = curl_multi_info_read(g->multi, &msgs_left))) {
  98.     if (msg->msg == CURLMSG_DONE) {
  99.       easy = msg->easy_handle;
  100.       res = msg->data.result;
  101.       curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
  102.       curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
  103.       // get http response code
  104.       unsigned long rc = 0;
  105.       curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &rc);
  106.       // call callback before we clean up the connection
  107.       g->callback(rc, conn->data, conn->data_pos, conn->error);
  108.       // clean up connection
  109.       curl_multi_remove_handle(g->multi, easy);
  110.       free(conn->url);
  111.       free(conn->data);
  112.       curl_easy_cleanup(easy);
  113.       free(conn);
  114.     }
  115.   }
  116. }
  117.  
  118. /* Called by libevent when we get action on a multi socket */
  119. static void event_cb(int fd, short kind, void *userp)
  120. {
  121.   GlobalInfo *g = (GlobalInfo*) userp;
  122.   CURLMcode rc;
  123.  
  124.   int action =
  125.     (kind & EV_READ ? CURL_CSELECT_IN : 0) |
  126.     (kind & EV_WRITE ? CURL_CSELECT_OUT : 0);
  127.  
  128.   rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
  129.   mcode_or_die("event_cb: curl_multi_socket_action", rc, g);
  130.  
  131.   check_multi_info(g);
  132.   if ( g->still_running <= 0 ) {
  133.     fprintf(MSG_OUT, "last transfer done, kill timeout\n");
  134.     if (evtimer_pending(g->timer_event, NULL)) {
  135.       evtimer_del(g->timer_event);
  136.     }
  137.     curl_multi_cleanup(g->multi);
  138.     free(g);
  139.   }
  140. }
  141.  
  142.  
  143.  
  144. /* Called by libevent when our timeout expires */
  145. static void timer_cb(int fd, short kind, void *userp)
  146. {
  147.   GlobalInfo *g = (GlobalInfo *)userp;
  148.   CURLMcode rc;
  149.   (void)fd;
  150.   (void)kind;
  151.  
  152.   rc = curl_multi_socket_action(g->multi,
  153.                                   CURL_SOCKET_TIMEOUT, 0, &g->still_running);
  154.   mcode_or_die("timer_cb: curl_multi_socket_action", rc, g);
  155.   check_multi_info(g);
  156. }
  157.  
  158.  
  159.  
  160. /* Clean up the SockInfo structure */
  161. static void remsock(SockInfo *f)
  162. {
  163.   if (f) {
  164.     if (f->evset)
  165.       event_del(f->ev);
  166.     free(f);
  167.   }
  168. }
  169.  
  170.  
  171.  
  172. /* Assign information to a SockInfo structure */
  173. static void setsock(SockInfo*f, curl_socket_t s, CURL*e, int act, GlobalInfo*g)
  174. {
  175.   int kind =
  176.      (act&CURL_POLL_IN?EV_READ:0)|(act&CURL_POLL_OUT?EV_WRITE:0)|EV_PERSIST;
  177.  
  178.   f->sockfd = s;
  179.   f->action = act;
  180.   f->easy = e;
  181.   if (f->evset) event_del(f->ev);
  182.   f->ev = event_new(g->base, f->sockfd, kind, event_cb, g);
  183.   f->evset=1;
  184.   event_add(f->ev, NULL);
  185. }
  186.  
  187.  
  188.  
  189. /* Initialize a new SockInfo structure */
  190. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g) {
  191.   SockInfo *fdp = (SockInfo*)calloc(sizeof(SockInfo), 1);
  192.   fdp->global = g;
  193.   setsock(fdp, s, easy, action, g);
  194.   curl_multi_assign(g->multi, s, fdp);
  195. }
  196.  
  197. /* CURLMOPT_SOCKETFUNCTION */
  198. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  199. {
  200.   GlobalInfo *g = (GlobalInfo*) cbp;
  201.   SockInfo *fdp = (SockInfo*) sockp;
  202.   const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
  203.  
  204.   fprintf(MSG_OUT,
  205.           "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  206.   if (what == CURL_POLL_REMOVE) {
  207.     fprintf(MSG_OUT, "\n");
  208.     remsock(fdp);
  209.   }
  210.   else {
  211.     if (!fdp) {
  212.       fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
  213.       fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
  214.       addsock(s, e, what, g);
  215.     }
  216.     else {
  217.       fprintf(MSG_OUT,
  218.               "Changing action from %s to %s\n",
  219.               whatstr[fdp->action], whatstr[what]);
  220.       setsock(fdp, s, e, what, g);
  221.     }
  222.   }
  223.   return 0;
  224. }
  225.  
  226.  
  227.  
  228. /* CURLOPT_WRITEFUNCTION */
  229. static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
  230. {
  231.   size_t realsize = size * nmemb;
  232.   ConnInfo *conn = (ConnInfo*) data;
  233.   while( conn->data_size - conn->data_pos < realsize )
  234.   {
  235.     fprintf(MSG_OUT, "!! resize buf size %i data_pos %i realsize %i\n", conn->data_size, conn->data_pos, realsize);
  236.     conn->data = (char*)realloc(conn->data, 2*conn->data_size);
  237.     conn->data_size *=2;
  238.   }
  239.   memcpy(conn->data + conn->data_pos, ptr, realsize);
  240.   conn->data_pos += realsize;
  241.   fprintf(MSG_OUT, "write_cb: %i\n", realsize);
  242.   return realsize;
  243. }
  244.  
  245.  
  246. /* CURLOPT_PROGRESSFUNCTION */
  247. static int prog_cb (void *p, double dltotal, double dlnow, double ult,
  248.                     double uln)
  249. {
  250.   ConnInfo *conn = (ConnInfo *)p;
  251.   (void)ult;
  252.   (void)uln;
  253.  
  254.   fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
  255.   return 0;
  256. }
  257.  
  258.  
  259. /* Create a new easy handle, and add it to the global curl_multi */
  260. static void new_conn(const char *url, GlobalInfo *g )
  261. {
  262.   ConnInfo *conn;
  263.   CURLMcode rc;
  264.  
  265.   conn = (ConnInfo *)calloc(1, sizeof(ConnInfo));
  266.   memset(conn, 0, sizeof(ConnInfo));
  267.   conn->error[0]='\0';
  268.   conn->data_size = 4096;
  269.   conn->data_pos = 0;
  270.   conn->data = (char*)malloc(4096);
  271.   conn->easy = curl_easy_init();
  272.   if (!conn->easy)
  273.   {
  274.     g->callback(-1, 0, 0, "curl_easy_init() failed" );
  275.     return;
  276.   }
  277.   conn->global = g;
  278.   conn->url = strdup(url);
  279.   curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  280.   curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  281.   curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
  282.   curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
  283.   curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  284.   curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  285.   curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
  286.   curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  287.   curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  288.   fprintf(MSG_OUT, "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  289.   rc = curl_multi_add_handle(g->multi, conn->easy);
  290.   mcode_or_die("new_conn: curl_multi_add_handle", rc, g);
  291.   /* note that the add_handle() will set a time-out to trigger very soon so
  292.      that the necessary socket_action() call will be called by this app */
  293. }
  294.  
  295. typedef void (*http_handler_fn)(int response_code, const char* data, size_t len, const char* error);
  296.  
  297. void add_http(const char* url, struct event_base* base, http_handler_fn callback)
  298. {
  299.   GlobalInfo* g = (GlobalInfo *)calloc(1, sizeof(GlobalInfo));
  300.   memset(g, 0, sizeof(GlobalInfo));
  301.   g->base = base;
  302.   g->multi = curl_multi_init();
  303.   g->callback = callback;
  304.   g->timer_event = event_new(base, -1, EV_PERSIST, timer_cb, g);
  305.   curl_multi_setopt(g->multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  306.   curl_multi_setopt(g->multi, CURLMOPT_SOCKETDATA, g);
  307.   curl_multi_setopt(g->multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
  308.   curl_multi_setopt(g->multi, CURLMOPT_TIMERDATA, g);
  309.   new_conn(url, g);
  310. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement