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