Merge branch 'pb/send-email-cccmd-fix'
[git] / http-push.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "tag.h"
4 #include "blob.h"
5 #include "http.h"
6 #include "refs.h"
7 #include "diff.h"
8 #include "revision.h"
9 #include "exec_cmd.h"
10 #include "remote.h"
11 #include "list-objects.h"
12 #include "sigchain.h"
13
14 #include <expat.h>
15
16 static const char http_push_usage[] =
17 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
18
19 #ifndef XML_STATUS_OK
20 enum XML_Status {
21   XML_STATUS_OK = 1,
22   XML_STATUS_ERROR = 0
23 };
24 #define XML_STATUS_OK    1
25 #define XML_STATUS_ERROR 0
26 #endif
27
28 #define PREV_BUF_SIZE 4096
29
30 /* DAV methods */
31 #define DAV_LOCK "LOCK"
32 #define DAV_MKCOL "MKCOL"
33 #define DAV_MOVE "MOVE"
34 #define DAV_PROPFIND "PROPFIND"
35 #define DAV_PUT "PUT"
36 #define DAV_UNLOCK "UNLOCK"
37 #define DAV_DELETE "DELETE"
38
39 /* DAV lock flags */
40 #define DAV_PROP_LOCKWR (1u << 0)
41 #define DAV_PROP_LOCKEX (1u << 1)
42 #define DAV_LOCK_OK (1u << 2)
43
44 /* DAV XML properties */
45 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
46 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
47 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
48 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
49 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
50 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
51 #define DAV_PROPFIND_RESP ".multistatus.response"
52 #define DAV_PROPFIND_NAME ".multistatus.response.href"
53 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
54
55 /* DAV request body templates */
56 #define PROPFIND_SUPPORTEDLOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:prop xmlns:R=\"%s\">\n<D:supportedlock/>\n</D:prop>\n</D:propfind>"
57 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
58 #define LOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:lockinfo xmlns:D=\"DAV:\">\n<D:lockscope><D:exclusive/></D:lockscope>\n<D:locktype><D:write/></D:locktype>\n<D:owner>\n<D:href>mailto:%s</D:href>\n</D:owner>\n</D:lockinfo>"
59
60 #define LOCK_TIME 600
61 #define LOCK_REFRESH 30
62
63 /* bits #0-15 in revision.h */
64
65 #define LOCAL    (1u<<16)
66 #define REMOTE   (1u<<17)
67 #define FETCHING (1u<<18)
68 #define PUSHING  (1u<<19)
69
70 /* We allow "recursive" symbolic refs. Only within reason, though */
71 #define MAXDEPTH 5
72
73 static int pushing;
74 static int aborted;
75 static signed char remote_dir_exists[256];
76
77 static int push_verbosely;
78 static int push_all = MATCH_REFS_NONE;
79 static int force_all;
80 static int dry_run;
81
82 static struct object_list *objects;
83
84 struct repo
85 {
86         char *url;
87         char *path;
88         int path_len;
89         int has_info_refs;
90         int can_update_info_refs;
91         int has_info_packs;
92         struct packed_git *packs;
93         struct remote_lock *locks;
94 };
95
96 static struct repo *repo;
97
98 enum transfer_state {
99         NEED_FETCH,
100         RUN_FETCH_LOOSE,
101         RUN_FETCH_PACKED,
102         NEED_PUSH,
103         RUN_MKCOL,
104         RUN_PUT,
105         RUN_MOVE,
106         ABORTED,
107         COMPLETE,
108 };
109
110 struct transfer_request
111 {
112         struct object *obj;
113         char *url;
114         char *dest;
115         struct remote_lock *lock;
116         struct curl_slist *headers;
117         struct buffer buffer;
118         enum transfer_state state;
119         CURLcode curl_result;
120         char errorstr[CURL_ERROR_SIZE];
121         long http_code;
122         void *userData;
123         struct active_request_slot *slot;
124         struct transfer_request *next;
125 };
126
127 static struct transfer_request *request_queue_head;
128
129 struct xml_ctx
130 {
131         char *name;
132         int len;
133         char *cdata;
134         void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
135         void *userData;
136 };
137
138 struct remote_lock
139 {
140         char *url;
141         char *owner;
142         char *token;
143         char tmpfile_suffix[41];
144         time_t start_time;
145         long timeout;
146         int refreshing;
147         struct remote_lock *next;
148 };
149
150 /* Flags that control remote_ls processing */
151 #define PROCESS_FILES (1u << 0)
152 #define PROCESS_DIRS  (1u << 1)
153 #define RECURSIVE     (1u << 2)
154
155 /* Flags that remote_ls passes to callback functions */
156 #define IS_DIR (1u << 0)
157
158 struct remote_ls_ctx
159 {
160         char *path;
161         void (*userFunc)(struct remote_ls_ctx *ls);
162         void *userData;
163         int flags;
164         char *dentry_name;
165         int dentry_flags;
166         struct remote_ls_ctx *parent;
167 };
168
169 /* get_dav_token_headers options */
170 enum dav_header_flag {
171         DAV_HEADER_IF = (1u << 0),
172         DAV_HEADER_LOCK = (1u << 1),
173         DAV_HEADER_TIMEOUT = (1u << 2)
174 };
175
176 static char *xml_entities(char *s)
177 {
178         struct strbuf buf = STRBUF_INIT;
179         while (*s) {
180                 size_t len = strcspn(s, "\"<>&");
181                 strbuf_add(&buf, s, len);
182                 s += len;
183                 switch (*s) {
184                 case '"':
185                         strbuf_addstr(&buf, "&quot;");
186                         break;
187                 case '<':
188                         strbuf_addstr(&buf, "&lt;");
189                         break;
190                 case '>':
191                         strbuf_addstr(&buf, "&gt;");
192                         break;
193                 case '&':
194                         strbuf_addstr(&buf, "&amp;");
195                         break;
196                 }
197                 s++;
198         }
199         return strbuf_detach(&buf, NULL);
200 }
201
202 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
203 {
204         struct strbuf buf = STRBUF_INIT;
205         struct curl_slist *dav_headers = NULL;
206
207         if (options & DAV_HEADER_IF) {
208                 strbuf_addf(&buf, "If: (<%s>)", lock->token);
209                 dav_headers = curl_slist_append(dav_headers, buf.buf);
210                 strbuf_reset(&buf);
211         }
212         if (options & DAV_HEADER_LOCK) {
213                 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
214                 dav_headers = curl_slist_append(dav_headers, buf.buf);
215                 strbuf_reset(&buf);
216         }
217         if (options & DAV_HEADER_TIMEOUT) {
218                 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
219                 dav_headers = curl_slist_append(dav_headers, buf.buf);
220                 strbuf_reset(&buf);
221         }
222         strbuf_release(&buf);
223
224         return dav_headers;
225 }
226
227 static void finish_request(struct transfer_request *request);
228 static void release_request(struct transfer_request *request);
229
230 static void process_response(void *callback_data)
231 {
232         struct transfer_request *request =
233                 (struct transfer_request *)callback_data;
234
235         finish_request(request);
236 }
237
238 #ifdef USE_CURL_MULTI
239
240 static void start_fetch_loose(struct transfer_request *request)
241 {
242         struct active_request_slot *slot;
243         struct http_object_request *obj_req;
244
245         obj_req = new_http_object_request(repo->url, request->obj->sha1);
246         if (obj_req == NULL) {
247                 request->state = ABORTED;
248                 return;
249         }
250
251         slot = obj_req->slot;
252         slot->callback_func = process_response;
253         slot->callback_data = request;
254         request->slot = slot;
255         request->userData = obj_req;
256
257         /* Try to get the request started, abort the request on error */
258         request->state = RUN_FETCH_LOOSE;
259         if (!start_active_slot(slot)) {
260                 fprintf(stderr, "Unable to start GET request\n");
261                 repo->can_update_info_refs = 0;
262                 release_http_object_request(obj_req);
263                 release_request(request);
264         }
265 }
266
267 static void start_mkcol(struct transfer_request *request)
268 {
269         char *hex = sha1_to_hex(request->obj->sha1);
270         struct active_request_slot *slot;
271
272         request->url = get_remote_object_url(repo->url, hex, 1);
273
274         slot = get_active_slot();
275         slot->callback_func = process_response;
276         slot->callback_data = request;
277         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
278         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
279         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
280         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
281         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
282
283         if (start_active_slot(slot)) {
284                 request->slot = slot;
285                 request->state = RUN_MKCOL;
286         } else {
287                 request->state = ABORTED;
288                 free(request->url);
289                 request->url = NULL;
290         }
291 }
292 #endif
293
294 static void start_fetch_packed(struct transfer_request *request)
295 {
296         struct packed_git *target;
297
298         struct transfer_request *check_request = request_queue_head;
299         struct http_pack_request *preq;
300
301         target = find_sha1_pack(request->obj->sha1, repo->packs);
302         if (!target) {
303                 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
304                 repo->can_update_info_refs = 0;
305                 release_request(request);
306                 return;
307         }
308
309         fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
310         fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
311
312         preq = new_http_pack_request(target, repo->url);
313         if (preq == NULL) {
314                 release_http_pack_request(preq);
315                 repo->can_update_info_refs = 0;
316                 return;
317         }
318         preq->lst = &repo->packs;
319
320         /* Make sure there isn't another open request for this pack */
321         while (check_request) {
322                 if (check_request->state == RUN_FETCH_PACKED &&
323                     !strcmp(check_request->url, preq->url)) {
324                         release_http_pack_request(preq);
325                         release_request(request);
326                         return;
327                 }
328                 check_request = check_request->next;
329         }
330
331         preq->slot->callback_func = process_response;
332         preq->slot->callback_data = request;
333         request->slot = preq->slot;
334         request->userData = preq;
335
336         /* Try to get the request started, abort the request on error */
337         request->state = RUN_FETCH_PACKED;
338         if (!start_active_slot(preq->slot)) {
339                 fprintf(stderr, "Unable to start GET request\n");
340                 release_http_pack_request(preq);
341                 repo->can_update_info_refs = 0;
342                 release_request(request);
343         }
344 }
345
346 static void start_put(struct transfer_request *request)
347 {
348         char *hex = sha1_to_hex(request->obj->sha1);
349         struct active_request_slot *slot;
350         struct strbuf buf = STRBUF_INIT;
351         enum object_type type;
352         char hdr[50];
353         void *unpacked;
354         unsigned long len;
355         int hdrlen;
356         ssize_t size;
357         z_stream stream;
358
359         unpacked = read_sha1_file(request->obj->sha1, &type, &len);
360         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
361
362         /* Set it up */
363         memset(&stream, 0, sizeof(stream));
364         deflateInit(&stream, zlib_compression_level);
365         size = deflateBound(&stream, len + hdrlen);
366         strbuf_init(&request->buffer.buf, size);
367         request->buffer.posn = 0;
368
369         /* Compress it */
370         stream.next_out = (unsigned char *)request->buffer.buf.buf;
371         stream.avail_out = size;
372
373         /* First header.. */
374         stream.next_in = (void *)hdr;
375         stream.avail_in = hdrlen;
376         while (deflate(&stream, 0) == Z_OK)
377                 /* nothing */;
378
379         /* Then the data itself.. */
380         stream.next_in = unpacked;
381         stream.avail_in = len;
382         while (deflate(&stream, Z_FINISH) == Z_OK)
383                 /* nothing */;
384         deflateEnd(&stream);
385         free(unpacked);
386
387         request->buffer.buf.len = stream.total_out;
388
389         strbuf_addstr(&buf, "Destination: ");
390         append_remote_object_url(&buf, repo->url, hex, 0);
391         request->dest = strbuf_detach(&buf, NULL);
392
393         append_remote_object_url(&buf, repo->url, hex, 0);
394         strbuf_add(&buf, request->lock->tmpfile_suffix, 41);
395         request->url = strbuf_detach(&buf, NULL);
396
397         slot = get_active_slot();
398         slot->callback_func = process_response;
399         slot->callback_data = request;
400         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
401         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.buf.len);
402         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
403 #ifndef NO_CURL_IOCTL
404         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
405         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &request->buffer);
406 #endif
407         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
408         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
409         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
410         curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
411         curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
412         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
413
414         if (start_active_slot(slot)) {
415                 request->slot = slot;
416                 request->state = RUN_PUT;
417         } else {
418                 request->state = ABORTED;
419                 free(request->url);
420                 request->url = NULL;
421         }
422 }
423
424 static void start_move(struct transfer_request *request)
425 {
426         struct active_request_slot *slot;
427         struct curl_slist *dav_headers = NULL;
428
429         slot = get_active_slot();
430         slot->callback_func = process_response;
431         slot->callback_data = request;
432         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
433         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
434         dav_headers = curl_slist_append(dav_headers, request->dest);
435         dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
436         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
437         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
438         curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
439
440         if (start_active_slot(slot)) {
441                 request->slot = slot;
442                 request->state = RUN_MOVE;
443         } else {
444                 request->state = ABORTED;
445                 free(request->url);
446                 request->url = NULL;
447         }
448 }
449
450 static int refresh_lock(struct remote_lock *lock)
451 {
452         struct active_request_slot *slot;
453         struct slot_results results;
454         struct curl_slist *dav_headers;
455         int rc = 0;
456
457         lock->refreshing = 1;
458
459         dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
460
461         slot = get_active_slot();
462         slot->results = &results;
463         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
464         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
465         curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
466         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
467         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
468
469         if (start_active_slot(slot)) {
470                 run_active_slot(slot);
471                 if (results.curl_result != CURLE_OK) {
472                         fprintf(stderr, "LOCK HTTP error %ld\n",
473                                 results.http_code);
474                 } else {
475                         lock->start_time = time(NULL);
476                         rc = 1;
477                 }
478         }
479
480         lock->refreshing = 0;
481         curl_slist_free_all(dav_headers);
482
483         return rc;
484 }
485
486 static void check_locks(void)
487 {
488         struct remote_lock *lock = repo->locks;
489         time_t current_time = time(NULL);
490         int time_remaining;
491
492         while (lock) {
493                 time_remaining = lock->start_time + lock->timeout -
494                         current_time;
495                 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
496                         if (!refresh_lock(lock)) {
497                                 fprintf(stderr,
498                                         "Unable to refresh lock for %s\n",
499                                         lock->url);
500                                 aborted = 1;
501                                 return;
502                         }
503                 }
504                 lock = lock->next;
505         }
506 }
507
508 static void release_request(struct transfer_request *request)
509 {
510         struct transfer_request *entry = request_queue_head;
511
512         if (request == request_queue_head) {
513                 request_queue_head = request->next;
514         } else {
515                 while (entry->next != NULL && entry->next != request)
516                         entry = entry->next;
517                 if (entry->next == request)
518                         entry->next = entry->next->next;
519         }
520
521         free(request->url);
522         free(request);
523 }
524
525 static void finish_request(struct transfer_request *request)
526 {
527         struct http_pack_request *preq;
528         struct http_object_request *obj_req;
529
530         request->curl_result = request->slot->curl_result;
531         request->http_code = request->slot->http_code;
532         request->slot = NULL;
533
534         /* Keep locks active */
535         check_locks();
536
537         if (request->headers != NULL)
538                 curl_slist_free_all(request->headers);
539
540         /* URL is reused for MOVE after PUT */
541         if (request->state != RUN_PUT) {
542                 free(request->url);
543                 request->url = NULL;
544         }
545
546         if (request->state == RUN_MKCOL) {
547                 if (request->curl_result == CURLE_OK ||
548                     request->http_code == 405) {
549                         remote_dir_exists[request->obj->sha1[0]] = 1;
550                         start_put(request);
551                 } else {
552                         fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
553                                 sha1_to_hex(request->obj->sha1),
554                                 request->curl_result, request->http_code);
555                         request->state = ABORTED;
556                         aborted = 1;
557                 }
558         } else if (request->state == RUN_PUT) {
559                 if (request->curl_result == CURLE_OK) {
560                         start_move(request);
561                 } else {
562                         fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
563                                 sha1_to_hex(request->obj->sha1),
564                                 request->curl_result, request->http_code);
565                         request->state = ABORTED;
566                         aborted = 1;
567                 }
568         } else if (request->state == RUN_MOVE) {
569                 if (request->curl_result == CURLE_OK) {
570                         if (push_verbosely)
571                                 fprintf(stderr, "    sent %s\n",
572                                         sha1_to_hex(request->obj->sha1));
573                         request->obj->flags |= REMOTE;
574                         release_request(request);
575                 } else {
576                         fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
577                                 sha1_to_hex(request->obj->sha1),
578                                 request->curl_result, request->http_code);
579                         request->state = ABORTED;
580                         aborted = 1;
581                 }
582         } else if (request->state == RUN_FETCH_LOOSE) {
583                 obj_req = (struct http_object_request *)request->userData;
584
585                 if (finish_http_object_request(obj_req) == 0)
586                         if (obj_req->rename == 0)
587                                 request->obj->flags |= (LOCAL | REMOTE);
588
589                 /* Try fetching packed if necessary */
590                 if (request->obj->flags & LOCAL) {
591                         release_http_object_request(obj_req);
592                         release_request(request);
593                 } else
594                         start_fetch_packed(request);
595
596         } else if (request->state == RUN_FETCH_PACKED) {
597                 int fail = 1;
598                 if (request->curl_result != CURLE_OK) {
599                         fprintf(stderr, "Unable to get pack file %s\n%s",
600                                 request->url, curl_errorstr);
601                 } else {
602                         preq = (struct http_pack_request *)request->userData;
603
604                         if (preq) {
605                                 if (finish_http_pack_request(preq) > 0)
606                                         fail = 0;
607                                 release_http_pack_request(preq);
608                         }
609                 }
610                 if (fail)
611                         repo->can_update_info_refs = 0;
612                 release_request(request);
613         }
614 }
615
616 #ifdef USE_CURL_MULTI
617 static int is_running_queue;
618 static int fill_active_slot(void *unused)
619 {
620         struct transfer_request *request;
621
622         if (aborted || !is_running_queue)
623                 return 0;
624
625         for (request = request_queue_head; request; request = request->next) {
626                 if (request->state == NEED_FETCH) {
627                         start_fetch_loose(request);
628                         return 1;
629                 } else if (pushing && request->state == NEED_PUSH) {
630                         if (remote_dir_exists[request->obj->sha1[0]] == 1) {
631                                 start_put(request);
632                         } else {
633                                 start_mkcol(request);
634                         }
635                         return 1;
636                 }
637         }
638         return 0;
639 }
640 #endif
641
642 static void get_remote_object_list(unsigned char parent);
643
644 static void add_fetch_request(struct object *obj)
645 {
646         struct transfer_request *request;
647
648         check_locks();
649
650         /*
651          * Don't fetch the object if it's known to exist locally
652          * or is already in the request queue
653          */
654         if (remote_dir_exists[obj->sha1[0]] == -1)
655                 get_remote_object_list(obj->sha1[0]);
656         if (obj->flags & (LOCAL | FETCHING))
657                 return;
658
659         obj->flags |= FETCHING;
660         request = xmalloc(sizeof(*request));
661         request->obj = obj;
662         request->url = NULL;
663         request->lock = NULL;
664         request->headers = NULL;
665         request->state = NEED_FETCH;
666         request->next = request_queue_head;
667         request_queue_head = request;
668
669 #ifdef USE_CURL_MULTI
670         fill_active_slots();
671         step_active_slots();
672 #endif
673 }
674
675 static int add_send_request(struct object *obj, struct remote_lock *lock)
676 {
677         struct transfer_request *request = request_queue_head;
678         struct packed_git *target;
679
680         /* Keep locks active */
681         check_locks();
682
683         /*
684          * Don't push the object if it's known to exist on the remote
685          * or is already in the request queue
686          */
687         if (remote_dir_exists[obj->sha1[0]] == -1)
688                 get_remote_object_list(obj->sha1[0]);
689         if (obj->flags & (REMOTE | PUSHING))
690                 return 0;
691         target = find_sha1_pack(obj->sha1, repo->packs);
692         if (target) {
693                 obj->flags |= REMOTE;
694                 return 0;
695         }
696
697         obj->flags |= PUSHING;
698         request = xmalloc(sizeof(*request));
699         request->obj = obj;
700         request->url = NULL;
701         request->lock = lock;
702         request->headers = NULL;
703         request->state = NEED_PUSH;
704         request->next = request_queue_head;
705         request_queue_head = request;
706
707 #ifdef USE_CURL_MULTI
708         fill_active_slots();
709         step_active_slots();
710 #endif
711
712         return 1;
713 }
714
715 static int fetch_indices(void)
716 {
717         int ret;
718
719         if (push_verbosely)
720                 fprintf(stderr, "Getting pack list\n");
721
722         switch (http_get_info_packs(repo->url, &repo->packs)) {
723         case HTTP_OK:
724         case HTTP_MISSING_TARGET:
725                 ret = 0;
726                 break;
727         default:
728                 ret = -1;
729         }
730
731         return ret;
732 }
733
734 static void one_remote_object(const char *hex)
735 {
736         unsigned char sha1[20];
737         struct object *obj;
738
739         if (get_sha1_hex(hex, sha1) != 0)
740                 return;
741
742         obj = lookup_object(sha1);
743         if (!obj)
744                 obj = parse_object(sha1);
745
746         /* Ignore remote objects that don't exist locally */
747         if (!obj)
748                 return;
749
750         obj->flags |= REMOTE;
751         if (!object_list_contains(objects, obj))
752                 object_list_insert(obj, &objects);
753 }
754
755 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
756 {
757         int *lock_flags = (int *)ctx->userData;
758
759         if (tag_closed) {
760                 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
761                         if ((*lock_flags & DAV_PROP_LOCKEX) &&
762                             (*lock_flags & DAV_PROP_LOCKWR)) {
763                                 *lock_flags |= DAV_LOCK_OK;
764                         }
765                         *lock_flags &= DAV_LOCK_OK;
766                 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
767                         *lock_flags |= DAV_PROP_LOCKWR;
768                 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
769                         *lock_flags |= DAV_PROP_LOCKEX;
770                 }
771         }
772 }
773
774 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
775 {
776         struct remote_lock *lock = (struct remote_lock *)ctx->userData;
777         git_SHA_CTX sha_ctx;
778         unsigned char lock_token_sha1[20];
779
780         if (tag_closed && ctx->cdata) {
781                 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
782                         lock->owner = xmalloc(strlen(ctx->cdata) + 1);
783                         strcpy(lock->owner, ctx->cdata);
784                 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
785                         if (!prefixcmp(ctx->cdata, "Second-"))
786                                 lock->timeout =
787                                         strtol(ctx->cdata + 7, NULL, 10);
788                 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
789                         lock->token = xmalloc(strlen(ctx->cdata) + 1);
790                         strcpy(lock->token, ctx->cdata);
791
792                         git_SHA1_Init(&sha_ctx);
793                         git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
794                         git_SHA1_Final(lock_token_sha1, &sha_ctx);
795
796                         lock->tmpfile_suffix[0] = '_';
797                         memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
798                 }
799         }
800 }
801
802 static void one_remote_ref(char *refname);
803
804 static void
805 xml_start_tag(void *userData, const char *name, const char **atts)
806 {
807         struct xml_ctx *ctx = (struct xml_ctx *)userData;
808         const char *c = strchr(name, ':');
809         int new_len;
810
811         if (c == NULL)
812                 c = name;
813         else
814                 c++;
815
816         new_len = strlen(ctx->name) + strlen(c) + 2;
817
818         if (new_len > ctx->len) {
819                 ctx->name = xrealloc(ctx->name, new_len);
820                 ctx->len = new_len;
821         }
822         strcat(ctx->name, ".");
823         strcat(ctx->name, c);
824
825         free(ctx->cdata);
826         ctx->cdata = NULL;
827
828         ctx->userFunc(ctx, 0);
829 }
830
831 static void
832 xml_end_tag(void *userData, const char *name)
833 {
834         struct xml_ctx *ctx = (struct xml_ctx *)userData;
835         const char *c = strchr(name, ':');
836         char *ep;
837
838         ctx->userFunc(ctx, 1);
839
840         if (c == NULL)
841                 c = name;
842         else
843                 c++;
844
845         ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
846         *ep = 0;
847 }
848
849 static void
850 xml_cdata(void *userData, const XML_Char *s, int len)
851 {
852         struct xml_ctx *ctx = (struct xml_ctx *)userData;
853         free(ctx->cdata);
854         ctx->cdata = xmemdupz(s, len);
855 }
856
857 static struct remote_lock *lock_remote(const char *path, long timeout)
858 {
859         struct active_request_slot *slot;
860         struct slot_results results;
861         struct buffer out_buffer = { STRBUF_INIT, 0 };
862         struct strbuf in_buffer = STRBUF_INIT;
863         char *url;
864         char *ep;
865         char timeout_header[25];
866         struct remote_lock *lock = NULL;
867         struct curl_slist *dav_headers = NULL;
868         struct xml_ctx ctx;
869         char *escaped;
870
871         url = xmalloc(strlen(repo->url) + strlen(path) + 1);
872         sprintf(url, "%s%s", repo->url, path);
873
874         /* Make sure leading directories exist for the remote ref */
875         ep = strchr(url + strlen(repo->url) + 1, '/');
876         while (ep) {
877                 char saved_character = ep[1];
878                 ep[1] = '\0';
879                 slot = get_active_slot();
880                 slot->results = &results;
881                 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
882                 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
883                 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
884                 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
885                 if (start_active_slot(slot)) {
886                         run_active_slot(slot);
887                         if (results.curl_result != CURLE_OK &&
888                             results.http_code != 405) {
889                                 fprintf(stderr,
890                                         "Unable to create branch path %s\n",
891                                         url);
892                                 free(url);
893                                 return NULL;
894                         }
895                 } else {
896                         fprintf(stderr, "Unable to start MKCOL request\n");
897                         free(url);
898                         return NULL;
899                 }
900                 ep[1] = saved_character;
901                 ep = strchr(ep + 1, '/');
902         }
903
904         escaped = xml_entities(git_default_email);
905         strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
906         free(escaped);
907
908         sprintf(timeout_header, "Timeout: Second-%ld", timeout);
909         dav_headers = curl_slist_append(dav_headers, timeout_header);
910         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
911
912         slot = get_active_slot();
913         slot->results = &results;
914         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
915         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
916         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
917 #ifndef NO_CURL_IOCTL
918         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
919         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
920 #endif
921         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
922         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
923         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
924         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
925         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
926         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
927
928         lock = xcalloc(1, sizeof(*lock));
929         lock->timeout = -1;
930
931         if (start_active_slot(slot)) {
932                 run_active_slot(slot);
933                 if (results.curl_result == CURLE_OK) {
934                         XML_Parser parser = XML_ParserCreate(NULL);
935                         enum XML_Status result;
936                         ctx.name = xcalloc(10, 1);
937                         ctx.len = 0;
938                         ctx.cdata = NULL;
939                         ctx.userFunc = handle_new_lock_ctx;
940                         ctx.userData = lock;
941                         XML_SetUserData(parser, &ctx);
942                         XML_SetElementHandler(parser, xml_start_tag,
943                                               xml_end_tag);
944                         XML_SetCharacterDataHandler(parser, xml_cdata);
945                         result = XML_Parse(parser, in_buffer.buf,
946                                            in_buffer.len, 1);
947                         free(ctx.name);
948                         if (result != XML_STATUS_OK) {
949                                 fprintf(stderr, "XML error: %s\n",
950                                         XML_ErrorString(
951                                                 XML_GetErrorCode(parser)));
952                                 lock->timeout = -1;
953                         }
954                         XML_ParserFree(parser);
955                 }
956         } else {
957                 fprintf(stderr, "Unable to start LOCK request\n");
958         }
959
960         curl_slist_free_all(dav_headers);
961         strbuf_release(&out_buffer.buf);
962         strbuf_release(&in_buffer);
963
964         if (lock->token == NULL || lock->timeout <= 0) {
965                 free(lock->token);
966                 free(lock->owner);
967                 free(url);
968                 free(lock);
969                 lock = NULL;
970         } else {
971                 lock->url = url;
972                 lock->start_time = time(NULL);
973                 lock->next = repo->locks;
974                 repo->locks = lock;
975         }
976
977         return lock;
978 }
979
980 static int unlock_remote(struct remote_lock *lock)
981 {
982         struct active_request_slot *slot;
983         struct slot_results results;
984         struct remote_lock *prev = repo->locks;
985         struct curl_slist *dav_headers;
986         int rc = 0;
987
988         dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
989
990         slot = get_active_slot();
991         slot->results = &results;
992         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
993         curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
994         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
995         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
996
997         if (start_active_slot(slot)) {
998                 run_active_slot(slot);
999                 if (results.curl_result == CURLE_OK)
1000                         rc = 1;
1001                 else
1002                         fprintf(stderr, "UNLOCK HTTP error %ld\n",
1003                                 results.http_code);
1004         } else {
1005                 fprintf(stderr, "Unable to start UNLOCK request\n");
1006         }
1007
1008         curl_slist_free_all(dav_headers);
1009
1010         if (repo->locks == lock) {
1011                 repo->locks = lock->next;
1012         } else {
1013                 while (prev && prev->next != lock)
1014                         prev = prev->next;
1015                 if (prev)
1016                         prev->next = prev->next->next;
1017         }
1018
1019         free(lock->owner);
1020         free(lock->url);
1021         free(lock->token);
1022         free(lock);
1023
1024         return rc;
1025 }
1026
1027 static void remove_locks(void)
1028 {
1029         struct remote_lock *lock = repo->locks;
1030
1031         fprintf(stderr, "Removing remote locks...\n");
1032         while (lock) {
1033                 struct remote_lock *next = lock->next;
1034                 unlock_remote(lock);
1035                 lock = next;
1036         }
1037 }
1038
1039 static void remove_locks_on_signal(int signo)
1040 {
1041         remove_locks();
1042         sigchain_pop(signo);
1043         raise(signo);
1044 }
1045
1046 static void remote_ls(const char *path, int flags,
1047                       void (*userFunc)(struct remote_ls_ctx *ls),
1048                       void *userData);
1049
1050 static void process_ls_object(struct remote_ls_ctx *ls)
1051 {
1052         unsigned int *parent = (unsigned int *)ls->userData;
1053         char *path = ls->dentry_name;
1054         char *obj_hex;
1055
1056         if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1057                 remote_dir_exists[*parent] = 1;
1058                 return;
1059         }
1060
1061         if (strlen(path) != 49)
1062                 return;
1063         path += 8;
1064         obj_hex = xmalloc(strlen(path));
1065         /* NB: path is not null-terminated, can not use strlcpy here */
1066         memcpy(obj_hex, path, 2);
1067         strcpy(obj_hex + 2, path + 3);
1068         one_remote_object(obj_hex);
1069         free(obj_hex);
1070 }
1071
1072 static void process_ls_ref(struct remote_ls_ctx *ls)
1073 {
1074         if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1075                 fprintf(stderr, "  %s\n", ls->dentry_name);
1076                 return;
1077         }
1078
1079         if (!(ls->dentry_flags & IS_DIR))
1080                 one_remote_ref(ls->dentry_name);
1081 }
1082
1083 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1084 {
1085         struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1086
1087         if (tag_closed) {
1088                 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1089                         if (ls->dentry_flags & IS_DIR) {
1090                                 if (ls->flags & PROCESS_DIRS) {
1091                                         ls->userFunc(ls);
1092                                 }
1093                                 if (strcmp(ls->dentry_name, ls->path) &&
1094                                     ls->flags & RECURSIVE) {
1095                                         remote_ls(ls->dentry_name,
1096                                                   ls->flags,
1097                                                   ls->userFunc,
1098                                                   ls->userData);
1099                                 }
1100                         } else if (ls->flags & PROCESS_FILES) {
1101                                 ls->userFunc(ls);
1102                         }
1103                 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1104                         char *path = ctx->cdata;
1105                         if (*ctx->cdata == 'h') {
1106                                 path = strstr(path, "//");
1107                                 if (path) {
1108                                         path = strchr(path+2, '/');
1109                                 }
1110                         }
1111                         if (path) {
1112                                 path += repo->path_len;
1113                                 ls->dentry_name = xstrdup(path);
1114                         }
1115                 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1116                         ls->dentry_flags |= IS_DIR;
1117                 }
1118         } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1119                 free(ls->dentry_name);
1120                 ls->dentry_name = NULL;
1121                 ls->dentry_flags = 0;
1122         }
1123 }
1124
1125 /*
1126  * NEEDSWORK: remote_ls() ignores info/refs on the remote side.  But it
1127  * should _only_ heed the information from that file, instead of trying to
1128  * determine the refs from the remote file system (badly: it does not even
1129  * know about packed-refs).
1130  */
1131 static void remote_ls(const char *path, int flags,
1132                       void (*userFunc)(struct remote_ls_ctx *ls),
1133                       void *userData)
1134 {
1135         char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1136         struct active_request_slot *slot;
1137         struct slot_results results;
1138         struct strbuf in_buffer = STRBUF_INIT;
1139         struct buffer out_buffer = { STRBUF_INIT, 0 };
1140         struct curl_slist *dav_headers = NULL;
1141         struct xml_ctx ctx;
1142         struct remote_ls_ctx ls;
1143
1144         ls.flags = flags;
1145         ls.path = xstrdup(path);
1146         ls.dentry_name = NULL;
1147         ls.dentry_flags = 0;
1148         ls.userData = userData;
1149         ls.userFunc = userFunc;
1150
1151         sprintf(url, "%s%s", repo->url, path);
1152
1153         strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1154
1155         dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1156         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1157
1158         slot = get_active_slot();
1159         slot->results = &results;
1160         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1161         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1162         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1163 #ifndef NO_CURL_IOCTL
1164         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1165         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1166 #endif
1167         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1168         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1169         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1170         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1171         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1172         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1173
1174         if (start_active_slot(slot)) {
1175                 run_active_slot(slot);
1176                 if (results.curl_result == CURLE_OK) {
1177                         XML_Parser parser = XML_ParserCreate(NULL);
1178                         enum XML_Status result;
1179                         ctx.name = xcalloc(10, 1);
1180                         ctx.len = 0;
1181                         ctx.cdata = NULL;
1182                         ctx.userFunc = handle_remote_ls_ctx;
1183                         ctx.userData = &ls;
1184                         XML_SetUserData(parser, &ctx);
1185                         XML_SetElementHandler(parser, xml_start_tag,
1186                                               xml_end_tag);
1187                         XML_SetCharacterDataHandler(parser, xml_cdata);
1188                         result = XML_Parse(parser, in_buffer.buf,
1189                                            in_buffer.len, 1);
1190                         free(ctx.name);
1191
1192                         if (result != XML_STATUS_OK) {
1193                                 fprintf(stderr, "XML error: %s\n",
1194                                         XML_ErrorString(
1195                                                 XML_GetErrorCode(parser)));
1196                         }
1197                         XML_ParserFree(parser);
1198                 }
1199         } else {
1200                 fprintf(stderr, "Unable to start PROPFIND request\n");
1201         }
1202
1203         free(ls.path);
1204         free(url);
1205         strbuf_release(&out_buffer.buf);
1206         strbuf_release(&in_buffer);
1207         curl_slist_free_all(dav_headers);
1208 }
1209
1210 static void get_remote_object_list(unsigned char parent)
1211 {
1212         char path[] = "objects/XX/";
1213         static const char hex[] = "0123456789abcdef";
1214         unsigned int val = parent;
1215
1216         path[8] = hex[val >> 4];
1217         path[9] = hex[val & 0xf];
1218         remote_dir_exists[val] = 0;
1219         remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1220                   process_ls_object, &val);
1221 }
1222
1223 static int locking_available(void)
1224 {
1225         struct active_request_slot *slot;
1226         struct slot_results results;
1227         struct strbuf in_buffer = STRBUF_INIT;
1228         struct buffer out_buffer = { STRBUF_INIT, 0 };
1229         struct curl_slist *dav_headers = NULL;
1230         struct xml_ctx ctx;
1231         int lock_flags = 0;
1232         char *escaped;
1233
1234         escaped = xml_entities(repo->url);
1235         strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1236         free(escaped);
1237
1238         dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1239         dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1240
1241         slot = get_active_slot();
1242         slot->results = &results;
1243         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1244         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1245         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1246 #ifndef NO_CURL_IOCTL
1247         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1248         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1249 #endif
1250         curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1251         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1252         curl_easy_setopt(slot->curl, CURLOPT_URL, repo->url);
1253         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1254         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1255         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1256
1257         if (start_active_slot(slot)) {
1258                 run_active_slot(slot);
1259                 if (results.curl_result == CURLE_OK) {
1260                         XML_Parser parser = XML_ParserCreate(NULL);
1261                         enum XML_Status result;
1262                         ctx.name = xcalloc(10, 1);
1263                         ctx.len = 0;
1264                         ctx.cdata = NULL;
1265                         ctx.userFunc = handle_lockprop_ctx;
1266                         ctx.userData = &lock_flags;
1267                         XML_SetUserData(parser, &ctx);
1268                         XML_SetElementHandler(parser, xml_start_tag,
1269                                               xml_end_tag);
1270                         result = XML_Parse(parser, in_buffer.buf,
1271                                            in_buffer.len, 1);
1272                         free(ctx.name);
1273
1274                         if (result != XML_STATUS_OK) {
1275                                 fprintf(stderr, "XML error: %s\n",
1276                                         XML_ErrorString(
1277                                                 XML_GetErrorCode(parser)));
1278                                 lock_flags = 0;
1279                         }
1280                         XML_ParserFree(parser);
1281                         if (!lock_flags)
1282                                 error("no DAV locking support on %s",
1283                                       repo->url);
1284
1285                 } else {
1286                         error("Cannot access URL %s, return code %d",
1287                               repo->url, results.curl_result);
1288                         lock_flags = 0;
1289                 }
1290         } else {
1291                 error("Unable to start PROPFIND request on %s", repo->url);
1292         }
1293
1294         strbuf_release(&out_buffer.buf);
1295         strbuf_release(&in_buffer);
1296         curl_slist_free_all(dav_headers);
1297
1298         return lock_flags;
1299 }
1300
1301 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1302 {
1303         struct object_list *entry = xmalloc(sizeof(struct object_list));
1304         entry->item = obj;
1305         entry->next = *p;
1306         *p = entry;
1307         return &entry->next;
1308 }
1309
1310 static struct object_list **process_blob(struct blob *blob,
1311                                          struct object_list **p,
1312                                          struct name_path *path,
1313                                          const char *name)
1314 {
1315         struct object *obj = &blob->object;
1316
1317         obj->flags |= LOCAL;
1318
1319         if (obj->flags & (UNINTERESTING | SEEN))
1320                 return p;
1321
1322         obj->flags |= SEEN;
1323         return add_one_object(obj, p);
1324 }
1325
1326 static struct object_list **process_tree(struct tree *tree,
1327                                          struct object_list **p,
1328                                          struct name_path *path,
1329                                          const char *name)
1330 {
1331         struct object *obj = &tree->object;
1332         struct tree_desc desc;
1333         struct name_entry entry;
1334         struct name_path me;
1335
1336         obj->flags |= LOCAL;
1337
1338         if (obj->flags & (UNINTERESTING | SEEN))
1339                 return p;
1340         if (parse_tree(tree) < 0)
1341                 die("bad tree object %s", sha1_to_hex(obj->sha1));
1342
1343         obj->flags |= SEEN;
1344         name = xstrdup(name);
1345         p = add_one_object(obj, p);
1346         me.up = path;
1347         me.elem = name;
1348         me.elem_len = strlen(name);
1349
1350         init_tree_desc(&desc, tree->buffer, tree->size);
1351
1352         while (tree_entry(&desc, &entry))
1353                 switch (object_type(entry.mode)) {
1354                 case OBJ_TREE:
1355                         p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1356                         break;
1357                 case OBJ_BLOB:
1358                         p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1359                         break;
1360                 default:
1361                         /* Subproject commit - not in this repository */
1362                         break;
1363                 }
1364
1365         free(tree->buffer);
1366         tree->buffer = NULL;
1367         return p;
1368 }
1369
1370 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1371 {
1372         int i;
1373         struct commit *commit;
1374         struct object_list **p = &objects;
1375         int count = 0;
1376
1377         while ((commit = get_revision(revs)) != NULL) {
1378                 p = process_tree(commit->tree, p, NULL, "");
1379                 commit->object.flags |= LOCAL;
1380                 if (!(commit->object.flags & UNINTERESTING))
1381                         count += add_send_request(&commit->object, lock);
1382         }
1383
1384         for (i = 0; i < revs->pending.nr; i++) {
1385                 struct object_array_entry *entry = revs->pending.objects + i;
1386                 struct object *obj = entry->item;
1387                 const char *name = entry->name;
1388
1389                 if (obj->flags & (UNINTERESTING | SEEN))
1390                         continue;
1391                 if (obj->type == OBJ_TAG) {
1392                         obj->flags |= SEEN;
1393                         p = add_one_object(obj, p);
1394                         continue;
1395                 }
1396                 if (obj->type == OBJ_TREE) {
1397                         p = process_tree((struct tree *)obj, p, NULL, name);
1398                         continue;
1399                 }
1400                 if (obj->type == OBJ_BLOB) {
1401                         p = process_blob((struct blob *)obj, p, NULL, name);
1402                         continue;
1403                 }
1404                 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1405         }
1406
1407         while (objects) {
1408                 if (!(objects->item->flags & UNINTERESTING))
1409                         count += add_send_request(objects->item, lock);
1410                 objects = objects->next;
1411         }
1412
1413         return count;
1414 }
1415
1416 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1417 {
1418         struct active_request_slot *slot;
1419         struct slot_results results;
1420         struct buffer out_buffer = { STRBUF_INIT, 0 };
1421         struct curl_slist *dav_headers;
1422
1423         dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1424
1425         strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1426
1427         slot = get_active_slot();
1428         slot->results = &results;
1429         curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1430         curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.buf.len);
1431         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1432 #ifndef NO_CURL_IOCTL
1433         curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1434         curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &out_buffer);
1435 #endif
1436         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1437         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1438         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1439         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1440         curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1441         curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1442
1443         if (start_active_slot(slot)) {
1444                 run_active_slot(slot);
1445                 strbuf_release(&out_buffer.buf);
1446                 if (results.curl_result != CURLE_OK) {
1447                         fprintf(stderr,
1448                                 "PUT error: curl result=%d, HTTP code=%ld\n",
1449                                 results.curl_result, results.http_code);
1450                         /* We should attempt recovery? */
1451                         return 0;
1452                 }
1453         } else {
1454                 strbuf_release(&out_buffer.buf);
1455                 fprintf(stderr, "Unable to start PUT request\n");
1456                 return 0;
1457         }
1458
1459         return 1;
1460 }
1461
1462 static struct ref *remote_refs;
1463
1464 static void one_remote_ref(char *refname)
1465 {
1466         struct ref *ref;
1467         struct object *obj;
1468
1469         ref = alloc_ref(refname);
1470
1471         if (http_fetch_ref(repo->url, ref) != 0) {
1472                 fprintf(stderr,
1473                         "Unable to fetch ref %s from %s\n",
1474                         refname, repo->url);
1475                 free(ref);
1476                 return;
1477         }
1478
1479         /*
1480          * Fetch a copy of the object if it doesn't exist locally - it
1481          * may be required for updating server info later.
1482          */
1483         if (repo->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1484                 obj = lookup_unknown_object(ref->old_sha1);
1485                 if (obj) {
1486                         fprintf(stderr, "  fetch %s for %s\n",
1487                                 sha1_to_hex(ref->old_sha1), refname);
1488                         add_fetch_request(obj);
1489                 }
1490         }
1491
1492         ref->next = remote_refs;
1493         remote_refs = ref;
1494 }
1495
1496 static void get_dav_remote_heads(void)
1497 {
1498         remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1499 }
1500
1501 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1502 {
1503         struct strbuf *buf = (struct strbuf *)ls->userData;
1504         struct object *o;
1505         int len;
1506         char *ref_info;
1507         struct ref *ref;
1508
1509         ref = alloc_ref(ls->dentry_name);
1510
1511         if (http_fetch_ref(repo->url, ref) != 0) {
1512                 fprintf(stderr,
1513                         "Unable to fetch ref %s from %s\n",
1514                         ls->dentry_name, repo->url);
1515                 aborted = 1;
1516                 free(ref);
1517                 return;
1518         }
1519
1520         o = parse_object(ref->old_sha1);
1521         if (!o) {
1522                 fprintf(stderr,
1523                         "Unable to parse object %s for remote ref %s\n",
1524                         sha1_to_hex(ref->old_sha1), ls->dentry_name);
1525                 aborted = 1;
1526                 free(ref);
1527                 return;
1528         }
1529
1530         len = strlen(ls->dentry_name) + 42;
1531         ref_info = xcalloc(len + 1, 1);
1532         sprintf(ref_info, "%s   %s\n",
1533                 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1534         fwrite_buffer(ref_info, 1, len, buf);
1535         free(ref_info);
1536
1537         if (o->type == OBJ_TAG) {
1538                 o = deref_tag(o, ls->dentry_name, 0);
1539                 if (o) {
1540                         len = strlen(ls->dentry_name) + 45;
1541                         ref_info = xcalloc(len + 1, 1);
1542                         sprintf(ref_info, "%s   %s^{}\n",
1543                                 sha1_to_hex(o->sha1), ls->dentry_name);
1544                         fwrite_buffer(ref_info, 1, len, buf);
1545                         free(ref_info);
1546                 }
1547         }
1548         free(ref);
1549 }
1550
1551 static void update_remote_info_refs(struct remote_lock *lock)
1552 {
1553         struct buffer buffer = { STRBUF_INIT, 0 };
1554         struct active_request_slot *slot;
1555         struct slot_results results;
1556         struct curl_slist *dav_headers;
1557
1558         remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1559                   add_remote_info_ref, &buffer.buf);
1560         if (!aborted) {
1561                 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1562
1563                 slot = get_active_slot();
1564                 slot->results = &results;
1565                 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &buffer);
1566                 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, buffer.buf.len);
1567                 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1568 #ifndef NO_CURL_IOCTL
1569                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
1570                 curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, &buffer);
1571 #endif
1572                 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1573                 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1574                 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1575                 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1576                 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1577                 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1578
1579                 if (start_active_slot(slot)) {
1580                         run_active_slot(slot);
1581                         if (results.curl_result != CURLE_OK) {
1582                                 fprintf(stderr,
1583                                         "PUT error: curl result=%d, HTTP code=%ld\n",
1584                                         results.curl_result, results.http_code);
1585                         }
1586                 }
1587         }
1588         strbuf_release(&buffer.buf);
1589 }
1590
1591 static int remote_exists(const char *path)
1592 {
1593         char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1594         int ret;
1595
1596         sprintf(url, "%s%s", repo->url, path);
1597
1598         switch (http_get_strbuf(url, NULL, 0)) {
1599         case HTTP_OK:
1600                 ret = 1;
1601                 break;
1602         case HTTP_MISSING_TARGET:
1603                 ret = 0;
1604                 break;
1605         case HTTP_ERROR:
1606                 http_error(url, HTTP_ERROR);
1607         default:
1608                 ret = -1;
1609         }
1610         free(url);
1611         return ret;
1612 }
1613
1614 static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
1615 {
1616         char *url;
1617         struct strbuf buffer = STRBUF_INIT;
1618
1619         url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1620         sprintf(url, "%s%s", repo->url, path);
1621
1622         if (http_get_strbuf(url, &buffer, 0) != HTTP_OK)
1623                 die("Couldn't get %s for remote symref\n%s", url,
1624                     curl_errorstr);
1625         free(url);
1626
1627         free(*symref);
1628         *symref = NULL;
1629         hashclr(sha1);
1630
1631         if (buffer.len == 0)
1632                 return;
1633
1634         /* If it's a symref, set the refname; otherwise try for a sha1 */
1635         if (!prefixcmp((char *)buffer.buf, "ref: ")) {
1636                 *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
1637         } else {
1638                 get_sha1_hex(buffer.buf, sha1);
1639         }
1640
1641         strbuf_release(&buffer);
1642 }
1643
1644 static int verify_merge_base(unsigned char *head_sha1, unsigned char *branch_sha1)
1645 {
1646         struct commit *head = lookup_commit(head_sha1);
1647         struct commit *branch = lookup_commit(branch_sha1);
1648         struct commit_list *merge_bases = get_merge_bases(head, branch, 1);
1649
1650         return (merge_bases && !merge_bases->next && merge_bases->item == branch);
1651 }
1652
1653 static int delete_remote_branch(char *pattern, int force)
1654 {
1655         struct ref *refs = remote_refs;
1656         struct ref *remote_ref = NULL;
1657         unsigned char head_sha1[20];
1658         char *symref = NULL;
1659         int match;
1660         int patlen = strlen(pattern);
1661         int i;
1662         struct active_request_slot *slot;
1663         struct slot_results results;
1664         char *url;
1665
1666         /* Find the remote branch(es) matching the specified branch name */
1667         for (match = 0; refs; refs = refs->next) {
1668                 char *name = refs->name;
1669                 int namelen = strlen(name);
1670                 if (namelen < patlen ||
1671                     memcmp(name + namelen - patlen, pattern, patlen))
1672                         continue;
1673                 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1674                         continue;
1675                 match++;
1676                 remote_ref = refs;
1677         }
1678         if (match == 0)
1679                 return error("No remote branch matches %s", pattern);
1680         if (match != 1)
1681                 return error("More than one remote branch matches %s",
1682                              pattern);
1683
1684         /*
1685          * Remote HEAD must be a symref (not exactly foolproof; a remote
1686          * symlink to a symref will look like a symref)
1687          */
1688         fetch_symref("HEAD", &symref, head_sha1);
1689         if (!symref)
1690                 return error("Remote HEAD is not a symref");
1691
1692         /* Remote branch must not be the remote HEAD */
1693         for (i=0; symref && i<MAXDEPTH; i++) {
1694                 if (!strcmp(remote_ref->name, symref))
1695                         return error("Remote branch %s is the current HEAD",
1696                                      remote_ref->name);
1697                 fetch_symref(symref, &symref, head_sha1);
1698         }
1699
1700         /* Run extra sanity checks if delete is not forced */
1701         if (!force) {
1702                 /* Remote HEAD must resolve to a known object */
1703                 if (symref)
1704                         return error("Remote HEAD symrefs too deep");
1705                 if (is_null_sha1(head_sha1))
1706                         return error("Unable to resolve remote HEAD");
1707                 if (!has_sha1_file(head_sha1))
1708                         return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
1709
1710                 /* Remote branch must resolve to a known object */
1711                 if (is_null_sha1(remote_ref->old_sha1))
1712                         return error("Unable to resolve remote branch %s",
1713                                      remote_ref->name);
1714                 if (!has_sha1_file(remote_ref->old_sha1))
1715                         return error("Remote branch %s resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", remote_ref->name, sha1_to_hex(remote_ref->old_sha1));
1716
1717                 /* Remote branch must be an ancestor of remote HEAD */
1718                 if (!verify_merge_base(head_sha1, remote_ref->old_sha1)) {
1719                         return error("The branch '%s' is not an ancestor "
1720                                      "of your current HEAD.\n"
1721                                      "If you are sure you want to delete it,"
1722                                      " run:\n\t'git http-push -D %s %s'",
1723                                      remote_ref->name, repo->url, pattern);
1724                 }
1725         }
1726
1727         /* Send delete request */
1728         fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1729         if (dry_run)
1730                 return 0;
1731         url = xmalloc(strlen(repo->url) + strlen(remote_ref->name) + 1);
1732         sprintf(url, "%s%s", repo->url, remote_ref->name);
1733         slot = get_active_slot();
1734         slot->results = &results;
1735         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1736         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1737         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1738         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_DELETE);
1739         if (start_active_slot(slot)) {
1740                 run_active_slot(slot);
1741                 free(url);
1742                 if (results.curl_result != CURLE_OK)
1743                         return error("DELETE request failed (%d/%ld)\n",
1744                                      results.curl_result, results.http_code);
1745         } else {
1746                 free(url);
1747                 return error("Unable to start DELETE request");
1748         }
1749
1750         return 0;
1751 }
1752
1753 void run_request_queue(void)
1754 {
1755 #ifdef USE_CURL_MULTI
1756         is_running_queue = 1;
1757         fill_active_slots();
1758         add_fill_function(NULL, fill_active_slot);
1759 #endif
1760         do {
1761                 finish_all_active_slots();
1762 #ifdef USE_CURL_MULTI
1763                 fill_active_slots();
1764 #endif
1765         } while (request_queue_head && !aborted);
1766
1767 #ifdef USE_CURL_MULTI
1768         is_running_queue = 0;
1769 #endif
1770 }
1771
1772 int main(int argc, char **argv)
1773 {
1774         struct transfer_request *request;
1775         struct transfer_request *next_request;
1776         int nr_refspec = 0;
1777         char **refspec = NULL;
1778         struct remote_lock *ref_lock = NULL;
1779         struct remote_lock *info_ref_lock = NULL;
1780         struct rev_info revs;
1781         int delete_branch = 0;
1782         int force_delete = 0;
1783         int objects_to_send;
1784         int rc = 0;
1785         int i;
1786         int new_refs;
1787         struct ref *ref, *local_refs;
1788         struct remote *remote;
1789         char *rewritten_url = NULL;
1790
1791         git_extract_argv0_path(argv[0]);
1792
1793         setup_git_directory();
1794
1795         repo = xcalloc(sizeof(*repo), 1);
1796
1797         argv++;
1798         for (i = 1; i < argc; i++, argv++) {
1799                 char *arg = *argv;
1800
1801                 if (*arg == '-') {
1802                         if (!strcmp(arg, "--all")) {
1803                                 push_all = MATCH_REFS_ALL;
1804                                 continue;
1805                         }
1806                         if (!strcmp(arg, "--force")) {
1807                                 force_all = 1;
1808                                 continue;
1809                         }
1810                         if (!strcmp(arg, "--dry-run")) {
1811                                 dry_run = 1;
1812                                 continue;
1813                         }
1814                         if (!strcmp(arg, "--verbose")) {
1815                                 push_verbosely = 1;
1816                                 http_is_verbose = 1;
1817                                 continue;
1818                         }
1819                         if (!strcmp(arg, "-d")) {
1820                                 delete_branch = 1;
1821                                 continue;
1822                         }
1823                         if (!strcmp(arg, "-D")) {
1824                                 delete_branch = 1;
1825                                 force_delete = 1;
1826                                 continue;
1827                         }
1828                 }
1829                 if (!repo->url) {
1830                         char *path = strstr(arg, "//");
1831                         repo->url = arg;
1832                         repo->path_len = strlen(arg);
1833                         if (path) {
1834                                 repo->path = strchr(path+2, '/');
1835                                 if (repo->path)
1836                                         repo->path_len = strlen(repo->path);
1837                         }
1838                         continue;
1839                 }
1840                 refspec = argv;
1841                 nr_refspec = argc - i;
1842                 break;
1843         }
1844
1845 #ifndef USE_CURL_MULTI
1846         die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
1847 #endif
1848
1849         if (!repo->url)
1850                 usage(http_push_usage);
1851
1852         if (delete_branch && nr_refspec != 1)
1853                 die("You must specify only one branch name when deleting a remote branch");
1854
1855         memset(remote_dir_exists, -1, 256);
1856
1857         /*
1858          * Create a minimum remote by hand to give to http_init(),
1859          * primarily to allow it to look at the URL.
1860          */
1861         remote = xcalloc(sizeof(*remote), 1);
1862         ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
1863         remote->url[remote->url_nr++] = repo->url;
1864         http_init(remote);
1865
1866         if (repo->url && repo->url[strlen(repo->url)-1] != '/') {
1867                 rewritten_url = xmalloc(strlen(repo->url)+2);
1868                 strcpy(rewritten_url, repo->url);
1869                 strcat(rewritten_url, "/");
1870                 repo->path = rewritten_url + (repo->path - repo->url);
1871                 repo->path_len++;
1872                 repo->url = rewritten_url;
1873         }
1874
1875 #ifdef USE_CURL_MULTI
1876         is_running_queue = 0;
1877 #endif
1878
1879         /* Verify DAV compliance/lock support */
1880         if (!locking_available()) {
1881                 rc = 1;
1882                 goto cleanup;
1883         }
1884
1885         sigchain_push_common(remove_locks_on_signal);
1886
1887         /* Check whether the remote has server info files */
1888         repo->can_update_info_refs = 0;
1889         repo->has_info_refs = remote_exists("info/refs");
1890         repo->has_info_packs = remote_exists("objects/info/packs");
1891         if (repo->has_info_refs) {
1892                 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1893                 if (info_ref_lock)
1894                         repo->can_update_info_refs = 1;
1895                 else {
1896                         error("cannot lock existing info/refs");
1897                         rc = 1;
1898                         goto cleanup;
1899                 }
1900         }
1901         if (repo->has_info_packs)
1902                 fetch_indices();
1903
1904         /* Get a list of all local and remote heads to validate refspecs */
1905         local_refs = get_local_heads();
1906         fprintf(stderr, "Fetching remote heads...\n");
1907         get_dav_remote_heads();
1908         run_request_queue();
1909
1910         /* Remove a remote branch if -d or -D was specified */
1911         if (delete_branch) {
1912                 if (delete_remote_branch(refspec[0], force_delete) == -1)
1913                         fprintf(stderr, "Unable to delete remote branch %s\n",
1914                                 refspec[0]);
1915                 goto cleanup;
1916         }
1917
1918         /* match them up */
1919         if (match_refs(local_refs, &remote_refs,
1920                        nr_refspec, (const char **) refspec, push_all)) {
1921                 rc = -1;
1922                 goto cleanup;
1923         }
1924         if (!remote_refs) {
1925                 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1926                 rc = 0;
1927                 goto cleanup;
1928         }
1929
1930         new_refs = 0;
1931         for (ref = remote_refs; ref; ref = ref->next) {
1932                 char old_hex[60], *new_hex;
1933                 const char *commit_argv[5];
1934                 int commit_argc;
1935                 char *new_sha1_hex, *old_sha1_hex;
1936
1937                 if (!ref->peer_ref)
1938                         continue;
1939
1940                 if (is_null_sha1(ref->peer_ref->new_sha1)) {
1941                         if (delete_remote_branch(ref->name, 1) == -1) {
1942                                 error("Could not remove %s", ref->name);
1943                                 rc = -4;
1944                         }
1945                         new_refs++;
1946                         continue;
1947                 }
1948
1949                 if (!hashcmp(ref->old_sha1, ref->peer_ref->new_sha1)) {
1950                         if (push_verbosely || 1)
1951                                 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1952                         continue;
1953                 }
1954
1955                 if (!force_all &&
1956                     !is_null_sha1(ref->old_sha1) &&
1957                     !ref->force) {
1958                         if (!has_sha1_file(ref->old_sha1) ||
1959                             !ref_newer(ref->peer_ref->new_sha1,
1960                                        ref->old_sha1)) {
1961                                 /*
1962                                  * We do not have the remote ref, or
1963                                  * we know that the remote ref is not
1964                                  * an ancestor of what we are trying to
1965                                  * push.  Either way this can be losing
1966                                  * commits at the remote end and likely
1967                                  * we were not up to date to begin with.
1968                                  */
1969                                 error("remote '%s' is not an ancestor of\n"
1970                                       "local '%s'.\n"
1971                                       "Maybe you are not up-to-date and "
1972                                       "need to pull first?",
1973                                       ref->name,
1974                                       ref->peer_ref->name);
1975                                 rc = -2;
1976                                 continue;
1977                         }
1978                 }
1979                 hashcpy(ref->new_sha1, ref->peer_ref->new_sha1);
1980                 new_refs++;
1981                 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
1982                 new_hex = sha1_to_hex(ref->new_sha1);
1983
1984                 fprintf(stderr, "updating '%s'", ref->name);
1985                 if (strcmp(ref->name, ref->peer_ref->name))
1986                         fprintf(stderr, " using '%s'", ref->peer_ref->name);
1987                 fprintf(stderr, "\n  from %s\n  to   %s\n", old_hex, new_hex);
1988                 if (dry_run)
1989                         continue;
1990
1991                 /* Lock remote branch ref */
1992                 ref_lock = lock_remote(ref->name, LOCK_TIME);
1993                 if (ref_lock == NULL) {
1994                         fprintf(stderr, "Unable to lock remote branch %s\n",
1995                                 ref->name);
1996                         rc = 1;
1997                         continue;
1998                 }
1999
2000                 /* Set up revision info for this refspec */
2001                 commit_argc = 3;
2002                 new_sha1_hex = xstrdup(sha1_to_hex(ref->new_sha1));
2003                 old_sha1_hex = NULL;
2004                 commit_argv[1] = "--objects";
2005                 commit_argv[2] = new_sha1_hex;
2006                 if (!push_all && !is_null_sha1(ref->old_sha1)) {
2007                         old_sha1_hex = xmalloc(42);
2008                         sprintf(old_sha1_hex, "^%s",
2009                                 sha1_to_hex(ref->old_sha1));
2010                         commit_argv[3] = old_sha1_hex;
2011                         commit_argc++;
2012                 }
2013                 commit_argv[commit_argc] = NULL;
2014                 init_revisions(&revs, setup_git_directory());
2015                 setup_revisions(commit_argc, commit_argv, &revs, NULL);
2016                 revs.edge_hint = 0; /* just in case */
2017                 free(new_sha1_hex);
2018                 if (old_sha1_hex) {
2019                         free(old_sha1_hex);
2020                         commit_argv[1] = NULL;
2021                 }
2022
2023                 /* Generate a list of objects that need to be pushed */
2024                 pushing = 0;
2025                 if (prepare_revision_walk(&revs))
2026                         die("revision walk setup failed");
2027                 mark_edges_uninteresting(revs.commits, &revs, NULL);
2028                 objects_to_send = get_delta(&revs, ref_lock);
2029                 finish_all_active_slots();
2030
2031                 /* Push missing objects to remote, this would be a
2032                    convenient time to pack them first if appropriate. */
2033                 pushing = 1;
2034                 if (objects_to_send)
2035                         fprintf(stderr, "    sending %d objects\n",
2036                                 objects_to_send);
2037
2038                 run_request_queue();
2039
2040                 /* Update the remote branch if all went well */
2041                 if (aborted || !update_remote(ref->new_sha1, ref_lock))
2042                         rc = 1;
2043
2044                 if (!rc)
2045                         fprintf(stderr, "    done\n");
2046                 unlock_remote(ref_lock);
2047                 check_locks();
2048         }
2049
2050         /* Update remote server info if appropriate */
2051         if (repo->has_info_refs && new_refs) {
2052                 if (info_ref_lock && repo->can_update_info_refs) {
2053                         fprintf(stderr, "Updating remote server info\n");
2054                         if (!dry_run)
2055                                 update_remote_info_refs(info_ref_lock);
2056                 } else {
2057                         fprintf(stderr, "Unable to update server info\n");
2058                 }
2059         }
2060
2061  cleanup:
2062         free(rewritten_url);
2063         if (info_ref_lock)
2064                 unlock_remote(info_ref_lock);
2065         free(repo);
2066
2067         http_cleanup();
2068
2069         request = request_queue_head;
2070         while (request != NULL) {
2071                 next_request = request->next;
2072                 release_request(request);
2073                 request = next_request;
2074         }
2075
2076         return rc;
2077 }