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