The eighth batch
[git.git] / http-push.c
blob43da1c7cd33b402ea77e3ce79e496f670ffdcc3b
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "environment.h"
5 #include "hex.h"
6 #include "repository.h"
7 #include "commit.h"
8 #include "tag.h"
9 #include "blob.h"
10 #include "http.h"
11 #include "diff.h"
12 #include "revision.h"
13 #include "remote.h"
14 #include "list-objects.h"
15 #include "setup.h"
16 #include "sigchain.h"
17 #include "strvec.h"
18 #include "tree.h"
19 #include "tree-walk.h"
20 #include "url.h"
21 #include "packfile.h"
22 #include "object-store-ll.h"
23 #include "commit-reach.h"
25 #ifdef EXPAT_NEEDS_XMLPARSE_H
26 #include <xmlparse.h>
27 #else
28 #include <expat.h>
29 #endif
31 static const char http_push_usage[] =
32 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
34 #ifndef XML_STATUS_OK
35 enum XML_Status {
36 XML_STATUS_OK = 1,
37 XML_STATUS_ERROR = 0
39 #define XML_STATUS_OK 1
40 #define XML_STATUS_ERROR 0
41 #endif
43 #define PREV_BUF_SIZE 4096
45 /* DAV methods */
46 #define DAV_LOCK "LOCK"
47 #define DAV_MKCOL "MKCOL"
48 #define DAV_MOVE "MOVE"
49 #define DAV_PROPFIND "PROPFIND"
50 #define DAV_PUT "PUT"
51 #define DAV_UNLOCK "UNLOCK"
52 #define DAV_DELETE "DELETE"
54 /* DAV lock flags */
55 #define DAV_PROP_LOCKWR (1u << 0)
56 #define DAV_PROP_LOCKEX (1u << 1)
57 #define DAV_LOCK_OK (1u << 2)
59 /* DAV XML properties */
60 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
61 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
62 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
63 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
64 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
65 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
66 #define DAV_PROPFIND_RESP ".multistatus.response"
67 #define DAV_PROPFIND_NAME ".multistatus.response.href"
68 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
70 /* DAV request body templates */
71 #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>"
72 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
73 #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>"
75 #define LOCK_TIME 600
76 #define LOCK_REFRESH 30
78 /* Remember to update object flag allocation in object.h */
79 #define LOCAL (1u<<11)
80 #define REMOTE (1u<<12)
81 #define FETCHING (1u<<13)
82 #define PUSHING (1u<<14)
84 /* We allow "recursive" symbolic refs. Only within reason, though */
85 #define MAXDEPTH 5
87 static int pushing;
88 static int aborted;
89 static signed char remote_dir_exists[256];
91 static int push_verbosely;
92 static int push_all = MATCH_REFS_NONE;
93 static int force_all;
94 static int dry_run;
95 static int helper_status;
97 static struct object_list *objects;
99 struct repo {
100 char *url;
101 char *path;
102 int path_len;
103 int has_info_refs;
104 int can_update_info_refs;
105 int has_info_packs;
106 struct packed_git *packs;
107 struct remote_lock *locks;
110 static struct repo *repo;
112 enum transfer_state {
113 NEED_FETCH,
114 RUN_FETCH_LOOSE,
115 RUN_FETCH_PACKED,
116 NEED_PUSH,
117 RUN_MKCOL,
118 RUN_PUT,
119 RUN_MOVE,
120 ABORTED,
121 COMPLETE
124 struct transfer_request {
125 struct object *obj;
126 struct packed_git *target;
127 char *url;
128 char *dest;
129 struct remote_lock *lock;
130 struct curl_slist *headers;
131 struct buffer buffer;
132 enum transfer_state state;
133 CURLcode curl_result;
134 char errorstr[CURL_ERROR_SIZE];
135 long http_code;
136 void *userData;
137 struct active_request_slot *slot;
138 struct transfer_request *next;
141 static struct transfer_request *request_queue_head;
143 struct xml_ctx {
144 char *name;
145 int len;
146 char *cdata;
147 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
148 void *userData;
151 struct remote_lock {
152 char *url;
153 char *owner;
154 char *token;
155 char tmpfile_suffix[GIT_MAX_HEXSZ + 1];
156 time_t start_time;
157 long timeout;
158 int refreshing;
159 struct remote_lock *next;
162 /* Flags that control remote_ls processing */
163 #define PROCESS_FILES (1u << 0)
164 #define PROCESS_DIRS (1u << 1)
165 #define RECURSIVE (1u << 2)
167 /* Flags that remote_ls passes to callback functions */
168 #define IS_DIR (1u << 0)
170 struct remote_ls_ctx {
171 char *path;
172 void (*userFunc)(struct remote_ls_ctx *ls);
173 void *userData;
174 int flags;
175 char *dentry_name;
176 int dentry_flags;
177 struct remote_ls_ctx *parent;
180 /* get_dav_token_headers options */
181 enum dav_header_flag {
182 DAV_HEADER_IF = (1u << 0),
183 DAV_HEADER_LOCK = (1u << 1),
184 DAV_HEADER_TIMEOUT = (1u << 2)
187 static char *xml_entities(const char *s)
189 struct strbuf buf = STRBUF_INIT;
190 strbuf_addstr_xml_quoted(&buf, s);
191 return strbuf_detach(&buf, NULL);
194 static void curl_setup_http_get(CURL *curl, const char *url,
195 const char *custom_req)
197 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
198 curl_easy_setopt(curl, CURLOPT_URL, url);
199 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
200 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
203 static void curl_setup_http(CURL *curl, const char *url,
204 const char *custom_req, struct buffer *buffer,
205 curl_write_callback write_fn)
207 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
208 curl_easy_setopt(curl, CURLOPT_URL, url);
209 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
210 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
211 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
212 curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, seek_buffer);
213 curl_easy_setopt(curl, CURLOPT_SEEKDATA, buffer);
214 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
215 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
216 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
217 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
220 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
222 struct strbuf buf = STRBUF_INIT;
223 struct curl_slist *dav_headers = http_copy_default_headers();
225 if (options & DAV_HEADER_IF) {
226 strbuf_addf(&buf, "If: (<%s>)", lock->token);
227 dav_headers = curl_slist_append(dav_headers, buf.buf);
228 strbuf_reset(&buf);
230 if (options & DAV_HEADER_LOCK) {
231 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
232 dav_headers = curl_slist_append(dav_headers, buf.buf);
233 strbuf_reset(&buf);
235 if (options & DAV_HEADER_TIMEOUT) {
236 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
237 dav_headers = curl_slist_append(dav_headers, buf.buf);
238 strbuf_reset(&buf);
240 strbuf_release(&buf);
242 return dav_headers;
245 static void finish_request(struct transfer_request *request);
246 static void release_request(struct transfer_request *request);
248 static void process_response(void *callback_data)
250 struct transfer_request *request =
251 (struct transfer_request *)callback_data;
253 finish_request(request);
256 static void start_fetch_loose(struct transfer_request *request)
258 struct active_request_slot *slot;
259 struct http_object_request *obj_req;
261 obj_req = new_http_object_request(repo->url, &request->obj->oid);
262 if (!obj_req) {
263 request->state = ABORTED;
264 return;
267 slot = obj_req->slot;
268 slot->callback_func = process_response;
269 slot->callback_data = request;
270 request->slot = slot;
271 request->userData = obj_req;
273 /* Try to get the request started, abort the request on error */
274 request->state = RUN_FETCH_LOOSE;
275 if (!start_active_slot(slot)) {
276 fprintf(stderr, "Unable to start GET request\n");
277 repo->can_update_info_refs = 0;
278 release_http_object_request(&obj_req);
279 release_request(request);
283 static void start_mkcol(struct transfer_request *request)
285 char *hex = oid_to_hex(&request->obj->oid);
286 struct active_request_slot *slot;
288 request->url = get_remote_object_url(repo->url, hex, 1);
290 slot = get_active_slot();
291 slot->callback_func = process_response;
292 slot->callback_data = request;
293 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
294 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
296 if (start_active_slot(slot)) {
297 request->slot = slot;
298 request->state = RUN_MKCOL;
299 } else {
300 request->state = ABORTED;
301 FREE_AND_NULL(request->url);
305 static void start_fetch_packed(struct transfer_request *request)
307 struct packed_git *target;
309 struct transfer_request *check_request = request_queue_head;
310 struct http_pack_request *preq;
312 target = find_oid_pack(&request->obj->oid, repo->packs);
313 if (!target) {
314 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", oid_to_hex(&request->obj->oid));
315 repo->can_update_info_refs = 0;
316 release_request(request);
317 return;
319 close_pack_index(target);
320 request->target = target;
322 fprintf(stderr, "Fetching pack %s\n",
323 hash_to_hex(target->hash));
324 fprintf(stderr, " which contains %s\n", oid_to_hex(&request->obj->oid));
326 preq = new_http_pack_request(target->hash, repo->url);
327 if (!preq) {
328 repo->can_update_info_refs = 0;
329 return;
332 /* Make sure there isn't another open request for this pack */
333 while (check_request) {
334 if (check_request->state == RUN_FETCH_PACKED &&
335 !strcmp(check_request->url, preq->url)) {
336 release_http_pack_request(preq);
337 release_request(request);
338 return;
340 check_request = check_request->next;
343 preq->slot->callback_func = process_response;
344 preq->slot->callback_data = request;
345 request->slot = preq->slot;
346 request->userData = preq;
348 /* Try to get the request started, abort the request on error */
349 request->state = RUN_FETCH_PACKED;
350 if (!start_active_slot(preq->slot)) {
351 fprintf(stderr, "Unable to start GET request\n");
352 release_http_pack_request(preq);
353 repo->can_update_info_refs = 0;
354 release_request(request);
358 static void start_put(struct transfer_request *request)
360 char *hex = oid_to_hex(&request->obj->oid);
361 struct active_request_slot *slot;
362 struct strbuf buf = STRBUF_INIT;
363 enum object_type type;
364 char hdr[50];
365 void *unpacked;
366 unsigned long len;
367 int hdrlen;
368 ssize_t size;
369 git_zstream stream;
371 unpacked = repo_read_object_file(the_repository, &request->obj->oid,
372 &type, &len);
373 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
375 /* Set it up */
376 git_deflate_init(&stream, zlib_compression_level);
377 size = git_deflate_bound(&stream, len + hdrlen);
378 strbuf_grow(&request->buffer.buf, size);
379 request->buffer.posn = 0;
381 /* Compress it */
382 stream.next_out = (unsigned char *)request->buffer.buf.buf;
383 stream.avail_out = size;
385 /* First header.. */
386 stream.next_in = (void *)hdr;
387 stream.avail_in = hdrlen;
388 while (git_deflate(&stream, 0) == Z_OK)
389 ; /* nothing */
391 /* Then the data itself.. */
392 stream.next_in = unpacked;
393 stream.avail_in = len;
394 while (git_deflate(&stream, Z_FINISH) == Z_OK)
395 ; /* nothing */
396 git_deflate_end(&stream);
397 free(unpacked);
399 request->buffer.buf.len = stream.total_out;
401 strbuf_addstr(&buf, "Destination: ");
402 append_remote_object_url(&buf, repo->url, hex, 0);
403 request->dest = strbuf_detach(&buf, NULL);
405 append_remote_object_url(&buf, repo->url, hex, 0);
406 strbuf_add(&buf, request->lock->tmpfile_suffix, the_hash_algo->hexsz + 1);
407 request->url = strbuf_detach(&buf, NULL);
409 slot = get_active_slot();
410 slot->callback_func = process_response;
411 slot->callback_data = request;
412 curl_setup_http(slot->curl, request->url, DAV_PUT,
413 &request->buffer, fwrite_null);
415 if (start_active_slot(slot)) {
416 request->slot = slot;
417 request->state = RUN_PUT;
418 } else {
419 request->state = ABORTED;
420 FREE_AND_NULL(request->url);
424 static void start_move(struct transfer_request *request)
426 struct active_request_slot *slot;
427 struct curl_slist *dav_headers = http_copy_default_headers();
429 slot = get_active_slot();
430 slot->callback_func = process_response;
431 slot->callback_data = request;
432 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
433 dav_headers = curl_slist_append(dav_headers, request->dest);
434 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
435 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
437 if (start_active_slot(slot)) {
438 request->slot = slot;
439 request->state = RUN_MOVE;
440 request->headers = dav_headers;
441 } else {
442 request->state = ABORTED;
443 FREE_AND_NULL(request->url);
444 curl_slist_free_all(dav_headers);
448 static int refresh_lock(struct remote_lock *lock)
450 struct active_request_slot *slot;
451 struct slot_results results;
452 struct curl_slist *dav_headers;
453 int rc = 0;
455 lock->refreshing = 1;
457 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
459 slot = get_active_slot();
460 slot->results = &results;
461 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
462 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
464 if (start_active_slot(slot)) {
465 run_active_slot(slot);
466 if (results.curl_result != CURLE_OK) {
467 fprintf(stderr, "LOCK HTTP error %ld\n",
468 results.http_code);
469 } else {
470 lock->start_time = time(NULL);
471 rc = 1;
475 lock->refreshing = 0;
476 curl_slist_free_all(dav_headers);
478 return rc;
481 static void check_locks(void)
483 struct remote_lock *lock = repo->locks;
484 time_t current_time = time(NULL);
485 int time_remaining;
487 while (lock) {
488 time_remaining = lock->start_time + lock->timeout -
489 current_time;
490 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
491 if (!refresh_lock(lock)) {
492 fprintf(stderr,
493 "Unable to refresh lock for %s\n",
494 lock->url);
495 aborted = 1;
496 return;
499 lock = lock->next;
503 static void release_request(struct transfer_request *request)
505 struct transfer_request *entry = request_queue_head;
507 if (request == request_queue_head) {
508 request_queue_head = request->next;
509 } else {
510 while (entry && entry->next != request)
511 entry = entry->next;
512 if (entry)
513 entry->next = request->next;
516 free(request->url);
517 free(request->dest);
518 strbuf_release(&request->buffer.buf);
519 free(request);
522 static void finish_request(struct transfer_request *request)
524 struct http_pack_request *preq;
525 struct http_object_request *obj_req;
527 request->curl_result = request->slot->curl_result;
528 request->http_code = request->slot->http_code;
529 request->slot = NULL;
531 /* Keep locks active */
532 check_locks();
534 if (request->headers)
535 curl_slist_free_all(request->headers);
537 /* URL is reused for MOVE after PUT and used during FETCH */
538 if (request->state != RUN_PUT && request->state != RUN_FETCH_PACKED) {
539 FREE_AND_NULL(request->url);
542 if (request->state == RUN_MKCOL) {
543 if (request->curl_result == CURLE_OK ||
544 request->http_code == 405) {
545 remote_dir_exists[request->obj->oid.hash[0]] = 1;
546 start_put(request);
547 } else {
548 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
549 oid_to_hex(&request->obj->oid),
550 request->curl_result, request->http_code);
551 request->state = ABORTED;
552 aborted = 1;
554 } else if (request->state == RUN_PUT) {
555 if (request->curl_result == CURLE_OK) {
556 start_move(request);
557 } else {
558 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
559 oid_to_hex(&request->obj->oid),
560 request->curl_result, request->http_code);
561 request->state = ABORTED;
562 aborted = 1;
564 } else if (request->state == RUN_MOVE) {
565 if (request->curl_result == CURLE_OK) {
566 if (push_verbosely)
567 fprintf(stderr, " sent %s\n",
568 oid_to_hex(&request->obj->oid));
569 request->obj->flags |= REMOTE;
570 release_request(request);
571 } else {
572 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
573 oid_to_hex(&request->obj->oid),
574 request->curl_result, request->http_code);
575 request->state = ABORTED;
576 aborted = 1;
578 } else if (request->state == RUN_FETCH_LOOSE) {
579 obj_req = (struct http_object_request *)request->userData;
581 if (finish_http_object_request(obj_req) == 0)
582 if (obj_req->rename == 0)
583 request->obj->flags |= (LOCAL | REMOTE);
585 release_http_object_request(&obj_req);
587 /* Try fetching packed if necessary */
588 if (request->obj->flags & LOCAL) {
589 release_request(request);
590 } else
591 start_fetch_packed(request);
593 } else if (request->state == RUN_FETCH_PACKED) {
594 int fail = 1;
595 if (request->curl_result != CURLE_OK) {
596 fprintf(stderr, "Unable to get pack file %s\n%s",
597 request->url, curl_errorstr);
598 } else {
599 preq = (struct http_pack_request *)request->userData;
601 if (preq) {
602 if (finish_http_pack_request(preq) == 0)
603 fail = 0;
604 release_http_pack_request(preq);
607 if (fail)
608 repo->can_update_info_refs = 0;
609 else
610 http_install_packfile(request->target, &repo->packs);
611 release_request(request);
615 static int is_running_queue;
616 static int fill_active_slot(void *data UNUSED)
618 struct transfer_request *request;
620 if (aborted || !is_running_queue)
621 return 0;
623 for (request = request_queue_head; request; request = request->next) {
624 if (request->state == NEED_FETCH) {
625 start_fetch_loose(request);
626 return 1;
627 } else if (pushing && request->state == NEED_PUSH) {
628 if (remote_dir_exists[request->obj->oid.hash[0]] == 1) {
629 start_put(request);
630 } else {
631 start_mkcol(request);
633 return 1;
636 return 0;
639 static void get_remote_object_list(unsigned char parent);
641 static void add_fetch_request(struct object *obj)
643 struct transfer_request *request;
645 check_locks();
648 * Don't fetch the object if it's known to exist locally
649 * or is already in the request queue
651 if (remote_dir_exists[obj->oid.hash[0]] == -1)
652 get_remote_object_list(obj->oid.hash[0]);
653 if (obj->flags & (LOCAL | FETCHING))
654 return;
656 obj->flags |= FETCHING;
657 CALLOC_ARRAY(request, 1);
658 request->obj = obj;
659 request->state = NEED_FETCH;
660 strbuf_init(&request->buffer.buf, 0);
661 request->next = request_queue_head;
662 request_queue_head = request;
664 fill_active_slots();
665 step_active_slots();
668 static int add_send_request(struct object *obj, struct remote_lock *lock)
670 struct transfer_request *request;
671 struct packed_git *target;
673 /* Keep locks active */
674 check_locks();
677 * Don't push the object if it's known to exist on the remote
678 * or is already in the request queue
680 if (remote_dir_exists[obj->oid.hash[0]] == -1)
681 get_remote_object_list(obj->oid.hash[0]);
682 if (obj->flags & (REMOTE | PUSHING))
683 return 0;
684 target = find_oid_pack(&obj->oid, repo->packs);
685 if (target) {
686 obj->flags |= REMOTE;
687 return 0;
690 obj->flags |= PUSHING;
691 CALLOC_ARRAY(request, 1);
692 request->obj = obj;
693 request->lock = lock;
694 request->state = NEED_PUSH;
695 strbuf_init(&request->buffer.buf, 0);
696 request->next = request_queue_head;
697 request_queue_head = request;
699 fill_active_slots();
700 step_active_slots();
702 return 1;
705 static int fetch_indices(void)
707 int ret;
709 if (push_verbosely)
710 fprintf(stderr, "Getting pack list\n");
712 switch (http_get_info_packs(repo->url, &repo->packs)) {
713 case HTTP_OK:
714 case HTTP_MISSING_TARGET:
715 ret = 0;
716 break;
717 default:
718 ret = -1;
721 return ret;
724 static void one_remote_object(const struct object_id *oid)
726 struct object *obj;
728 obj = lookup_object(the_repository, oid);
729 if (!obj)
730 obj = parse_object(the_repository, oid);
732 /* Ignore remote objects that don't exist locally */
733 if (!obj)
734 return;
736 obj->flags |= REMOTE;
737 if (!object_list_contains(objects, obj))
738 object_list_insert(obj, &objects);
741 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
743 int *lock_flags = (int *)ctx->userData;
745 if (tag_closed) {
746 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
747 if ((*lock_flags & DAV_PROP_LOCKEX) &&
748 (*lock_flags & DAV_PROP_LOCKWR)) {
749 *lock_flags |= DAV_LOCK_OK;
751 *lock_flags &= DAV_LOCK_OK;
752 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
753 *lock_flags |= DAV_PROP_LOCKWR;
754 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
755 *lock_flags |= DAV_PROP_LOCKEX;
760 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
762 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
763 git_hash_ctx hash_ctx;
764 unsigned char lock_token_hash[GIT_MAX_RAWSZ];
766 if (tag_closed && ctx->cdata) {
767 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
768 lock->owner = xstrdup(ctx->cdata);
769 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
770 const char *arg;
771 if (skip_prefix(ctx->cdata, "Second-", &arg))
772 lock->timeout = strtol(arg, NULL, 10);
773 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
774 lock->token = xstrdup(ctx->cdata);
776 the_hash_algo->init_fn(&hash_ctx);
777 the_hash_algo->update_fn(&hash_ctx, lock->token, strlen(lock->token));
778 the_hash_algo->final_fn(lock_token_hash, &hash_ctx);
780 lock->tmpfile_suffix[0] = '_';
781 memcpy(lock->tmpfile_suffix + 1, hash_to_hex(lock_token_hash), the_hash_algo->hexsz);
786 static void one_remote_ref(const char *refname);
788 static void
789 xml_start_tag(void *userData, const char *name, const char **atts UNUSED)
791 struct xml_ctx *ctx = (struct xml_ctx *)userData;
792 const char *c = strchr(name, ':');
793 int old_namelen, new_len;
795 if (!c)
796 c = name;
797 else
798 c++;
800 old_namelen = strlen(ctx->name);
801 new_len = old_namelen + strlen(c) + 2;
803 if (new_len > ctx->len) {
804 ctx->name = xrealloc(ctx->name, new_len);
805 ctx->len = new_len;
807 xsnprintf(ctx->name + old_namelen, ctx->len - old_namelen, ".%s", c);
809 FREE_AND_NULL(ctx->cdata);
811 ctx->userFunc(ctx, 0);
814 static void
815 xml_end_tag(void *userData, const char *name)
817 struct xml_ctx *ctx = (struct xml_ctx *)userData;
818 const char *c = strchr(name, ':');
819 char *ep;
821 ctx->userFunc(ctx, 1);
823 if (!c)
824 c = name;
825 else
826 c++;
828 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
829 *ep = 0;
832 static void
833 xml_cdata(void *userData, const XML_Char *s, int len)
835 struct xml_ctx *ctx = (struct xml_ctx *)userData;
836 free(ctx->cdata);
837 ctx->cdata = xmemdupz(s, len);
840 static struct remote_lock *lock_remote(const char *path, long timeout)
842 struct active_request_slot *slot;
843 struct slot_results results;
844 struct buffer out_buffer = { STRBUF_INIT, 0 };
845 struct strbuf in_buffer = STRBUF_INIT;
846 char *url;
847 char *ep;
848 char timeout_header[25];
849 struct remote_lock *lock = NULL;
850 struct curl_slist *dav_headers = http_copy_default_headers();
851 struct xml_ctx ctx;
852 char *escaped;
854 url = xstrfmt("%s%s", repo->url, path);
856 /* Make sure leading directories exist for the remote ref */
857 ep = strchr(url + strlen(repo->url) + 1, '/');
858 while (ep) {
859 char saved_character = ep[1];
860 ep[1] = '\0';
861 slot = get_active_slot();
862 slot->results = &results;
863 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
864 if (start_active_slot(slot)) {
865 run_active_slot(slot);
866 if (results.curl_result != CURLE_OK &&
867 results.http_code != 405) {
868 fprintf(stderr,
869 "Unable to create branch path %s\n",
870 url);
871 free(url);
872 return NULL;
874 } else {
875 fprintf(stderr, "Unable to start MKCOL request\n");
876 free(url);
877 return NULL;
879 ep[1] = saved_character;
880 ep = strchr(ep + 1, '/');
883 escaped = xml_entities(ident_default_email());
884 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
885 free(escaped);
887 xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout);
888 dav_headers = curl_slist_append(dav_headers, timeout_header);
889 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
891 slot = get_active_slot();
892 slot->results = &results;
893 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
894 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
895 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
897 CALLOC_ARRAY(lock, 1);
898 lock->timeout = -1;
900 if (start_active_slot(slot)) {
901 run_active_slot(slot);
902 if (results.curl_result == CURLE_OK) {
903 XML_Parser parser = XML_ParserCreate(NULL);
904 enum XML_Status result;
905 ctx.name = xcalloc(10, 1);
906 ctx.len = 0;
907 ctx.cdata = NULL;
908 ctx.userFunc = handle_new_lock_ctx;
909 ctx.userData = lock;
910 XML_SetUserData(parser, &ctx);
911 XML_SetElementHandler(parser, xml_start_tag,
912 xml_end_tag);
913 XML_SetCharacterDataHandler(parser, xml_cdata);
914 result = XML_Parse(parser, in_buffer.buf,
915 in_buffer.len, 1);
916 free(ctx.name);
917 free(ctx.cdata);
918 if (result != XML_STATUS_OK) {
919 fprintf(stderr, "XML error: %s\n",
920 XML_ErrorString(
921 XML_GetErrorCode(parser)));
922 lock->timeout = -1;
924 XML_ParserFree(parser);
925 } else {
926 fprintf(stderr,
927 "error: curl result=%d, HTTP code=%ld\n",
928 results.curl_result, results.http_code);
930 } else {
931 fprintf(stderr, "Unable to start LOCK request\n");
934 curl_slist_free_all(dav_headers);
935 strbuf_release(&out_buffer.buf);
936 strbuf_release(&in_buffer);
938 if (lock->token == NULL || lock->timeout <= 0) {
939 free(lock->token);
940 free(lock->owner);
941 free(url);
942 FREE_AND_NULL(lock);
943 } else {
944 lock->url = url;
945 lock->start_time = time(NULL);
946 lock->next = repo->locks;
947 repo->locks = lock;
950 return lock;
953 static int unlock_remote(struct remote_lock *lock)
955 struct active_request_slot *slot;
956 struct slot_results results;
957 struct remote_lock *prev = repo->locks;
958 struct curl_slist *dav_headers;
959 int rc = 0;
961 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
963 slot = get_active_slot();
964 slot->results = &results;
965 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
966 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
968 if (start_active_slot(slot)) {
969 run_active_slot(slot);
970 if (results.curl_result == CURLE_OK)
971 rc = 1;
972 else
973 fprintf(stderr, "UNLOCK HTTP error %ld\n",
974 results.http_code);
975 } else {
976 fprintf(stderr, "Unable to start UNLOCK request\n");
979 curl_slist_free_all(dav_headers);
981 if (repo->locks == lock) {
982 repo->locks = lock->next;
983 } else {
984 while (prev && prev->next != lock)
985 prev = prev->next;
986 if (prev)
987 prev->next = lock->next;
990 free(lock->owner);
991 free(lock->url);
992 free(lock->token);
993 free(lock);
995 return rc;
998 static void remove_locks(void)
1000 struct remote_lock *lock = repo->locks;
1002 fprintf(stderr, "Removing remote locks...\n");
1003 while (lock) {
1004 struct remote_lock *next = lock->next;
1005 unlock_remote(lock);
1006 lock = next;
1010 static void remove_locks_on_signal(int signo)
1012 remove_locks();
1013 sigchain_pop(signo);
1014 raise(signo);
1017 static void remote_ls(const char *path, int flags,
1018 void (*userFunc)(struct remote_ls_ctx *ls),
1019 void *userData);
1021 /* extract hex from sharded "xx/x{38}" filename */
1022 static int get_oid_hex_from_objpath(const char *path, struct object_id *oid)
1024 memset(oid->hash, 0, GIT_MAX_RAWSZ);
1025 oid->algo = hash_algo_by_ptr(the_hash_algo);
1027 if (strlen(path) != the_hash_algo->hexsz + 1)
1028 return -1;
1030 if (hex_to_bytes(oid->hash, path, 1))
1031 return -1;
1032 path += 2;
1033 path++; /* skip '/' */
1035 return hex_to_bytes(oid->hash + 1, path, the_hash_algo->rawsz - 1);
1038 static void process_ls_object(struct remote_ls_ctx *ls)
1040 unsigned int *parent = (unsigned int *)ls->userData;
1041 const char *path = ls->dentry_name;
1042 struct object_id oid;
1044 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1045 remote_dir_exists[*parent] = 1;
1046 return;
1049 if (!skip_prefix(path, "objects/", &path) ||
1050 get_oid_hex_from_objpath(path, &oid))
1051 return;
1053 one_remote_object(&oid);
1056 static void process_ls_ref(struct remote_ls_ctx *ls)
1058 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1059 fprintf(stderr, " %s\n", ls->dentry_name);
1060 return;
1063 if (!(ls->dentry_flags & IS_DIR))
1064 one_remote_ref(ls->dentry_name);
1067 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1069 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1071 if (tag_closed) {
1072 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1073 if (ls->dentry_flags & IS_DIR) {
1075 /* ensure collection names end with slash */
1076 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1078 if (ls->flags & PROCESS_DIRS) {
1079 ls->userFunc(ls);
1081 if (strcmp(ls->dentry_name, ls->path) &&
1082 ls->flags & RECURSIVE) {
1083 remote_ls(ls->dentry_name,
1084 ls->flags,
1085 ls->userFunc,
1086 ls->userData);
1088 } else if (ls->flags & PROCESS_FILES) {
1089 ls->userFunc(ls);
1091 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1092 char *path = ctx->cdata;
1093 if (*ctx->cdata == 'h') {
1094 path = strstr(path, "//");
1095 if (path) {
1096 path = strchr(path+2, '/');
1099 if (path) {
1100 const char *url = repo->url;
1101 if (repo->path)
1102 url = repo->path;
1103 if (strncmp(path, url, repo->path_len))
1104 error("Parsed path '%s' does not match url: '%s'",
1105 path, url);
1106 else {
1107 path += repo->path_len;
1108 ls->dentry_name = xstrdup(path);
1111 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1112 ls->dentry_flags |= IS_DIR;
1114 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1115 FREE_AND_NULL(ls->dentry_name);
1116 ls->dentry_flags = 0;
1121 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1122 * should _only_ heed the information from that file, instead of trying to
1123 * determine the refs from the remote file system (badly: it does not even
1124 * know about packed-refs).
1126 static void remote_ls(const char *path, int flags,
1127 void (*userFunc)(struct remote_ls_ctx *ls),
1128 void *userData)
1130 char *url = xstrfmt("%s%s", repo->url, path);
1131 struct active_request_slot *slot;
1132 struct slot_results results;
1133 struct strbuf in_buffer = STRBUF_INIT;
1134 struct buffer out_buffer = { STRBUF_INIT, 0 };
1135 struct curl_slist *dav_headers = http_copy_default_headers();
1136 struct xml_ctx ctx;
1137 struct remote_ls_ctx ls;
1139 ls.flags = flags;
1140 ls.path = xstrdup(path);
1141 ls.dentry_name = NULL;
1142 ls.dentry_flags = 0;
1143 ls.userData = userData;
1144 ls.userFunc = userFunc;
1146 strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1148 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1149 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1151 slot = get_active_slot();
1152 slot->results = &results;
1153 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1154 &out_buffer, fwrite_buffer);
1155 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1156 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1158 if (start_active_slot(slot)) {
1159 run_active_slot(slot);
1160 if (results.curl_result == CURLE_OK) {
1161 XML_Parser parser = XML_ParserCreate(NULL);
1162 enum XML_Status result;
1163 ctx.name = xcalloc(10, 1);
1164 ctx.len = 0;
1165 ctx.cdata = NULL;
1166 ctx.userFunc = handle_remote_ls_ctx;
1167 ctx.userData = &ls;
1168 XML_SetUserData(parser, &ctx);
1169 XML_SetElementHandler(parser, xml_start_tag,
1170 xml_end_tag);
1171 XML_SetCharacterDataHandler(parser, xml_cdata);
1172 result = XML_Parse(parser, in_buffer.buf,
1173 in_buffer.len, 1);
1174 free(ctx.name);
1175 free(ctx.cdata);
1177 if (result != XML_STATUS_OK) {
1178 fprintf(stderr, "XML error: %s\n",
1179 XML_ErrorString(
1180 XML_GetErrorCode(parser)));
1182 XML_ParserFree(parser);
1184 } else {
1185 fprintf(stderr, "Unable to start PROPFIND request\n");
1188 free(ls.path);
1189 free(ls.dentry_name);
1190 free(url);
1191 strbuf_release(&out_buffer.buf);
1192 strbuf_release(&in_buffer);
1193 curl_slist_free_all(dav_headers);
1196 static void get_remote_object_list(unsigned char parent)
1198 char path[] = "objects/XX/";
1199 static const char hex[] = "0123456789abcdef";
1200 unsigned int val = parent;
1202 path[8] = hex[val >> 4];
1203 path[9] = hex[val & 0xf];
1204 remote_dir_exists[val] = 0;
1205 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1206 process_ls_object, &val);
1209 static int locking_available(void)
1211 struct active_request_slot *slot;
1212 struct slot_results results;
1213 struct strbuf in_buffer = STRBUF_INIT;
1214 struct buffer out_buffer = { STRBUF_INIT, 0 };
1215 struct curl_slist *dav_headers = http_copy_default_headers();
1216 struct xml_ctx ctx;
1217 int lock_flags = 0;
1218 char *escaped;
1220 escaped = xml_entities(repo->url);
1221 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1222 free(escaped);
1224 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1225 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1227 slot = get_active_slot();
1228 slot->results = &results;
1229 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1230 &out_buffer, fwrite_buffer);
1231 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1232 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1234 if (start_active_slot(slot)) {
1235 run_active_slot(slot);
1236 if (results.curl_result == CURLE_OK) {
1237 XML_Parser parser = XML_ParserCreate(NULL);
1238 enum XML_Status result;
1239 ctx.name = xcalloc(10, 1);
1240 ctx.len = 0;
1241 ctx.cdata = NULL;
1242 ctx.userFunc = handle_lockprop_ctx;
1243 ctx.userData = &lock_flags;
1244 XML_SetUserData(parser, &ctx);
1245 XML_SetElementHandler(parser, xml_start_tag,
1246 xml_end_tag);
1247 result = XML_Parse(parser, in_buffer.buf,
1248 in_buffer.len, 1);
1249 free(ctx.name);
1251 if (result != XML_STATUS_OK) {
1252 fprintf(stderr, "XML error: %s\n",
1253 XML_ErrorString(
1254 XML_GetErrorCode(parser)));
1255 lock_flags = 0;
1257 XML_ParserFree(parser);
1258 if (!lock_flags)
1259 error("no DAV locking support on %s",
1260 repo->url);
1262 } else {
1263 error("Cannot access URL %s, return code %d",
1264 repo->url, results.curl_result);
1265 lock_flags = 0;
1267 } else {
1268 error("Unable to start PROPFIND request on %s", repo->url);
1271 strbuf_release(&out_buffer.buf);
1272 strbuf_release(&in_buffer);
1273 curl_slist_free_all(dav_headers);
1275 return lock_flags;
1278 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1280 struct object_list *entry = xmalloc(sizeof(struct object_list));
1281 entry->item = obj;
1282 entry->next = *p;
1283 *p = entry;
1284 return &entry->next;
1287 static struct object_list **process_blob(struct blob *blob,
1288 struct object_list **p)
1290 struct object *obj = &blob->object;
1292 obj->flags |= LOCAL;
1294 if (obj->flags & (UNINTERESTING | SEEN))
1295 return p;
1297 obj->flags |= SEEN;
1298 return add_one_object(obj, p);
1301 static struct object_list **process_tree(struct tree *tree,
1302 struct object_list **p)
1304 struct object *obj = &tree->object;
1305 struct tree_desc desc;
1306 struct name_entry entry;
1308 obj->flags |= LOCAL;
1310 if (obj->flags & (UNINTERESTING | SEEN))
1311 return p;
1312 if (parse_tree(tree) < 0)
1313 die("bad tree object %s", oid_to_hex(&obj->oid));
1315 obj->flags |= SEEN;
1316 p = add_one_object(obj, p);
1318 init_tree_desc(&desc, &tree->object.oid, tree->buffer, tree->size);
1320 while (tree_entry(&desc, &entry))
1321 switch (object_type(entry.mode)) {
1322 case OBJ_TREE:
1323 p = process_tree(lookup_tree(the_repository, &entry.oid),
1325 break;
1326 case OBJ_BLOB:
1327 p = process_blob(lookup_blob(the_repository, &entry.oid),
1329 break;
1330 default:
1331 /* Subproject commit - not in this repository */
1332 break;
1335 free_tree_buffer(tree);
1336 return p;
1339 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1341 struct commit *commit;
1342 struct object_list **p = &objects;
1343 int count = 0;
1345 while ((commit = get_revision(revs)) != NULL) {
1346 p = process_tree(repo_get_commit_tree(the_repository, commit),
1348 commit->object.flags |= LOCAL;
1349 if (!(commit->object.flags & UNINTERESTING))
1350 count += add_send_request(&commit->object, lock);
1353 for (size_t i = 0; i < revs->pending.nr; i++) {
1354 struct object_array_entry *entry = revs->pending.objects + i;
1355 struct object *obj = entry->item;
1356 const char *name = entry->name;
1358 if (obj->flags & (UNINTERESTING | SEEN))
1359 continue;
1360 if (obj->type == OBJ_TAG) {
1361 obj->flags |= SEEN;
1362 p = add_one_object(obj, p);
1363 continue;
1365 if (obj->type == OBJ_TREE) {
1366 p = process_tree((struct tree *)obj, p);
1367 continue;
1369 if (obj->type == OBJ_BLOB) {
1370 p = process_blob((struct blob *)obj, p);
1371 continue;
1373 die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name);
1376 while (objects) {
1377 struct object_list *next = objects->next;
1379 if (!(objects->item->flags & UNINTERESTING))
1380 count += add_send_request(objects->item, lock);
1382 free(objects);
1383 objects = next;
1386 return count;
1389 static int update_remote(const struct object_id *oid, struct remote_lock *lock)
1391 struct active_request_slot *slot;
1392 struct slot_results results;
1393 struct buffer out_buffer = { STRBUF_INIT, 0 };
1394 struct curl_slist *dav_headers;
1396 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1398 strbuf_addf(&out_buffer.buf, "%s\n", oid_to_hex(oid));
1400 slot = get_active_slot();
1401 slot->results = &results;
1402 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1403 &out_buffer, fwrite_null);
1404 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1406 if (start_active_slot(slot)) {
1407 run_active_slot(slot);
1408 strbuf_release(&out_buffer.buf);
1409 curl_slist_free_all(dav_headers);
1410 if (results.curl_result != CURLE_OK) {
1411 fprintf(stderr,
1412 "PUT error: curl result=%d, HTTP code=%ld\n",
1413 results.curl_result, results.http_code);
1414 /* We should attempt recovery? */
1415 return 0;
1417 } else {
1418 strbuf_release(&out_buffer.buf);
1419 curl_slist_free_all(dav_headers);
1420 fprintf(stderr, "Unable to start PUT request\n");
1421 return 0;
1424 return 1;
1427 static struct ref *remote_refs;
1429 static void one_remote_ref(const char *refname)
1431 struct ref *ref;
1432 struct object *obj;
1434 ref = alloc_ref(refname);
1436 if (http_fetch_ref(repo->url, ref) != 0) {
1437 fprintf(stderr,
1438 "Unable to fetch ref %s from %s\n",
1439 refname, repo->url);
1440 free(ref);
1441 return;
1445 * Fetch a copy of the object if it doesn't exist locally - it
1446 * may be required for updating server info later.
1448 if (repo->can_update_info_refs && !repo_has_object_file(the_repository, &ref->old_oid)) {
1449 obj = lookup_unknown_object(the_repository, &ref->old_oid);
1450 fprintf(stderr, " fetch %s for %s\n",
1451 oid_to_hex(&ref->old_oid), refname);
1452 add_fetch_request(obj);
1455 ref->next = remote_refs;
1456 remote_refs = ref;
1459 static void get_dav_remote_heads(void)
1461 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1464 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1466 struct strbuf *buf = (struct strbuf *)ls->userData;
1467 struct object *o;
1468 struct ref *ref;
1470 ref = alloc_ref(ls->dentry_name);
1472 if (http_fetch_ref(repo->url, ref) != 0) {
1473 fprintf(stderr,
1474 "Unable to fetch ref %s from %s\n",
1475 ls->dentry_name, repo->url);
1476 aborted = 1;
1477 free(ref);
1478 return;
1481 o = parse_object(the_repository, &ref->old_oid);
1482 if (!o) {
1483 fprintf(stderr,
1484 "Unable to parse object %s for remote ref %s\n",
1485 oid_to_hex(&ref->old_oid), ls->dentry_name);
1486 aborted = 1;
1487 free(ref);
1488 return;
1491 strbuf_addf(buf, "%s\t%s\n",
1492 oid_to_hex(&ref->old_oid), ls->dentry_name);
1494 if (o->type == OBJ_TAG) {
1495 o = deref_tag(the_repository, o, ls->dentry_name, 0);
1496 if (o)
1497 strbuf_addf(buf, "%s\t%s^{}\n",
1498 oid_to_hex(&o->oid), ls->dentry_name);
1500 free(ref);
1503 static void update_remote_info_refs(struct remote_lock *lock)
1505 struct buffer buffer = { STRBUF_INIT, 0 };
1506 struct active_request_slot *slot;
1507 struct slot_results results;
1508 struct curl_slist *dav_headers;
1510 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1511 add_remote_info_ref, &buffer.buf);
1512 if (!aborted) {
1513 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1515 slot = get_active_slot();
1516 slot->results = &results;
1517 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1518 &buffer, fwrite_null);
1519 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1521 if (start_active_slot(slot)) {
1522 run_active_slot(slot);
1523 if (results.curl_result != CURLE_OK) {
1524 fprintf(stderr,
1525 "PUT error: curl result=%d, HTTP code=%ld\n",
1526 results.curl_result, results.http_code);
1529 curl_slist_free_all(dav_headers);
1531 strbuf_release(&buffer.buf);
1534 static int remote_exists(const char *path)
1536 char *url = xstrfmt("%s%s", repo->url, path);
1537 int ret;
1540 switch (http_get_strbuf(url, NULL, NULL)) {
1541 case HTTP_OK:
1542 ret = 1;
1543 break;
1544 case HTTP_MISSING_TARGET:
1545 ret = 0;
1546 break;
1547 case HTTP_ERROR:
1548 error("unable to access '%s': %s", url, curl_errorstr);
1549 /* fallthrough */
1550 default:
1551 ret = -1;
1553 free(url);
1554 return ret;
1557 static void fetch_symref(const char *path, char **symref, struct object_id *oid)
1559 char *url = xstrfmt("%s%s", repo->url, path);
1560 struct strbuf buffer = STRBUF_INIT;
1561 const char *name;
1563 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1564 die("Couldn't get %s for remote symref\n%s", url,
1565 curl_errorstr);
1566 free(url);
1568 FREE_AND_NULL(*symref);
1569 oidclr(oid, the_repository->hash_algo);
1571 if (buffer.len == 0)
1572 return;
1574 /* Cut off trailing newline. */
1575 strbuf_rtrim(&buffer);
1577 /* If it's a symref, set the refname; otherwise try for a sha1 */
1578 if (skip_prefix(buffer.buf, "ref: ", &name)) {
1579 *symref = xmemdupz(name, buffer.len - (name - buffer.buf));
1580 } else {
1581 get_oid_hex(buffer.buf, oid);
1584 strbuf_release(&buffer);
1587 static int verify_merge_base(struct object_id *head_oid, struct ref *remote)
1589 struct commit *head = lookup_commit_or_die(head_oid, "HEAD");
1590 struct commit *branch = lookup_commit_or_die(&remote->old_oid,
1591 remote->name);
1592 int ret = repo_in_merge_bases(the_repository, branch, head);
1594 if (ret < 0)
1595 exit(128);
1596 return ret;
1599 static int delete_remote_branch(const char *pattern, int force)
1601 struct ref *refs = remote_refs;
1602 struct ref *remote_ref = NULL;
1603 struct object_id head_oid;
1604 char *symref = NULL;
1605 int match;
1606 int patlen = strlen(pattern);
1607 int i;
1608 struct active_request_slot *slot;
1609 struct slot_results results;
1610 char *url;
1612 /* Find the remote branch(es) matching the specified branch name */
1613 for (match = 0; refs; refs = refs->next) {
1614 char *name = refs->name;
1615 int namelen = strlen(name);
1616 if (namelen < patlen ||
1617 memcmp(name + namelen - patlen, pattern, patlen))
1618 continue;
1619 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1620 continue;
1621 match++;
1622 remote_ref = refs;
1624 if (match == 0)
1625 return error("No remote branch matches %s", pattern);
1626 if (match != 1)
1627 return error("More than one remote branch matches %s",
1628 pattern);
1631 * Remote HEAD must be a symref (not exactly foolproof; a remote
1632 * symlink to a symref will look like a symref)
1634 fetch_symref("HEAD", &symref, &head_oid);
1635 if (!symref)
1636 return error("Remote HEAD is not a symref");
1638 /* Remote branch must not be the remote HEAD */
1639 for (i = 0; symref && i < MAXDEPTH; i++) {
1640 if (!strcmp(remote_ref->name, symref))
1641 return error("Remote branch %s is the current HEAD",
1642 remote_ref->name);
1643 fetch_symref(symref, &symref, &head_oid);
1646 /* Run extra sanity checks if delete is not forced */
1647 if (!force) {
1648 /* Remote HEAD must resolve to a known object */
1649 if (symref)
1650 return error("Remote HEAD symrefs too deep");
1651 if (is_null_oid(&head_oid))
1652 return error("Unable to resolve remote HEAD");
1653 if (!repo_has_object_file(the_repository, &head_oid))
1654 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", oid_to_hex(&head_oid));
1656 /* Remote branch must resolve to a known object */
1657 if (is_null_oid(&remote_ref->old_oid))
1658 return error("Unable to resolve remote branch %s",
1659 remote_ref->name);
1660 if (!repo_has_object_file(the_repository, &remote_ref->old_oid))
1661 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));
1663 /* Remote branch must be an ancestor of remote HEAD */
1664 if (!verify_merge_base(&head_oid, remote_ref)) {
1665 return error("The branch '%s' is not an ancestor "
1666 "of your current HEAD.\n"
1667 "If you are sure you want to delete it,"
1668 " run:\n\t'git http-push -D %s %s'",
1669 remote_ref->name, repo->url, pattern);
1673 /* Send delete request */
1674 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1675 if (dry_run)
1676 return 0;
1677 url = xstrfmt("%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");
1692 return 0;
1695 static void run_request_queue(void)
1697 is_running_queue = 1;
1698 fill_active_slots();
1699 add_fill_function(NULL, fill_active_slot);
1700 do {
1701 finish_all_active_slots();
1702 fill_active_slots();
1703 } while (request_queue_head && !aborted);
1705 is_running_queue = 0;
1708 int cmd_main(int argc, const char **argv)
1710 struct transfer_request *request;
1711 struct transfer_request *next_request;
1712 struct refspec rs = REFSPEC_INIT_PUSH;
1713 struct remote_lock *ref_lock = NULL;
1714 struct remote_lock *info_ref_lock = NULL;
1715 int delete_branch = 0;
1716 int force_delete = 0;
1717 int objects_to_send;
1718 int rc = 0;
1719 int i;
1720 int new_refs;
1721 struct ref *ref, *local_refs = NULL;
1723 CALLOC_ARRAY(repo, 1);
1725 argv++;
1726 for (i = 1; i < argc; i++, argv++) {
1727 const char *arg = *argv;
1729 if (*arg == '-') {
1730 if (!strcmp(arg, "--all")) {
1731 push_all = MATCH_REFS_ALL;
1732 continue;
1734 if (!strcmp(arg, "--force")) {
1735 force_all = 1;
1736 continue;
1738 if (!strcmp(arg, "--dry-run")) {
1739 dry_run = 1;
1740 continue;
1742 if (!strcmp(arg, "--helper-status")) {
1743 helper_status = 1;
1744 continue;
1746 if (!strcmp(arg, "--verbose")) {
1747 push_verbosely = 1;
1748 http_is_verbose = 1;
1749 continue;
1751 if (!strcmp(arg, "-d")) {
1752 delete_branch = 1;
1753 continue;
1755 if (!strcmp(arg, "-D")) {
1756 delete_branch = 1;
1757 force_delete = 1;
1758 continue;
1760 if (!strcmp(arg, "-h"))
1761 usage(http_push_usage);
1763 if (!repo->url) {
1764 char *path = strstr(arg, "//");
1765 str_end_url_with_slash(arg, &repo->url);
1766 repo->path_len = strlen(repo->url);
1767 if (path) {
1768 repo->path = strchr(path+2, '/');
1769 if (repo->path)
1770 repo->path_len = strlen(repo->path);
1772 continue;
1774 refspec_appendn(&rs, argv, argc - i);
1775 break;
1778 if (!repo->url)
1779 usage(http_push_usage);
1781 if (delete_branch && rs.nr != 1)
1782 die("You must specify only one branch name when deleting a remote branch");
1784 setup_git_directory();
1786 memset(remote_dir_exists, -1, 256);
1788 http_init(NULL, repo->url, 1);
1790 is_running_queue = 0;
1792 /* Verify DAV compliance/lock support */
1793 if (!locking_available()) {
1794 rc = 1;
1795 goto cleanup;
1798 sigchain_push_common(remove_locks_on_signal);
1800 /* Check whether the remote has server info files */
1801 repo->can_update_info_refs = 0;
1802 repo->has_info_refs = remote_exists("info/refs");
1803 repo->has_info_packs = remote_exists("objects/info/packs");
1804 if (repo->has_info_refs) {
1805 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1806 if (info_ref_lock)
1807 repo->can_update_info_refs = 1;
1808 else {
1809 error("cannot lock existing info/refs");
1810 rc = 1;
1811 goto cleanup;
1814 if (repo->has_info_packs)
1815 fetch_indices();
1817 /* Get a list of all local and remote heads to validate refspecs */
1818 local_refs = get_local_heads();
1819 fprintf(stderr, "Fetching remote heads...\n");
1820 get_dav_remote_heads();
1821 run_request_queue();
1823 /* Remove a remote branch if -d or -D was specified */
1824 if (delete_branch) {
1825 const char *branch = rs.items[i].src;
1826 if (delete_remote_branch(branch, force_delete) == -1) {
1827 fprintf(stderr, "Unable to delete remote branch %s\n",
1828 branch);
1829 if (helper_status)
1830 printf("error %s cannot remove\n", branch);
1832 goto cleanup;
1835 /* match them up */
1836 if (match_push_refs(local_refs, &remote_refs, &rs, push_all)) {
1837 rc = -1;
1838 goto cleanup;
1840 if (!remote_refs) {
1841 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1842 if (helper_status)
1843 printf("error null no match\n");
1844 rc = 0;
1845 goto cleanup;
1848 new_refs = 0;
1849 for (ref = remote_refs; ref; ref = ref->next) {
1850 struct rev_info revs;
1851 struct strvec commit_argv = STRVEC_INIT;
1853 if (!ref->peer_ref)
1854 continue;
1856 if (is_null_oid(&ref->peer_ref->new_oid)) {
1857 if (delete_remote_branch(ref->name, 1) == -1) {
1858 error("Could not remove %s", ref->name);
1859 if (helper_status)
1860 printf("error %s cannot remove\n", ref->name);
1861 rc = -4;
1863 else if (helper_status)
1864 printf("ok %s\n", ref->name);
1865 new_refs++;
1866 continue;
1869 if (oideq(&ref->old_oid, &ref->peer_ref->new_oid)) {
1870 if (push_verbosely)
1871 /* stable plumbing output; do not modify or localize */
1872 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1873 if (helper_status)
1874 printf("ok %s up to date\n", ref->name);
1875 continue;
1878 if (!force_all &&
1879 !is_null_oid(&ref->old_oid) &&
1880 !ref->force) {
1881 if (!repo_has_object_file(the_repository, &ref->old_oid) ||
1882 !ref_newer(&ref->peer_ref->new_oid,
1883 &ref->old_oid)) {
1885 * We do not have the remote ref, or
1886 * we know that the remote ref is not
1887 * an ancestor of what we are trying to
1888 * push. Either way this can be losing
1889 * commits at the remote end and likely
1890 * we were not up to date to begin with.
1892 /* stable plumbing output; do not modify or localize */
1893 error("remote '%s' is not an ancestor of\n"
1894 "local '%s'.\n"
1895 "Maybe you are not up-to-date and "
1896 "need to pull first?",
1897 ref->name,
1898 ref->peer_ref->name);
1899 if (helper_status)
1900 printf("error %s non-fast forward\n", ref->name);
1901 rc = -2;
1902 continue;
1905 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1906 new_refs++;
1908 fprintf(stderr, "updating '%s'", ref->name);
1909 if (strcmp(ref->name, ref->peer_ref->name))
1910 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1911 fprintf(stderr, "\n from %s\n to %s\n",
1912 oid_to_hex(&ref->old_oid), oid_to_hex(&ref->new_oid));
1913 if (dry_run) {
1914 if (helper_status)
1915 printf("ok %s\n", ref->name);
1916 continue;
1919 /* Lock remote branch ref */
1920 ref_lock = lock_remote(ref->name, LOCK_TIME);
1921 if (!ref_lock) {
1922 fprintf(stderr, "Unable to lock remote branch %s\n",
1923 ref->name);
1924 if (helper_status)
1925 printf("error %s lock error\n", ref->name);
1926 rc = 1;
1927 continue;
1930 /* Set up revision info for this refspec */
1931 strvec_push(&commit_argv, ""); /* ignored */
1932 strvec_push(&commit_argv, "--objects");
1933 strvec_push(&commit_argv, oid_to_hex(&ref->new_oid));
1934 if (!push_all && !is_null_oid(&ref->old_oid))
1935 strvec_pushf(&commit_argv, "^%s",
1936 oid_to_hex(&ref->old_oid));
1937 repo_init_revisions(the_repository, &revs, setup_git_directory());
1938 setup_revisions(commit_argv.nr, commit_argv.v, &revs, NULL);
1939 revs.edge_hint = 0; /* just in case */
1941 /* Generate a list of objects that need to be pushed */
1942 pushing = 0;
1943 if (prepare_revision_walk(&revs))
1944 die("revision walk setup failed");
1945 mark_edges_uninteresting(&revs, NULL, 0);
1946 objects_to_send = get_delta(&revs, ref_lock);
1947 finish_all_active_slots();
1949 /* Push missing objects to remote, this would be a
1950 convenient time to pack them first if appropriate. */
1951 pushing = 1;
1952 if (objects_to_send)
1953 fprintf(stderr, " sending %d objects\n",
1954 objects_to_send);
1956 run_request_queue();
1958 /* Update the remote branch if all went well */
1959 if (aborted || !update_remote(&ref->new_oid, ref_lock))
1960 rc = 1;
1962 if (!rc)
1963 fprintf(stderr, " done\n");
1964 if (helper_status)
1965 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1966 unlock_remote(ref_lock);
1967 check_locks();
1968 strvec_clear(&commit_argv);
1969 release_revisions(&revs);
1972 /* Update remote server info if appropriate */
1973 if (repo->has_info_refs && new_refs) {
1974 if (info_ref_lock && repo->can_update_info_refs) {
1975 fprintf(stderr, "Updating remote server info\n");
1976 if (!dry_run)
1977 update_remote_info_refs(info_ref_lock);
1978 } else {
1979 fprintf(stderr, "Unable to update server info\n");
1983 cleanup:
1984 if (info_ref_lock)
1985 unlock_remote(info_ref_lock);
1986 free(repo->url);
1987 free(repo);
1989 http_cleanup();
1991 request = request_queue_head;
1992 while (request != NULL) {
1993 next_request = request->next;
1994 release_request(request);
1995 request = next_request;
1998 refspec_clear(&rs);
1999 free_refs(local_refs);
2001 return rc;