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