Update to 7.44.0
[platform/upstream/curl.git] / docs / examples / http2-upload.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  * Multiplexed HTTP/2 uploads over a single connection
24  * </DESC>
25  */
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30
31 /* somewhat unix-specific */
32 #include <sys/time.h>
33 #include <unistd.h>
34
35 /* curl stuff */
36 #include <curl/curl.h>
37
38 #ifndef CURLPIPE_MULTIPLEX
39 /* This little trick will just make sure that we don't enable pipelining for
40    libcurls old enough to not have this symbol. It is _not_ defined to zero in
41    a recent libcurl header. */
42 #define CURLPIPE_MULTIPLEX 0
43 #endif
44
45 #define NUM_HANDLES 1000
46
47 void *curl_hnd[NUM_HANDLES];
48 int num_transfers;
49
50 /* a handle to number lookup, highly ineffective when we do many
51    transfers... */
52 static int hnd2num(CURL *hnd)
53 {
54   int i;
55   for(i=0; i< num_transfers; i++) {
56     if(curl_hnd[i] == hnd)
57       return i;
58   }
59   return 0; /* weird, but just a fail-safe */
60 }
61
62 static
63 void dump(const char *text, int num, unsigned char *ptr, size_t size,
64           char nohex)
65 {
66   size_t i;
67   size_t c;
68   unsigned int width=0x10;
69
70   if(nohex)
71     /* without the hex output, we can fit more on screen */
72     width = 0x40;
73
74   fprintf(stderr, "%d %s, %ld bytes (0x%lx)\n",
75           num, text, (long)size, (long)size);
76
77   for(i=0; i<size; i+= width) {
78
79     fprintf(stderr, "%4.4lx: ", (long)i);
80
81     if(!nohex) {
82       /* hex not disabled, show it */
83       for(c = 0; c < width; c++)
84         if(i+c < size)
85           fprintf(stderr, "%02x ", ptr[i+c]);
86         else
87           fputs("   ", stderr);
88     }
89
90     for(c = 0; (c < width) && (i+c < size); c++) {
91       /* check for 0D0A; if found, skip past and start a new line of output */
92       if (nohex && (i+c+1 < size) && ptr[i+c]==0x0D && ptr[i+c+1]==0x0A) {
93         i+=(c+2-width);
94         break;
95       }
96       fprintf(stderr, "%c",
97               (ptr[i+c]>=0x20) && (ptr[i+c]<0x80)?ptr[i+c]:'.');
98       /* check again for 0D0A, to avoid an extra \n if it's at width */
99       if (nohex && (i+c+2 < size) && ptr[i+c+1]==0x0D && ptr[i+c+2]==0x0A) {
100         i+=(c+3-width);
101         break;
102       }
103     }
104     fputc('\n', stderr); /* newline */
105   }
106 }
107
108 static
109 int my_trace(CURL *handle, curl_infotype type,
110              char *data, size_t size,
111              void *userp)
112 {
113   char timebuf[20];
114   const char *text;
115   int num = hnd2num(handle);
116   static time_t epoch_offset;
117   static int    known_offset;
118   struct timeval tv;
119   time_t secs;
120   struct tm *now;
121
122   (void)handle; /* prevent compiler warning */
123   (void)userp;
124
125   gettimeofday(&tv, NULL);
126   if(!known_offset) {
127     epoch_offset = time(NULL) - tv.tv_sec;
128     known_offset = 1;
129   }
130   secs = epoch_offset + tv.tv_sec;
131   now = localtime(&secs);  /* not thread safe but we don't care */
132   snprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld",
133            now->tm_hour, now->tm_min, now->tm_sec, (long)tv.tv_usec);
134
135   switch (type) {
136   case CURLINFO_TEXT:
137     fprintf(stderr, "%s [%d] Info: %s", timebuf, num, data);
138   default: /* in case a new one is introduced to shock us */
139     return 0;
140
141   case CURLINFO_HEADER_OUT:
142     text = "=> Send header";
143     break;
144   case CURLINFO_DATA_OUT:
145     text = "=> Send data";
146     break;
147   case CURLINFO_SSL_DATA_OUT:
148     text = "=> Send SSL data";
149     break;
150   case CURLINFO_HEADER_IN:
151     text = "<= Recv header";
152     break;
153   case CURLINFO_DATA_IN:
154     text = "<= Recv data";
155     break;
156   case CURLINFO_SSL_DATA_IN:
157     text = "<= Recv SSL data";
158     break;
159   }
160
161   dump(text, num, (unsigned char *)data, size, 1);
162   return 0;
163 }
164
165 struct input {
166   FILE *in;
167   size_t bytes_read; /* count up */
168   CURL *hnd;
169 };
170
171 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
172 {
173   struct input *i = userp;
174   size_t retcode = fread(ptr, size, nmemb, i->in);
175   i->bytes_read += retcode;
176   return retcode;
177 }
178
179 struct input indata[NUM_HANDLES];
180
181 static void setup(CURL *hnd, int num, const char *upload)
182 {
183   FILE *out;
184   char url[256];
185   char filename[128];
186   struct stat file_info;
187   curl_off_t uploadsize;
188
189   sprintf(filename, "dl-%d", num);
190   out = fopen(filename, "wb");
191
192   sprintf(url, "https://localhost:8443/upload-%d", num);
193
194   /* get the file size of the local file */
195   stat(upload, &file_info);
196   uploadsize = file_info.st_size;
197
198   indata[num].in = fopen(upload, "rb");
199   indata[num].hnd = hnd;
200
201   /* write to this file */
202   curl_easy_setopt(hnd, CURLOPT_WRITEDATA, out);
203
204   /* we want to use our own read function */
205   curl_easy_setopt(hnd, CURLOPT_READFUNCTION, read_callback);
206   /* read from this file */
207   curl_easy_setopt(hnd, CURLOPT_READDATA, &indata[num]);
208   /* provide the size of the upload */
209   curl_easy_setopt(hnd, CURLOPT_INFILESIZE_LARGE, uploadsize);
210
211   /* send in the URL to store the upload as */
212   curl_easy_setopt(hnd, CURLOPT_URL, url);
213
214   /* upload please */
215   curl_easy_setopt(hnd, CURLOPT_UPLOAD, 1L);
216
217   /* send it verbose for max debuggaility */
218   curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L);
219   curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, my_trace);
220
221   /* HTTP/2 please */
222   curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
223
224   /* we use a self-signed test server, skip verification during debugging */
225   curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);
226   curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
227
228 #if (CURLPIPE_MULTIPLEX > 0)
229   /* wait for pipe connection to confirm */
230   curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L);
231 #endif
232
233   curl_hnd[num] = hnd;
234 }
235
236 /*
237  * Upload all files over HTTP/2, using the same physical connection!
238  */
239 int main(int argc, char **argv)
240 {
241   CURL *easy[NUM_HANDLES];
242   CURLM *multi_handle;
243   int i;
244   int still_running; /* keep number of running handles */
245   const char *filename = "index.html";
246
247   if(argc > 1)
248     /* if given a number, do that many transfers */
249     num_transfers = atoi(argv[1]);
250
251   if(argc > 2)
252     /* if given a file name, upload this! */
253     filename = argv[2];
254
255   if(!num_transfers || (num_transfers > NUM_HANDLES))
256     num_transfers = 3; /* a suitable low default */
257
258   /* init a multi stack */
259   multi_handle = curl_multi_init();
260
261   for(i=0; i<num_transfers; i++) {
262     easy[i] = curl_easy_init();
263     /* set options */
264     setup(easy[i], i, filename);
265
266     /* add the individual transfer */
267     curl_multi_add_handle(multi_handle, easy[i]);
268   }
269
270   curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
271
272   /* We do HTTP/2 so let's stick to one connection per host */
273   curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, 1L);
274
275   /* we start some action by calling perform right away */
276   curl_multi_perform(multi_handle, &still_running);
277
278   do {
279     struct timeval timeout;
280     int rc; /* select() return code */
281     CURLMcode mc; /* curl_multi_fdset() return code */
282
283     fd_set fdread;
284     fd_set fdwrite;
285     fd_set fdexcep;
286     int maxfd = -1;
287
288     long curl_timeo = -1;
289
290     FD_ZERO(&fdread);
291     FD_ZERO(&fdwrite);
292     FD_ZERO(&fdexcep);
293
294     /* set a suitable timeout to play around with */
295     timeout.tv_sec = 1;
296     timeout.tv_usec = 0;
297
298     curl_multi_timeout(multi_handle, &curl_timeo);
299     if(curl_timeo >= 0) {
300       timeout.tv_sec = curl_timeo / 1000;
301       if(timeout.tv_sec > 1)
302         timeout.tv_sec = 1;
303       else
304         timeout.tv_usec = (curl_timeo % 1000) * 1000;
305     }
306
307     /* get file descriptors from the transfers */
308     mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
309
310     if(mc != CURLM_OK)
311     {
312       fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);
313       break;
314     }
315
316     /* On success the value of maxfd is guaranteed to be >= -1. We call
317        select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
318        no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
319        to sleep 100ms, which is the minimum suggested value in the
320        curl_multi_fdset() doc. */
321
322     if(maxfd == -1) {
323 #ifdef _WIN32
324       Sleep(100);
325       rc = 0;
326 #else
327       /* Portable sleep for platforms other than Windows. */
328       struct timeval wait = { 0, 100 * 1000 }; /* 100ms */
329       rc = select(0, NULL, NULL, NULL, &wait);
330 #endif
331     }
332     else {
333       /* Note that on some platforms 'timeout' may be modified by select().
334          If you need access to the original value save a copy beforehand. */
335       rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
336     }
337
338     switch(rc) {
339     case -1:
340       /* select error */
341       break;
342     case 0:
343     default:
344       /* timeout or readable/writable sockets */
345       curl_multi_perform(multi_handle, &still_running);
346       break;
347     }
348   } while(still_running);
349
350   curl_multi_cleanup(multi_handle);
351
352   for(i=0; i<num_transfers; i++)
353     curl_easy_cleanup(easy[i]);
354
355   return 0;
356 }