Merge branch 'jk/diff-do-not-reuse-wtf-needs-cleaning'
[git] / http.c
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "pack.h"
4 #include "sideband.h"
5 #include "run-command.h"
6 #include "url.h"
7 #include "urlmatch.h"
8 #include "credential.h"
9 #include "version.h"
10 #include "pkt-line.h"
11 #include "gettext.h"
12 #include "transport.h"
13
14 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
15 #if LIBCURL_VERSION_NUM >= 0x070a08
16 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
17 #else
18 long int git_curl_ipresolve;
19 #endif
20 int active_requests;
21 int http_is_verbose;
22 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
23
24 #if LIBCURL_VERSION_NUM >= 0x070a06
25 #define LIBCURL_CAN_HANDLE_AUTH_ANY
26 #endif
27
28 static int min_curl_sessions = 1;
29 static int curl_session_count;
30 #ifdef USE_CURL_MULTI
31 static int max_requests = -1;
32 static CURLM *curlm;
33 #endif
34 #ifndef NO_CURL_EASY_DUPHANDLE
35 static CURL *curl_default;
36 #endif
37
38 #define PREV_BUF_SIZE 4096
39
40 char curl_errorstr[CURL_ERROR_SIZE];
41
42 static int curl_ssl_verify = -1;
43 static int curl_ssl_try;
44 static const char *ssl_cert;
45 static const char *ssl_cipherlist;
46 static const char *ssl_version;
47 static struct {
48         const char *name;
49         long ssl_version;
50 } sslversions[] = {
51         { "sslv2", CURL_SSLVERSION_SSLv2 },
52         { "sslv3", CURL_SSLVERSION_SSLv3 },
53         { "tlsv1", CURL_SSLVERSION_TLSv1 },
54 #if LIBCURL_VERSION_NUM >= 0x072200
55         { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
56         { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
57         { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
58 #endif
59 };
60 #if LIBCURL_VERSION_NUM >= 0x070903
61 static const char *ssl_key;
62 #endif
63 #if LIBCURL_VERSION_NUM >= 0x070908
64 static const char *ssl_capath;
65 #endif
66 #if LIBCURL_VERSION_NUM >= 0x072c00
67 static const char *ssl_pinnedkey;
68 #endif
69 static const char *ssl_cainfo;
70 static long curl_low_speed_limit = -1;
71 static long curl_low_speed_time = -1;
72 static int curl_ftp_no_epsv;
73 static const char *curl_http_proxy;
74 static const char *curl_no_proxy;
75 static const char *http_proxy_authmethod;
76 static struct {
77         const char *name;
78         long curlauth_param;
79 } proxy_authmethods[] = {
80         { "basic", CURLAUTH_BASIC },
81         { "digest", CURLAUTH_DIGEST },
82         { "negotiate", CURLAUTH_GSSNEGOTIATE },
83         { "ntlm", CURLAUTH_NTLM },
84 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
85         { "anyauth", CURLAUTH_ANY },
86 #endif
87         /*
88          * CURLAUTH_DIGEST_IE has no corresponding command-line option in
89          * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
90          * here, too
91          */
92 };
93 static struct credential proxy_auth = CREDENTIAL_INIT;
94 static const char *curl_proxyuserpwd;
95 static const char *curl_cookie_file;
96 static int curl_save_cookies;
97 struct credential http_auth = CREDENTIAL_INIT;
98 static int http_proactive_auth;
99 static const char *user_agent;
100 static int curl_empty_auth;
101
102 #if LIBCURL_VERSION_NUM >= 0x071700
103 /* Use CURLOPT_KEYPASSWD as is */
104 #elif LIBCURL_VERSION_NUM >= 0x070903
105 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
106 #else
107 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
108 #endif
109
110 static struct credential cert_auth = CREDENTIAL_INIT;
111 static int ssl_cert_password_required;
112 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
113 static unsigned long http_auth_methods = CURLAUTH_ANY;
114 #endif
115
116 static struct curl_slist *pragma_header;
117 static struct curl_slist *no_pragma_header;
118 static struct curl_slist *extra_http_headers;
119
120 static struct active_request_slot *active_queue_head;
121
122 static char *cached_accept_language;
123
124 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
125 {
126         size_t size = eltsize * nmemb;
127         struct buffer *buffer = buffer_;
128
129         if (size > buffer->buf.len - buffer->posn)
130                 size = buffer->buf.len - buffer->posn;
131         memcpy(ptr, buffer->buf.buf + buffer->posn, size);
132         buffer->posn += size;
133
134         return size;
135 }
136
137 #ifndef NO_CURL_IOCTL
138 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
139 {
140         struct buffer *buffer = clientp;
141
142         switch (cmd) {
143         case CURLIOCMD_NOP:
144                 return CURLIOE_OK;
145
146         case CURLIOCMD_RESTARTREAD:
147                 buffer->posn = 0;
148                 return CURLIOE_OK;
149
150         default:
151                 return CURLIOE_UNKNOWNCMD;
152         }
153 }
154 #endif
155
156 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
157 {
158         size_t size = eltsize * nmemb;
159         struct strbuf *buffer = buffer_;
160
161         strbuf_add(buffer, ptr, size);
162         return size;
163 }
164
165 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
166 {
167         return eltsize * nmemb;
168 }
169
170 static void closedown_active_slot(struct active_request_slot *slot)
171 {
172         active_requests--;
173         slot->in_use = 0;
174 }
175
176 static void finish_active_slot(struct active_request_slot *slot)
177 {
178         closedown_active_slot(slot);
179         curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
180
181         if (slot->finished != NULL)
182                 (*slot->finished) = 1;
183
184         /* Store slot results so they can be read after the slot is reused */
185         if (slot->results != NULL) {
186                 slot->results->curl_result = slot->curl_result;
187                 slot->results->http_code = slot->http_code;
188 #if LIBCURL_VERSION_NUM >= 0x070a08
189                 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
190                                   &slot->results->auth_avail);
191 #else
192                 slot->results->auth_avail = 0;
193 #endif
194
195                 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
196                         &slot->results->http_connectcode);
197         }
198
199         /* Run callback if appropriate */
200         if (slot->callback_func != NULL)
201                 slot->callback_func(slot->callback_data);
202 }
203
204 #ifdef USE_CURL_MULTI
205 static void process_curl_messages(void)
206 {
207         int num_messages;
208         struct active_request_slot *slot;
209         CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
210
211         while (curl_message != NULL) {
212                 if (curl_message->msg == CURLMSG_DONE) {
213                         int curl_result = curl_message->data.result;
214                         slot = active_queue_head;
215                         while (slot != NULL &&
216                                slot->curl != curl_message->easy_handle)
217                                 slot = slot->next;
218                         if (slot != NULL) {
219                                 curl_multi_remove_handle(curlm, slot->curl);
220                                 slot->curl_result = curl_result;
221                                 finish_active_slot(slot);
222                         } else {
223                                 fprintf(stderr, "Received DONE message for unknown request!\n");
224                         }
225                 } else {
226                         fprintf(stderr, "Unknown CURL message received: %d\n",
227                                 (int)curl_message->msg);
228                 }
229                 curl_message = curl_multi_info_read(curlm, &num_messages);
230         }
231 }
232 #endif
233
234 static int http_options(const char *var, const char *value, void *cb)
235 {
236         if (!strcmp("http.sslverify", var)) {
237                 curl_ssl_verify = git_config_bool(var, value);
238                 return 0;
239         }
240         if (!strcmp("http.sslcipherlist", var))
241                 return git_config_string(&ssl_cipherlist, var, value);
242         if (!strcmp("http.sslversion", var))
243                 return git_config_string(&ssl_version, var, value);
244         if (!strcmp("http.sslcert", var))
245                 return git_config_string(&ssl_cert, var, value);
246 #if LIBCURL_VERSION_NUM >= 0x070903
247         if (!strcmp("http.sslkey", var))
248                 return git_config_string(&ssl_key, var, value);
249 #endif
250 #if LIBCURL_VERSION_NUM >= 0x070908
251         if (!strcmp("http.sslcapath", var))
252                 return git_config_pathname(&ssl_capath, var, value);
253 #endif
254         if (!strcmp("http.sslcainfo", var))
255                 return git_config_pathname(&ssl_cainfo, var, value);
256         if (!strcmp("http.sslcertpasswordprotected", var)) {
257                 ssl_cert_password_required = git_config_bool(var, value);
258                 return 0;
259         }
260         if (!strcmp("http.ssltry", var)) {
261                 curl_ssl_try = git_config_bool(var, value);
262                 return 0;
263         }
264         if (!strcmp("http.minsessions", var)) {
265                 min_curl_sessions = git_config_int(var, value);
266 #ifndef USE_CURL_MULTI
267                 if (min_curl_sessions > 1)
268                         min_curl_sessions = 1;
269 #endif
270                 return 0;
271         }
272 #ifdef USE_CURL_MULTI
273         if (!strcmp("http.maxrequests", var)) {
274                 max_requests = git_config_int(var, value);
275                 return 0;
276         }
277 #endif
278         if (!strcmp("http.lowspeedlimit", var)) {
279                 curl_low_speed_limit = (long)git_config_int(var, value);
280                 return 0;
281         }
282         if (!strcmp("http.lowspeedtime", var)) {
283                 curl_low_speed_time = (long)git_config_int(var, value);
284                 return 0;
285         }
286
287         if (!strcmp("http.noepsv", var)) {
288                 curl_ftp_no_epsv = git_config_bool(var, value);
289                 return 0;
290         }
291         if (!strcmp("http.proxy", var))
292                 return git_config_string(&curl_http_proxy, var, value);
293
294         if (!strcmp("http.proxyauthmethod", var))
295                 return git_config_string(&http_proxy_authmethod, var, value);
296
297         if (!strcmp("http.cookiefile", var))
298                 return git_config_pathname(&curl_cookie_file, var, value);
299         if (!strcmp("http.savecookies", var)) {
300                 curl_save_cookies = git_config_bool(var, value);
301                 return 0;
302         }
303
304         if (!strcmp("http.postbuffer", var)) {
305                 http_post_buffer = git_config_int(var, value);
306                 if (http_post_buffer < LARGE_PACKET_MAX)
307                         http_post_buffer = LARGE_PACKET_MAX;
308                 return 0;
309         }
310
311         if (!strcmp("http.useragent", var))
312                 return git_config_string(&user_agent, var, value);
313
314         if (!strcmp("http.emptyauth", var)) {
315                 curl_empty_auth = git_config_bool(var, value);
316                 return 0;
317         }
318
319         if (!strcmp("http.pinnedpubkey", var)) {
320 #if LIBCURL_VERSION_NUM >= 0x072c00
321                 return git_config_pathname(&ssl_pinnedkey, var, value);
322 #else
323                 warning(_("Public key pinning not supported with cURL < 7.44.0"));
324                 return 0;
325 #endif
326         }
327
328         if (!strcmp("http.extraheader", var)) {
329                 if (!value) {
330                         return config_error_nonbool(var);
331                 } else if (!*value) {
332                         curl_slist_free_all(extra_http_headers);
333                         extra_http_headers = NULL;
334                 } else {
335                         extra_http_headers =
336                                 curl_slist_append(extra_http_headers, value);
337                 }
338                 return 0;
339         }
340
341         /* Fall back on the default ones */
342         return git_default_config(var, value, cb);
343 }
344
345 static void init_curl_http_auth(CURL *result)
346 {
347         if (!http_auth.username) {
348                 if (curl_empty_auth)
349                         curl_easy_setopt(result, CURLOPT_USERPWD, ":");
350                 return;
351         }
352
353         credential_fill(&http_auth);
354
355 #if LIBCURL_VERSION_NUM >= 0x071301
356         curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
357         curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
358 #else
359         {
360                 static struct strbuf up = STRBUF_INIT;
361                 /*
362                  * Note that we assume we only ever have a single set of
363                  * credentials in a given program run, so we do not have
364                  * to worry about updating this buffer, only setting its
365                  * initial value.
366                  */
367                 if (!up.len)
368                         strbuf_addf(&up, "%s:%s",
369                                 http_auth.username, http_auth.password);
370                 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
371         }
372 #endif
373 }
374
375 /* *var must be free-able */
376 static void var_override(const char **var, char *value)
377 {
378         if (value) {
379                 free((void *)*var);
380                 *var = xstrdup(value);
381         }
382 }
383
384 static void set_proxyauth_name_password(CURL *result)
385 {
386 #if LIBCURL_VERSION_NUM >= 0x071301
387                 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
388                         proxy_auth.username);
389                 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
390                         proxy_auth.password);
391 #else
392                 struct strbuf s = STRBUF_INIT;
393
394                 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
395                 strbuf_addch(&s, ':');
396                 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
397                 curl_proxyuserpwd = strbuf_detach(&s, NULL);
398                 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
399 #endif
400 }
401
402 static void init_curl_proxy_auth(CURL *result)
403 {
404         if (proxy_auth.username) {
405                 if (!proxy_auth.password)
406                         credential_fill(&proxy_auth);
407                 set_proxyauth_name_password(result);
408         }
409
410         var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
411
412 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
413         if (http_proxy_authmethod) {
414                 int i;
415                 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
416                         if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
417                                 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
418                                                 proxy_authmethods[i].curlauth_param);
419                                 break;
420                         }
421                 }
422                 if (i == ARRAY_SIZE(proxy_authmethods)) {
423                         warning("unsupported proxy authentication method %s: using anyauth",
424                                         http_proxy_authmethod);
425                         curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
426                 }
427         }
428         else
429                 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
430 #endif
431 }
432
433 static int has_cert_password(void)
434 {
435         if (ssl_cert == NULL || ssl_cert_password_required != 1)
436                 return 0;
437         if (!cert_auth.password) {
438                 cert_auth.protocol = xstrdup("cert");
439                 cert_auth.username = xstrdup("");
440                 cert_auth.path = xstrdup(ssl_cert);
441                 credential_fill(&cert_auth);
442         }
443         return 1;
444 }
445
446 #if LIBCURL_VERSION_NUM >= 0x071900
447 static void set_curl_keepalive(CURL *c)
448 {
449         curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
450 }
451
452 #elif LIBCURL_VERSION_NUM >= 0x071000
453 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
454 {
455         int ka = 1;
456         int rc;
457         socklen_t len = (socklen_t)sizeof(ka);
458
459         if (type != CURLSOCKTYPE_IPCXN)
460                 return 0;
461
462         rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
463         if (rc < 0)
464                 warning_errno("unable to set SO_KEEPALIVE on socket");
465
466         return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
467 }
468
469 static void set_curl_keepalive(CURL *c)
470 {
471         curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
472 }
473
474 #else
475 static void set_curl_keepalive(CURL *c)
476 {
477         /* not supported on older curl versions */
478 }
479 #endif
480
481 static void redact_sensitive_header(struct strbuf *header)
482 {
483         const char *sensitive_header;
484
485         if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
486             skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
487                 /* The first token is the type, which is OK to log */
488                 while (isspace(*sensitive_header))
489                         sensitive_header++;
490                 while (*sensitive_header && !isspace(*sensitive_header))
491                         sensitive_header++;
492                 /* Everything else is opaque and possibly sensitive */
493                 strbuf_setlen(header,  sensitive_header - header->buf);
494                 strbuf_addstr(header, " <redacted>");
495         }
496 }
497
498 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
499 {
500         struct strbuf out = STRBUF_INIT;
501         struct strbuf **headers, **header;
502
503         strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
504                 text, (long)size, (long)size);
505         trace_strbuf(&trace_curl, &out);
506         strbuf_reset(&out);
507         strbuf_add(&out, ptr, size);
508         headers = strbuf_split_max(&out, '\n', 0);
509
510         for (header = headers; *header; header++) {
511                 if (hide_sensitive_header)
512                         redact_sensitive_header(*header);
513                 strbuf_insert((*header), 0, text, strlen(text));
514                 strbuf_insert((*header), strlen(text), ": ", 2);
515                 strbuf_rtrim((*header));
516                 strbuf_addch((*header), '\n');
517                 trace_strbuf(&trace_curl, (*header));
518         }
519         strbuf_list_free(headers);
520         strbuf_release(&out);
521 }
522
523 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
524 {
525         size_t i;
526         struct strbuf out = STRBUF_INIT;
527         unsigned int width = 60;
528
529         strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
530                 text, (long)size, (long)size);
531         trace_strbuf(&trace_curl, &out);
532
533         for (i = 0; i < size; i += width) {
534                 size_t w;
535
536                 strbuf_reset(&out);
537                 strbuf_addf(&out, "%s: ", text);
538                 for (w = 0; (w < width) && (i + w < size); w++) {
539                         unsigned char ch = ptr[i + w];
540
541                         strbuf_addch(&out,
542                                        (ch >= 0x20) && (ch < 0x80)
543                                        ? ch : '.');
544                 }
545                 strbuf_addch(&out, '\n');
546                 trace_strbuf(&trace_curl, &out);
547         }
548         strbuf_release(&out);
549 }
550
551 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
552 {
553         const char *text;
554         enum { NO_FILTER = 0, DO_FILTER = 1 };
555
556         switch (type) {
557         case CURLINFO_TEXT:
558                 trace_printf_key(&trace_curl, "== Info: %s", data);
559         default:                /* we ignore unknown types by default */
560                 return 0;
561
562         case CURLINFO_HEADER_OUT:
563                 text = "=> Send header";
564                 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
565                 break;
566         case CURLINFO_DATA_OUT:
567                 text = "=> Send data";
568                 curl_dump_data(text, (unsigned char *)data, size);
569                 break;
570         case CURLINFO_SSL_DATA_OUT:
571                 text = "=> Send SSL data";
572                 curl_dump_data(text, (unsigned char *)data, size);
573                 break;
574         case CURLINFO_HEADER_IN:
575                 text = "<= Recv header";
576                 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
577                 break;
578         case CURLINFO_DATA_IN:
579                 text = "<= Recv data";
580                 curl_dump_data(text, (unsigned char *)data, size);
581                 break;
582         case CURLINFO_SSL_DATA_IN:
583                 text = "<= Recv SSL data";
584                 curl_dump_data(text, (unsigned char *)data, size);
585                 break;
586         }
587         return 0;
588 }
589
590 void setup_curl_trace(CURL *handle)
591 {
592         if (!trace_want(&trace_curl))
593                 return;
594         curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
595         curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
596         curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
597 }
598
599
600 static CURL *get_curl_handle(void)
601 {
602         CURL *result = curl_easy_init();
603         long allowed_protocols = 0;
604
605         if (!result)
606                 die("curl_easy_init failed");
607
608         if (!curl_ssl_verify) {
609                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
610                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
611         } else {
612                 /* Verify authenticity of the peer's certificate */
613                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
614                 /* The name in the cert must match whom we tried to connect */
615                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
616         }
617
618 #if LIBCURL_VERSION_NUM >= 0x070907
619         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
620 #endif
621 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
622         curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
623 #endif
624
625         if (http_proactive_auth)
626                 init_curl_http_auth(result);
627
628         if (getenv("GIT_SSL_VERSION"))
629                 ssl_version = getenv("GIT_SSL_VERSION");
630         if (ssl_version && *ssl_version) {
631                 int i;
632                 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
633                         if (!strcmp(ssl_version, sslversions[i].name)) {
634                                 curl_easy_setopt(result, CURLOPT_SSLVERSION,
635                                                  sslversions[i].ssl_version);
636                                 break;
637                         }
638                 }
639                 if (i == ARRAY_SIZE(sslversions))
640                         warning("unsupported ssl version %s: using default",
641                                 ssl_version);
642         }
643
644         if (getenv("GIT_SSL_CIPHER_LIST"))
645                 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
646         if (ssl_cipherlist != NULL && *ssl_cipherlist)
647                 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
648                                 ssl_cipherlist);
649
650         if (ssl_cert != NULL)
651                 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
652         if (has_cert_password())
653                 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
654 #if LIBCURL_VERSION_NUM >= 0x070903
655         if (ssl_key != NULL)
656                 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
657 #endif
658 #if LIBCURL_VERSION_NUM >= 0x070908
659         if (ssl_capath != NULL)
660                 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
661 #endif
662 #if LIBCURL_VERSION_NUM >= 0x072c00
663         if (ssl_pinnedkey != NULL)
664                 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
665 #endif
666         if (ssl_cainfo != NULL)
667                 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
668
669         if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
670                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
671                                  curl_low_speed_limit);
672                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
673                                  curl_low_speed_time);
674         }
675
676         curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
677         curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
678 #if LIBCURL_VERSION_NUM >= 0x071301
679         curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
680 #elif LIBCURL_VERSION_NUM >= 0x071101
681         curl_easy_setopt(result, CURLOPT_POST301, 1);
682 #endif
683 #if LIBCURL_VERSION_NUM >= 0x071304
684         if (is_transport_allowed("http"))
685                 allowed_protocols |= CURLPROTO_HTTP;
686         if (is_transport_allowed("https"))
687                 allowed_protocols |= CURLPROTO_HTTPS;
688         if (is_transport_allowed("ftp"))
689                 allowed_protocols |= CURLPROTO_FTP;
690         if (is_transport_allowed("ftps"))
691                 allowed_protocols |= CURLPROTO_FTPS;
692         curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
693 #else
694         if (transport_restrict_protocols())
695                 warning("protocol restrictions not applied to curl redirects because\n"
696                         "your curl version is too old (>= 7.19.4)");
697 #endif
698         if (getenv("GIT_CURL_VERBOSE"))
699                 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
700         setup_curl_trace(result);
701
702         curl_easy_setopt(result, CURLOPT_USERAGENT,
703                 user_agent ? user_agent : git_user_agent());
704
705         if (curl_ftp_no_epsv)
706                 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
707
708 #ifdef CURLOPT_USE_SSL
709         if (curl_ssl_try)
710                 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
711 #endif
712
713         /*
714          * CURL also examines these variables as a fallback; but we need to query
715          * them here in order to decide whether to prompt for missing password (cf.
716          * init_curl_proxy_auth()).
717          *
718          * Unlike many other common environment variables, these are historically
719          * lowercase only. It appears that CURL did not know this and implemented
720          * only uppercase variants, which was later corrected to take both - with
721          * the exception of http_proxy, which is lowercase only also in CURL. As
722          * the lowercase versions are the historical quasi-standard, they take
723          * precedence here, as in CURL.
724          */
725         if (!curl_http_proxy) {
726                 if (!strcmp(http_auth.protocol, "https")) {
727                         var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
728                         var_override(&curl_http_proxy, getenv("https_proxy"));
729                 } else {
730                         var_override(&curl_http_proxy, getenv("http_proxy"));
731                 }
732                 if (!curl_http_proxy) {
733                         var_override(&curl_http_proxy, getenv("ALL_PROXY"));
734                         var_override(&curl_http_proxy, getenv("all_proxy"));
735                 }
736         }
737
738         if (curl_http_proxy) {
739                 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
740 #if LIBCURL_VERSION_NUM >= 0x071800
741                 if (starts_with(curl_http_proxy, "socks5h"))
742                         curl_easy_setopt(result,
743                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
744                 else if (starts_with(curl_http_proxy, "socks5"))
745                         curl_easy_setopt(result,
746                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
747                 else if (starts_with(curl_http_proxy, "socks4a"))
748                         curl_easy_setopt(result,
749                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
750                 else if (starts_with(curl_http_proxy, "socks"))
751                         curl_easy_setopt(result,
752                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
753 #endif
754                 if (strstr(curl_http_proxy, "://"))
755                         credential_from_url(&proxy_auth, curl_http_proxy);
756                 else {
757                         struct strbuf url = STRBUF_INIT;
758                         strbuf_addf(&url, "http://%s", curl_http_proxy);
759                         credential_from_url(&proxy_auth, url.buf);
760                         strbuf_release(&url);
761                 }
762
763                 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
764 #if LIBCURL_VERSION_NUM >= 0x071304
765                 var_override(&curl_no_proxy, getenv("NO_PROXY"));
766                 var_override(&curl_no_proxy, getenv("no_proxy"));
767                 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
768 #endif
769         }
770         init_curl_proxy_auth(result);
771
772         set_curl_keepalive(result);
773
774         return result;
775 }
776
777 static void set_from_env(const char **var, const char *envname)
778 {
779         const char *val = getenv(envname);
780         if (val)
781                 *var = val;
782 }
783
784 void http_init(struct remote *remote, const char *url, int proactive_auth)
785 {
786         char *low_speed_limit;
787         char *low_speed_time;
788         char *normalized_url;
789         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
790
791         config.section = "http";
792         config.key = NULL;
793         config.collect_fn = http_options;
794         config.cascade_fn = git_default_config;
795         config.cb = NULL;
796
797         http_is_verbose = 0;
798         normalized_url = url_normalize(url, &config.url);
799
800         git_config(urlmatch_config_entry, &config);
801         free(normalized_url);
802
803         if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
804                 die("curl_global_init failed");
805
806         http_proactive_auth = proactive_auth;
807
808         if (remote && remote->http_proxy)
809                 curl_http_proxy = xstrdup(remote->http_proxy);
810
811         if (remote)
812                 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
813
814         pragma_header = curl_slist_append(http_copy_default_headers(),
815                 "Pragma: no-cache");
816         no_pragma_header = curl_slist_append(http_copy_default_headers(),
817                 "Pragma:");
818
819 #ifdef USE_CURL_MULTI
820         {
821                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
822                 if (http_max_requests != NULL)
823                         max_requests = atoi(http_max_requests);
824         }
825
826         curlm = curl_multi_init();
827         if (!curlm)
828                 die("curl_multi_init failed");
829 #endif
830
831         if (getenv("GIT_SSL_NO_VERIFY"))
832                 curl_ssl_verify = 0;
833
834         set_from_env(&ssl_cert, "GIT_SSL_CERT");
835 #if LIBCURL_VERSION_NUM >= 0x070903
836         set_from_env(&ssl_key, "GIT_SSL_KEY");
837 #endif
838 #if LIBCURL_VERSION_NUM >= 0x070908
839         set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
840 #endif
841         set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
842
843         set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
844
845         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
846         if (low_speed_limit != NULL)
847                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
848         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
849         if (low_speed_time != NULL)
850                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
851
852         if (curl_ssl_verify == -1)
853                 curl_ssl_verify = 1;
854
855         curl_session_count = 0;
856 #ifdef USE_CURL_MULTI
857         if (max_requests < 1)
858                 max_requests = DEFAULT_MAX_REQUESTS;
859 #endif
860
861         if (getenv("GIT_CURL_FTP_NO_EPSV"))
862                 curl_ftp_no_epsv = 1;
863
864         if (url) {
865                 credential_from_url(&http_auth, url);
866                 if (!ssl_cert_password_required &&
867                     getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
868                     starts_with(url, "https://"))
869                         ssl_cert_password_required = 1;
870         }
871
872 #ifndef NO_CURL_EASY_DUPHANDLE
873         curl_default = get_curl_handle();
874 #endif
875 }
876
877 void http_cleanup(void)
878 {
879         struct active_request_slot *slot = active_queue_head;
880
881         while (slot != NULL) {
882                 struct active_request_slot *next = slot->next;
883                 if (slot->curl != NULL) {
884 #ifdef USE_CURL_MULTI
885                         curl_multi_remove_handle(curlm, slot->curl);
886 #endif
887                         curl_easy_cleanup(slot->curl);
888                 }
889                 free(slot);
890                 slot = next;
891         }
892         active_queue_head = NULL;
893
894 #ifndef NO_CURL_EASY_DUPHANDLE
895         curl_easy_cleanup(curl_default);
896 #endif
897
898 #ifdef USE_CURL_MULTI
899         curl_multi_cleanup(curlm);
900 #endif
901         curl_global_cleanup();
902
903         curl_slist_free_all(extra_http_headers);
904         extra_http_headers = NULL;
905
906         curl_slist_free_all(pragma_header);
907         pragma_header = NULL;
908
909         curl_slist_free_all(no_pragma_header);
910         no_pragma_header = NULL;
911
912         if (curl_http_proxy) {
913                 free((void *)curl_http_proxy);
914                 curl_http_proxy = NULL;
915         }
916
917         if (proxy_auth.password) {
918                 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
919                 free(proxy_auth.password);
920                 proxy_auth.password = NULL;
921         }
922
923         free((void *)curl_proxyuserpwd);
924         curl_proxyuserpwd = NULL;
925
926         free((void *)http_proxy_authmethod);
927         http_proxy_authmethod = NULL;
928
929         if (cert_auth.password != NULL) {
930                 memset(cert_auth.password, 0, strlen(cert_auth.password));
931                 free(cert_auth.password);
932                 cert_auth.password = NULL;
933         }
934         ssl_cert_password_required = 0;
935
936         free(cached_accept_language);
937         cached_accept_language = NULL;
938 }
939
940 struct active_request_slot *get_active_slot(void)
941 {
942         struct active_request_slot *slot = active_queue_head;
943         struct active_request_slot *newslot;
944
945 #ifdef USE_CURL_MULTI
946         int num_transfers;
947
948         /* Wait for a slot to open up if the queue is full */
949         while (active_requests >= max_requests) {
950                 curl_multi_perform(curlm, &num_transfers);
951                 if (num_transfers < active_requests)
952                         process_curl_messages();
953         }
954 #endif
955
956         while (slot != NULL && slot->in_use)
957                 slot = slot->next;
958
959         if (slot == NULL) {
960                 newslot = xmalloc(sizeof(*newslot));
961                 newslot->curl = NULL;
962                 newslot->in_use = 0;
963                 newslot->next = NULL;
964
965                 slot = active_queue_head;
966                 if (slot == NULL) {
967                         active_queue_head = newslot;
968                 } else {
969                         while (slot->next != NULL)
970                                 slot = slot->next;
971                         slot->next = newslot;
972                 }
973                 slot = newslot;
974         }
975
976         if (slot->curl == NULL) {
977 #ifdef NO_CURL_EASY_DUPHANDLE
978                 slot->curl = get_curl_handle();
979 #else
980                 slot->curl = curl_easy_duphandle(curl_default);
981 #endif
982                 curl_session_count++;
983         }
984
985         active_requests++;
986         slot->in_use = 1;
987         slot->results = NULL;
988         slot->finished = NULL;
989         slot->callback_data = NULL;
990         slot->callback_func = NULL;
991         curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
992         if (curl_save_cookies)
993                 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
994         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
995         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
996         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
997         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
998         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
999         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1000         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1001         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1002         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1003         curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1004
1005 #if LIBCURL_VERSION_NUM >= 0x070a08
1006         curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1007 #endif
1008 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1009         curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1010 #endif
1011         if (http_auth.password || curl_empty_auth)
1012                 init_curl_http_auth(slot->curl);
1013
1014         return slot;
1015 }
1016
1017 int start_active_slot(struct active_request_slot *slot)
1018 {
1019 #ifdef USE_CURL_MULTI
1020         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1021         int num_transfers;
1022
1023         if (curlm_result != CURLM_OK &&
1024             curlm_result != CURLM_CALL_MULTI_PERFORM) {
1025                 active_requests--;
1026                 slot->in_use = 0;
1027                 return 0;
1028         }
1029
1030         /*
1031          * We know there must be something to do, since we just added
1032          * something.
1033          */
1034         curl_multi_perform(curlm, &num_transfers);
1035 #endif
1036         return 1;
1037 }
1038
1039 #ifdef USE_CURL_MULTI
1040 struct fill_chain {
1041         void *data;
1042         int (*fill)(void *);
1043         struct fill_chain *next;
1044 };
1045
1046 static struct fill_chain *fill_cfg;
1047
1048 void add_fill_function(void *data, int (*fill)(void *))
1049 {
1050         struct fill_chain *new = xmalloc(sizeof(*new));
1051         struct fill_chain **linkp = &fill_cfg;
1052         new->data = data;
1053         new->fill = fill;
1054         new->next = NULL;
1055         while (*linkp)
1056                 linkp = &(*linkp)->next;
1057         *linkp = new;
1058 }
1059
1060 void fill_active_slots(void)
1061 {
1062         struct active_request_slot *slot = active_queue_head;
1063
1064         while (active_requests < max_requests) {
1065                 struct fill_chain *fill;
1066                 for (fill = fill_cfg; fill; fill = fill->next)
1067                         if (fill->fill(fill->data))
1068                                 break;
1069
1070                 if (!fill)
1071                         break;
1072         }
1073
1074         while (slot != NULL) {
1075                 if (!slot->in_use && slot->curl != NULL
1076                         && curl_session_count > min_curl_sessions) {
1077                         curl_easy_cleanup(slot->curl);
1078                         slot->curl = NULL;
1079                         curl_session_count--;
1080                 }
1081                 slot = slot->next;
1082         }
1083 }
1084
1085 void step_active_slots(void)
1086 {
1087         int num_transfers;
1088         CURLMcode curlm_result;
1089
1090         do {
1091                 curlm_result = curl_multi_perform(curlm, &num_transfers);
1092         } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1093         if (num_transfers < active_requests) {
1094                 process_curl_messages();
1095                 fill_active_slots();
1096         }
1097 }
1098 #endif
1099
1100 void run_active_slot(struct active_request_slot *slot)
1101 {
1102 #ifdef USE_CURL_MULTI
1103         fd_set readfds;
1104         fd_set writefds;
1105         fd_set excfds;
1106         int max_fd;
1107         struct timeval select_timeout;
1108         int finished = 0;
1109
1110         slot->finished = &finished;
1111         while (!finished) {
1112                 step_active_slots();
1113
1114                 if (slot->in_use) {
1115 #if LIBCURL_VERSION_NUM >= 0x070f04
1116                         long curl_timeout;
1117                         curl_multi_timeout(curlm, &curl_timeout);
1118                         if (curl_timeout == 0) {
1119                                 continue;
1120                         } else if (curl_timeout == -1) {
1121                                 select_timeout.tv_sec  = 0;
1122                                 select_timeout.tv_usec = 50000;
1123                         } else {
1124                                 select_timeout.tv_sec  =  curl_timeout / 1000;
1125                                 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1126                         }
1127 #else
1128                         select_timeout.tv_sec  = 0;
1129                         select_timeout.tv_usec = 50000;
1130 #endif
1131
1132                         max_fd = -1;
1133                         FD_ZERO(&readfds);
1134                         FD_ZERO(&writefds);
1135                         FD_ZERO(&excfds);
1136                         curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1137
1138                         /*
1139                          * It can happen that curl_multi_timeout returns a pathologically
1140                          * long timeout when curl_multi_fdset returns no file descriptors
1141                          * to read.  See commit message for more details.
1142                          */
1143                         if (max_fd < 0 &&
1144                             (select_timeout.tv_sec > 0 ||
1145                              select_timeout.tv_usec > 50000)) {
1146                                 select_timeout.tv_sec  = 0;
1147                                 select_timeout.tv_usec = 50000;
1148                         }
1149
1150                         select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1151                 }
1152         }
1153 #else
1154         while (slot->in_use) {
1155                 slot->curl_result = curl_easy_perform(slot->curl);
1156                 finish_active_slot(slot);
1157         }
1158 #endif
1159 }
1160
1161 static void release_active_slot(struct active_request_slot *slot)
1162 {
1163         closedown_active_slot(slot);
1164         if (slot->curl && curl_session_count > min_curl_sessions) {
1165 #ifdef USE_CURL_MULTI
1166                 curl_multi_remove_handle(curlm, slot->curl);
1167 #endif
1168                 curl_easy_cleanup(slot->curl);
1169                 slot->curl = NULL;
1170                 curl_session_count--;
1171         }
1172 #ifdef USE_CURL_MULTI
1173         fill_active_slots();
1174 #endif
1175 }
1176
1177 void finish_all_active_slots(void)
1178 {
1179         struct active_request_slot *slot = active_queue_head;
1180
1181         while (slot != NULL)
1182                 if (slot->in_use) {
1183                         run_active_slot(slot);
1184                         slot = active_queue_head;
1185                 } else {
1186                         slot = slot->next;
1187                 }
1188 }
1189
1190 /* Helpers for modifying and creating URLs */
1191 static inline int needs_quote(int ch)
1192 {
1193         if (((ch >= 'A') && (ch <= 'Z'))
1194                         || ((ch >= 'a') && (ch <= 'z'))
1195                         || ((ch >= '0') && (ch <= '9'))
1196                         || (ch == '/')
1197                         || (ch == '-')
1198                         || (ch == '.'))
1199                 return 0;
1200         return 1;
1201 }
1202
1203 static char *quote_ref_url(const char *base, const char *ref)
1204 {
1205         struct strbuf buf = STRBUF_INIT;
1206         const char *cp;
1207         int ch;
1208
1209         end_url_with_slash(&buf, base);
1210
1211         for (cp = ref; (ch = *cp) != 0; cp++)
1212                 if (needs_quote(ch))
1213                         strbuf_addf(&buf, "%%%02x", ch);
1214                 else
1215                         strbuf_addch(&buf, *cp);
1216
1217         return strbuf_detach(&buf, NULL);
1218 }
1219
1220 void append_remote_object_url(struct strbuf *buf, const char *url,
1221                               const char *hex,
1222                               int only_two_digit_prefix)
1223 {
1224         end_url_with_slash(buf, url);
1225
1226         strbuf_addf(buf, "objects/%.*s/", 2, hex);
1227         if (!only_two_digit_prefix)
1228                 strbuf_addf(buf, "%s", hex+2);
1229 }
1230
1231 char *get_remote_object_url(const char *url, const char *hex,
1232                             int only_two_digit_prefix)
1233 {
1234         struct strbuf buf = STRBUF_INIT;
1235         append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1236         return strbuf_detach(&buf, NULL);
1237 }
1238
1239 static int handle_curl_result(struct slot_results *results)
1240 {
1241         /*
1242          * If we see a failing http code with CURLE_OK, we have turned off
1243          * FAILONERROR (to keep the server's custom error response), and should
1244          * translate the code into failure here.
1245          */
1246         if (results->curl_result == CURLE_OK &&
1247             results->http_code >= 400) {
1248                 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1249                 /*
1250                  * Normally curl will already have put the "reason phrase"
1251                  * from the server into curl_errorstr; unfortunately without
1252                  * FAILONERROR it is lost, so we can give only the numeric
1253                  * status code.
1254                  */
1255                 snprintf(curl_errorstr, sizeof(curl_errorstr),
1256                          "The requested URL returned error: %ld",
1257                          results->http_code);
1258         }
1259
1260         if (results->curl_result == CURLE_OK) {
1261                 credential_approve(&http_auth);
1262                 if (proxy_auth.password)
1263                         credential_approve(&proxy_auth);
1264                 return HTTP_OK;
1265         } else if (missing_target(results))
1266                 return HTTP_MISSING_TARGET;
1267         else if (results->http_code == 401) {
1268                 if (http_auth.username && http_auth.password) {
1269                         credential_reject(&http_auth);
1270                         return HTTP_NOAUTH;
1271                 } else {
1272 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1273                         http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1274 #endif
1275                         return HTTP_REAUTH;
1276                 }
1277         } else {
1278                 if (results->http_connectcode == 407)
1279                         credential_reject(&proxy_auth);
1280 #if LIBCURL_VERSION_NUM >= 0x070c00
1281                 if (!curl_errorstr[0])
1282                         strlcpy(curl_errorstr,
1283                                 curl_easy_strerror(results->curl_result),
1284                                 sizeof(curl_errorstr));
1285 #endif
1286                 return HTTP_ERROR;
1287         }
1288 }
1289
1290 int run_one_slot(struct active_request_slot *slot,
1291                  struct slot_results *results)
1292 {
1293         slot->results = results;
1294         if (!start_active_slot(slot)) {
1295                 snprintf(curl_errorstr, sizeof(curl_errorstr),
1296                          "failed to start HTTP request");
1297                 return HTTP_START_FAILED;
1298         }
1299
1300         run_active_slot(slot);
1301         return handle_curl_result(results);
1302 }
1303
1304 struct curl_slist *http_copy_default_headers(void)
1305 {
1306         struct curl_slist *headers = NULL, *h;
1307
1308         for (h = extra_http_headers; h; h = h->next)
1309                 headers = curl_slist_append(headers, h->data);
1310
1311         return headers;
1312 }
1313
1314 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1315 {
1316         char *ptr;
1317         CURLcode ret;
1318
1319         strbuf_reset(buf);
1320         ret = curl_easy_getinfo(curl, info, &ptr);
1321         if (!ret && ptr)
1322                 strbuf_addstr(buf, ptr);
1323         return ret;
1324 }
1325
1326 /*
1327  * Check for and extract a content-type parameter. "raw"
1328  * should be positioned at the start of the potential
1329  * parameter, with any whitespace already removed.
1330  *
1331  * "name" is the name of the parameter. The value is appended
1332  * to "out".
1333  */
1334 static int extract_param(const char *raw, const char *name,
1335                          struct strbuf *out)
1336 {
1337         size_t len = strlen(name);
1338
1339         if (strncasecmp(raw, name, len))
1340                 return -1;
1341         raw += len;
1342
1343         if (*raw != '=')
1344                 return -1;
1345         raw++;
1346
1347         while (*raw && !isspace(*raw) && *raw != ';')
1348                 strbuf_addch(out, *raw++);
1349         return 0;
1350 }
1351
1352 /*
1353  * Extract a normalized version of the content type, with any
1354  * spaces suppressed, all letters lowercased, and no trailing ";"
1355  * or parameters.
1356  *
1357  * Note that we will silently remove even invalid whitespace. For
1358  * example, "text / plain" is specifically forbidden by RFC 2616,
1359  * but "text/plain" is the only reasonable output, and this keeps
1360  * our code simple.
1361  *
1362  * If the "charset" argument is not NULL, store the value of any
1363  * charset parameter there.
1364  *
1365  * Example:
1366  *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1367  *   "text / plain" -> "text/plain"
1368  */
1369 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1370                                  struct strbuf *charset)
1371 {
1372         const char *p;
1373
1374         strbuf_reset(type);
1375         strbuf_grow(type, raw->len);
1376         for (p = raw->buf; *p; p++) {
1377                 if (isspace(*p))
1378                         continue;
1379                 if (*p == ';') {
1380                         p++;
1381                         break;
1382                 }
1383                 strbuf_addch(type, tolower(*p));
1384         }
1385
1386         if (!charset)
1387                 return;
1388
1389         strbuf_reset(charset);
1390         while (*p) {
1391                 while (isspace(*p) || *p == ';')
1392                         p++;
1393                 if (!extract_param(p, "charset", charset))
1394                         return;
1395                 while (*p && !isspace(*p))
1396                         p++;
1397         }
1398
1399         if (!charset->len && starts_with(type->buf, "text/"))
1400                 strbuf_addstr(charset, "ISO-8859-1");
1401 }
1402
1403 static void write_accept_language(struct strbuf *buf)
1404 {
1405         /*
1406          * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1407          * that, q-value will be smaller than 0.001, the minimum q-value the
1408          * HTTP specification allows. See
1409          * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1410          */
1411         const int MAX_DECIMAL_PLACES = 3;
1412         const int MAX_LANGUAGE_TAGS = 1000;
1413         const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1414         char **language_tags = NULL;
1415         int num_langs = 0;
1416         const char *s = get_preferred_languages();
1417         int i;
1418         struct strbuf tag = STRBUF_INIT;
1419
1420         /* Don't add Accept-Language header if no language is preferred. */
1421         if (!s)
1422                 return;
1423
1424         /*
1425          * Split the colon-separated string of preferred languages into
1426          * language_tags array.
1427          */
1428         do {
1429                 /* collect language tag */
1430                 for (; *s && (isalnum(*s) || *s == '_'); s++)
1431                         strbuf_addch(&tag, *s == '_' ? '-' : *s);
1432
1433                 /* skip .codeset, @modifier and any other unnecessary parts */
1434                 while (*s && *s != ':')
1435                         s++;
1436
1437                 if (tag.len) {
1438                         num_langs++;
1439                         REALLOC_ARRAY(language_tags, num_langs);
1440                         language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1441                         if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1442                                 break;
1443                 }
1444         } while (*s++);
1445
1446         /* write Accept-Language header into buf */
1447         if (num_langs) {
1448                 int last_buf_len = 0;
1449                 int max_q;
1450                 int decimal_places;
1451                 char q_format[32];
1452
1453                 /* add '*' */
1454                 REALLOC_ARRAY(language_tags, num_langs + 1);
1455                 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1456
1457                 /* compute decimal_places */
1458                 for (max_q = 1, decimal_places = 0;
1459                      max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1460                      decimal_places++, max_q *= 10)
1461                         ;
1462
1463                 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1464
1465                 strbuf_addstr(buf, "Accept-Language: ");
1466
1467                 for (i = 0; i < num_langs; i++) {
1468                         if (i > 0)
1469                                 strbuf_addstr(buf, ", ");
1470
1471                         strbuf_addstr(buf, language_tags[i]);
1472
1473                         if (i > 0)
1474                                 strbuf_addf(buf, q_format, max_q - i);
1475
1476                         if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1477                                 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1478                                 break;
1479                         }
1480
1481                         last_buf_len = buf->len;
1482                 }
1483         }
1484
1485         /* free language tags -- last one is a static '*' */
1486         for (i = 0; i < num_langs - 1; i++)
1487                 free(language_tags[i]);
1488         free(language_tags);
1489 }
1490
1491 /*
1492  * Get an Accept-Language header which indicates user's preferred languages.
1493  *
1494  * Examples:
1495  *   LANGUAGE= -> ""
1496  *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1497  *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1498  *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1499  *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1500  *   LANGUAGE= LANG=C -> ""
1501  */
1502 static const char *get_accept_language(void)
1503 {
1504         if (!cached_accept_language) {
1505                 struct strbuf buf = STRBUF_INIT;
1506                 write_accept_language(&buf);
1507                 if (buf.len > 0)
1508                         cached_accept_language = strbuf_detach(&buf, NULL);
1509         }
1510
1511         return cached_accept_language;
1512 }
1513
1514 static void http_opt_request_remainder(CURL *curl, off_t pos)
1515 {
1516         char buf[128];
1517         xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1518         curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1519 }
1520
1521 /* http_request() targets */
1522 #define HTTP_REQUEST_STRBUF     0
1523 #define HTTP_REQUEST_FILE       1
1524
1525 static int http_request(const char *url,
1526                         void *result, int target,
1527                         const struct http_get_options *options)
1528 {
1529         struct active_request_slot *slot;
1530         struct slot_results results;
1531         struct curl_slist *headers = http_copy_default_headers();
1532         struct strbuf buf = STRBUF_INIT;
1533         const char *accept_language;
1534         int ret;
1535
1536         slot = get_active_slot();
1537         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1538
1539         if (result == NULL) {
1540                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1541         } else {
1542                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1543                 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1544
1545                 if (target == HTTP_REQUEST_FILE) {
1546                         off_t posn = ftello(result);
1547                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1548                                          fwrite);
1549                         if (posn > 0)
1550                                 http_opt_request_remainder(slot->curl, posn);
1551                 } else
1552                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1553                                          fwrite_buffer);
1554         }
1555
1556         accept_language = get_accept_language();
1557
1558         if (accept_language)
1559                 headers = curl_slist_append(headers, accept_language);
1560
1561         strbuf_addstr(&buf, "Pragma:");
1562         if (options && options->no_cache)
1563                 strbuf_addstr(&buf, " no-cache");
1564         if (options && options->keep_error)
1565                 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1566
1567         headers = curl_slist_append(headers, buf.buf);
1568
1569         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1570         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1571         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1572
1573         ret = run_one_slot(slot, &results);
1574
1575         if (options && options->content_type) {
1576                 struct strbuf raw = STRBUF_INIT;
1577                 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1578                 extract_content_type(&raw, options->content_type,
1579                                      options->charset);
1580                 strbuf_release(&raw);
1581         }
1582
1583         if (options && options->effective_url)
1584                 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1585                                 options->effective_url);
1586
1587         curl_slist_free_all(headers);
1588         strbuf_release(&buf);
1589
1590         return ret;
1591 }
1592
1593 /*
1594  * Update the "base" url to a more appropriate value, as deduced by
1595  * redirects seen when requesting a URL starting with "url".
1596  *
1597  * The "asked" parameter is a URL that we asked curl to access, and must begin
1598  * with "base".
1599  *
1600  * The "got" parameter is the URL that curl reported to us as where we ended
1601  * up.
1602  *
1603  * Returns 1 if we updated the base url, 0 otherwise.
1604  *
1605  * Our basic strategy is to compare "base" and "asked" to find the bits
1606  * specific to our request. We then strip those bits off of "got" to yield the
1607  * new base. So for example, if our base is "http://example.com/foo.git",
1608  * and we ask for "http://example.com/foo.git/info/refs", we might end up
1609  * with "https://other.example.com/foo.git/info/refs". We would want the
1610  * new URL to become "https://other.example.com/foo.git".
1611  *
1612  * Note that this assumes a sane redirect scheme. It's entirely possible
1613  * in the example above to end up at a URL that does not even end in
1614  * "info/refs".  In such a case we simply punt, as there is not much we can
1615  * do (and such a scheme is unlikely to represent a real git repository,
1616  * which means we are likely about to abort anyway).
1617  */
1618 static int update_url_from_redirect(struct strbuf *base,
1619                                     const char *asked,
1620                                     const struct strbuf *got)
1621 {
1622         const char *tail;
1623         size_t tail_len;
1624
1625         if (!strcmp(asked, got->buf))
1626                 return 0;
1627
1628         if (!skip_prefix(asked, base->buf, &tail))
1629                 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1630                     asked, base->buf);
1631
1632         tail_len = strlen(tail);
1633
1634         if (got->len < tail_len ||
1635             strcmp(tail, got->buf + got->len - tail_len))
1636                 return 0; /* insane redirect scheme */
1637
1638         strbuf_reset(base);
1639         strbuf_add(base, got->buf, got->len - tail_len);
1640         return 1;
1641 }
1642
1643 static int http_request_reauth(const char *url,
1644                                void *result, int target,
1645                                struct http_get_options *options)
1646 {
1647         int ret = http_request(url, result, target, options);
1648
1649         if (options && options->effective_url && options->base_url) {
1650                 if (update_url_from_redirect(options->base_url,
1651                                              url, options->effective_url)) {
1652                         credential_from_url(&http_auth, options->base_url->buf);
1653                         url = options->effective_url->buf;
1654                 }
1655         }
1656
1657         if (ret != HTTP_REAUTH)
1658                 return ret;
1659
1660         /*
1661          * If we are using KEEP_ERROR, the previous request may have
1662          * put cruft into our output stream; we should clear it out before
1663          * making our next request. We only know how to do this for
1664          * the strbuf case, but that is enough to satisfy current callers.
1665          */
1666         if (options && options->keep_error) {
1667                 switch (target) {
1668                 case HTTP_REQUEST_STRBUF:
1669                         strbuf_reset(result);
1670                         break;
1671                 default:
1672                         die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1673                 }
1674         }
1675
1676         credential_fill(&http_auth);
1677
1678         return http_request(url, result, target, options);
1679 }
1680
1681 int http_get_strbuf(const char *url,
1682                     struct strbuf *result,
1683                     struct http_get_options *options)
1684 {
1685         return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1686 }
1687
1688 /*
1689  * Downloads a URL and stores the result in the given file.
1690  *
1691  * If a previous interrupted download is detected (i.e. a previous temporary
1692  * file is still around) the download is resumed.
1693  */
1694 static int http_get_file(const char *url, const char *filename,
1695                          struct http_get_options *options)
1696 {
1697         int ret;
1698         struct strbuf tmpfile = STRBUF_INIT;
1699         FILE *result;
1700
1701         strbuf_addf(&tmpfile, "%s.temp", filename);
1702         result = fopen(tmpfile.buf, "a");
1703         if (!result) {
1704                 error("Unable to open local file %s", tmpfile.buf);
1705                 ret = HTTP_ERROR;
1706                 goto cleanup;
1707         }
1708
1709         ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1710         fclose(result);
1711
1712         if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1713                 ret = HTTP_ERROR;
1714 cleanup:
1715         strbuf_release(&tmpfile);
1716         return ret;
1717 }
1718
1719 int http_fetch_ref(const char *base, struct ref *ref)
1720 {
1721         struct http_get_options options = {0};
1722         char *url;
1723         struct strbuf buffer = STRBUF_INIT;
1724         int ret = -1;
1725
1726         options.no_cache = 1;
1727
1728         url = quote_ref_url(base, ref->name);
1729         if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1730                 strbuf_rtrim(&buffer);
1731                 if (buffer.len == 40)
1732                         ret = get_oid_hex(buffer.buf, &ref->old_oid);
1733                 else if (starts_with(buffer.buf, "ref: ")) {
1734                         ref->symref = xstrdup(buffer.buf + 5);
1735                         ret = 0;
1736                 }
1737         }
1738
1739         strbuf_release(&buffer);
1740         free(url);
1741         return ret;
1742 }
1743
1744 /* Helpers for fetching packs */
1745 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1746 {
1747         char *url, *tmp;
1748         struct strbuf buf = STRBUF_INIT;
1749
1750         if (http_is_verbose)
1751                 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1752
1753         end_url_with_slash(&buf, base_url);
1754         strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1755         url = strbuf_detach(&buf, NULL);
1756
1757         strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1758         tmp = strbuf_detach(&buf, NULL);
1759
1760         if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1761                 error("Unable to get pack index %s", url);
1762                 free(tmp);
1763                 tmp = NULL;
1764         }
1765
1766         free(url);
1767         return tmp;
1768 }
1769
1770 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1771         unsigned char *sha1, const char *base_url)
1772 {
1773         struct packed_git *new_pack;
1774         char *tmp_idx = NULL;
1775         int ret;
1776
1777         if (has_pack_index(sha1)) {
1778                 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1779                 if (!new_pack)
1780                         return -1; /* parse_pack_index() already issued error message */
1781                 goto add_pack;
1782         }
1783
1784         tmp_idx = fetch_pack_index(sha1, base_url);
1785         if (!tmp_idx)
1786                 return -1;
1787
1788         new_pack = parse_pack_index(sha1, tmp_idx);
1789         if (!new_pack) {
1790                 unlink(tmp_idx);
1791                 free(tmp_idx);
1792
1793                 return -1; /* parse_pack_index() already issued error message */
1794         }
1795
1796         ret = verify_pack_index(new_pack);
1797         if (!ret) {
1798                 close_pack_index(new_pack);
1799                 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1800         }
1801         free(tmp_idx);
1802         if (ret)
1803                 return -1;
1804
1805 add_pack:
1806         new_pack->next = *packs_head;
1807         *packs_head = new_pack;
1808         return 0;
1809 }
1810
1811 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1812 {
1813         struct http_get_options options = {0};
1814         int ret = 0, i = 0;
1815         char *url, *data;
1816         struct strbuf buf = STRBUF_INIT;
1817         unsigned char sha1[20];
1818
1819         end_url_with_slash(&buf, base_url);
1820         strbuf_addstr(&buf, "objects/info/packs");
1821         url = strbuf_detach(&buf, NULL);
1822
1823         options.no_cache = 1;
1824         ret = http_get_strbuf(url, &buf, &options);
1825         if (ret != HTTP_OK)
1826                 goto cleanup;
1827
1828         data = buf.buf;
1829         while (i < buf.len) {
1830                 switch (data[i]) {
1831                 case 'P':
1832                         i++;
1833                         if (i + 52 <= buf.len &&
1834                             starts_with(data + i, " pack-") &&
1835                             starts_with(data + i + 46, ".pack\n")) {
1836                                 get_sha1_hex(data + i + 6, sha1);
1837                                 fetch_and_setup_pack_index(packs_head, sha1,
1838                                                       base_url);
1839                                 i += 51;
1840                                 break;
1841                         }
1842                 default:
1843                         while (i < buf.len && data[i] != '\n')
1844                                 i++;
1845                 }
1846                 i++;
1847         }
1848
1849 cleanup:
1850         free(url);
1851         return ret;
1852 }
1853
1854 void release_http_pack_request(struct http_pack_request *preq)
1855 {
1856         if (preq->packfile != NULL) {
1857                 fclose(preq->packfile);
1858                 preq->packfile = NULL;
1859         }
1860         preq->slot = NULL;
1861         free(preq->url);
1862         free(preq);
1863 }
1864
1865 int finish_http_pack_request(struct http_pack_request *preq)
1866 {
1867         struct packed_git **lst;
1868         struct packed_git *p = preq->target;
1869         char *tmp_idx;
1870         size_t len;
1871         struct child_process ip = CHILD_PROCESS_INIT;
1872         const char *ip_argv[8];
1873
1874         close_pack_index(p);
1875
1876         fclose(preq->packfile);
1877         preq->packfile = NULL;
1878
1879         lst = preq->lst;
1880         while (*lst != p)
1881                 lst = &((*lst)->next);
1882         *lst = (*lst)->next;
1883
1884         if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1885                 die("BUG: pack tmpfile does not end in .pack.temp?");
1886         tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1887
1888         ip_argv[0] = "index-pack";
1889         ip_argv[1] = "-o";
1890         ip_argv[2] = tmp_idx;
1891         ip_argv[3] = preq->tmpfile;
1892         ip_argv[4] = NULL;
1893
1894         ip.argv = ip_argv;
1895         ip.git_cmd = 1;
1896         ip.no_stdin = 1;
1897         ip.no_stdout = 1;
1898
1899         if (run_command(&ip)) {
1900                 unlink(preq->tmpfile);
1901                 unlink(tmp_idx);
1902                 free(tmp_idx);
1903                 return -1;
1904         }
1905
1906         unlink(sha1_pack_index_name(p->sha1));
1907
1908         if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1909          || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1910                 free(tmp_idx);
1911                 return -1;
1912         }
1913
1914         install_packed_git(p);
1915         free(tmp_idx);
1916         return 0;
1917 }
1918
1919 struct http_pack_request *new_http_pack_request(
1920         struct packed_git *target, const char *base_url)
1921 {
1922         off_t prev_posn = 0;
1923         struct strbuf buf = STRBUF_INIT;
1924         struct http_pack_request *preq;
1925
1926         preq = xcalloc(1, sizeof(*preq));
1927         preq->target = target;
1928
1929         end_url_with_slash(&buf, base_url);
1930         strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1931                 sha1_to_hex(target->sha1));
1932         preq->url = strbuf_detach(&buf, NULL);
1933
1934         snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1935                 sha1_pack_name(target->sha1));
1936         preq->packfile = fopen(preq->tmpfile, "a");
1937         if (!preq->packfile) {
1938                 error("Unable to open local file %s for pack",
1939                       preq->tmpfile);
1940                 goto abort;
1941         }
1942
1943         preq->slot = get_active_slot();
1944         curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1945         curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1946         curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1947         curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1948                 no_pragma_header);
1949
1950         /*
1951          * If there is data present from a previous transfer attempt,
1952          * resume where it left off
1953          */
1954         prev_posn = ftello(preq->packfile);
1955         if (prev_posn>0) {
1956                 if (http_is_verbose)
1957                         fprintf(stderr,
1958                                 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1959                                 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1960                 http_opt_request_remainder(preq->slot->curl, prev_posn);
1961         }
1962
1963         return preq;
1964
1965 abort:
1966         free(preq->url);
1967         free(preq);
1968         return NULL;
1969 }
1970
1971 /* Helpers for fetching objects (loose) */
1972 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1973                                void *data)
1974 {
1975         unsigned char expn[4096];
1976         size_t size = eltsize * nmemb;
1977         int posn = 0;
1978         struct http_object_request *freq = data;
1979         struct active_request_slot *slot = freq->slot;
1980
1981         if (slot) {
1982                 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
1983                                                 &slot->http_code);
1984                 if (c != CURLE_OK)
1985                         die("BUG: curl_easy_getinfo for HTTP code failed: %s",
1986                                 curl_easy_strerror(c));
1987                 if (slot->http_code >= 400)
1988                         return size;
1989         }
1990
1991         do {
1992                 ssize_t retval = xwrite(freq->localfile,
1993                                         (char *) ptr + posn, size - posn);
1994                 if (retval < 0)
1995                         return posn;
1996                 posn += retval;
1997         } while (posn < size);
1998
1999         freq->stream.avail_in = size;
2000         freq->stream.next_in = (void *)ptr;
2001         do {
2002                 freq->stream.next_out = expn;
2003                 freq->stream.avail_out = sizeof(expn);
2004                 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2005                 git_SHA1_Update(&freq->c, expn,
2006                                 sizeof(expn) - freq->stream.avail_out);
2007         } while (freq->stream.avail_in && freq->zret == Z_OK);
2008         return size;
2009 }
2010
2011 struct http_object_request *new_http_object_request(const char *base_url,
2012         unsigned char *sha1)
2013 {
2014         char *hex = sha1_to_hex(sha1);
2015         const char *filename;
2016         char prevfile[PATH_MAX];
2017         int prevlocal;
2018         char prev_buf[PREV_BUF_SIZE];
2019         ssize_t prev_read = 0;
2020         off_t prev_posn = 0;
2021         struct http_object_request *freq;
2022
2023         freq = xcalloc(1, sizeof(*freq));
2024         hashcpy(freq->sha1, sha1);
2025         freq->localfile = -1;
2026
2027         filename = sha1_file_name(sha1);
2028         snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2029                  "%s.temp", filename);
2030
2031         snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2032         unlink_or_warn(prevfile);
2033         rename(freq->tmpfile, prevfile);
2034         unlink_or_warn(freq->tmpfile);
2035
2036         if (freq->localfile != -1)
2037                 error("fd leakage in start: %d", freq->localfile);
2038         freq->localfile = open(freq->tmpfile,
2039                                O_WRONLY | O_CREAT | O_EXCL, 0666);
2040         /*
2041          * This could have failed due to the "lazy directory creation";
2042          * try to mkdir the last path component.
2043          */
2044         if (freq->localfile < 0 && errno == ENOENT) {
2045                 char *dir = strrchr(freq->tmpfile, '/');
2046                 if (dir) {
2047                         *dir = 0;
2048                         mkdir(freq->tmpfile, 0777);
2049                         *dir = '/';
2050                 }
2051                 freq->localfile = open(freq->tmpfile,
2052                                        O_WRONLY | O_CREAT | O_EXCL, 0666);
2053         }
2054
2055         if (freq->localfile < 0) {
2056                 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2057                 goto abort;
2058         }
2059
2060         git_inflate_init(&freq->stream);
2061
2062         git_SHA1_Init(&freq->c);
2063
2064         freq->url = get_remote_object_url(base_url, hex, 0);
2065
2066         /*
2067          * If a previous temp file is present, process what was already
2068          * fetched.
2069          */
2070         prevlocal = open(prevfile, O_RDONLY);
2071         if (prevlocal != -1) {
2072                 do {
2073                         prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2074                         if (prev_read>0) {
2075                                 if (fwrite_sha1_file(prev_buf,
2076                                                      1,
2077                                                      prev_read,
2078                                                      freq) == prev_read) {
2079                                         prev_posn += prev_read;
2080                                 } else {
2081                                         prev_read = -1;
2082                                 }
2083                         }
2084                 } while (prev_read > 0);
2085                 close(prevlocal);
2086         }
2087         unlink_or_warn(prevfile);
2088
2089         /*
2090          * Reset inflate/SHA1 if there was an error reading the previous temp
2091          * file; also rewind to the beginning of the local file.
2092          */
2093         if (prev_read == -1) {
2094                 memset(&freq->stream, 0, sizeof(freq->stream));
2095                 git_inflate_init(&freq->stream);
2096                 git_SHA1_Init(&freq->c);
2097                 if (prev_posn>0) {
2098                         prev_posn = 0;
2099                         lseek(freq->localfile, 0, SEEK_SET);
2100                         if (ftruncate(freq->localfile, 0) < 0) {
2101                                 error_errno("Couldn't truncate temporary file %s",
2102                                             freq->tmpfile);
2103                                 goto abort;
2104                         }
2105                 }
2106         }
2107
2108         freq->slot = get_active_slot();
2109
2110         curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2111         curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2112         curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2113         curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2114         curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2115         curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2116
2117         /*
2118          * If we have successfully processed data from a previous fetch
2119          * attempt, only fetch the data we don't already have.
2120          */
2121         if (prev_posn>0) {
2122                 if (http_is_verbose)
2123                         fprintf(stderr,
2124                                 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2125                                 hex, (uintmax_t)prev_posn);
2126                 http_opt_request_remainder(freq->slot->curl, prev_posn);
2127         }
2128
2129         return freq;
2130
2131 abort:
2132         free(freq->url);
2133         free(freq);
2134         return NULL;
2135 }
2136
2137 void process_http_object_request(struct http_object_request *freq)
2138 {
2139         if (freq->slot == NULL)
2140                 return;
2141         freq->curl_result = freq->slot->curl_result;
2142         freq->http_code = freq->slot->http_code;
2143         freq->slot = NULL;
2144 }
2145
2146 int finish_http_object_request(struct http_object_request *freq)
2147 {
2148         struct stat st;
2149
2150         close(freq->localfile);
2151         freq->localfile = -1;
2152
2153         process_http_object_request(freq);
2154
2155         if (freq->http_code == 416) {
2156                 warning("requested range invalid; we may already have all the data.");
2157         } else if (freq->curl_result != CURLE_OK) {
2158                 if (stat(freq->tmpfile, &st) == 0)
2159                         if (st.st_size == 0)
2160                                 unlink_or_warn(freq->tmpfile);
2161                 return -1;
2162         }
2163
2164         git_inflate_end(&freq->stream);
2165         git_SHA1_Final(freq->real_sha1, &freq->c);
2166         if (freq->zret != Z_STREAM_END) {
2167                 unlink_or_warn(freq->tmpfile);
2168                 return -1;
2169         }
2170         if (hashcmp(freq->sha1, freq->real_sha1)) {
2171                 unlink_or_warn(freq->tmpfile);
2172                 return -1;
2173         }
2174         freq->rename =
2175                 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2176
2177         return freq->rename;
2178 }
2179
2180 void abort_http_object_request(struct http_object_request *freq)
2181 {
2182         unlink_or_warn(freq->tmpfile);
2183
2184         release_http_object_request(freq);
2185 }
2186
2187 void release_http_object_request(struct http_object_request *freq)
2188 {
2189         if (freq->localfile != -1) {
2190                 close(freq->localfile);
2191                 freq->localfile = -1;
2192         }
2193         if (freq->url != NULL) {
2194                 free(freq->url);
2195                 freq->url = NULL;
2196         }
2197         if (freq->slot != NULL) {
2198                 freq->slot->callback_func = NULL;
2199                 freq->slot->callback_data = NULL;
2200                 release_active_slot(freq->slot);
2201                 freq->slot = NULL;
2202         }
2203 }