pkt-line: share buffer/descriptor reading implementation
[git] / remote-curl.c
1 #include "cache.h"
2 #include "remote.h"
3 #include "strbuf.h"
4 #include "walker.h"
5 #include "http.h"
6 #include "exec_cmd.h"
7 #include "run-command.h"
8 #include "pkt-line.h"
9 #include "sideband.h"
10
11 static struct remote *remote;
12 static const char *url; /* always ends with a trailing slash */
13
14 struct options {
15         int verbosity;
16         unsigned long depth;
17         unsigned progress : 1,
18                 followtags : 1,
19                 dry_run : 1,
20                 thin : 1;
21 };
22 static struct options options;
23
24 static int set_option(const char *name, const char *value)
25 {
26         if (!strcmp(name, "verbosity")) {
27                 char *end;
28                 int v = strtol(value, &end, 10);
29                 if (value == end || *end)
30                         return -1;
31                 options.verbosity = v;
32                 return 0;
33         }
34         else if (!strcmp(name, "progress")) {
35                 if (!strcmp(value, "true"))
36                         options.progress = 1;
37                 else if (!strcmp(value, "false"))
38                         options.progress = 0;
39                 else
40                         return -1;
41                 return 0;
42         }
43         else if (!strcmp(name, "depth")) {
44                 char *end;
45                 unsigned long v = strtoul(value, &end, 10);
46                 if (value == end || *end)
47                         return -1;
48                 options.depth = v;
49                 return 0;
50         }
51         else if (!strcmp(name, "followtags")) {
52                 if (!strcmp(value, "true"))
53                         options.followtags = 1;
54                 else if (!strcmp(value, "false"))
55                         options.followtags = 0;
56                 else
57                         return -1;
58                 return 0;
59         }
60         else if (!strcmp(name, "dry-run")) {
61                 if (!strcmp(value, "true"))
62                         options.dry_run = 1;
63                 else if (!strcmp(value, "false"))
64                         options.dry_run = 0;
65                 else
66                         return -1;
67                 return 0;
68         }
69         else {
70                 return 1 /* unsupported */;
71         }
72 }
73
74 struct discovery {
75         const char *service;
76         char *buf_alloc;
77         char *buf;
78         size_t len;
79         unsigned proto_git : 1;
80 };
81 static struct discovery *last_discovery;
82
83 static void free_discovery(struct discovery *d)
84 {
85         if (d) {
86                 if (d == last_discovery)
87                         last_discovery = NULL;
88                 free(d->buf_alloc);
89                 free(d);
90         }
91 }
92
93 static struct discovery* discover_refs(const char *service)
94 {
95         struct strbuf exp = STRBUF_INIT;
96         struct strbuf type = STRBUF_INIT;
97         struct strbuf buffer = STRBUF_INIT;
98         struct discovery *last = last_discovery;
99         char *refs_url;
100         int http_ret, maybe_smart = 0;
101
102         if (last && !strcmp(service, last->service))
103                 return last;
104         free_discovery(last);
105
106         strbuf_addf(&buffer, "%sinfo/refs", url);
107         if ((!prefixcmp(url, "http://") || !prefixcmp(url, "https://")) &&
108              git_env_bool("GIT_SMART_HTTP", 1)) {
109                 maybe_smart = 1;
110                 if (!strchr(url, '?'))
111                         strbuf_addch(&buffer, '?');
112                 else
113                         strbuf_addch(&buffer, '&');
114                 strbuf_addf(&buffer, "service=%s", service);
115         }
116         refs_url = strbuf_detach(&buffer, NULL);
117
118         http_ret = http_get_strbuf(refs_url, &type, &buffer, HTTP_NO_CACHE);
119         switch (http_ret) {
120         case HTTP_OK:
121                 break;
122         case HTTP_MISSING_TARGET:
123                 die("%s not found: did you run git update-server-info on the"
124                     " server?", refs_url);
125         case HTTP_NOAUTH:
126                 die("Authentication failed");
127         default:
128                 http_error(refs_url, http_ret);
129                 die("HTTP request failed");
130         }
131
132         last= xcalloc(1, sizeof(*last_discovery));
133         last->service = service;
134         last->buf_alloc = strbuf_detach(&buffer, &last->len);
135         last->buf = last->buf_alloc;
136
137         strbuf_addf(&exp, "application/x-%s-advertisement", service);
138         if (maybe_smart &&
139             (5 <= last->len && last->buf[4] == '#') &&
140             !strbuf_cmp(&exp, &type)) {
141                 char *line;
142
143                 /*
144                  * smart HTTP response; validate that the service
145                  * pkt-line matches our request.
146                  */
147                 line = packet_read_line_buf(&last->buf, &last->len, NULL);
148
149                 strbuf_reset(&exp);
150                 strbuf_addf(&exp, "# service=%s", service);
151                 if (strcmp(line, exp.buf))
152                         die("invalid server response; got '%s'", line);
153                 strbuf_release(&exp);
154
155                 /* The header can include additional metadata lines, up
156                  * until a packet flush marker.  Ignore these now, but
157                  * in the future we might start to scan them.
158                  */
159                 while (packet_read_line_buf(&last->buf, &last->len, NULL))
160                         ;
161
162                 last->proto_git = 1;
163         }
164
165         free(refs_url);
166         strbuf_release(&exp);
167         strbuf_release(&type);
168         strbuf_release(&buffer);
169         last_discovery = last;
170         return last;
171 }
172
173 static int write_discovery(int in, int out, void *data)
174 {
175         struct discovery *heads = data;
176         int err = 0;
177         if (write_in_full(out, heads->buf, heads->len) != heads->len)
178                 err = 1;
179         close(out);
180         return err;
181 }
182
183 static struct ref *parse_git_refs(struct discovery *heads, int for_push)
184 {
185         struct ref *list = NULL;
186         struct async async;
187
188         memset(&async, 0, sizeof(async));
189         async.proc = write_discovery;
190         async.data = heads;
191         async.out = -1;
192
193         if (start_async(&async))
194                 die("cannot start thread to parse advertised refs");
195         get_remote_heads(async.out, &list,
196                         for_push ? REF_NORMAL : 0, NULL);
197         close(async.out);
198         if (finish_async(&async))
199                 die("ref parsing thread failed");
200         return list;
201 }
202
203 static struct ref *parse_info_refs(struct discovery *heads)
204 {
205         char *data, *start, *mid;
206         char *ref_name;
207         int i = 0;
208
209         struct ref *refs = NULL;
210         struct ref *ref = NULL;
211         struct ref *last_ref = NULL;
212
213         data = heads->buf;
214         start = NULL;
215         mid = data;
216         while (i < heads->len) {
217                 if (!start) {
218                         start = &data[i];
219                 }
220                 if (data[i] == '\t')
221                         mid = &data[i];
222                 if (data[i] == '\n') {
223                         if (mid - start != 40)
224                                 die("%sinfo/refs not valid: is this a git repository?", url);
225                         data[i] = 0;
226                         ref_name = mid + 1;
227                         ref = xmalloc(sizeof(struct ref) +
228                                       strlen(ref_name) + 1);
229                         memset(ref, 0, sizeof(struct ref));
230                         strcpy(ref->name, ref_name);
231                         get_sha1_hex(start, ref->old_sha1);
232                         if (!refs)
233                                 refs = ref;
234                         if (last_ref)
235                                 last_ref->next = ref;
236                         last_ref = ref;
237                         start = NULL;
238                 }
239                 i++;
240         }
241
242         ref = alloc_ref("HEAD");
243         if (!http_fetch_ref(url, ref) &&
244             !resolve_remote_symref(ref, refs)) {
245                 ref->next = refs;
246                 refs = ref;
247         } else {
248                 free(ref);
249         }
250
251         return refs;
252 }
253
254 static struct ref *get_refs(int for_push)
255 {
256         struct discovery *heads;
257
258         if (for_push)
259                 heads = discover_refs("git-receive-pack");
260         else
261                 heads = discover_refs("git-upload-pack");
262
263         if (heads->proto_git)
264                 return parse_git_refs(heads, for_push);
265         return parse_info_refs(heads);
266 }
267
268 static void output_refs(struct ref *refs)
269 {
270         struct ref *posn;
271         for (posn = refs; posn; posn = posn->next) {
272                 if (posn->symref)
273                         printf("@%s %s\n", posn->symref, posn->name);
274                 else
275                         printf("%s %s\n", sha1_to_hex(posn->old_sha1), posn->name);
276         }
277         printf("\n");
278         fflush(stdout);
279         free_refs(refs);
280 }
281
282 struct rpc_state {
283         const char *service_name;
284         const char **argv;
285         struct strbuf *stdin_preamble;
286         char *service_url;
287         char *hdr_content_type;
288         char *hdr_accept;
289         char *buf;
290         size_t alloc;
291         size_t len;
292         size_t pos;
293         int in;
294         int out;
295         struct strbuf result;
296         unsigned gzip_request : 1;
297         unsigned initial_buffer : 1;
298 };
299
300 static size_t rpc_out(void *ptr, size_t eltsize,
301                 size_t nmemb, void *buffer_)
302 {
303         size_t max = eltsize * nmemb;
304         struct rpc_state *rpc = buffer_;
305         size_t avail = rpc->len - rpc->pos;
306
307         if (!avail) {
308                 rpc->initial_buffer = 0;
309                 avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
310                 if (!avail)
311                         return 0;
312                 rpc->pos = 0;
313                 rpc->len = avail;
314         }
315
316         if (max < avail)
317                 avail = max;
318         memcpy(ptr, rpc->buf + rpc->pos, avail);
319         rpc->pos += avail;
320         return avail;
321 }
322
323 #ifndef NO_CURL_IOCTL
324 static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
325 {
326         struct rpc_state *rpc = clientp;
327
328         switch (cmd) {
329         case CURLIOCMD_NOP:
330                 return CURLIOE_OK;
331
332         case CURLIOCMD_RESTARTREAD:
333                 if (rpc->initial_buffer) {
334                         rpc->pos = 0;
335                         return CURLIOE_OK;
336                 }
337                 fprintf(stderr, "Unable to rewind rpc post data - try increasing http.postBuffer\n");
338                 return CURLIOE_FAILRESTART;
339
340         default:
341                 return CURLIOE_UNKNOWNCMD;
342         }
343 }
344 #endif
345
346 static size_t rpc_in(char *ptr, size_t eltsize,
347                 size_t nmemb, void *buffer_)
348 {
349         size_t size = eltsize * nmemb;
350         struct rpc_state *rpc = buffer_;
351         write_or_die(rpc->in, ptr, size);
352         return size;
353 }
354
355 static int run_slot(struct active_request_slot *slot)
356 {
357         int err;
358         struct slot_results results;
359
360         slot->results = &results;
361         slot->curl_result = curl_easy_perform(slot->curl);
362         finish_active_slot(slot);
363
364         err = handle_curl_result(&results);
365         if (err != HTTP_OK && err != HTTP_REAUTH) {
366                 error("RPC failed; result=%d, HTTP code = %ld",
367                       results.curl_result, results.http_code);
368         }
369
370         return err;
371 }
372
373 static int probe_rpc(struct rpc_state *rpc)
374 {
375         struct active_request_slot *slot;
376         struct curl_slist *headers = NULL;
377         struct strbuf buf = STRBUF_INIT;
378         int err;
379
380         slot = get_active_slot();
381
382         headers = curl_slist_append(headers, rpc->hdr_content_type);
383         headers = curl_slist_append(headers, rpc->hdr_accept);
384
385         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
386         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
387         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
388         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
389         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
390         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
391         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
392         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
393         curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
394
395         err = run_slot(slot);
396
397         curl_slist_free_all(headers);
398         strbuf_release(&buf);
399         return err;
400 }
401
402 static int post_rpc(struct rpc_state *rpc)
403 {
404         struct active_request_slot *slot;
405         struct curl_slist *headers = NULL;
406         int use_gzip = rpc->gzip_request;
407         char *gzip_body = NULL;
408         size_t gzip_size = 0;
409         int err, large_request = 0;
410
411         /* Try to load the entire request, if we can fit it into the
412          * allocated buffer space we can use HTTP/1.0 and avoid the
413          * chunked encoding mess.
414          */
415         while (1) {
416                 size_t left = rpc->alloc - rpc->len;
417                 char *buf = rpc->buf + rpc->len;
418                 int n;
419
420                 if (left < LARGE_PACKET_MAX) {
421                         large_request = 1;
422                         use_gzip = 0;
423                         break;
424                 }
425
426                 n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
427                 if (!n)
428                         break;
429                 rpc->len += n;
430         }
431
432         if (large_request) {
433                 do {
434                         err = probe_rpc(rpc);
435                 } while (err == HTTP_REAUTH);
436                 if (err != HTTP_OK)
437                         return -1;
438         }
439
440         headers = curl_slist_append(headers, rpc->hdr_content_type);
441         headers = curl_slist_append(headers, rpc->hdr_accept);
442         headers = curl_slist_append(headers, "Expect:");
443
444 retry:
445         slot = get_active_slot();
446
447         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
448         curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
449         curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
450         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
451
452         if (large_request) {
453                 /* The request body is large and the size cannot be predicted.
454                  * We must use chunked encoding to send it.
455                  */
456                 headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
457                 rpc->initial_buffer = 1;
458                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
459                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
460 #ifndef NO_CURL_IOCTL
461                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
462                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
463 #endif
464                 if (options.verbosity > 1) {
465                         fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
466                         fflush(stderr);
467                 }
468
469         } else if (gzip_body) {
470                 /*
471                  * If we are looping to retry authentication, then the previous
472                  * run will have set up the headers and gzip buffer already,
473                  * and we just need to send it.
474                  */
475                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
476                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
477
478         } else if (use_gzip && 1024 < rpc->len) {
479                 /* The client backend isn't giving us compressed data so
480                  * we can try to deflate it ourselves, this may save on.
481                  * the transfer time.
482                  */
483                 git_zstream stream;
484                 int ret;
485
486                 memset(&stream, 0, sizeof(stream));
487                 git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
488                 gzip_size = git_deflate_bound(&stream, rpc->len);
489                 gzip_body = xmalloc(gzip_size);
490
491                 stream.next_in = (unsigned char *)rpc->buf;
492                 stream.avail_in = rpc->len;
493                 stream.next_out = (unsigned char *)gzip_body;
494                 stream.avail_out = gzip_size;
495
496                 ret = git_deflate(&stream, Z_FINISH);
497                 if (ret != Z_STREAM_END)
498                         die("cannot deflate request; zlib deflate error %d", ret);
499
500                 ret = git_deflate_end_gently(&stream);
501                 if (ret != Z_OK)
502                         die("cannot deflate request; zlib end error %d", ret);
503
504                 gzip_size = stream.total_out;
505
506                 headers = curl_slist_append(headers, "Content-Encoding: gzip");
507                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
508                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
509
510                 if (options.verbosity > 1) {
511                         fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
512                                 rpc->service_name,
513                                 (unsigned long)rpc->len, (unsigned long)gzip_size);
514                         fflush(stderr);
515                 }
516         } else {
517                 /* We know the complete request size in advance, use the
518                  * more normal Content-Length approach.
519                  */
520                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
521                 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, rpc->len);
522                 if (options.verbosity > 1) {
523                         fprintf(stderr, "POST %s (%lu bytes)\n",
524                                 rpc->service_name, (unsigned long)rpc->len);
525                         fflush(stderr);
526                 }
527         }
528
529         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
530         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
531         curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
532
533         err = run_slot(slot);
534         if (err == HTTP_REAUTH && !large_request)
535                 goto retry;
536         if (err != HTTP_OK)
537                 err = -1;
538
539         curl_slist_free_all(headers);
540         free(gzip_body);
541         return err;
542 }
543
544 static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
545 {
546         const char *svc = rpc->service_name;
547         struct strbuf buf = STRBUF_INIT;
548         struct strbuf *preamble = rpc->stdin_preamble;
549         struct child_process client;
550         int err = 0;
551
552         memset(&client, 0, sizeof(client));
553         client.in = -1;
554         client.out = -1;
555         client.git_cmd = 1;
556         client.argv = rpc->argv;
557         if (start_command(&client))
558                 exit(1);
559         if (preamble)
560                 write_or_die(client.in, preamble->buf, preamble->len);
561         if (heads)
562                 write_or_die(client.in, heads->buf, heads->len);
563
564         rpc->alloc = http_post_buffer;
565         rpc->buf = xmalloc(rpc->alloc);
566         rpc->in = client.in;
567         rpc->out = client.out;
568         strbuf_init(&rpc->result, 0);
569
570         strbuf_addf(&buf, "%s%s", url, svc);
571         rpc->service_url = strbuf_detach(&buf, NULL);
572
573         strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
574         rpc->hdr_content_type = strbuf_detach(&buf, NULL);
575
576         strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
577         rpc->hdr_accept = strbuf_detach(&buf, NULL);
578
579         while (!err) {
580                 int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
581                 if (!n)
582                         break;
583                 rpc->pos = 0;
584                 rpc->len = n;
585                 err |= post_rpc(rpc);
586         }
587
588         close(client.in);
589         client.in = -1;
590         if (!err) {
591                 strbuf_read(&rpc->result, client.out, 0);
592         } else {
593                 char buf[4096];
594                 for (;;)
595                         if (xread(client.out, buf, sizeof(buf)) <= 0)
596                                 break;
597         }
598
599         close(client.out);
600         client.out = -1;
601
602         err |= finish_command(&client);
603         free(rpc->service_url);
604         free(rpc->hdr_content_type);
605         free(rpc->hdr_accept);
606         free(rpc->buf);
607         strbuf_release(&buf);
608         return err;
609 }
610
611 static int fetch_dumb(int nr_heads, struct ref **to_fetch)
612 {
613         struct walker *walker;
614         char **targets = xmalloc(nr_heads * sizeof(char*));
615         int ret, i;
616
617         if (options.depth)
618                 die("dumb http transport does not support --depth");
619         for (i = 0; i < nr_heads; i++)
620                 targets[i] = xstrdup(sha1_to_hex(to_fetch[i]->old_sha1));
621
622         walker = get_http_walker(url);
623         walker->get_all = 1;
624         walker->get_tree = 1;
625         walker->get_history = 1;
626         walker->get_verbosely = options.verbosity >= 3;
627         walker->get_recover = 0;
628         ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
629         walker_free(walker);
630
631         for (i = 0; i < nr_heads; i++)
632                 free(targets[i]);
633         free(targets);
634
635         return ret ? error("Fetch failed.") : 0;
636 }
637
638 static int fetch_git(struct discovery *heads,
639         int nr_heads, struct ref **to_fetch)
640 {
641         struct rpc_state rpc;
642         struct strbuf preamble = STRBUF_INIT;
643         char *depth_arg = NULL;
644         int argc = 0, i, err;
645         const char *argv[15];
646
647         argv[argc++] = "fetch-pack";
648         argv[argc++] = "--stateless-rpc";
649         argv[argc++] = "--stdin";
650         argv[argc++] = "--lock-pack";
651         if (options.followtags)
652                 argv[argc++] = "--include-tag";
653         if (options.thin)
654                 argv[argc++] = "--thin";
655         if (options.verbosity >= 3) {
656                 argv[argc++] = "-v";
657                 argv[argc++] = "-v";
658         }
659         if (!options.progress)
660                 argv[argc++] = "--no-progress";
661         if (options.depth) {
662                 struct strbuf buf = STRBUF_INIT;
663                 strbuf_addf(&buf, "--depth=%lu", options.depth);
664                 depth_arg = strbuf_detach(&buf, NULL);
665                 argv[argc++] = depth_arg;
666         }
667         argv[argc++] = url;
668         argv[argc++] = NULL;
669
670         for (i = 0; i < nr_heads; i++) {
671                 struct ref *ref = to_fetch[i];
672                 if (!ref->name || !*ref->name)
673                         die("cannot fetch by sha1 over smart http");
674                 packet_buf_write(&preamble, "%s\n", ref->name);
675         }
676         packet_buf_flush(&preamble);
677
678         memset(&rpc, 0, sizeof(rpc));
679         rpc.service_name = "git-upload-pack",
680         rpc.argv = argv;
681         rpc.stdin_preamble = &preamble;
682         rpc.gzip_request = 1;
683
684         err = rpc_service(&rpc, heads);
685         if (rpc.result.len)
686                 write_or_die(1, rpc.result.buf, rpc.result.len);
687         strbuf_release(&rpc.result);
688         strbuf_release(&preamble);
689         free(depth_arg);
690         return err;
691 }
692
693 static int fetch(int nr_heads, struct ref **to_fetch)
694 {
695         struct discovery *d = discover_refs("git-upload-pack");
696         if (d->proto_git)
697                 return fetch_git(d, nr_heads, to_fetch);
698         else
699                 return fetch_dumb(nr_heads, to_fetch);
700 }
701
702 static void parse_fetch(struct strbuf *buf)
703 {
704         struct ref **to_fetch = NULL;
705         struct ref *list_head = NULL;
706         struct ref **list = &list_head;
707         int alloc_heads = 0, nr_heads = 0;
708
709         do {
710                 if (!prefixcmp(buf->buf, "fetch ")) {
711                         char *p = buf->buf + strlen("fetch ");
712                         char *name;
713                         struct ref *ref;
714                         unsigned char old_sha1[20];
715
716                         if (strlen(p) < 40 || get_sha1_hex(p, old_sha1))
717                                 die("protocol error: expected sha/ref, got %s'", p);
718                         if (p[40] == ' ')
719                                 name = p + 41;
720                         else if (!p[40])
721                                 name = "";
722                         else
723                                 die("protocol error: expected sha/ref, got %s'", p);
724
725                         ref = alloc_ref(name);
726                         hashcpy(ref->old_sha1, old_sha1);
727
728                         *list = ref;
729                         list = &ref->next;
730
731                         ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
732                         to_fetch[nr_heads++] = ref;
733                 }
734                 else
735                         die("http transport does not support %s", buf->buf);
736
737                 strbuf_reset(buf);
738                 if (strbuf_getline(buf, stdin, '\n') == EOF)
739                         return;
740                 if (!*buf->buf)
741                         break;
742         } while (1);
743
744         if (fetch(nr_heads, to_fetch))
745                 exit(128); /* error already reported */
746         free_refs(list_head);
747         free(to_fetch);
748
749         printf("\n");
750         fflush(stdout);
751         strbuf_reset(buf);
752 }
753
754 static int push_dav(int nr_spec, char **specs)
755 {
756         const char **argv = xmalloc((10 + nr_spec) * sizeof(char*));
757         int argc = 0, i;
758
759         argv[argc++] = "http-push";
760         argv[argc++] = "--helper-status";
761         if (options.dry_run)
762                 argv[argc++] = "--dry-run";
763         if (options.verbosity > 1)
764                 argv[argc++] = "--verbose";
765         argv[argc++] = url;
766         for (i = 0; i < nr_spec; i++)
767                 argv[argc++] = specs[i];
768         argv[argc++] = NULL;
769
770         if (run_command_v_opt(argv, RUN_GIT_CMD))
771                 die("git-%s failed", argv[0]);
772         free(argv);
773         return 0;
774 }
775
776 static int push_git(struct discovery *heads, int nr_spec, char **specs)
777 {
778         struct rpc_state rpc;
779         const char **argv;
780         int argc = 0, i, err;
781
782         argv = xmalloc((10 + nr_spec) * sizeof(char*));
783         argv[argc++] = "send-pack";
784         argv[argc++] = "--stateless-rpc";
785         argv[argc++] = "--helper-status";
786         if (options.thin)
787                 argv[argc++] = "--thin";
788         if (options.dry_run)
789                 argv[argc++] = "--dry-run";
790         if (options.verbosity == 0)
791                 argv[argc++] = "--quiet";
792         else if (options.verbosity > 1)
793                 argv[argc++] = "--verbose";
794         argv[argc++] = options.progress ? "--progress" : "--no-progress";
795         argv[argc++] = url;
796         for (i = 0; i < nr_spec; i++)
797                 argv[argc++] = specs[i];
798         argv[argc++] = NULL;
799
800         memset(&rpc, 0, sizeof(rpc));
801         rpc.service_name = "git-receive-pack",
802         rpc.argv = argv;
803
804         err = rpc_service(&rpc, heads);
805         if (rpc.result.len)
806                 write_or_die(1, rpc.result.buf, rpc.result.len);
807         strbuf_release(&rpc.result);
808         free(argv);
809         return err;
810 }
811
812 static int push(int nr_spec, char **specs)
813 {
814         struct discovery *heads = discover_refs("git-receive-pack");
815         int ret;
816
817         if (heads->proto_git)
818                 ret = push_git(heads, nr_spec, specs);
819         else
820                 ret = push_dav(nr_spec, specs);
821         free_discovery(heads);
822         return ret;
823 }
824
825 static void parse_push(struct strbuf *buf)
826 {
827         char **specs = NULL;
828         int alloc_spec = 0, nr_spec = 0, i, ret;
829
830         do {
831                 if (!prefixcmp(buf->buf, "push ")) {
832                         ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
833                         specs[nr_spec++] = xstrdup(buf->buf + 5);
834                 }
835                 else
836                         die("http transport does not support %s", buf->buf);
837
838                 strbuf_reset(buf);
839                 if (strbuf_getline(buf, stdin, '\n') == EOF)
840                         goto free_specs;
841                 if (!*buf->buf)
842                         break;
843         } while (1);
844
845         ret = push(nr_spec, specs);
846         printf("\n");
847         fflush(stdout);
848
849         if (ret)
850                 exit(128); /* error already reported */
851
852  free_specs:
853         for (i = 0; i < nr_spec; i++)
854                 free(specs[i]);
855         free(specs);
856 }
857
858 int main(int argc, const char **argv)
859 {
860         struct strbuf buf = STRBUF_INIT;
861         int nongit;
862
863         git_extract_argv0_path(argv[0]);
864         setup_git_directory_gently(&nongit);
865         if (argc < 2) {
866                 fprintf(stderr, "Remote needed\n");
867                 return 1;
868         }
869
870         options.verbosity = 1;
871         options.progress = !!isatty(2);
872         options.thin = 1;
873
874         remote = remote_get(argv[1]);
875
876         if (argc > 2) {
877                 end_url_with_slash(&buf, argv[2]);
878         } else {
879                 end_url_with_slash(&buf, remote->url[0]);
880         }
881
882         url = strbuf_detach(&buf, NULL);
883
884         http_init(remote, url, 0);
885
886         do {
887                 if (strbuf_getline(&buf, stdin, '\n') == EOF) {
888                         if (ferror(stdin))
889                                 fprintf(stderr, "Error reading command stream\n");
890                         else
891                                 fprintf(stderr, "Unexpected end of command stream\n");
892                         return 1;
893                 }
894                 if (buf.len == 0)
895                         break;
896                 if (!prefixcmp(buf.buf, "fetch ")) {
897                         if (nongit)
898                                 die("Fetch attempted without a local repo");
899                         parse_fetch(&buf);
900
901                 } else if (!strcmp(buf.buf, "list") || !prefixcmp(buf.buf, "list ")) {
902                         int for_push = !!strstr(buf.buf + 4, "for-push");
903                         output_refs(get_refs(for_push));
904
905                 } else if (!prefixcmp(buf.buf, "push ")) {
906                         parse_push(&buf);
907
908                 } else if (!prefixcmp(buf.buf, "option ")) {
909                         char *name = buf.buf + strlen("option ");
910                         char *value = strchr(name, ' ');
911                         int result;
912
913                         if (value)
914                                 *value++ = '\0';
915                         else
916                                 value = "true";
917
918                         result = set_option(name, value);
919                         if (!result)
920                                 printf("ok\n");
921                         else if (result < 0)
922                                 printf("error invalid value\n");
923                         else
924                                 printf("unsupported\n");
925                         fflush(stdout);
926
927                 } else if (!strcmp(buf.buf, "capabilities")) {
928                         printf("fetch\n");
929                         printf("option\n");
930                         printf("push\n");
931                         printf("\n");
932                         fflush(stdout);
933                 } else {
934                         fprintf(stderr, "Unknown command '%s'\n", buf.buf);
935                         return 1;
936                 }
937                 strbuf_reset(&buf);
938         } while (1);
939
940         http_cleanup();
941
942         return 0;
943 }