remote-curl: unquote incoming push-options
[git] / remote-curl.c
1 #include "cache.h"
2 #include "config.h"
3 #include "remote.h"
4 #include "strbuf.h"
5 #include "walker.h"
6 #include "http.h"
7 #include "exec_cmd.h"
8 #include "run-command.h"
9 #include "pkt-line.h"
10 #include "string-list.h"
11 #include "sideband.h"
12 #include "argv-array.h"
13 #include "credential.h"
14 #include "sha1-array.h"
15 #include "send-pack.h"
16 #include "quote.h"
17
18 static struct remote *remote;
19 /* always ends with a trailing slash */
20 static struct strbuf url = STRBUF_INIT;
21
22 struct options {
23         int verbosity;
24         unsigned long depth;
25         char *deepen_since;
26         struct string_list deepen_not;
27         struct string_list push_options;
28         unsigned progress : 1,
29                 check_self_contained_and_connected : 1,
30                 cloning : 1,
31                 update_shallow : 1,
32                 followtags : 1,
33                 dry_run : 1,
34                 thin : 1,
35                 /* One of the SEND_PACK_PUSH_CERT_* constants. */
36                 push_cert : 2,
37                 deepen_relative : 1;
38 };
39 static struct options options;
40 static struct string_list cas_options = STRING_LIST_INIT_DUP;
41
42 static int set_option(const char *name, const char *value)
43 {
44         if (!strcmp(name, "verbosity")) {
45                 char *end;
46                 int v = strtol(value, &end, 10);
47                 if (value == end || *end)
48                         return -1;
49                 options.verbosity = v;
50                 return 0;
51         }
52         else if (!strcmp(name, "progress")) {
53                 if (!strcmp(value, "true"))
54                         options.progress = 1;
55                 else if (!strcmp(value, "false"))
56                         options.progress = 0;
57                 else
58                         return -1;
59                 return 0;
60         }
61         else if (!strcmp(name, "depth")) {
62                 char *end;
63                 unsigned long v = strtoul(value, &end, 10);
64                 if (value == end || *end)
65                         return -1;
66                 options.depth = v;
67                 return 0;
68         }
69         else if (!strcmp(name, "deepen-since")) {
70                 options.deepen_since = xstrdup(value);
71                 return 0;
72         }
73         else if (!strcmp(name, "deepen-not")) {
74                 string_list_append(&options.deepen_not, value);
75                 return 0;
76         }
77         else if (!strcmp(name, "deepen-relative")) {
78                 if (!strcmp(value, "true"))
79                         options.deepen_relative = 1;
80                 else if (!strcmp(value, "false"))
81                         options.deepen_relative = 0;
82                 else
83                         return -1;
84                 return 0;
85         }
86         else if (!strcmp(name, "followtags")) {
87                 if (!strcmp(value, "true"))
88                         options.followtags = 1;
89                 else if (!strcmp(value, "false"))
90                         options.followtags = 0;
91                 else
92                         return -1;
93                 return 0;
94         }
95         else if (!strcmp(name, "dry-run")) {
96                 if (!strcmp(value, "true"))
97                         options.dry_run = 1;
98                 else if (!strcmp(value, "false"))
99                         options.dry_run = 0;
100                 else
101                         return -1;
102                 return 0;
103         }
104         else if (!strcmp(name, "check-connectivity")) {
105                 if (!strcmp(value, "true"))
106                         options.check_self_contained_and_connected = 1;
107                 else if (!strcmp(value, "false"))
108                         options.check_self_contained_and_connected = 0;
109                 else
110                         return -1;
111                 return 0;
112         }
113         else if (!strcmp(name, "cas")) {
114                 struct strbuf val = STRBUF_INIT;
115                 strbuf_addf(&val, "--" CAS_OPT_NAME "=%s", value);
116                 string_list_append(&cas_options, val.buf);
117                 strbuf_release(&val);
118                 return 0;
119         } else if (!strcmp(name, "cloning")) {
120                 if (!strcmp(value, "true"))
121                         options.cloning = 1;
122                 else if (!strcmp(value, "false"))
123                         options.cloning = 0;
124                 else
125                         return -1;
126                 return 0;
127         } else if (!strcmp(name, "update-shallow")) {
128                 if (!strcmp(value, "true"))
129                         options.update_shallow = 1;
130                 else if (!strcmp(value, "false"))
131                         options.update_shallow = 0;
132                 else
133                         return -1;
134                 return 0;
135         } else if (!strcmp(name, "pushcert")) {
136                 if (!strcmp(value, "true"))
137                         options.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
138                 else if (!strcmp(value, "false"))
139                         options.push_cert = SEND_PACK_PUSH_CERT_NEVER;
140                 else if (!strcmp(value, "if-asked"))
141                         options.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
142                 else
143                         return -1;
144                 return 0;
145         } else if (!strcmp(name, "push-option")) {
146                 if (*value != '"')
147                         string_list_append(&options.push_options, value);
148                 else {
149                         struct strbuf unquoted = STRBUF_INIT;
150                         if (unquote_c_style(&unquoted, value, NULL) < 0)
151                                 die("invalid quoting in push-option value");
152                         string_list_append_nodup(&options.push_options,
153                                                  strbuf_detach(&unquoted, NULL));
154                 }
155                 return 0;
156
157 #if LIBCURL_VERSION_NUM >= 0x070a08
158         } else if (!strcmp(name, "family")) {
159                 if (!strcmp(value, "ipv4"))
160                         git_curl_ipresolve = CURL_IPRESOLVE_V4;
161                 else if (!strcmp(value, "ipv6"))
162                         git_curl_ipresolve = CURL_IPRESOLVE_V6;
163                 else if (!strcmp(value, "all"))
164                         git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
165                 else
166                         return -1;
167                 return 0;
168 #endif /* LIBCURL_VERSION_NUM >= 0x070a08 */
169         } else {
170                 return 1 /* unsupported */;
171         }
172 }
173
174 struct discovery {
175         const char *service;
176         char *buf_alloc;
177         char *buf;
178         size_t len;
179         struct ref *refs;
180         struct oid_array shallow;
181         unsigned proto_git : 1;
182 };
183 static struct discovery *last_discovery;
184
185 static struct ref *parse_git_refs(struct discovery *heads, int for_push)
186 {
187         struct ref *list = NULL;
188         get_remote_heads(-1, heads->buf, heads->len, &list,
189                          for_push ? REF_NORMAL : 0, NULL, &heads->shallow);
190         return list;
191 }
192
193 static struct ref *parse_info_refs(struct discovery *heads)
194 {
195         char *data, *start, *mid;
196         char *ref_name;
197         int i = 0;
198
199         struct ref *refs = NULL;
200         struct ref *ref = NULL;
201         struct ref *last_ref = NULL;
202
203         data = heads->buf;
204         start = NULL;
205         mid = data;
206         while (i < heads->len) {
207                 if (!start) {
208                         start = &data[i];
209                 }
210                 if (data[i] == '\t')
211                         mid = &data[i];
212                 if (data[i] == '\n') {
213                         if (mid - start != 40)
214                                 die("%sinfo/refs not valid: is this a git repository?",
215                                     url.buf);
216                         data[i] = 0;
217                         ref_name = mid + 1;
218                         ref = alloc_ref(ref_name);
219                         get_oid_hex(start, &ref->old_oid);
220                         if (!refs)
221                                 refs = ref;
222                         if (last_ref)
223                                 last_ref->next = ref;
224                         last_ref = ref;
225                         start = NULL;
226                 }
227                 i++;
228         }
229
230         ref = alloc_ref("HEAD");
231         if (!http_fetch_ref(url.buf, ref) &&
232             !resolve_remote_symref(ref, refs)) {
233                 ref->next = refs;
234                 refs = ref;
235         } else {
236                 free(ref);
237         }
238
239         return refs;
240 }
241
242 static void free_discovery(struct discovery *d)
243 {
244         if (d) {
245                 if (d == last_discovery)
246                         last_discovery = NULL;
247                 free(d->shallow.oid);
248                 free(d->buf_alloc);
249                 free_refs(d->refs);
250                 free(d);
251         }
252 }
253
254 static int show_http_message(struct strbuf *type, struct strbuf *charset,
255                              struct strbuf *msg)
256 {
257         const char *p, *eol;
258
259         /*
260          * We only show text/plain parts, as other types are likely
261          * to be ugly to look at on the user's terminal.
262          */
263         if (strcmp(type->buf, "text/plain"))
264                 return -1;
265         if (charset->len)
266                 strbuf_reencode(msg, charset->buf, get_log_output_encoding());
267
268         strbuf_trim(msg);
269         if (!msg->len)
270                 return -1;
271
272         p = msg->buf;
273         do {
274                 eol = strchrnul(p, '\n');
275                 fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
276                 p = eol + 1;
277         } while(*eol);
278         return 0;
279 }
280
281 static struct discovery *discover_refs(const char *service, int for_push)
282 {
283         struct strbuf exp = STRBUF_INIT;
284         struct strbuf type = STRBUF_INIT;
285         struct strbuf charset = STRBUF_INIT;
286         struct strbuf buffer = STRBUF_INIT;
287         struct strbuf refs_url = STRBUF_INIT;
288         struct strbuf effective_url = STRBUF_INIT;
289         struct discovery *last = last_discovery;
290         int http_ret, maybe_smart = 0;
291         struct http_get_options http_options;
292
293         if (last && !strcmp(service, last->service))
294                 return last;
295         free_discovery(last);
296
297         strbuf_addf(&refs_url, "%sinfo/refs", url.buf);
298         if ((starts_with(url.buf, "http://") || starts_with(url.buf, "https://")) &&
299              git_env_bool("GIT_SMART_HTTP", 1)) {
300                 maybe_smart = 1;
301                 if (!strchr(url.buf, '?'))
302                         strbuf_addch(&refs_url, '?');
303                 else
304                         strbuf_addch(&refs_url, '&');
305                 strbuf_addf(&refs_url, "service=%s", service);
306         }
307
308         memset(&http_options, 0, sizeof(http_options));
309         http_options.content_type = &type;
310         http_options.charset = &charset;
311         http_options.effective_url = &effective_url;
312         http_options.base_url = &url;
313         http_options.initial_request = 1;
314         http_options.no_cache = 1;
315         http_options.keep_error = 1;
316
317         http_ret = http_get_strbuf(refs_url.buf, &buffer, &http_options);
318         switch (http_ret) {
319         case HTTP_OK:
320                 break;
321         case HTTP_MISSING_TARGET:
322                 show_http_message(&type, &charset, &buffer);
323                 die("repository '%s' not found", url.buf);
324         case HTTP_NOAUTH:
325                 show_http_message(&type, &charset, &buffer);
326                 die("Authentication failed for '%s'", url.buf);
327         default:
328                 show_http_message(&type, &charset, &buffer);
329                 die("unable to access '%s': %s", url.buf, curl_errorstr);
330         }
331
332         if (options.verbosity && !starts_with(refs_url.buf, url.buf))
333                 warning(_("redirecting to %s"), url.buf);
334
335         last= xcalloc(1, sizeof(*last_discovery));
336         last->service = service;
337         last->buf_alloc = strbuf_detach(&buffer, &last->len);
338         last->buf = last->buf_alloc;
339
340         strbuf_addf(&exp, "application/x-%s-advertisement", service);
341         if (maybe_smart &&
342             (5 <= last->len && last->buf[4] == '#') &&
343             !strbuf_cmp(&exp, &type)) {
344                 char *line;
345
346                 /*
347                  * smart HTTP response; validate that the service
348                  * pkt-line matches our request.
349                  */
350                 line = packet_read_line_buf(&last->buf, &last->len, NULL);
351
352                 strbuf_reset(&exp);
353                 strbuf_addf(&exp, "# service=%s", service);
354                 if (strcmp(line, exp.buf))
355                         die("invalid server response; got '%s'", line);
356                 strbuf_release(&exp);
357
358                 /* The header can include additional metadata lines, up
359                  * until a packet flush marker.  Ignore these now, but
360                  * in the future we might start to scan them.
361                  */
362                 while (packet_read_line_buf(&last->buf, &last->len, NULL))
363                         ;
364
365                 last->proto_git = 1;
366         }
367
368         if (last->proto_git)
369                 last->refs = parse_git_refs(last, for_push);
370         else
371                 last->refs = parse_info_refs(last);
372
373         strbuf_release(&refs_url);
374         strbuf_release(&exp);
375         strbuf_release(&type);
376         strbuf_release(&charset);
377         strbuf_release(&effective_url);
378         strbuf_release(&buffer);
379         last_discovery = last;
380         return last;
381 }
382
383 static struct ref *get_refs(int for_push)
384 {
385         struct discovery *heads;
386
387         if (for_push)
388                 heads = discover_refs("git-receive-pack", for_push);
389         else
390                 heads = discover_refs("git-upload-pack", for_push);
391
392         return heads->refs;
393 }
394
395 static void output_refs(struct ref *refs)
396 {
397         struct ref *posn;
398         for (posn = refs; posn; posn = posn->next) {
399                 if (posn->symref)
400                         printf("@%s %s\n", posn->symref, posn->name);
401                 else
402                         printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
403         }
404         printf("\n");
405         fflush(stdout);
406 }
407
408 struct rpc_state {
409         const char *service_name;
410         const char **argv;
411         struct strbuf *stdin_preamble;
412         char *service_url;
413         char *hdr_content_type;
414         char *hdr_accept;
415         char *buf;
416         size_t alloc;
417         size_t len;
418         size_t pos;
419         int in;
420         int out;
421         int any_written;
422         struct strbuf result;
423         unsigned gzip_request : 1;
424         unsigned initial_buffer : 1;
425 };
426
427 static size_t rpc_out(void *ptr, size_t eltsize,
428                 size_t nmemb, void *buffer_)
429 {
430         size_t max = eltsize * nmemb;
431         struct rpc_state *rpc = buffer_;
432         size_t avail = rpc->len - rpc->pos;
433
434         if (!avail) {
435                 rpc->initial_buffer = 0;
436                 avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
437                 if (!avail)
438                         return 0;
439                 rpc->pos = 0;
440                 rpc->len = avail;
441         }
442
443         if (max < avail)
444                 avail = max;
445         memcpy(ptr, rpc->buf + rpc->pos, avail);
446         rpc->pos += avail;
447         return avail;
448 }
449
450 #ifndef NO_CURL_IOCTL
451 static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
452 {
453         struct rpc_state *rpc = clientp;
454
455         switch (cmd) {
456         case CURLIOCMD_NOP:
457                 return CURLIOE_OK;
458
459         case CURLIOCMD_RESTARTREAD:
460                 if (rpc->initial_buffer) {
461                         rpc->pos = 0;
462                         return CURLIOE_OK;
463                 }
464                 error("unable to rewind rpc post data - try increasing http.postBuffer");
465                 return CURLIOE_FAILRESTART;
466
467         default:
468                 return CURLIOE_UNKNOWNCMD;
469         }
470 }
471 #endif
472
473 static size_t rpc_in(char *ptr, size_t eltsize,
474                 size_t nmemb, void *buffer_)
475 {
476         size_t size = eltsize * nmemb;
477         struct rpc_state *rpc = buffer_;
478         if (size)
479                 rpc->any_written = 1;
480         write_or_die(rpc->in, ptr, size);
481         return size;
482 }
483
484 static int run_slot(struct active_request_slot *slot,
485                     struct slot_results *results)
486 {
487         int err;
488         struct slot_results results_buf;
489
490         if (!results)
491                 results = &results_buf;
492
493         err = run_one_slot(slot, results);
494
495         if (err != HTTP_OK && err != HTTP_REAUTH) {
496                 struct strbuf msg = STRBUF_INIT;
497                 if (results->http_code && results->http_code != 200)
498                         strbuf_addf(&msg, "HTTP %ld", results->http_code);
499                 if (results->curl_result != CURLE_OK) {
500                         if (msg.len)
501                                 strbuf_addch(&msg, ' ');
502                         strbuf_addf(&msg, "curl %d", results->curl_result);
503                         if (curl_errorstr[0]) {
504                                 strbuf_addch(&msg, ' ');
505                                 strbuf_addstr(&msg, curl_errorstr);
506                         }
507                 }
508                 error("RPC failed; %s", msg.buf);
509                 strbuf_release(&msg);
510         }
511
512         return err;
513 }
514
515 static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
516 {
517         struct active_request_slot *slot;
518         struct curl_slist *headers = http_copy_default_headers();
519         struct strbuf buf = STRBUF_INIT;
520         int err;
521
522         slot = get_active_slot();
523
524         headers = curl_slist_append(headers, rpc->hdr_content_type);
525         headers = curl_slist_append(headers, rpc->hdr_accept);
526
527         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
528         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
529         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
530         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
531         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
532         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
533         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
534         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
535         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
536
537         err = run_slot(slot, results);
538
539         curl_slist_free_all(headers);
540         strbuf_release(&buf);
541         return err;
542 }
543
544 static curl_off_t xcurl_off_t(ssize_t len) {
545         if (len > maximum_signed_value_of_type(curl_off_t))
546                 die("cannot handle pushes this big");
547         return (curl_off_t) len;
548 }
549
550 static int post_rpc(struct rpc_state *rpc)
551 {
552         struct active_request_slot *slot;
553         struct curl_slist *headers = http_copy_default_headers();
554         int use_gzip = rpc->gzip_request;
555         char *gzip_body = NULL;
556         size_t gzip_size = 0;
557         int err, large_request = 0;
558         int needs_100_continue = 0;
559
560         /* Try to load the entire request, if we can fit it into the
561          * allocated buffer space we can use HTTP/1.0 and avoid the
562          * chunked encoding mess.
563          */
564         while (1) {
565                 size_t left = rpc->alloc - rpc->len;
566                 char *buf = rpc->buf + rpc->len;
567                 int n;
568
569                 if (left < LARGE_PACKET_MAX) {
570                         large_request = 1;
571                         use_gzip = 0;
572                         break;
573                 }
574
575                 n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
576                 if (!n)
577                         break;
578                 rpc->len += n;
579         }
580
581         if (large_request) {
582                 struct slot_results results;
583
584                 do {
585                         err = probe_rpc(rpc, &results);
586                         if (err == HTTP_REAUTH)
587                                 credential_fill(&http_auth);
588                 } while (err == HTTP_REAUTH);
589                 if (err != HTTP_OK)
590                         return -1;
591
592                 if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
593                         needs_100_continue = 1;
594         }
595
596         headers = curl_slist_append(headers, rpc->hdr_content_type);
597         headers = curl_slist_append(headers, rpc->hdr_accept);
598         headers = curl_slist_append(headers, needs_100_continue ?
599                 "Expect: 100-continue" : "Expect:");
600
601 retry:
602         slot = get_active_slot();
603
604         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
605         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
606         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
607         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
608
609         if (large_request) {
610                 /* The request body is large and the size cannot be predicted.
611                  * We must use chunked encoding to send it.
612                  */
613                 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
614                 rpc->initial_buffer = 1;
615                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
616                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
617 #ifndef NO_CURL_IOCTL
618                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
619                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
620 #endif
621                 if (options.verbosity > 1) {
622                         fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
623                         fflush(stderr);
624                 }
625
626         } else if (gzip_body) {
627                 /*
628                  * If we are looping to retry authentication, then the previous
629                  * run will have set up the headers and gzip buffer already,
630                  * and we just need to send it.
631                  */
632                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
633                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
634
635         } else if (use_gzip && 1024 < rpc->len) {
636                 /* The client backend isn't giving us compressed data so
637                  * we can try to deflate it ourselves, this may save on.
638                  * the transfer time.
639                  */
640                 git_zstream stream;
641                 int ret;
642
643                 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
644                 gzip_size = git_deflate_bound(&stream, rpc->len);
645                 gzip_body = xmalloc(gzip_size);
646
647                 stream.next_in = (unsigned char *)rpc->buf;
648                 stream.avail_in = rpc->len;
649                 stream.next_out = (unsigned char *)gzip_body;
650                 stream.avail_out = gzip_size;
651
652                 ret = git_deflate(&stream, Z_FINISH);
653                 if (ret != Z_STREAM_END)
654                         die("cannot deflate request; zlib deflate error %d", ret);
655
656                 ret = git_deflate_end_gently(&stream);
657                 if (ret != Z_OK)
658                         die("cannot deflate request; zlib end error %d", ret);
659
660                 gzip_size = stream.total_out;
661
662                 headers = curl_slist_append(headers, "Content-Encoding: gzip");
663                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
664                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
665
666                 if (options.verbosity > 1) {
667                         fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
668                                 rpc->service_name,
669                                 (unsigned long)rpc->len, (unsigned long)gzip_size);
670                         fflush(stderr);
671                 }
672         } else {
673                 /* We know the complete request size in advance, use the
674                  * more normal Content-Length approach.
675                  */
676                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
677                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
678                 if (options.verbosity > 1) {
679                         fprintf(stderr, "POST %s (%lu bytes)\n",
680                                 rpc->service_name, (unsigned long)rpc->len);
681                         fflush(stderr);
682                 }
683         }
684
685         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
686         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
687         curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
688
689
690         rpc->any_written = 0;
691         err = run_slot(slot, NULL);
692         if (err == HTTP_REAUTH && !large_request) {
693                 credential_fill(&http_auth);
694                 goto retry;
695         }
696         if (err != HTTP_OK)
697                 err = -1;
698
699         if (!rpc->any_written)
700                 err = -1;
701
702         curl_slist_free_all(headers);
703         free(gzip_body);
704         return err;
705 }
706
707 static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
708 {
709         const char *svc = rpc->service_name;
710         struct strbuf buf = STRBUF_INIT;
711         struct strbuf *preamble = rpc->stdin_preamble;
712         struct child_process client = CHILD_PROCESS_INIT;
713         int err = 0;
714
715         client.in = -1;
716         client.out = -1;
717         client.git_cmd = 1;
718         client.argv = rpc->argv;
719         if (start_command(&client))
720                 exit(1);
721         if (preamble)
722                 write_or_die(client.in, preamble->buf, preamble->len);
723         if (heads)
724                 write_or_die(client.in, heads->buf, heads->len);
725
726         rpc->alloc = http_post_buffer;
727         rpc->buf = xmalloc(rpc->alloc);
728         rpc->in = client.in;
729         rpc->out = client.out;
730         strbuf_init(&rpc->result, 0);
731
732         strbuf_addf(&buf, "%s%s", url.buf, svc);
733         rpc->service_url = strbuf_detach(&buf, NULL);
734
735         strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
736         rpc->hdr_content_type = strbuf_detach(&buf, NULL);
737
738         strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
739         rpc->hdr_accept = strbuf_detach(&buf, NULL);
740
741         while (!err) {
742                 int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
743                 if (!n)
744                         break;
745                 rpc->pos = 0;
746                 rpc->len = n;
747                 err |= post_rpc(rpc);
748         }
749
750         close(client.in);
751         client.in = -1;
752         if (!err) {
753                 strbuf_read(&rpc->result, client.out, 0);
754         } else {
755                 char buf[4096];
756                 for (;;)
757                         if (xread(client.out, buf, sizeof(buf)) <= 0)
758                                 break;
759         }
760
761         close(client.out);
762         client.out = -1;
763
764         err |= finish_command(&client);
765         free(rpc->service_url);
766         free(rpc->hdr_content_type);
767         free(rpc->hdr_accept);
768         free(rpc->buf);
769         strbuf_release(&buf);
770         return err;
771 }
772
773 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
774 {
775         struct walker *walker;
776         char **targets;
777         int ret, i;
778
779         ALLOC_ARRAY(targets, nr_heads);
780         if (options.depth || options.deepen_since)
781                 die("dumb http transport does not support shallow capabilities");
782         for (i = 0; i < nr_heads; i++)
783                 targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
784
785         walker = get_http_walker(url.buf);
786         walker->get_all = 1;
787         walker->get_tree = 1;
788         walker->get_history = 1;
789         walker->get_verbosely = options.verbosity >= 3;
790         walker->get_recover = 0;
791         ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
792         walker_free(walker);
793
794         for (i = 0; i < nr_heads; i++)
795                 free(targets[i]);
796         free(targets);
797
798         return ret ? error("fetch failed.") : 0;
799 }
800
801 static int fetch_git(struct discovery *heads,
802         int nr_heads, struct ref **to_fetch)
803 {
804         struct rpc_state rpc;
805         struct strbuf preamble = STRBUF_INIT;
806         int i, err;
807         struct argv_array args = ARGV_ARRAY_INIT;
808
809         argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
810                          "--stdin", "--lock-pack", NULL);
811         if (options.followtags)
812                 argv_array_push(&args, "--include-tag");
813         if (options.thin)
814                 argv_array_push(&args, "--thin");
815         if (options.verbosity >= 3)
816                 argv_array_pushl(&args, "-v", "-v", NULL);
817         if (options.check_self_contained_and_connected)
818                 argv_array_push(&args, "--check-self-contained-and-connected");
819         if (options.cloning)
820                 argv_array_push(&args, "--cloning");
821         if (options.update_shallow)
822                 argv_array_push(&args, "--update-shallow");
823         if (!options.progress)
824                 argv_array_push(&args, "--no-progress");
825         if (options.depth)
826                 argv_array_pushf(&args, "--depth=%lu", options.depth);
827         if (options.deepen_since)
828                 argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
829         for (i = 0; i < options.deepen_not.nr; i++)
830                 argv_array_pushf(&args, "--shallow-exclude=%s",
831                                  options.deepen_not.items[i].string);
832         if (options.deepen_relative && options.depth)
833                 argv_array_push(&args, "--deepen-relative");
834         argv_array_push(&args, url.buf);
835
836         for (i = 0; i < nr_heads; i++) {
837                 struct ref *ref = to_fetch[i];
838                 if (!*ref->name)
839                         die("cannot fetch by sha1 over smart http");
840                 packet_buf_write(&preamble, "%s %s\n",
841                                  oid_to_hex(&ref->old_oid), ref->name);
842         }
843         packet_buf_flush(&preamble);
844
845         memset(&rpc, 0, sizeof(rpc));
846         rpc.service_name = "git-upload-pack",
847         rpc.argv = args.argv;
848         rpc.stdin_preamble = &preamble;
849         rpc.gzip_request = 1;
850
851         err = rpc_service(&rpc, heads);
852         if (rpc.result.len)
853                 write_or_die(1, rpc.result.buf, rpc.result.len);
854         strbuf_release(&rpc.result);
855         strbuf_release(&preamble);
856         argv_array_clear(&args);
857         return err;
858 }
859
860 static int fetch(int nr_heads, struct ref **to_fetch)
861 {
862         struct discovery *d = discover_refs("git-upload-pack", 0);
863         if (d->proto_git)
864                 return fetch_git(d, nr_heads, to_fetch);
865         else
866                 return fetch_dumb(nr_heads, to_fetch);
867 }
868
869 static void parse_fetch(struct strbuf *buf)
870 {
871         struct ref **to_fetch = NULL;
872         struct ref *list_head = NULL;
873         struct ref **list = &list_head;
874         int alloc_heads = 0, nr_heads = 0;
875
876         do {
877                 const char *p;
878                 if (skip_prefix(buf->buf, "fetch ", &p)) {
879                         const char *name;
880                         struct ref *ref;
881                         struct object_id old_oid;
882
883                         if (get_oid_hex(p, &old_oid))
884                                 die("protocol error: expected sha/ref, got %s'", p);
885                         if (p[GIT_SHA1_HEXSZ] == ' ')
886                                 name = p + GIT_SHA1_HEXSZ + 1;
887                         else if (!p[GIT_SHA1_HEXSZ])
888                                 name = "";
889                         else
890                                 die("protocol error: expected sha/ref, got %s'", p);
891
892                         ref = alloc_ref(name);
893                         oidcpy(&ref->old_oid, &old_oid);
894
895                         *list = ref;
896                         list = &ref->next;
897
898                         ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
899                         to_fetch[nr_heads++] = ref;
900                 }
901                 else
902                         die("http transport does not support %s", buf->buf);
903
904                 strbuf_reset(buf);
905                 if (strbuf_getline_lf(buf, stdin) == EOF)
906                         return;
907                 if (!*buf->buf)
908                         break;
909         } while (1);
910
911         if (fetch(nr_heads, to_fetch))
912                 exit(128); /* error already reported */
913         free_refs(list_head);
914         free(to_fetch);
915
916         printf("\n");
917         fflush(stdout);
918         strbuf_reset(buf);
919 }
920
921 static int push_dav(int nr_spec, char **specs)
922 {
923         struct child_process child = CHILD_PROCESS_INIT;
924         size_t i;
925
926         child.git_cmd = 1;
927         argv_array_push(&child.args, "http-push");
928         argv_array_push(&child.args, "--helper-status");
929         if (options.dry_run)
930                 argv_array_push(&child.args, "--dry-run");
931         if (options.verbosity > 1)
932                 argv_array_push(&child.args, "--verbose");
933         argv_array_push(&child.args, url.buf);
934         for (i = 0; i < nr_spec; i++)
935                 argv_array_push(&child.args, specs[i]);
936
937         if (run_command(&child))
938                 die("git-http-push failed");
939         return 0;
940 }
941
942 static int push_git(struct discovery *heads, int nr_spec, char **specs)
943 {
944         struct rpc_state rpc;
945         int i, err;
946         struct argv_array args;
947         struct string_list_item *cas_option;
948         struct strbuf preamble = STRBUF_INIT;
949
950         argv_array_init(&args);
951         argv_array_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
952                          NULL);
953
954         if (options.thin)
955                 argv_array_push(&args, "--thin");
956         if (options.dry_run)
957                 argv_array_push(&args, "--dry-run");
958         if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
959                 argv_array_push(&args, "--signed=yes");
960         else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
961                 argv_array_push(&args, "--signed=if-asked");
962         if (options.verbosity == 0)
963                 argv_array_push(&args, "--quiet");
964         else if (options.verbosity > 1)
965                 argv_array_push(&args, "--verbose");
966         for (i = 0; i < options.push_options.nr; i++)
967                 argv_array_pushf(&args, "--push-option=%s",
968                                  options.push_options.items[i].string);
969         argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
970         for_each_string_list_item(cas_option, &cas_options)
971                 argv_array_push(&args, cas_option->string);
972         argv_array_push(&args, url.buf);
973
974         argv_array_push(&args, "--stdin");
975         for (i = 0; i < nr_spec; i++)
976                 packet_buf_write(&preamble, "%s\n", specs[i]);
977         packet_buf_flush(&preamble);
978
979         memset(&rpc, 0, sizeof(rpc));
980         rpc.service_name = "git-receive-pack",
981         rpc.argv = args.argv;
982         rpc.stdin_preamble = &preamble;
983
984         err = rpc_service(&rpc, heads);
985         if (rpc.result.len)
986                 write_or_die(1, rpc.result.buf, rpc.result.len);
987         strbuf_release(&rpc.result);
988         strbuf_release(&preamble);
989         argv_array_clear(&args);
990         return err;
991 }
992
993 static int push(int nr_spec, char **specs)
994 {
995         struct discovery *heads = discover_refs("git-receive-pack", 1);
996         int ret;
997
998         if (heads->proto_git)
999                 ret = push_git(heads, nr_spec, specs);
1000         else
1001                 ret = push_dav(nr_spec, specs);
1002         free_discovery(heads);
1003         return ret;
1004 }
1005
1006 static void parse_push(struct strbuf *buf)
1007 {
1008         char **specs = NULL;
1009         int alloc_spec = 0, nr_spec = 0, i, ret;
1010
1011         do {
1012                 if (starts_with(buf->buf, "push ")) {
1013                         ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
1014                         specs[nr_spec++] = xstrdup(buf->buf + 5);
1015                 }
1016                 else
1017                         die("http transport does not support %s", buf->buf);
1018
1019                 strbuf_reset(buf);
1020                 if (strbuf_getline_lf(buf, stdin) == EOF)
1021                         goto free_specs;
1022                 if (!*buf->buf)
1023                         break;
1024         } while (1);
1025
1026         ret = push(nr_spec, specs);
1027         printf("\n");
1028         fflush(stdout);
1029
1030         if (ret)
1031                 exit(128); /* error already reported */
1032
1033  free_specs:
1034         for (i = 0; i < nr_spec; i++)
1035                 free(specs[i]);
1036         free(specs);
1037 }
1038
1039 int cmd_main(int argc, const char **argv)
1040 {
1041         struct strbuf buf = STRBUF_INIT;
1042         int nongit;
1043
1044         setup_git_directory_gently(&nongit);
1045         if (argc < 2) {
1046                 error("remote-curl: usage: git remote-curl <remote> [<url>]");
1047                 return 1;
1048         }
1049
1050         options.verbosity = 1;
1051         options.progress = !!isatty(2);
1052         options.thin = 1;
1053         string_list_init(&options.deepen_not, 1);
1054         string_list_init(&options.push_options, 1);
1055
1056         remote = remote_get(argv[1]);
1057
1058         if (argc > 2) {
1059                 end_url_with_slash(&url, argv[2]);
1060         } else {
1061                 end_url_with_slash(&url, remote->url[0]);
1062         }
1063
1064         http_init(remote, url.buf, 0);
1065
1066         do {
1067                 const char *arg;
1068
1069                 if (strbuf_getline_lf(&buf, stdin) == EOF) {
1070                         if (ferror(stdin))
1071                                 error("remote-curl: error reading command stream from git");
1072                         return 1;
1073                 }
1074                 if (buf.len == 0)
1075                         break;
1076                 if (starts_with(buf.buf, "fetch ")) {
1077                         if (nongit)
1078                                 die("remote-curl: fetch attempted without a local repo");
1079                         parse_fetch(&buf);
1080
1081                 } else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1082                         int for_push = !!strstr(buf.buf + 4, "for-push");
1083                         output_refs(get_refs(for_push));
1084
1085                 } else if (starts_with(buf.buf, "push ")) {
1086                         parse_push(&buf);
1087
1088                 } else if (skip_prefix(buf.buf, "option ", &arg)) {
1089                         char *value = strchr(arg, ' ');
1090                         int result;
1091
1092                         if (value)
1093                                 *value++ = '\0';
1094                         else
1095                                 value = "true";
1096
1097                         result = set_option(arg, value);
1098                         if (!result)
1099                                 printf("ok\n");
1100                         else if (result < 0)
1101                                 printf("error invalid value\n");
1102                         else
1103                                 printf("unsupported\n");
1104                         fflush(stdout);
1105
1106                 } else if (!strcmp(buf.buf, "capabilities")) {
1107                         printf("fetch\n");
1108                         printf("option\n");
1109                         printf("push\n");
1110                         printf("check-connectivity\n");
1111                         printf("\n");
1112                         fflush(stdout);
1113                 } else {
1114                         error("remote-curl: unknown command '%s' from git", buf.buf);
1115                         return 1;
1116                 }
1117                 strbuf_reset(&buf);
1118         } while (1);
1119
1120         http_cleanup();
1121
1122         return 0;
1123 }