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