Home | History | Annotate | Download | only in examples
      1 /***************************************************************************
      2  *                                  _   _ ____  _
      3  *  Project                     ___| | | |  _ \| |
      4  *                             / __| | | | |_) | |
      5  *                            | (__| |_| |  _ <| |___
      6  *                             \___|\___/|_| \_\_____|
      7  *
      8  * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel (at) haxx.se>, et al.
      9  *
     10  * This software is licensed as described in the file COPYING, which
     11  * you should have received as part of this distribution. The terms
     12  * are also available at https://curl.haxx.se/docs/copyright.html.
     13  *
     14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
     15  * copies of the Software, and permit persons to whom the Software is
     16  * furnished to do so, under the terms of the COPYING file.
     17  *
     18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
     19  * KIND, either express or implied.
     20  *
     21  ***************************************************************************/
     22 /* <DESC>
     23  * HTTP/2 server push
     24  * </DESC>
     25  */
     26 #include <stdio.h>
     27 #include <stdlib.h>
     28 #include <string.h>
     29 
     30 /* somewhat unix-specific */
     31 #include <sys/time.h>
     32 #include <unistd.h>
     33 
     34 /* curl stuff */
     35 #include <curl/curl.h>
     36 
     37 #ifndef CURLPIPE_MULTIPLEX
     38 #error "too old libcurl, can't do HTTP/2 server push!"
     39 #endif
     40 
     41 static
     42 void dump(const char *text, unsigned char *ptr, size_t size,
     43           char nohex)
     44 {
     45   size_t i;
     46   size_t c;
     47 
     48   unsigned int width=0x10;
     49 
     50   if(nohex)
     51     /* without the hex output, we can fit more on screen */
     52     width = 0x40;
     53 
     54   fprintf(stderr, "%s, %ld bytes (0x%lx)\n",
     55           text, (long)size, (long)size);
     56 
     57   for(i=0; i<size; i+= width) {
     58 
     59     fprintf(stderr, "%4.4lx: ", (long)i);
     60 
     61     if(!nohex) {
     62       /* hex not disabled, show it */
     63       for(c = 0; c < width; c++)
     64         if(i+c < size)
     65           fprintf(stderr, "%02x ", ptr[i+c]);
     66         else
     67           fputs("   ", stderr);
     68     }
     69 
     70     for(c = 0; (c < width) && (i+c < size); c++) {
     71       /* check for 0D0A; if found, skip past and start a new line of output */
     72       if(nohex && (i+c+1 < size) && ptr[i+c]==0x0D && ptr[i+c+1]==0x0A) {
     73         i+=(c+2-width);
     74         break;
     75       }
     76       fprintf(stderr, "%c",
     77               (ptr[i+c]>=0x20) && (ptr[i+c]<0x80)?ptr[i+c]:'.');
     78       /* check again for 0D0A, to avoid an extra \n if it's at width */
     79       if(nohex && (i+c+2 < size) && ptr[i+c+1]==0x0D && ptr[i+c+2]==0x0A) {
     80         i+=(c+3-width);
     81         break;
     82       }
     83     }
     84     fputc('\n', stderr); /* newline */
     85   }
     86 }
     87 
     88 static
     89 int my_trace(CURL *handle, curl_infotype type,
     90              char *data, size_t size,
     91              void *userp)
     92 {
     93   const char *text;
     94   (void)handle; /* prevent compiler warning */
     95   (void)userp;
     96   switch (type) {
     97   case CURLINFO_TEXT:
     98     fprintf(stderr, "== Info: %s", data);
     99   default: /* in case a new one is introduced to shock us */
    100     return 0;
    101 
    102   case CURLINFO_HEADER_OUT:
    103     text = "=> Send header";
    104     break;
    105   case CURLINFO_DATA_OUT:
    106     text = "=> Send data";
    107     break;
    108   case CURLINFO_SSL_DATA_OUT:
    109     text = "=> Send SSL data";
    110     break;
    111   case CURLINFO_HEADER_IN:
    112     text = "<= Recv header";
    113     break;
    114   case CURLINFO_DATA_IN:
    115     text = "<= Recv data";
    116     break;
    117   case CURLINFO_SSL_DATA_IN:
    118     text = "<= Recv SSL data";
    119     break;
    120   }
    121 
    122   dump(text, (unsigned char *)data, size, 1);
    123   return 0;
    124 }
    125 
    126 #define OUTPUTFILE "dl"
    127 
    128 static void setup(CURL *hnd)
    129 {
    130   FILE *out = fopen(OUTPUTFILE, "wb");
    131 
    132   /* write to this file */
    133   curl_easy_setopt(hnd, CURLOPT_WRITEDATA, out);
    134 
    135   /* set the same URL */
    136   curl_easy_setopt(hnd, CURLOPT_URL, "https://localhost:8443/index.html");
    137 
    138   /* send it verbose for max debuggaility */
    139   curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L);
    140   curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, my_trace);
    141 
    142   /* HTTP/2 please */
    143   curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
    144 
    145   /* we use a self-signed test server, skip verification during debugging */
    146   curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
    147   curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
    148 
    149 #if (CURLPIPE_MULTIPLEX > 0)
    150   /* wait for pipe connection to confirm */
    151   curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L);
    152 #endif
    153 
    154 }
    155 
    156 /* called when there's an incoming push */
    157 static int server_push_callback(CURL *parent,
    158                                 CURL *easy,
    159                                 size_t num_headers,
    160                                 struct curl_pushheaders *headers,
    161                                 void *userp)
    162 {
    163   char *headp;
    164   size_t i;
    165   int *transfers = (int *)userp;
    166   char filename[128];
    167   FILE *out;
    168   static unsigned int count = 0;
    169 
    170   (void)parent; /* we have no use for this */
    171 
    172   snprintf(filename, 128, "push%u", count++);
    173 
    174   /* here's a new stream, save it in a new file for each new push */
    175   out = fopen(filename, "wb");
    176 
    177   /* write to this file */
    178   curl_easy_setopt(easy, CURLOPT_WRITEDATA, out);
    179 
    180   fprintf(stderr, "**** push callback approves stream %u, got %d headers!\n",
    181           count, (int)num_headers);
    182 
    183   for(i=0; i<num_headers; i++) {
    184     headp = curl_pushheader_bynum(headers, i);
    185     fprintf(stderr, "**** header %u: %s\n", (int)i, headp);
    186   }
    187 
    188   headp = curl_pushheader_byname(headers, ":path");
    189   if(headp) {
    190     fprintf(stderr, "**** The PATH is %s\n", headp /* skip :path + colon */);
    191   }
    192 
    193   (*transfers)++; /* one more */
    194   return CURL_PUSH_OK;
    195 }
    196 
    197 
    198 /*
    199  * Download a file over HTTP/2, take care of server push.
    200  */
    201 int main(void)
    202 {
    203   CURL *easy;
    204   CURLM *multi_handle;
    205   int still_running; /* keep number of running handles */
    206   int transfers=1; /* we start with one */
    207   struct CURLMsg *m;
    208 
    209   /* init a multi stack */
    210   multi_handle = curl_multi_init();
    211 
    212   easy = curl_easy_init();
    213 
    214   /* set options */
    215   setup(easy);
    216 
    217   /* add the easy transfer */
    218   curl_multi_add_handle(multi_handle, easy);
    219 
    220   curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
    221   curl_multi_setopt(multi_handle, CURLMOPT_PUSHFUNCTION, server_push_callback);
    222   curl_multi_setopt(multi_handle, CURLMOPT_PUSHDATA, &transfers);
    223 
    224   /* we start some action by calling perform right away */
    225   curl_multi_perform(multi_handle, &still_running);
    226 
    227   do {
    228     struct timeval timeout;
    229     int rc; /* select() return code */
    230     CURLMcode mc; /* curl_multi_fdset() return code */
    231 
    232     fd_set fdread;
    233     fd_set fdwrite;
    234     fd_set fdexcep;
    235     int maxfd = -1;
    236 
    237     long curl_timeo = -1;
    238 
    239     FD_ZERO(&fdread);
    240     FD_ZERO(&fdwrite);
    241     FD_ZERO(&fdexcep);
    242 
    243     /* set a suitable timeout to play around with */
    244     timeout.tv_sec = 1;
    245     timeout.tv_usec = 0;
    246 
    247     curl_multi_timeout(multi_handle, &curl_timeo);
    248     if(curl_timeo >= 0) {
    249       timeout.tv_sec = curl_timeo / 1000;
    250       if(timeout.tv_sec > 1)
    251         timeout.tv_sec = 1;
    252       else
    253         timeout.tv_usec = (curl_timeo % 1000) * 1000;
    254     }
    255 
    256     /* get file descriptors from the transfers */
    257     mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
    258 
    259     if(mc != CURLM_OK) {
    260       fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);
    261       break;
    262     }
    263 
    264     /* On success the value of maxfd is guaranteed to be >= -1. We call
    265        select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
    266        no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
    267        to sleep 100ms, which is the minimum suggested value in the
    268        curl_multi_fdset() doc. */
    269 
    270     if(maxfd == -1) {
    271 #ifdef _WIN32
    272       Sleep(100);
    273       rc = 0;
    274 #else
    275       /* Portable sleep for platforms other than Windows. */
    276       struct timeval wait = { 0, 100 * 1000 }; /* 100ms */
    277       rc = select(0, NULL, NULL, NULL, &wait);
    278 #endif
    279     }
    280     else {
    281       /* Note that on some platforms 'timeout' may be modified by select().
    282          If you need access to the original value save a copy beforehand. */
    283       rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
    284     }
    285 
    286     switch(rc) {
    287     case -1:
    288       /* select error */
    289       break;
    290     case 0:
    291     default:
    292       /* timeout or readable/writable sockets */
    293       curl_multi_perform(multi_handle, &still_running);
    294       break;
    295     }
    296 
    297     /*
    298      * A little caution when doing server push is that libcurl itself has
    299      * created and added one or more easy handles but we need to clean them up
    300      * when we are done.
    301      */
    302 
    303     do {
    304       int msgq = 0;;
    305       m = curl_multi_info_read(multi_handle, &msgq);
    306       if(m && (m->msg == CURLMSG_DONE)) {
    307         CURL *e = m->easy_handle;
    308         transfers--;
    309         curl_multi_remove_handle(multi_handle, e);
    310         curl_easy_cleanup(e);
    311       }
    312     } while(m);
    313 
    314   } while(transfers); /* as long as we have transfers going */
    315 
    316   curl_multi_cleanup(multi_handle);
    317 
    318 
    319   return 0;
    320 }
    321