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