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