fast-export: factor out anonymized_entry creation
[git/debian.git] / http-push.c
blob88aa045ecba453eaab7f56c02c54a972ab07fd7c
1 #include "cache.h"
2 #include "hex.h"
3 #include "repository.h"
4 #include "commit.h"
5 #include "tag.h"
6 #include "blob.h"
7 #include "http.h"
8 #include "refs.h"
9 #include "diff.h"
10 #include "revision.h"
11 #include "exec-cmd.h"
12 #include "remote.h"
13 #include "list-objects.h"
14 #include "sigchain.h"
15 #include "strvec.h"
16 #include "packfile.h"
17 #include "object-store.h"
18 #include "commit-reach.h"
20 #ifdef EXPAT_NEEDS_XMLPARSE_H
21 #include <xmlparse.h>
22 #else
23 #include <expat.h>
24 #endif
26 static const char http_push_usage[] =
27 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
29 #ifndef XML_STATUS_OK
30 enum XML_Status {
31 XML_STATUS_OK = 1,
32 XML_STATUS_ERROR = 0
34 #define XML_STATUS_OK 1
35 #define XML_STATUS_ERROR 0
36 #endif
38 #define PREV_BUF_SIZE 4096
40 /* DAV methods */
41 #define DAV_LOCK "LOCK"
42 #define DAV_MKCOL "MKCOL"
43 #define DAV_MOVE "MOVE"
44 #define DAV_PROPFIND "PROPFIND"
45 #define DAV_PUT "PUT"
46 #define DAV_UNLOCK "UNLOCK"
47 #define DAV_DELETE "DELETE"
49 /* DAV lock flags */
50 #define DAV_PROP_LOCKWR (1u << 0)
51 #define DAV_PROP_LOCKEX (1u << 1)
52 #define DAV_LOCK_OK (1u << 2)
54 /* DAV XML properties */
55 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
56 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
57 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
58 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
59 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
60 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
61 #define DAV_PROPFIND_RESP ".multistatus.response"
62 #define DAV_PROPFIND_NAME ".multistatus.response.href"
63 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
65 /* DAV request body templates */
66 #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>"
67 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
68 #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>"
70 #define LOCK_TIME 600
71 #define LOCK_REFRESH 30
73 /* Remember to update object flag allocation in object.h */
74 #define LOCAL (1u<<11)
75 #define REMOTE (1u<<12)
76 #define FETCHING (1u<<13)
77 #define PUSHING (1u<<14)
79 /* We allow "recursive" symbolic refs. Only within reason, though */
80 #define MAXDEPTH 5
82 static int pushing;
83 static int aborted;
84 static signed char remote_dir_exists[256];
86 static int push_verbosely;
87 static int push_all = MATCH_REFS_NONE;
88 static int force_all;
89 static int dry_run;
90 static int helper_status;
92 static struct object_list *objects;
94 struct repo {
95 char *url;
96 char *path;
97 int path_len;
98 int has_info_refs;
99 int can_update_info_refs;
100 int has_info_packs;
101 struct packed_git *packs;
102 struct remote_lock *locks;
105 static struct repo *repo;
107 enum transfer_state {
108 NEED_FETCH,
109 RUN_FETCH_LOOSE,
110 RUN_FETCH_PACKED,
111 NEED_PUSH,
112 RUN_MKCOL,
113 RUN_PUT,
114 RUN_MOVE,
115 ABORTED,
116 COMPLETE
119 struct transfer_request {
120 struct object *obj;
121 struct packed_git *target;
122 char *url;
123 char *dest;
124 struct remote_lock *lock;
125 struct curl_slist *headers;
126 struct buffer buffer;
127 enum transfer_state state;
128 CURLcode curl_result;
129 char errorstr[CURL_ERROR_SIZE];
130 long http_code;
131 void *userData;
132 struct active_request_slot *slot;
133 struct transfer_request *next;
136 static struct transfer_request *request_queue_head;
138 struct xml_ctx {
139 char *name;
140 int len;
141 char *cdata;
142 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
143 void *userData;
146 struct remote_lock {
147 char *url;
148 char *owner;
149 char *token;
150 char tmpfile_suffix[GIT_MAX_HEXSZ + 1];
151 time_t start_time;
152 long timeout;
153 int refreshing;
154 struct remote_lock *next;
157 /* Flags that control remote_ls processing */
158 #define PROCESS_FILES (1u << 0)
159 #define PROCESS_DIRS (1u << 1)
160 #define RECURSIVE (1u << 2)
162 /* Flags that remote_ls passes to callback functions */
163 #define IS_DIR (1u << 0)
165 struct remote_ls_ctx {
166 char *path;
167 void (*userFunc)(struct remote_ls_ctx *ls);
168 void *userData;
169 int flags;
170 char *dentry_name;
171 int dentry_flags;
172 struct remote_ls_ctx *parent;
175 /* get_dav_token_headers options */
176 enum dav_header_flag {
177 DAV_HEADER_IF = (1u << 0),
178 DAV_HEADER_LOCK = (1u << 1),
179 DAV_HEADER_TIMEOUT = (1u << 2)
182 static char *xml_entities(const char *s)
184 struct strbuf buf = STRBUF_INIT;
185 strbuf_addstr_xml_quoted(&buf, s);
186 return strbuf_detach(&buf, NULL);
189 static void curl_setup_http_get(CURL *curl, const char *url,
190 const char *custom_req)
192 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
193 curl_easy_setopt(curl, CURLOPT_URL, url);
194 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
195 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
198 static void curl_setup_http(CURL *curl, const char *url,
199 const char *custom_req, struct buffer *buffer,
200 curl_write_callback write_fn)
202 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
203 curl_easy_setopt(curl, CURLOPT_URL, url);
204 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
205 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
206 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
207 curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, seek_buffer);
208 curl_easy_setopt(curl, CURLOPT_SEEKDATA, buffer);
209 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
210 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
211 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
212 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
215 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
217 struct strbuf buf = STRBUF_INIT;
218 struct curl_slist *dav_headers = http_copy_default_headers();
220 if (options & DAV_HEADER_IF) {
221 strbuf_addf(&buf, "If: (<%s>)", lock->token);
222 dav_headers = curl_slist_append(dav_headers, buf.buf);
223 strbuf_reset(&buf);
225 if (options & DAV_HEADER_LOCK) {
226 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
227 dav_headers = curl_slist_append(dav_headers, buf.buf);
228 strbuf_reset(&buf);
230 if (options & DAV_HEADER_TIMEOUT) {
231 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
232 dav_headers = curl_slist_append(dav_headers, buf.buf);
233 strbuf_reset(&buf);
235 strbuf_release(&buf);
237 return dav_headers;
240 static void finish_request(struct transfer_request *request);
241 static void release_request(struct transfer_request *request);
243 static void process_response(void *callback_data)
245 struct transfer_request *request =
246 (struct transfer_request *)callback_data;
248 finish_request(request);
251 static void start_fetch_loose(struct transfer_request *request)
253 struct active_request_slot *slot;
254 struct http_object_request *obj_req;
256 obj_req = new_http_object_request(repo->url, &request->obj->oid);
257 if (!obj_req) {
258 request->state = ABORTED;
259 return;
262 slot = obj_req->slot;
263 slot->callback_func = process_response;
264 slot->callback_data = request;
265 request->slot = slot;
266 request->userData = obj_req;
268 /* Try to get the request started, abort the request on error */
269 request->state = RUN_FETCH_LOOSE;
270 if (!start_active_slot(slot)) {
271 fprintf(stderr, "Unable to start GET request\n");
272 repo->can_update_info_refs = 0;
273 release_http_object_request(obj_req);
274 release_request(request);
278 static void start_mkcol(struct transfer_request *request)
280 char *hex = oid_to_hex(&request->obj->oid);
281 struct active_request_slot *slot;
283 request->url = get_remote_object_url(repo->url, hex, 1);
285 slot = get_active_slot();
286 slot->callback_func = process_response;
287 slot->callback_data = request;
288 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
289 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
291 if (start_active_slot(slot)) {
292 request->slot = slot;
293 request->state = RUN_MKCOL;
294 } else {
295 request->state = ABORTED;
296 FREE_AND_NULL(request->url);
300 static void start_fetch_packed(struct transfer_request *request)
302 struct packed_git *target;
304 struct transfer_request *check_request = request_queue_head;
305 struct http_pack_request *preq;
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;
314 close_pack_index(target);
315 request->target = target;
317 fprintf(stderr, "Fetching pack %s\n",
318 hash_to_hex(target->hash));
319 fprintf(stderr, " which contains %s\n", oid_to_hex(&request->obj->oid));
321 preq = new_http_pack_request(target->hash, repo->url);
322 if (!preq) {
323 repo->can_update_info_refs = 0;
324 return;
327 /* Make sure there isn't another open request for this pack */
328 while (check_request) {
329 if (check_request->state == RUN_FETCH_PACKED &&
330 !strcmp(check_request->url, preq->url)) {
331 release_http_pack_request(preq);
332 release_request(request);
333 return;
335 check_request = check_request->next;
338 preq->slot->callback_func = process_response;
339 preq->slot->callback_data = request;
340 request->slot = preq->slot;
341 request->userData = preq;
343 /* Try to get the request started, abort the request on error */
344 request->state = RUN_FETCH_PACKED;
345 if (!start_active_slot(preq->slot)) {
346 fprintf(stderr, "Unable to start GET request\n");
347 release_http_pack_request(preq);
348 repo->can_update_info_refs = 0;
349 release_request(request);
353 static void start_put(struct transfer_request *request)
355 char *hex = oid_to_hex(&request->obj->oid);
356 struct active_request_slot *slot;
357 struct strbuf buf = STRBUF_INIT;
358 enum object_type type;
359 char hdr[50];
360 void *unpacked;
361 unsigned long len;
362 int hdrlen;
363 ssize_t size;
364 git_zstream stream;
366 unpacked = read_object_file(&request->obj->oid, &type, &len);
367 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
369 /* Set it up */
370 git_deflate_init(&stream, zlib_compression_level);
371 size = git_deflate_bound(&stream, len + hdrlen);
372 strbuf_init(&request->buffer.buf, size);
373 request->buffer.posn = 0;
375 /* Compress it */
376 stream.next_out = (unsigned char *)request->buffer.buf.buf;
377 stream.avail_out = size;
379 /* First header.. */
380 stream.next_in = (void *)hdr;
381 stream.avail_in = hdrlen;
382 while (git_deflate(&stream, 0) == Z_OK)
383 ; /* nothing */
385 /* Then the data itself.. */
386 stream.next_in = unpacked;
387 stream.avail_in = len;
388 while (git_deflate(&stream, Z_FINISH) == Z_OK)
389 ; /* nothing */
390 git_deflate_end(&stream);
391 free(unpacked);
393 request->buffer.buf.len = stream.total_out;
395 strbuf_addstr(&buf, "Destination: ");
396 append_remote_object_url(&buf, repo->url, hex, 0);
397 request->dest = strbuf_detach(&buf, NULL);
399 append_remote_object_url(&buf, repo->url, hex, 0);
400 strbuf_add(&buf, request->lock->tmpfile_suffix, the_hash_algo->hexsz + 1);
401 request->url = strbuf_detach(&buf, NULL);
403 slot = get_active_slot();
404 slot->callback_func = process_response;
405 slot->callback_data = request;
406 curl_setup_http(slot->curl, request->url, DAV_PUT,
407 &request->buffer, fwrite_null);
409 if (start_active_slot(slot)) {
410 request->slot = slot;
411 request->state = RUN_PUT;
412 } else {
413 request->state = ABORTED;
414 FREE_AND_NULL(request->url);
418 static void start_move(struct transfer_request *request)
420 struct active_request_slot *slot;
421 struct curl_slist *dav_headers = http_copy_default_headers();
423 slot = get_active_slot();
424 slot->callback_func = process_response;
425 slot->callback_data = request;
426 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
427 dav_headers = curl_slist_append(dav_headers, request->dest);
428 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
429 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
431 if (start_active_slot(slot)) {
432 request->slot = slot;
433 request->state = RUN_MOVE;
434 } else {
435 request->state = ABORTED;
436 FREE_AND_NULL(request->url);
440 static int refresh_lock(struct remote_lock *lock)
442 struct active_request_slot *slot;
443 struct slot_results results;
444 struct curl_slist *dav_headers;
445 int rc = 0;
447 lock->refreshing = 1;
449 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
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);
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;
467 lock->refreshing = 0;
468 curl_slist_free_all(dav_headers);
470 return rc;
473 static void check_locks(void)
475 struct remote_lock *lock = repo->locks;
476 time_t current_time = time(NULL);
477 int time_remaining;
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;
491 lock = lock->next;
495 static void release_request(struct transfer_request *request)
497 struct transfer_request *entry = request_queue_head;
499 if (request == request_queue_head) {
500 request_queue_head = request->next;
501 } else {
502 while (entry && entry->next != request)
503 entry = entry->next;
504 if (entry)
505 entry->next = request->next;
508 free(request->url);
509 free(request);
512 static void finish_request(struct transfer_request *request)
514 struct http_pack_request *preq;
515 struct http_object_request *obj_req;
517 request->curl_result = request->slot->curl_result;
518 request->http_code = request->slot->http_code;
519 request->slot = NULL;
521 /* Keep locks active */
522 check_locks();
524 if (request->headers)
525 curl_slist_free_all(request->headers);
527 /* URL is reused for MOVE after PUT and used during FETCH */
528 if (request->state != RUN_PUT && request->state != RUN_FETCH_PACKED) {
529 FREE_AND_NULL(request->url);
532 if (request->state == RUN_MKCOL) {
533 if (request->curl_result == CURLE_OK ||
534 request->http_code == 405) {
535 remote_dir_exists[request->obj->oid.hash[0]] = 1;
536 start_put(request);
537 } else {
538 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
539 oid_to_hex(&request->obj->oid),
540 request->curl_result, request->http_code);
541 request->state = ABORTED;
542 aborted = 1;
544 } else if (request->state == RUN_PUT) {
545 if (request->curl_result == CURLE_OK) {
546 start_move(request);
547 } else {
548 fprintf(stderr, "PUT %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_MOVE) {
555 if (request->curl_result == CURLE_OK) {
556 if (push_verbosely)
557 fprintf(stderr, " sent %s\n",
558 oid_to_hex(&request->obj->oid));
559 request->obj->flags |= REMOTE;
560 release_request(request);
561 } else {
562 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
563 oid_to_hex(&request->obj->oid),
564 request->curl_result, request->http_code);
565 request->state = ABORTED;
566 aborted = 1;
568 } else if (request->state == RUN_FETCH_LOOSE) {
569 obj_req = (struct http_object_request *)request->userData;
571 if (finish_http_object_request(obj_req) == 0)
572 if (obj_req->rename == 0)
573 request->obj->flags |= (LOCAL | REMOTE);
575 /* Try fetching packed if necessary */
576 if (request->obj->flags & LOCAL) {
577 release_http_object_request(obj_req);
578 release_request(request);
579 } else
580 start_fetch_packed(request);
582 } else if (request->state == RUN_FETCH_PACKED) {
583 int fail = 1;
584 if (request->curl_result != CURLE_OK) {
585 fprintf(stderr, "Unable to get pack file %s\n%s",
586 request->url, curl_errorstr);
587 } else {
588 preq = (struct http_pack_request *)request->userData;
590 if (preq) {
591 if (finish_http_pack_request(preq) == 0)
592 fail = 0;
593 release_http_pack_request(preq);
596 if (fail)
597 repo->can_update_info_refs = 0;
598 else
599 http_install_packfile(request->target, &repo->packs);
600 release_request(request);
604 static int is_running_queue;
605 static int fill_active_slot(void *unused)
607 struct transfer_request *request;
609 if (aborted || !is_running_queue)
610 return 0;
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);
622 return 1;
625 return 0;
628 static void get_remote_object_list(unsigned char parent);
630 static void add_fetch_request(struct object *obj)
632 struct transfer_request *request;
634 check_locks();
637 * Don't fetch the object if it's known to exist locally
638 * or is already in the request queue
640 if (remote_dir_exists[obj->oid.hash[0]] == -1)
641 get_remote_object_list(obj->oid.hash[0]);
642 if (obj->flags & (LOCAL | FETCHING))
643 return;
645 obj->flags |= FETCHING;
646 request = xmalloc(sizeof(*request));
647 request->obj = obj;
648 request->url = NULL;
649 request->lock = NULL;
650 request->headers = NULL;
651 request->state = NEED_FETCH;
652 request->next = request_queue_head;
653 request_queue_head = request;
655 fill_active_slots();
656 step_active_slots();
659 static int add_send_request(struct object *obj, struct remote_lock *lock)
661 struct transfer_request *request;
662 struct packed_git *target;
664 /* Keep locks active */
665 check_locks();
668 * Don't push the object if it's known to exist on the remote
669 * or is already in the request queue
671 if (remote_dir_exists[obj->oid.hash[0]] == -1)
672 get_remote_object_list(obj->oid.hash[0]);
673 if (obj->flags & (REMOTE | PUSHING))
674 return 0;
675 target = find_sha1_pack(obj->oid.hash, repo->packs);
676 if (target) {
677 obj->flags |= REMOTE;
678 return 0;
681 obj->flags |= PUSHING;
682 request = xmalloc(sizeof(*request));
683 request->obj = obj;
684 request->url = NULL;
685 request->lock = lock;
686 request->headers = NULL;
687 request->state = NEED_PUSH;
688 request->next = request_queue_head;
689 request_queue_head = request;
691 fill_active_slots();
692 step_active_slots();
694 return 1;
697 static int fetch_indices(void)
699 int ret;
701 if (push_verbosely)
702 fprintf(stderr, "Getting pack list\n");
704 switch (http_get_info_packs(repo->url, &repo->packs)) {
705 case HTTP_OK:
706 case HTTP_MISSING_TARGET:
707 ret = 0;
708 break;
709 default:
710 ret = -1;
713 return ret;
716 static void one_remote_object(const struct object_id *oid)
718 struct object *obj;
720 obj = lookup_object(the_repository, oid);
721 if (!obj)
722 obj = parse_object(the_repository, oid);
724 /* Ignore remote objects that don't exist locally */
725 if (!obj)
726 return;
728 obj->flags |= REMOTE;
729 if (!object_list_contains(objects, obj))
730 object_list_insert(obj, &objects);
733 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
735 int *lock_flags = (int *)ctx->userData;
737 if (tag_closed) {
738 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
739 if ((*lock_flags & DAV_PROP_LOCKEX) &&
740 (*lock_flags & DAV_PROP_LOCKWR)) {
741 *lock_flags |= DAV_LOCK_OK;
743 *lock_flags &= DAV_LOCK_OK;
744 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
745 *lock_flags |= DAV_PROP_LOCKWR;
746 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
747 *lock_flags |= DAV_PROP_LOCKEX;
752 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
754 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
755 git_hash_ctx hash_ctx;
756 unsigned char lock_token_hash[GIT_MAX_RAWSZ];
758 if (tag_closed && ctx->cdata) {
759 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
760 lock->owner = xstrdup(ctx->cdata);
761 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
762 const char *arg;
763 if (skip_prefix(ctx->cdata, "Second-", &arg))
764 lock->timeout = strtol(arg, NULL, 10);
765 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
766 lock->token = xstrdup(ctx->cdata);
768 the_hash_algo->init_fn(&hash_ctx);
769 the_hash_algo->update_fn(&hash_ctx, lock->token, strlen(lock->token));
770 the_hash_algo->final_fn(lock_token_hash, &hash_ctx);
772 lock->tmpfile_suffix[0] = '_';
773 memcpy(lock->tmpfile_suffix + 1, hash_to_hex(lock_token_hash), the_hash_algo->hexsz);
778 static void one_remote_ref(const char *refname);
780 static void
781 xml_start_tag(void *userData, const char *name, const char **atts)
783 struct xml_ctx *ctx = (struct xml_ctx *)userData;
784 const char *c = strchr(name, ':');
785 int old_namelen, new_len;
787 if (!c)
788 c = name;
789 else
790 c++;
792 old_namelen = strlen(ctx->name);
793 new_len = old_namelen + strlen(c) + 2;
795 if (new_len > ctx->len) {
796 ctx->name = xrealloc(ctx->name, new_len);
797 ctx->len = new_len;
799 xsnprintf(ctx->name + old_namelen, ctx->len - old_namelen, ".%s", c);
801 FREE_AND_NULL(ctx->cdata);
803 ctx->userFunc(ctx, 0);
806 static void
807 xml_end_tag(void *userData, const char *name)
809 struct xml_ctx *ctx = (struct xml_ctx *)userData;
810 const char *c = strchr(name, ':');
811 char *ep;
813 ctx->userFunc(ctx, 1);
815 if (!c)
816 c = name;
817 else
818 c++;
820 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
821 *ep = 0;
824 static void
825 xml_cdata(void *userData, const XML_Char *s, int len)
827 struct xml_ctx *ctx = (struct xml_ctx *)userData;
828 free(ctx->cdata);
829 ctx->cdata = xmemdupz(s, len);
832 static struct remote_lock *lock_remote(const char *path, long timeout)
834 struct active_request_slot *slot;
835 struct slot_results results;
836 struct buffer out_buffer = { STRBUF_INIT, 0 };
837 struct strbuf in_buffer = STRBUF_INIT;
838 char *url;
839 char *ep;
840 char timeout_header[25];
841 struct remote_lock *lock = NULL;
842 struct curl_slist *dav_headers = http_copy_default_headers();
843 struct xml_ctx ctx;
844 char *escaped;
846 url = xstrfmt("%s%s", repo->url, path);
848 /* Make sure leading directories exist for the remote ref */
849 ep = strchr(url + strlen(repo->url) + 1, '/');
850 while (ep) {
851 char saved_character = ep[1];
852 ep[1] = '\0';
853 slot = get_active_slot();
854 slot->results = &results;
855 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
856 if (start_active_slot(slot)) {
857 run_active_slot(slot);
858 if (results.curl_result != CURLE_OK &&
859 results.http_code != 405) {
860 fprintf(stderr,
861 "Unable to create branch path %s\n",
862 url);
863 free(url);
864 return NULL;
866 } else {
867 fprintf(stderr, "Unable to start MKCOL request\n");
868 free(url);
869 return NULL;
871 ep[1] = saved_character;
872 ep = strchr(ep + 1, '/');
875 escaped = xml_entities(ident_default_email());
876 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
877 free(escaped);
879 xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout);
880 dav_headers = curl_slist_append(dav_headers, timeout_header);
881 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
883 slot = get_active_slot();
884 slot->results = &results;
885 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
886 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
887 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
889 CALLOC_ARRAY(lock, 1);
890 lock->timeout = -1;
892 if (start_active_slot(slot)) {
893 run_active_slot(slot);
894 if (results.curl_result == CURLE_OK) {
895 XML_Parser parser = XML_ParserCreate(NULL);
896 enum XML_Status result;
897 ctx.name = xcalloc(10, 1);
898 ctx.len = 0;
899 ctx.cdata = NULL;
900 ctx.userFunc = handle_new_lock_ctx;
901 ctx.userData = lock;
902 XML_SetUserData(parser, &ctx);
903 XML_SetElementHandler(parser, xml_start_tag,
904 xml_end_tag);
905 XML_SetCharacterDataHandler(parser, xml_cdata);
906 result = XML_Parse(parser, in_buffer.buf,
907 in_buffer.len, 1);
908 free(ctx.name);
909 if (result != XML_STATUS_OK) {
910 fprintf(stderr, "XML error: %s\n",
911 XML_ErrorString(
912 XML_GetErrorCode(parser)));
913 lock->timeout = -1;
915 XML_ParserFree(parser);
916 } else {
917 fprintf(stderr,
918 "error: curl result=%d, HTTP code=%ld\n",
919 results.curl_result, results.http_code);
921 } else {
922 fprintf(stderr, "Unable to start LOCK request\n");
925 curl_slist_free_all(dav_headers);
926 strbuf_release(&out_buffer.buf);
927 strbuf_release(&in_buffer);
929 if (lock->token == NULL || lock->timeout <= 0) {
930 free(lock->token);
931 free(lock->owner);
932 free(url);
933 FREE_AND_NULL(lock);
934 } else {
935 lock->url = url;
936 lock->start_time = time(NULL);
937 lock->next = repo->locks;
938 repo->locks = lock;
941 return lock;
944 static int unlock_remote(struct remote_lock *lock)
946 struct active_request_slot *slot;
947 struct slot_results results;
948 struct remote_lock *prev = repo->locks;
949 struct curl_slist *dav_headers;
950 int rc = 0;
952 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
954 slot = get_active_slot();
955 slot->results = &results;
956 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
957 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
959 if (start_active_slot(slot)) {
960 run_active_slot(slot);
961 if (results.curl_result == CURLE_OK)
962 rc = 1;
963 else
964 fprintf(stderr, "UNLOCK HTTP error %ld\n",
965 results.http_code);
966 } else {
967 fprintf(stderr, "Unable to start UNLOCK request\n");
970 curl_slist_free_all(dav_headers);
972 if (repo->locks == lock) {
973 repo->locks = lock->next;
974 } else {
975 while (prev && prev->next != lock)
976 prev = prev->next;
977 if (prev)
978 prev->next = lock->next;
981 free(lock->owner);
982 free(lock->url);
983 free(lock->token);
984 free(lock);
986 return rc;
989 static void remove_locks(void)
991 struct remote_lock *lock = repo->locks;
993 fprintf(stderr, "Removing remote locks...\n");
994 while (lock) {
995 struct remote_lock *next = lock->next;
996 unlock_remote(lock);
997 lock = next;
1001 static void remove_locks_on_signal(int signo)
1003 remove_locks();
1004 sigchain_pop(signo);
1005 raise(signo);
1008 static void remote_ls(const char *path, int flags,
1009 void (*userFunc)(struct remote_ls_ctx *ls),
1010 void *userData);
1012 /* extract hex from sharded "xx/x{38}" filename */
1013 static int get_oid_hex_from_objpath(const char *path, struct object_id *oid)
1015 oid->algo = hash_algo_by_ptr(the_hash_algo);
1017 if (strlen(path) != the_hash_algo->hexsz + 1)
1018 return -1;
1020 if (hex_to_bytes(oid->hash, path, 1))
1021 return -1;
1022 path += 2;
1023 path++; /* skip '/' */
1025 return hex_to_bytes(oid->hash + 1, path, the_hash_algo->rawsz - 1);
1028 static void process_ls_object(struct remote_ls_ctx *ls)
1030 unsigned int *parent = (unsigned int *)ls->userData;
1031 const char *path = ls->dentry_name;
1032 struct object_id oid;
1034 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1035 remote_dir_exists[*parent] = 1;
1036 return;
1039 if (!skip_prefix(path, "objects/", &path) ||
1040 get_oid_hex_from_objpath(path, &oid))
1041 return;
1043 one_remote_object(&oid);
1046 static void process_ls_ref(struct remote_ls_ctx *ls)
1048 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1049 fprintf(stderr, " %s\n", ls->dentry_name);
1050 return;
1053 if (!(ls->dentry_flags & IS_DIR))
1054 one_remote_ref(ls->dentry_name);
1057 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1059 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1061 if (tag_closed) {
1062 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1063 if (ls->dentry_flags & IS_DIR) {
1065 /* ensure collection names end with slash */
1066 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1068 if (ls->flags & PROCESS_DIRS) {
1069 ls->userFunc(ls);
1071 if (strcmp(ls->dentry_name, ls->path) &&
1072 ls->flags & RECURSIVE) {
1073 remote_ls(ls->dentry_name,
1074 ls->flags,
1075 ls->userFunc,
1076 ls->userData);
1078 } else if (ls->flags & PROCESS_FILES) {
1079 ls->userFunc(ls);
1081 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1082 char *path = ctx->cdata;
1083 if (*ctx->cdata == 'h') {
1084 path = strstr(path, "//");
1085 if (path) {
1086 path = strchr(path+2, '/');
1089 if (path) {
1090 const char *url = repo->url;
1091 if (repo->path)
1092 url = repo->path;
1093 if (strncmp(path, url, repo->path_len))
1094 error("Parsed path '%s' does not match url: '%s'",
1095 path, url);
1096 else {
1097 path += repo->path_len;
1098 ls->dentry_name = xstrdup(path);
1101 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1102 ls->dentry_flags |= IS_DIR;
1104 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1105 FREE_AND_NULL(ls->dentry_name);
1106 ls->dentry_flags = 0;
1111 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1112 * should _only_ heed the information from that file, instead of trying to
1113 * determine the refs from the remote file system (badly: it does not even
1114 * know about packed-refs).
1116 static void remote_ls(const char *path, int flags,
1117 void (*userFunc)(struct remote_ls_ctx *ls),
1118 void *userData)
1120 char *url = xstrfmt("%s%s", repo->url, path);
1121 struct active_request_slot *slot;
1122 struct slot_results results;
1123 struct strbuf in_buffer = STRBUF_INIT;
1124 struct buffer out_buffer = { STRBUF_INIT, 0 };
1125 struct curl_slist *dav_headers = http_copy_default_headers();
1126 struct xml_ctx ctx;
1127 struct remote_ls_ctx ls;
1129 ls.flags = flags;
1130 ls.path = xstrdup(path);
1131 ls.dentry_name = NULL;
1132 ls.dentry_flags = 0;
1133 ls.userData = userData;
1134 ls.userFunc = userFunc;
1136 strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1138 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1139 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1141 slot = get_active_slot();
1142 slot->results = &results;
1143 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1144 &out_buffer, fwrite_buffer);
1145 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1146 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1148 if (start_active_slot(slot)) {
1149 run_active_slot(slot);
1150 if (results.curl_result == CURLE_OK) {
1151 XML_Parser parser = XML_ParserCreate(NULL);
1152 enum XML_Status result;
1153 ctx.name = xcalloc(10, 1);
1154 ctx.len = 0;
1155 ctx.cdata = NULL;
1156 ctx.userFunc = handle_remote_ls_ctx;
1157 ctx.userData = &ls;
1158 XML_SetUserData(parser, &ctx);
1159 XML_SetElementHandler(parser, xml_start_tag,
1160 xml_end_tag);
1161 XML_SetCharacterDataHandler(parser, xml_cdata);
1162 result = XML_Parse(parser, in_buffer.buf,
1163 in_buffer.len, 1);
1164 free(ctx.name);
1166 if (result != XML_STATUS_OK) {
1167 fprintf(stderr, "XML error: %s\n",
1168 XML_ErrorString(
1169 XML_GetErrorCode(parser)));
1171 XML_ParserFree(parser);
1173 } else {
1174 fprintf(stderr, "Unable to start PROPFIND request\n");
1177 free(ls.path);
1178 free(url);
1179 strbuf_release(&out_buffer.buf);
1180 strbuf_release(&in_buffer);
1181 curl_slist_free_all(dav_headers);
1184 static void get_remote_object_list(unsigned char parent)
1186 char path[] = "objects/XX/";
1187 static const char hex[] = "0123456789abcdef";
1188 unsigned int val = parent;
1190 path[8] = hex[val >> 4];
1191 path[9] = hex[val & 0xf];
1192 remote_dir_exists[val] = 0;
1193 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1194 process_ls_object, &val);
1197 static int locking_available(void)
1199 struct active_request_slot *slot;
1200 struct slot_results results;
1201 struct strbuf in_buffer = STRBUF_INIT;
1202 struct buffer out_buffer = { STRBUF_INIT, 0 };
1203 struct curl_slist *dav_headers = http_copy_default_headers();
1204 struct xml_ctx ctx;
1205 int lock_flags = 0;
1206 char *escaped;
1208 escaped = xml_entities(repo->url);
1209 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1210 free(escaped);
1212 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1213 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1215 slot = get_active_slot();
1216 slot->results = &results;
1217 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1218 &out_buffer, fwrite_buffer);
1219 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1220 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1222 if (start_active_slot(slot)) {
1223 run_active_slot(slot);
1224 if (results.curl_result == CURLE_OK) {
1225 XML_Parser parser = XML_ParserCreate(NULL);
1226 enum XML_Status result;
1227 ctx.name = xcalloc(10, 1);
1228 ctx.len = 0;
1229 ctx.cdata = NULL;
1230 ctx.userFunc = handle_lockprop_ctx;
1231 ctx.userData = &lock_flags;
1232 XML_SetUserData(parser, &ctx);
1233 XML_SetElementHandler(parser, xml_start_tag,
1234 xml_end_tag);
1235 result = XML_Parse(parser, in_buffer.buf,
1236 in_buffer.len, 1);
1237 free(ctx.name);
1239 if (result != XML_STATUS_OK) {
1240 fprintf(stderr, "XML error: %s\n",
1241 XML_ErrorString(
1242 XML_GetErrorCode(parser)));
1243 lock_flags = 0;
1245 XML_ParserFree(parser);
1246 if (!lock_flags)
1247 error("no DAV locking support on %s",
1248 repo->url);
1250 } else {
1251 error("Cannot access URL %s, return code %d",
1252 repo->url, results.curl_result);
1253 lock_flags = 0;
1255 } else {
1256 error("Unable to start PROPFIND request on %s", repo->url);
1259 strbuf_release(&out_buffer.buf);
1260 strbuf_release(&in_buffer);
1261 curl_slist_free_all(dav_headers);
1263 return lock_flags;
1266 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1268 struct object_list *entry = xmalloc(sizeof(struct object_list));
1269 entry->item = obj;
1270 entry->next = *p;
1271 *p = entry;
1272 return &entry->next;
1275 static struct object_list **process_blob(struct blob *blob,
1276 struct object_list **p)
1278 struct object *obj = &blob->object;
1280 obj->flags |= LOCAL;
1282 if (obj->flags & (UNINTERESTING | SEEN))
1283 return p;
1285 obj->flags |= SEEN;
1286 return add_one_object(obj, p);
1289 static struct object_list **process_tree(struct tree *tree,
1290 struct object_list **p)
1292 struct object *obj = &tree->object;
1293 struct tree_desc desc;
1294 struct name_entry entry;
1296 obj->flags |= LOCAL;
1298 if (obj->flags & (UNINTERESTING | SEEN))
1299 return p;
1300 if (parse_tree(tree) < 0)
1301 die("bad tree object %s", oid_to_hex(&obj->oid));
1303 obj->flags |= SEEN;
1304 p = add_one_object(obj, p);
1306 init_tree_desc(&desc, tree->buffer, tree->size);
1308 while (tree_entry(&desc, &entry))
1309 switch (object_type(entry.mode)) {
1310 case OBJ_TREE:
1311 p = process_tree(lookup_tree(the_repository, &entry.oid),
1313 break;
1314 case OBJ_BLOB:
1315 p = process_blob(lookup_blob(the_repository, &entry.oid),
1317 break;
1318 default:
1319 /* Subproject commit - not in this repository */
1320 break;
1323 free_tree_buffer(tree);
1324 return p;
1327 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1329 int i;
1330 struct commit *commit;
1331 struct object_list **p = &objects;
1332 int count = 0;
1334 while ((commit = get_revision(revs)) != NULL) {
1335 p = process_tree(get_commit_tree(commit), p);
1336 commit->object.flags |= LOCAL;
1337 if (!(commit->object.flags & UNINTERESTING))
1338 count += add_send_request(&commit->object, lock);
1341 for (i = 0; i < revs->pending.nr; i++) {
1342 struct object_array_entry *entry = revs->pending.objects + i;
1343 struct object *obj = entry->item;
1344 const char *name = entry->name;
1346 if (obj->flags & (UNINTERESTING | SEEN))
1347 continue;
1348 if (obj->type == OBJ_TAG) {
1349 obj->flags |= SEEN;
1350 p = add_one_object(obj, p);
1351 continue;
1353 if (obj->type == OBJ_TREE) {
1354 p = process_tree((struct tree *)obj, p);
1355 continue;
1357 if (obj->type == OBJ_BLOB) {
1358 p = process_blob((struct blob *)obj, p);
1359 continue;
1361 die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name);
1364 while (objects) {
1365 if (!(objects->item->flags & UNINTERESTING))
1366 count += add_send_request(objects->item, lock);
1367 objects = objects->next;
1370 return count;
1373 static int update_remote(const struct object_id *oid, struct remote_lock *lock)
1375 struct active_request_slot *slot;
1376 struct slot_results results;
1377 struct buffer out_buffer = { STRBUF_INIT, 0 };
1378 struct curl_slist *dav_headers;
1380 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1382 strbuf_addf(&out_buffer.buf, "%s\n", oid_to_hex(oid));
1384 slot = get_active_slot();
1385 slot->results = &results;
1386 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1387 &out_buffer, fwrite_null);
1388 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1390 if (start_active_slot(slot)) {
1391 run_active_slot(slot);
1392 strbuf_release(&out_buffer.buf);
1393 if (results.curl_result != CURLE_OK) {
1394 fprintf(stderr,
1395 "PUT error: curl result=%d, HTTP code=%ld\n",
1396 results.curl_result, results.http_code);
1397 /* We should attempt recovery? */
1398 return 0;
1400 } else {
1401 strbuf_release(&out_buffer.buf);
1402 fprintf(stderr, "Unable to start PUT request\n");
1403 return 0;
1406 return 1;
1409 static struct ref *remote_refs;
1411 static void one_remote_ref(const char *refname)
1413 struct ref *ref;
1414 struct object *obj;
1416 ref = alloc_ref(refname);
1418 if (http_fetch_ref(repo->url, ref) != 0) {
1419 fprintf(stderr,
1420 "Unable to fetch ref %s from %s\n",
1421 refname, repo->url);
1422 free(ref);
1423 return;
1427 * Fetch a copy of the object if it doesn't exist locally - it
1428 * may be required for updating server info later.
1430 if (repo->can_update_info_refs && !has_object_file(&ref->old_oid)) {
1431 obj = lookup_unknown_object(the_repository, &ref->old_oid);
1432 fprintf(stderr, " fetch %s for %s\n",
1433 oid_to_hex(&ref->old_oid), refname);
1434 add_fetch_request(obj);
1437 ref->next = remote_refs;
1438 remote_refs = ref;
1441 static void get_dav_remote_heads(void)
1443 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1446 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1448 struct strbuf *buf = (struct strbuf *)ls->userData;
1449 struct object *o;
1450 struct ref *ref;
1452 ref = alloc_ref(ls->dentry_name);
1454 if (http_fetch_ref(repo->url, ref) != 0) {
1455 fprintf(stderr,
1456 "Unable to fetch ref %s from %s\n",
1457 ls->dentry_name, repo->url);
1458 aborted = 1;
1459 free(ref);
1460 return;
1463 o = parse_object(the_repository, &ref->old_oid);
1464 if (!o) {
1465 fprintf(stderr,
1466 "Unable to parse object %s for remote ref %s\n",
1467 oid_to_hex(&ref->old_oid), ls->dentry_name);
1468 aborted = 1;
1469 free(ref);
1470 return;
1473 strbuf_addf(buf, "%s\t%s\n",
1474 oid_to_hex(&ref->old_oid), ls->dentry_name);
1476 if (o->type == OBJ_TAG) {
1477 o = deref_tag(the_repository, o, ls->dentry_name, 0);
1478 if (o)
1479 strbuf_addf(buf, "%s\t%s^{}\n",
1480 oid_to_hex(&o->oid), ls->dentry_name);
1482 free(ref);
1485 static void update_remote_info_refs(struct remote_lock *lock)
1487 struct buffer buffer = { STRBUF_INIT, 0 };
1488 struct active_request_slot *slot;
1489 struct slot_results results;
1490 struct curl_slist *dav_headers;
1492 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1493 add_remote_info_ref, &buffer.buf);
1494 if (!aborted) {
1495 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1497 slot = get_active_slot();
1498 slot->results = &results;
1499 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1500 &buffer, fwrite_null);
1501 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1503 if (start_active_slot(slot)) {
1504 run_active_slot(slot);
1505 if (results.curl_result != CURLE_OK) {
1506 fprintf(stderr,
1507 "PUT error: curl result=%d, HTTP code=%ld\n",
1508 results.curl_result, results.http_code);
1512 strbuf_release(&buffer.buf);
1515 static int remote_exists(const char *path)
1517 char *url = xstrfmt("%s%s", repo->url, path);
1518 int ret;
1521 switch (http_get_strbuf(url, NULL, NULL)) {
1522 case HTTP_OK:
1523 ret = 1;
1524 break;
1525 case HTTP_MISSING_TARGET:
1526 ret = 0;
1527 break;
1528 case HTTP_ERROR:
1529 error("unable to access '%s': %s", url, curl_errorstr);
1530 /* fallthrough */
1531 default:
1532 ret = -1;
1534 free(url);
1535 return ret;
1538 static void fetch_symref(const char *path, char **symref, struct object_id *oid)
1540 char *url = xstrfmt("%s%s", repo->url, path);
1541 struct strbuf buffer = STRBUF_INIT;
1542 const char *name;
1544 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1545 die("Couldn't get %s for remote symref\n%s", url,
1546 curl_errorstr);
1547 free(url);
1549 FREE_AND_NULL(*symref);
1550 oidclr(oid);
1552 if (buffer.len == 0)
1553 return;
1555 /* Cut off trailing newline. */
1556 strbuf_rtrim(&buffer);
1558 /* If it's a symref, set the refname; otherwise try for a sha1 */
1559 if (skip_prefix(buffer.buf, "ref: ", &name)) {
1560 *symref = xmemdupz(name, buffer.len - (name - buffer.buf));
1561 } else {
1562 get_oid_hex(buffer.buf, oid);
1565 strbuf_release(&buffer);
1568 static int verify_merge_base(struct object_id *head_oid, struct ref *remote)
1570 struct commit *head = lookup_commit_or_die(head_oid, "HEAD");
1571 struct commit *branch = lookup_commit_or_die(&remote->old_oid,
1572 remote->name);
1574 return in_merge_bases(branch, head);
1577 static int delete_remote_branch(const char *pattern, int force)
1579 struct ref *refs = remote_refs;
1580 struct ref *remote_ref = NULL;
1581 struct object_id head_oid;
1582 char *symref = NULL;
1583 int match;
1584 int patlen = strlen(pattern);
1585 int i;
1586 struct active_request_slot *slot;
1587 struct slot_results results;
1588 char *url;
1590 /* Find the remote branch(es) matching the specified branch name */
1591 for (match = 0; refs; refs = refs->next) {
1592 char *name = refs->name;
1593 int namelen = strlen(name);
1594 if (namelen < patlen ||
1595 memcmp(name + namelen - patlen, pattern, patlen))
1596 continue;
1597 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1598 continue;
1599 match++;
1600 remote_ref = refs;
1602 if (match == 0)
1603 return error("No remote branch matches %s", pattern);
1604 if (match != 1)
1605 return error("More than one remote branch matches %s",
1606 pattern);
1609 * Remote HEAD must be a symref (not exactly foolproof; a remote
1610 * symlink to a symref will look like a symref)
1612 fetch_symref("HEAD", &symref, &head_oid);
1613 if (!symref)
1614 return error("Remote HEAD is not a symref");
1616 /* Remote branch must not be the remote HEAD */
1617 for (i = 0; symref && i < MAXDEPTH; i++) {
1618 if (!strcmp(remote_ref->name, symref))
1619 return error("Remote branch %s is the current HEAD",
1620 remote_ref->name);
1621 fetch_symref(symref, &symref, &head_oid);
1624 /* Run extra sanity checks if delete is not forced */
1625 if (!force) {
1626 /* Remote HEAD must resolve to a known object */
1627 if (symref)
1628 return error("Remote HEAD symrefs too deep");
1629 if (is_null_oid(&head_oid))
1630 return error("Unable to resolve remote HEAD");
1631 if (!has_object_file(&head_oid))
1632 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", oid_to_hex(&head_oid));
1634 /* Remote branch must resolve to a known object */
1635 if (is_null_oid(&remote_ref->old_oid))
1636 return error("Unable to resolve remote branch %s",
1637 remote_ref->name);
1638 if (!has_object_file(&remote_ref->old_oid))
1639 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));
1641 /* Remote branch must be an ancestor of remote HEAD */
1642 if (!verify_merge_base(&head_oid, remote_ref)) {
1643 return error("The branch '%s' is not an ancestor "
1644 "of your current HEAD.\n"
1645 "If you are sure you want to delete it,"
1646 " run:\n\t'git http-push -D %s %s'",
1647 remote_ref->name, repo->url, pattern);
1651 /* Send delete request */
1652 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1653 if (dry_run)
1654 return 0;
1655 url = xstrfmt("%s%s", repo->url, remote_ref->name);
1656 slot = get_active_slot();
1657 slot->results = &results;
1658 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1659 if (start_active_slot(slot)) {
1660 run_active_slot(slot);
1661 free(url);
1662 if (results.curl_result != CURLE_OK)
1663 return error("DELETE request failed (%d/%ld)",
1664 results.curl_result, results.http_code);
1665 } else {
1666 free(url);
1667 return error("Unable to start DELETE request");
1670 return 0;
1673 static void run_request_queue(void)
1675 is_running_queue = 1;
1676 fill_active_slots();
1677 add_fill_function(NULL, fill_active_slot);
1678 do {
1679 finish_all_active_slots();
1680 fill_active_slots();
1681 } while (request_queue_head && !aborted);
1683 is_running_queue = 0;
1686 int cmd_main(int argc, const char **argv)
1688 struct transfer_request *request;
1689 struct transfer_request *next_request;
1690 struct refspec rs = REFSPEC_INIT_PUSH;
1691 struct remote_lock *ref_lock = NULL;
1692 struct remote_lock *info_ref_lock = NULL;
1693 int delete_branch = 0;
1694 int force_delete = 0;
1695 int objects_to_send;
1696 int rc = 0;
1697 int i;
1698 int new_refs;
1699 struct ref *ref, *local_refs;
1701 CALLOC_ARRAY(repo, 1);
1703 argv++;
1704 for (i = 1; i < argc; i++, argv++) {
1705 const char *arg = *argv;
1707 if (*arg == '-') {
1708 if (!strcmp(arg, "--all")) {
1709 push_all = MATCH_REFS_ALL;
1710 continue;
1712 if (!strcmp(arg, "--force")) {
1713 force_all = 1;
1714 continue;
1716 if (!strcmp(arg, "--dry-run")) {
1717 dry_run = 1;
1718 continue;
1720 if (!strcmp(arg, "--helper-status")) {
1721 helper_status = 1;
1722 continue;
1724 if (!strcmp(arg, "--verbose")) {
1725 push_verbosely = 1;
1726 http_is_verbose = 1;
1727 continue;
1729 if (!strcmp(arg, "-d")) {
1730 delete_branch = 1;
1731 continue;
1733 if (!strcmp(arg, "-D")) {
1734 delete_branch = 1;
1735 force_delete = 1;
1736 continue;
1738 if (!strcmp(arg, "-h"))
1739 usage(http_push_usage);
1741 if (!repo->url) {
1742 char *path = strstr(arg, "//");
1743 str_end_url_with_slash(arg, &repo->url);
1744 repo->path_len = strlen(repo->url);
1745 if (path) {
1746 repo->path = strchr(path+2, '/');
1747 if (repo->path)
1748 repo->path_len = strlen(repo->path);
1750 continue;
1752 refspec_appendn(&rs, argv, argc - i);
1753 break;
1756 if (!repo->url)
1757 usage(http_push_usage);
1759 if (delete_branch && rs.nr != 1)
1760 die("You must specify only one branch name when deleting a remote branch");
1762 setup_git_directory();
1764 memset(remote_dir_exists, -1, 256);
1766 http_init(NULL, repo->url, 1);
1768 is_running_queue = 0;
1770 /* Verify DAV compliance/lock support */
1771 if (!locking_available()) {
1772 rc = 1;
1773 goto cleanup;
1776 sigchain_push_common(remove_locks_on_signal);
1778 /* Check whether the remote has server info files */
1779 repo->can_update_info_refs = 0;
1780 repo->has_info_refs = remote_exists("info/refs");
1781 repo->has_info_packs = remote_exists("objects/info/packs");
1782 if (repo->has_info_refs) {
1783 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1784 if (info_ref_lock)
1785 repo->can_update_info_refs = 1;
1786 else {
1787 error("cannot lock existing info/refs");
1788 rc = 1;
1789 goto cleanup;
1792 if (repo->has_info_packs)
1793 fetch_indices();
1795 /* Get a list of all local and remote heads to validate refspecs */
1796 local_refs = get_local_heads();
1797 fprintf(stderr, "Fetching remote heads...\n");
1798 get_dav_remote_heads();
1799 run_request_queue();
1801 /* Remove a remote branch if -d or -D was specified */
1802 if (delete_branch) {
1803 const char *branch = rs.items[i].src;
1804 if (delete_remote_branch(branch, force_delete) == -1) {
1805 fprintf(stderr, "Unable to delete remote branch %s\n",
1806 branch);
1807 if (helper_status)
1808 printf("error %s cannot remove\n", branch);
1810 goto cleanup;
1813 /* match them up */
1814 if (match_push_refs(local_refs, &remote_refs, &rs, push_all)) {
1815 rc = -1;
1816 goto cleanup;
1818 if (!remote_refs) {
1819 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1820 if (helper_status)
1821 printf("error null no match\n");
1822 rc = 0;
1823 goto cleanup;
1826 new_refs = 0;
1827 for (ref = remote_refs; ref; ref = ref->next) {
1828 struct rev_info revs;
1829 struct strvec commit_argv = STRVEC_INIT;
1831 if (!ref->peer_ref)
1832 continue;
1834 if (is_null_oid(&ref->peer_ref->new_oid)) {
1835 if (delete_remote_branch(ref->name, 1) == -1) {
1836 error("Could not remove %s", ref->name);
1837 if (helper_status)
1838 printf("error %s cannot remove\n", ref->name);
1839 rc = -4;
1841 else if (helper_status)
1842 printf("ok %s\n", ref->name);
1843 new_refs++;
1844 continue;
1847 if (oideq(&ref->old_oid, &ref->peer_ref->new_oid)) {
1848 if (push_verbosely)
1849 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1850 if (helper_status)
1851 printf("ok %s up to date\n", ref->name);
1852 continue;
1855 if (!force_all &&
1856 !is_null_oid(&ref->old_oid) &&
1857 !ref->force) {
1858 if (!has_object_file(&ref->old_oid) ||
1859 !ref_newer(&ref->peer_ref->new_oid,
1860 &ref->old_oid)) {
1862 * We do not have the remote ref, or
1863 * we know that the remote ref is not
1864 * an ancestor of what we are trying to
1865 * push. Either way this can be losing
1866 * commits at the remote end and likely
1867 * we were not up to date to begin with.
1869 error("remote '%s' is not an ancestor of\n"
1870 "local '%s'.\n"
1871 "Maybe you are not up-to-date and "
1872 "need to pull first?",
1873 ref->name,
1874 ref->peer_ref->name);
1875 if (helper_status)
1876 printf("error %s non-fast forward\n", ref->name);
1877 rc = -2;
1878 continue;
1881 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1882 new_refs++;
1884 fprintf(stderr, "updating '%s'", ref->name);
1885 if (strcmp(ref->name, ref->peer_ref->name))
1886 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1887 fprintf(stderr, "\n from %s\n to %s\n",
1888 oid_to_hex(&ref->old_oid), oid_to_hex(&ref->new_oid));
1889 if (dry_run) {
1890 if (helper_status)
1891 printf("ok %s\n", ref->name);
1892 continue;
1895 /* Lock remote branch ref */
1896 ref_lock = lock_remote(ref->name, LOCK_TIME);
1897 if (!ref_lock) {
1898 fprintf(stderr, "Unable to lock remote branch %s\n",
1899 ref->name);
1900 if (helper_status)
1901 printf("error %s lock error\n", ref->name);
1902 rc = 1;
1903 continue;
1906 /* Set up revision info for this refspec */
1907 strvec_push(&commit_argv, ""); /* ignored */
1908 strvec_push(&commit_argv, "--objects");
1909 strvec_push(&commit_argv, oid_to_hex(&ref->new_oid));
1910 if (!push_all && !is_null_oid(&ref->old_oid))
1911 strvec_pushf(&commit_argv, "^%s",
1912 oid_to_hex(&ref->old_oid));
1913 repo_init_revisions(the_repository, &revs, setup_git_directory());
1914 setup_revisions(commit_argv.nr, commit_argv.v, &revs, NULL);
1915 revs.edge_hint = 0; /* just in case */
1917 /* Generate a list of objects that need to be pushed */
1918 pushing = 0;
1919 if (prepare_revision_walk(&revs))
1920 die("revision walk setup failed");
1921 mark_edges_uninteresting(&revs, NULL, 0);
1922 objects_to_send = get_delta(&revs, ref_lock);
1923 finish_all_active_slots();
1925 /* Push missing objects to remote, this would be a
1926 convenient time to pack them first if appropriate. */
1927 pushing = 1;
1928 if (objects_to_send)
1929 fprintf(stderr, " sending %d objects\n",
1930 objects_to_send);
1932 run_request_queue();
1934 /* Update the remote branch if all went well */
1935 if (aborted || !update_remote(&ref->new_oid, ref_lock))
1936 rc = 1;
1938 if (!rc)
1939 fprintf(stderr, " done\n");
1940 if (helper_status)
1941 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1942 unlock_remote(ref_lock);
1943 check_locks();
1944 strvec_clear(&commit_argv);
1945 release_revisions(&revs);
1948 /* Update remote server info if appropriate */
1949 if (repo->has_info_refs && new_refs) {
1950 if (info_ref_lock && repo->can_update_info_refs) {
1951 fprintf(stderr, "Updating remote server info\n");
1952 if (!dry_run)
1953 update_remote_info_refs(info_ref_lock);
1954 } else {
1955 fprintf(stderr, "Unable to update server info\n");
1959 cleanup:
1960 if (info_ref_lock)
1961 unlock_remote(info_ref_lock);
1962 free(repo);
1964 http_cleanup();
1966 request = request_queue_head;
1967 while (request != NULL) {
1968 next_request = request->next;
1969 release_request(request);
1970 request = next_request;
1973 return rc;