setup.h: move declarations for setup.c functions from cache.h
[git.git] / http-push.c
blobe73864b51f51f4c933d993db6b10a2a4b243805c
1 #include "cache.h"
2 #include "environment.h"
3 #include "hex.h"
4 #include "repository.h"
5 #include "commit.h"
6 #include "tag.h"
7 #include "blob.h"
8 #include "http.h"
9 #include "refs.h"
10 #include "diff.h"
11 #include "revision.h"
12 #include "exec-cmd.h"
13 #include "remote.h"
14 #include "list-objects.h"
15 #include "setup.h"
16 #include "sigchain.h"
17 #include "strvec.h"
18 #include "packfile.h"
19 #include "object-store.h"
20 #include "commit-reach.h"
22 #ifdef EXPAT_NEEDS_XMLPARSE_H
23 #include <xmlparse.h>
24 #else
25 #include <expat.h>
26 #endif
28 static const char http_push_usage[] =
29 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
31 #ifndef XML_STATUS_OK
32 enum XML_Status {
33 XML_STATUS_OK = 1,
34 XML_STATUS_ERROR = 0
36 #define XML_STATUS_OK 1
37 #define XML_STATUS_ERROR 0
38 #endif
40 #define PREV_BUF_SIZE 4096
42 /* DAV methods */
43 #define DAV_LOCK "LOCK"
44 #define DAV_MKCOL "MKCOL"
45 #define DAV_MOVE "MOVE"
46 #define DAV_PROPFIND "PROPFIND"
47 #define DAV_PUT "PUT"
48 #define DAV_UNLOCK "UNLOCK"
49 #define DAV_DELETE "DELETE"
51 /* DAV lock flags */
52 #define DAV_PROP_LOCKWR (1u << 0)
53 #define DAV_PROP_LOCKEX (1u << 1)
54 #define DAV_LOCK_OK (1u << 2)
56 /* DAV XML properties */
57 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
58 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
59 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
60 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
61 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
62 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
63 #define DAV_PROPFIND_RESP ".multistatus.response"
64 #define DAV_PROPFIND_NAME ".multistatus.response.href"
65 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
67 /* DAV request body templates */
68 #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>"
69 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
70 #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>"
72 #define LOCK_TIME 600
73 #define LOCK_REFRESH 30
75 /* Remember to update object flag allocation in object.h */
76 #define LOCAL (1u<<11)
77 #define REMOTE (1u<<12)
78 #define FETCHING (1u<<13)
79 #define PUSHING (1u<<14)
81 /* We allow "recursive" symbolic refs. Only within reason, though */
82 #define MAXDEPTH 5
84 static int pushing;
85 static int aborted;
86 static signed char remote_dir_exists[256];
88 static int push_verbosely;
89 static int push_all = MATCH_REFS_NONE;
90 static int force_all;
91 static int dry_run;
92 static int helper_status;
94 static struct object_list *objects;
96 struct repo {
97 char *url;
98 char *path;
99 int path_len;
100 int has_info_refs;
101 int can_update_info_refs;
102 int has_info_packs;
103 struct packed_git *packs;
104 struct remote_lock *locks;
107 static struct repo *repo;
109 enum transfer_state {
110 NEED_FETCH,
111 RUN_FETCH_LOOSE,
112 RUN_FETCH_PACKED,
113 NEED_PUSH,
114 RUN_MKCOL,
115 RUN_PUT,
116 RUN_MOVE,
117 ABORTED,
118 COMPLETE
121 struct transfer_request {
122 struct object *obj;
123 struct packed_git *target;
124 char *url;
125 char *dest;
126 struct remote_lock *lock;
127 struct curl_slist *headers;
128 struct buffer buffer;
129 enum transfer_state state;
130 CURLcode curl_result;
131 char errorstr[CURL_ERROR_SIZE];
132 long http_code;
133 void *userData;
134 struct active_request_slot *slot;
135 struct transfer_request *next;
138 static struct transfer_request *request_queue_head;
140 struct xml_ctx {
141 char *name;
142 int len;
143 char *cdata;
144 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
145 void *userData;
148 struct remote_lock {
149 char *url;
150 char *owner;
151 char *token;
152 char tmpfile_suffix[GIT_MAX_HEXSZ + 1];
153 time_t start_time;
154 long timeout;
155 int refreshing;
156 struct remote_lock *next;
159 /* Flags that control remote_ls processing */
160 #define PROCESS_FILES (1u << 0)
161 #define PROCESS_DIRS (1u << 1)
162 #define RECURSIVE (1u << 2)
164 /* Flags that remote_ls passes to callback functions */
165 #define IS_DIR (1u << 0)
167 struct remote_ls_ctx {
168 char *path;
169 void (*userFunc)(struct remote_ls_ctx *ls);
170 void *userData;
171 int flags;
172 char *dentry_name;
173 int dentry_flags;
174 struct remote_ls_ctx *parent;
177 /* get_dav_token_headers options */
178 enum dav_header_flag {
179 DAV_HEADER_IF = (1u << 0),
180 DAV_HEADER_LOCK = (1u << 1),
181 DAV_HEADER_TIMEOUT = (1u << 2)
184 static char *xml_entities(const char *s)
186 struct strbuf buf = STRBUF_INIT;
187 strbuf_addstr_xml_quoted(&buf, s);
188 return strbuf_detach(&buf, NULL);
191 static void curl_setup_http_get(CURL *curl, const char *url,
192 const char *custom_req)
194 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
195 curl_easy_setopt(curl, CURLOPT_URL, url);
196 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
197 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
200 static void curl_setup_http(CURL *curl, const char *url,
201 const char *custom_req, struct buffer *buffer,
202 curl_write_callback write_fn)
204 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
205 curl_easy_setopt(curl, CURLOPT_URL, url);
206 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
207 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
208 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
209 curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, seek_buffer);
210 curl_easy_setopt(curl, CURLOPT_SEEKDATA, buffer);
211 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
212 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
213 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
214 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
217 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
219 struct strbuf buf = STRBUF_INIT;
220 struct curl_slist *dav_headers = http_copy_default_headers();
222 if (options & DAV_HEADER_IF) {
223 strbuf_addf(&buf, "If: (<%s>)", lock->token);
224 dav_headers = curl_slist_append(dav_headers, buf.buf);
225 strbuf_reset(&buf);
227 if (options & DAV_HEADER_LOCK) {
228 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
229 dav_headers = curl_slist_append(dav_headers, buf.buf);
230 strbuf_reset(&buf);
232 if (options & DAV_HEADER_TIMEOUT) {
233 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
234 dav_headers = curl_slist_append(dav_headers, buf.buf);
235 strbuf_reset(&buf);
237 strbuf_release(&buf);
239 return dav_headers;
242 static void finish_request(struct transfer_request *request);
243 static void release_request(struct transfer_request *request);
245 static void process_response(void *callback_data)
247 struct transfer_request *request =
248 (struct transfer_request *)callback_data;
250 finish_request(request);
253 static void start_fetch_loose(struct transfer_request *request)
255 struct active_request_slot *slot;
256 struct http_object_request *obj_req;
258 obj_req = new_http_object_request(repo->url, &request->obj->oid);
259 if (!obj_req) {
260 request->state = ABORTED;
261 return;
264 slot = obj_req->slot;
265 slot->callback_func = process_response;
266 slot->callback_data = request;
267 request->slot = slot;
268 request->userData = obj_req;
270 /* Try to get the request started, abort the request on error */
271 request->state = RUN_FETCH_LOOSE;
272 if (!start_active_slot(slot)) {
273 fprintf(stderr, "Unable to start GET request\n");
274 repo->can_update_info_refs = 0;
275 release_http_object_request(obj_req);
276 release_request(request);
280 static void start_mkcol(struct transfer_request *request)
282 char *hex = oid_to_hex(&request->obj->oid);
283 struct active_request_slot *slot;
285 request->url = get_remote_object_url(repo->url, hex, 1);
287 slot = get_active_slot();
288 slot->callback_func = process_response;
289 slot->callback_data = request;
290 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
291 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
293 if (start_active_slot(slot)) {
294 request->slot = slot;
295 request->state = RUN_MKCOL;
296 } else {
297 request->state = ABORTED;
298 FREE_AND_NULL(request->url);
302 static void start_fetch_packed(struct transfer_request *request)
304 struct packed_git *target;
306 struct transfer_request *check_request = request_queue_head;
307 struct http_pack_request *preq;
309 target = find_sha1_pack(request->obj->oid.hash, repo->packs);
310 if (!target) {
311 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", oid_to_hex(&request->obj->oid));
312 repo->can_update_info_refs = 0;
313 release_request(request);
314 return;
316 close_pack_index(target);
317 request->target = target;
319 fprintf(stderr, "Fetching pack %s\n",
320 hash_to_hex(target->hash));
321 fprintf(stderr, " which contains %s\n", oid_to_hex(&request->obj->oid));
323 preq = new_http_pack_request(target->hash, repo->url);
324 if (!preq) {
325 repo->can_update_info_refs = 0;
326 return;
329 /* Make sure there isn't another open request for this pack */
330 while (check_request) {
331 if (check_request->state == RUN_FETCH_PACKED &&
332 !strcmp(check_request->url, preq->url)) {
333 release_http_pack_request(preq);
334 release_request(request);
335 return;
337 check_request = check_request->next;
340 preq->slot->callback_func = process_response;
341 preq->slot->callback_data = request;
342 request->slot = preq->slot;
343 request->userData = preq;
345 /* Try to get the request started, abort the request on error */
346 request->state = RUN_FETCH_PACKED;
347 if (!start_active_slot(preq->slot)) {
348 fprintf(stderr, "Unable to start GET request\n");
349 release_http_pack_request(preq);
350 repo->can_update_info_refs = 0;
351 release_request(request);
355 static void start_put(struct transfer_request *request)
357 char *hex = oid_to_hex(&request->obj->oid);
358 struct active_request_slot *slot;
359 struct strbuf buf = STRBUF_INIT;
360 enum object_type type;
361 char hdr[50];
362 void *unpacked;
363 unsigned long len;
364 int hdrlen;
365 ssize_t size;
366 git_zstream stream;
368 unpacked = read_object_file(&request->obj->oid, &type, &len);
369 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
371 /* Set it up */
372 git_deflate_init(&stream, zlib_compression_level);
373 size = git_deflate_bound(&stream, len + hdrlen);
374 strbuf_init(&request->buffer.buf, size);
375 request->buffer.posn = 0;
377 /* Compress it */
378 stream.next_out = (unsigned char *)request->buffer.buf.buf;
379 stream.avail_out = size;
381 /* First header.. */
382 stream.next_in = (void *)hdr;
383 stream.avail_in = hdrlen;
384 while (git_deflate(&stream, 0) == Z_OK)
385 ; /* nothing */
387 /* Then the data itself.. */
388 stream.next_in = unpacked;
389 stream.avail_in = len;
390 while (git_deflate(&stream, Z_FINISH) == Z_OK)
391 ; /* nothing */
392 git_deflate_end(&stream);
393 free(unpacked);
395 request->buffer.buf.len = stream.total_out;
397 strbuf_addstr(&buf, "Destination: ");
398 append_remote_object_url(&buf, repo->url, hex, 0);
399 request->dest = strbuf_detach(&buf, NULL);
401 append_remote_object_url(&buf, repo->url, hex, 0);
402 strbuf_add(&buf, request->lock->tmpfile_suffix, the_hash_algo->hexsz + 1);
403 request->url = strbuf_detach(&buf, NULL);
405 slot = get_active_slot();
406 slot->callback_func = process_response;
407 slot->callback_data = request;
408 curl_setup_http(slot->curl, request->url, DAV_PUT,
409 &request->buffer, fwrite_null);
411 if (start_active_slot(slot)) {
412 request->slot = slot;
413 request->state = RUN_PUT;
414 } else {
415 request->state = ABORTED;
416 FREE_AND_NULL(request->url);
420 static void start_move(struct transfer_request *request)
422 struct active_request_slot *slot;
423 struct curl_slist *dav_headers = http_copy_default_headers();
425 slot = get_active_slot();
426 slot->callback_func = process_response;
427 slot->callback_data = request;
428 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
429 dav_headers = curl_slist_append(dav_headers, request->dest);
430 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
431 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
433 if (start_active_slot(slot)) {
434 request->slot = slot;
435 request->state = RUN_MOVE;
436 } else {
437 request->state = ABORTED;
438 FREE_AND_NULL(request->url);
442 static int refresh_lock(struct remote_lock *lock)
444 struct active_request_slot *slot;
445 struct slot_results results;
446 struct curl_slist *dav_headers;
447 int rc = 0;
449 lock->refreshing = 1;
451 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
453 slot = get_active_slot();
454 slot->results = &results;
455 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
456 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
458 if (start_active_slot(slot)) {
459 run_active_slot(slot);
460 if (results.curl_result != CURLE_OK) {
461 fprintf(stderr, "LOCK HTTP error %ld\n",
462 results.http_code);
463 } else {
464 lock->start_time = time(NULL);
465 rc = 1;
469 lock->refreshing = 0;
470 curl_slist_free_all(dav_headers);
472 return rc;
475 static void check_locks(void)
477 struct remote_lock *lock = repo->locks;
478 time_t current_time = time(NULL);
479 int time_remaining;
481 while (lock) {
482 time_remaining = lock->start_time + lock->timeout -
483 current_time;
484 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
485 if (!refresh_lock(lock)) {
486 fprintf(stderr,
487 "Unable to refresh lock for %s\n",
488 lock->url);
489 aborted = 1;
490 return;
493 lock = lock->next;
497 static void release_request(struct transfer_request *request)
499 struct transfer_request *entry = request_queue_head;
501 if (request == request_queue_head) {
502 request_queue_head = request->next;
503 } else {
504 while (entry && entry->next != request)
505 entry = entry->next;
506 if (entry)
507 entry->next = request->next;
510 free(request->url);
511 free(request);
514 static void finish_request(struct transfer_request *request)
516 struct http_pack_request *preq;
517 struct http_object_request *obj_req;
519 request->curl_result = request->slot->curl_result;
520 request->http_code = request->slot->http_code;
521 request->slot = NULL;
523 /* Keep locks active */
524 check_locks();
526 if (request->headers)
527 curl_slist_free_all(request->headers);
529 /* URL is reused for MOVE after PUT and used during FETCH */
530 if (request->state != RUN_PUT && request->state != RUN_FETCH_PACKED) {
531 FREE_AND_NULL(request->url);
534 if (request->state == RUN_MKCOL) {
535 if (request->curl_result == CURLE_OK ||
536 request->http_code == 405) {
537 remote_dir_exists[request->obj->oid.hash[0]] = 1;
538 start_put(request);
539 } else {
540 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
541 oid_to_hex(&request->obj->oid),
542 request->curl_result, request->http_code);
543 request->state = ABORTED;
544 aborted = 1;
546 } else if (request->state == RUN_PUT) {
547 if (request->curl_result == CURLE_OK) {
548 start_move(request);
549 } else {
550 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
551 oid_to_hex(&request->obj->oid),
552 request->curl_result, request->http_code);
553 request->state = ABORTED;
554 aborted = 1;
556 } else if (request->state == RUN_MOVE) {
557 if (request->curl_result == CURLE_OK) {
558 if (push_verbosely)
559 fprintf(stderr, " sent %s\n",
560 oid_to_hex(&request->obj->oid));
561 request->obj->flags |= REMOTE;
562 release_request(request);
563 } else {
564 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
565 oid_to_hex(&request->obj->oid),
566 request->curl_result, request->http_code);
567 request->state = ABORTED;
568 aborted = 1;
570 } else if (request->state == RUN_FETCH_LOOSE) {
571 obj_req = (struct http_object_request *)request->userData;
573 if (finish_http_object_request(obj_req) == 0)
574 if (obj_req->rename == 0)
575 request->obj->flags |= (LOCAL | REMOTE);
577 /* Try fetching packed if necessary */
578 if (request->obj->flags & LOCAL) {
579 release_http_object_request(obj_req);
580 release_request(request);
581 } else
582 start_fetch_packed(request);
584 } else if (request->state == RUN_FETCH_PACKED) {
585 int fail = 1;
586 if (request->curl_result != CURLE_OK) {
587 fprintf(stderr, "Unable to get pack file %s\n%s",
588 request->url, curl_errorstr);
589 } else {
590 preq = (struct http_pack_request *)request->userData;
592 if (preq) {
593 if (finish_http_pack_request(preq) == 0)
594 fail = 0;
595 release_http_pack_request(preq);
598 if (fail)
599 repo->can_update_info_refs = 0;
600 else
601 http_install_packfile(request->target, &repo->packs);
602 release_request(request);
606 static int is_running_queue;
607 static int fill_active_slot(void *unused)
609 struct transfer_request *request;
611 if (aborted || !is_running_queue)
612 return 0;
614 for (request = request_queue_head; request; request = request->next) {
615 if (request->state == NEED_FETCH) {
616 start_fetch_loose(request);
617 return 1;
618 } else if (pushing && request->state == NEED_PUSH) {
619 if (remote_dir_exists[request->obj->oid.hash[0]] == 1) {
620 start_put(request);
621 } else {
622 start_mkcol(request);
624 return 1;
627 return 0;
630 static void get_remote_object_list(unsigned char parent);
632 static void add_fetch_request(struct object *obj)
634 struct transfer_request *request;
636 check_locks();
639 * Don't fetch the object if it's known to exist locally
640 * or is already in the request queue
642 if (remote_dir_exists[obj->oid.hash[0]] == -1)
643 get_remote_object_list(obj->oid.hash[0]);
644 if (obj->flags & (LOCAL | FETCHING))
645 return;
647 obj->flags |= FETCHING;
648 request = xmalloc(sizeof(*request));
649 request->obj = obj;
650 request->url = NULL;
651 request->lock = NULL;
652 request->headers = NULL;
653 request->state = NEED_FETCH;
654 request->next = request_queue_head;
655 request_queue_head = request;
657 fill_active_slots();
658 step_active_slots();
661 static int add_send_request(struct object *obj, struct remote_lock *lock)
663 struct transfer_request *request;
664 struct packed_git *target;
666 /* Keep locks active */
667 check_locks();
670 * Don't push the object if it's known to exist on the remote
671 * or is already in the request queue
673 if (remote_dir_exists[obj->oid.hash[0]] == -1)
674 get_remote_object_list(obj->oid.hash[0]);
675 if (obj->flags & (REMOTE | PUSHING))
676 return 0;
677 target = find_sha1_pack(obj->oid.hash, repo->packs);
678 if (target) {
679 obj->flags |= REMOTE;
680 return 0;
683 obj->flags |= PUSHING;
684 request = xmalloc(sizeof(*request));
685 request->obj = obj;
686 request->url = NULL;
687 request->lock = lock;
688 request->headers = NULL;
689 request->state = NEED_PUSH;
690 request->next = request_queue_head;
691 request_queue_head = request;
693 fill_active_slots();
694 step_active_slots();
696 return 1;
699 static int fetch_indices(void)
701 int ret;
703 if (push_verbosely)
704 fprintf(stderr, "Getting pack list\n");
706 switch (http_get_info_packs(repo->url, &repo->packs)) {
707 case HTTP_OK:
708 case HTTP_MISSING_TARGET:
709 ret = 0;
710 break;
711 default:
712 ret = -1;
715 return ret;
718 static void one_remote_object(const struct object_id *oid)
720 struct object *obj;
722 obj = lookup_object(the_repository, oid);
723 if (!obj)
724 obj = parse_object(the_repository, oid);
726 /* Ignore remote objects that don't exist locally */
727 if (!obj)
728 return;
730 obj->flags |= REMOTE;
731 if (!object_list_contains(objects, obj))
732 object_list_insert(obj, &objects);
735 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
737 int *lock_flags = (int *)ctx->userData;
739 if (tag_closed) {
740 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
741 if ((*lock_flags & DAV_PROP_LOCKEX) &&
742 (*lock_flags & DAV_PROP_LOCKWR)) {
743 *lock_flags |= DAV_LOCK_OK;
745 *lock_flags &= DAV_LOCK_OK;
746 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
747 *lock_flags |= DAV_PROP_LOCKWR;
748 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
749 *lock_flags |= DAV_PROP_LOCKEX;
754 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
756 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
757 git_hash_ctx hash_ctx;
758 unsigned char lock_token_hash[GIT_MAX_RAWSZ];
760 if (tag_closed && ctx->cdata) {
761 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
762 lock->owner = xstrdup(ctx->cdata);
763 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
764 const char *arg;
765 if (skip_prefix(ctx->cdata, "Second-", &arg))
766 lock->timeout = strtol(arg, NULL, 10);
767 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
768 lock->token = xstrdup(ctx->cdata);
770 the_hash_algo->init_fn(&hash_ctx);
771 the_hash_algo->update_fn(&hash_ctx, lock->token, strlen(lock->token));
772 the_hash_algo->final_fn(lock_token_hash, &hash_ctx);
774 lock->tmpfile_suffix[0] = '_';
775 memcpy(lock->tmpfile_suffix + 1, hash_to_hex(lock_token_hash), the_hash_algo->hexsz);
780 static void one_remote_ref(const char *refname);
782 static void
783 xml_start_tag(void *userData, const char *name, const char **atts)
785 struct xml_ctx *ctx = (struct xml_ctx *)userData;
786 const char *c = strchr(name, ':');
787 int old_namelen, new_len;
789 if (!c)
790 c = name;
791 else
792 c++;
794 old_namelen = strlen(ctx->name);
795 new_len = old_namelen + strlen(c) + 2;
797 if (new_len > ctx->len) {
798 ctx->name = xrealloc(ctx->name, new_len);
799 ctx->len = new_len;
801 xsnprintf(ctx->name + old_namelen, ctx->len - old_namelen, ".%s", c);
803 FREE_AND_NULL(ctx->cdata);
805 ctx->userFunc(ctx, 0);
808 static void
809 xml_end_tag(void *userData, const char *name)
811 struct xml_ctx *ctx = (struct xml_ctx *)userData;
812 const char *c = strchr(name, ':');
813 char *ep;
815 ctx->userFunc(ctx, 1);
817 if (!c)
818 c = name;
819 else
820 c++;
822 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
823 *ep = 0;
826 static void
827 xml_cdata(void *userData, const XML_Char *s, int len)
829 struct xml_ctx *ctx = (struct xml_ctx *)userData;
830 free(ctx->cdata);
831 ctx->cdata = xmemdupz(s, len);
834 static struct remote_lock *lock_remote(const char *path, long timeout)
836 struct active_request_slot *slot;
837 struct slot_results results;
838 struct buffer out_buffer = { STRBUF_INIT, 0 };
839 struct strbuf in_buffer = STRBUF_INIT;
840 char *url;
841 char *ep;
842 char timeout_header[25];
843 struct remote_lock *lock = NULL;
844 struct curl_slist *dav_headers = http_copy_default_headers();
845 struct xml_ctx ctx;
846 char *escaped;
848 url = xstrfmt("%s%s", repo->url, path);
850 /* Make sure leading directories exist for the remote ref */
851 ep = strchr(url + strlen(repo->url) + 1, '/');
852 while (ep) {
853 char saved_character = ep[1];
854 ep[1] = '\0';
855 slot = get_active_slot();
856 slot->results = &results;
857 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
858 if (start_active_slot(slot)) {
859 run_active_slot(slot);
860 if (results.curl_result != CURLE_OK &&
861 results.http_code != 405) {
862 fprintf(stderr,
863 "Unable to create branch path %s\n",
864 url);
865 free(url);
866 return NULL;
868 } else {
869 fprintf(stderr, "Unable to start MKCOL request\n");
870 free(url);
871 return NULL;
873 ep[1] = saved_character;
874 ep = strchr(ep + 1, '/');
877 escaped = xml_entities(ident_default_email());
878 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
879 free(escaped);
881 xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout);
882 dav_headers = curl_slist_append(dav_headers, timeout_header);
883 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
885 slot = get_active_slot();
886 slot->results = &results;
887 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
888 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
889 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
891 CALLOC_ARRAY(lock, 1);
892 lock->timeout = -1;
894 if (start_active_slot(slot)) {
895 run_active_slot(slot);
896 if (results.curl_result == CURLE_OK) {
897 XML_Parser parser = XML_ParserCreate(NULL);
898 enum XML_Status result;
899 ctx.name = xcalloc(10, 1);
900 ctx.len = 0;
901 ctx.cdata = NULL;
902 ctx.userFunc = handle_new_lock_ctx;
903 ctx.userData = lock;
904 XML_SetUserData(parser, &ctx);
905 XML_SetElementHandler(parser, xml_start_tag,
906 xml_end_tag);
907 XML_SetCharacterDataHandler(parser, xml_cdata);
908 result = XML_Parse(parser, in_buffer.buf,
909 in_buffer.len, 1);
910 free(ctx.name);
911 if (result != XML_STATUS_OK) {
912 fprintf(stderr, "XML error: %s\n",
913 XML_ErrorString(
914 XML_GetErrorCode(parser)));
915 lock->timeout = -1;
917 XML_ParserFree(parser);
918 } else {
919 fprintf(stderr,
920 "error: curl result=%d, HTTP code=%ld\n",
921 results.curl_result, results.http_code);
923 } else {
924 fprintf(stderr, "Unable to start LOCK request\n");
927 curl_slist_free_all(dav_headers);
928 strbuf_release(&out_buffer.buf);
929 strbuf_release(&in_buffer);
931 if (lock->token == NULL || lock->timeout <= 0) {
932 free(lock->token);
933 free(lock->owner);
934 free(url);
935 FREE_AND_NULL(lock);
936 } else {
937 lock->url = url;
938 lock->start_time = time(NULL);
939 lock->next = repo->locks;
940 repo->locks = lock;
943 return lock;
946 static int unlock_remote(struct remote_lock *lock)
948 struct active_request_slot *slot;
949 struct slot_results results;
950 struct remote_lock *prev = repo->locks;
951 struct curl_slist *dav_headers;
952 int rc = 0;
954 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
956 slot = get_active_slot();
957 slot->results = &results;
958 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
959 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
961 if (start_active_slot(slot)) {
962 run_active_slot(slot);
963 if (results.curl_result == CURLE_OK)
964 rc = 1;
965 else
966 fprintf(stderr, "UNLOCK HTTP error %ld\n",
967 results.http_code);
968 } else {
969 fprintf(stderr, "Unable to start UNLOCK request\n");
972 curl_slist_free_all(dav_headers);
974 if (repo->locks == lock) {
975 repo->locks = lock->next;
976 } else {
977 while (prev && prev->next != lock)
978 prev = prev->next;
979 if (prev)
980 prev->next = lock->next;
983 free(lock->owner);
984 free(lock->url);
985 free(lock->token);
986 free(lock);
988 return rc;
991 static void remove_locks(void)
993 struct remote_lock *lock = repo->locks;
995 fprintf(stderr, "Removing remote locks...\n");
996 while (lock) {
997 struct remote_lock *next = lock->next;
998 unlock_remote(lock);
999 lock = next;
1003 static void remove_locks_on_signal(int signo)
1005 remove_locks();
1006 sigchain_pop(signo);
1007 raise(signo);
1010 static void remote_ls(const char *path, int flags,
1011 void (*userFunc)(struct remote_ls_ctx *ls),
1012 void *userData);
1014 /* extract hex from sharded "xx/x{38}" filename */
1015 static int get_oid_hex_from_objpath(const char *path, struct object_id *oid)
1017 oid->algo = hash_algo_by_ptr(the_hash_algo);
1019 if (strlen(path) != the_hash_algo->hexsz + 1)
1020 return -1;
1022 if (hex_to_bytes(oid->hash, path, 1))
1023 return -1;
1024 path += 2;
1025 path++; /* skip '/' */
1027 return hex_to_bytes(oid->hash + 1, path, the_hash_algo->rawsz - 1);
1030 static void process_ls_object(struct remote_ls_ctx *ls)
1032 unsigned int *parent = (unsigned int *)ls->userData;
1033 const char *path = ls->dentry_name;
1034 struct object_id oid;
1036 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1037 remote_dir_exists[*parent] = 1;
1038 return;
1041 if (!skip_prefix(path, "objects/", &path) ||
1042 get_oid_hex_from_objpath(path, &oid))
1043 return;
1045 one_remote_object(&oid);
1048 static void process_ls_ref(struct remote_ls_ctx *ls)
1050 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1051 fprintf(stderr, " %s\n", ls->dentry_name);
1052 return;
1055 if (!(ls->dentry_flags & IS_DIR))
1056 one_remote_ref(ls->dentry_name);
1059 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1061 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1063 if (tag_closed) {
1064 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1065 if (ls->dentry_flags & IS_DIR) {
1067 /* ensure collection names end with slash */
1068 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1070 if (ls->flags & PROCESS_DIRS) {
1071 ls->userFunc(ls);
1073 if (strcmp(ls->dentry_name, ls->path) &&
1074 ls->flags & RECURSIVE) {
1075 remote_ls(ls->dentry_name,
1076 ls->flags,
1077 ls->userFunc,
1078 ls->userData);
1080 } else if (ls->flags & PROCESS_FILES) {
1081 ls->userFunc(ls);
1083 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1084 char *path = ctx->cdata;
1085 if (*ctx->cdata == 'h') {
1086 path = strstr(path, "//");
1087 if (path) {
1088 path = strchr(path+2, '/');
1091 if (path) {
1092 const char *url = repo->url;
1093 if (repo->path)
1094 url = repo->path;
1095 if (strncmp(path, url, repo->path_len))
1096 error("Parsed path '%s' does not match url: '%s'",
1097 path, url);
1098 else {
1099 path += repo->path_len;
1100 ls->dentry_name = xstrdup(path);
1103 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1104 ls->dentry_flags |= IS_DIR;
1106 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1107 FREE_AND_NULL(ls->dentry_name);
1108 ls->dentry_flags = 0;
1113 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1114 * should _only_ heed the information from that file, instead of trying to
1115 * determine the refs from the remote file system (badly: it does not even
1116 * know about packed-refs).
1118 static void remote_ls(const char *path, int flags,
1119 void (*userFunc)(struct remote_ls_ctx *ls),
1120 void *userData)
1122 char *url = xstrfmt("%s%s", repo->url, path);
1123 struct active_request_slot *slot;
1124 struct slot_results results;
1125 struct strbuf in_buffer = STRBUF_INIT;
1126 struct buffer out_buffer = { STRBUF_INIT, 0 };
1127 struct curl_slist *dav_headers = http_copy_default_headers();
1128 struct xml_ctx ctx;
1129 struct remote_ls_ctx ls;
1131 ls.flags = flags;
1132 ls.path = xstrdup(path);
1133 ls.dentry_name = NULL;
1134 ls.dentry_flags = 0;
1135 ls.userData = userData;
1136 ls.userFunc = userFunc;
1138 strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1140 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1141 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1143 slot = get_active_slot();
1144 slot->results = &results;
1145 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1146 &out_buffer, fwrite_buffer);
1147 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1148 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1150 if (start_active_slot(slot)) {
1151 run_active_slot(slot);
1152 if (results.curl_result == CURLE_OK) {
1153 XML_Parser parser = XML_ParserCreate(NULL);
1154 enum XML_Status result;
1155 ctx.name = xcalloc(10, 1);
1156 ctx.len = 0;
1157 ctx.cdata = NULL;
1158 ctx.userFunc = handle_remote_ls_ctx;
1159 ctx.userData = &ls;
1160 XML_SetUserData(parser, &ctx);
1161 XML_SetElementHandler(parser, xml_start_tag,
1162 xml_end_tag);
1163 XML_SetCharacterDataHandler(parser, xml_cdata);
1164 result = XML_Parse(parser, in_buffer.buf,
1165 in_buffer.len, 1);
1166 free(ctx.name);
1168 if (result != XML_STATUS_OK) {
1169 fprintf(stderr, "XML error: %s\n",
1170 XML_ErrorString(
1171 XML_GetErrorCode(parser)));
1173 XML_ParserFree(parser);
1175 } else {
1176 fprintf(stderr, "Unable to start PROPFIND request\n");
1179 free(ls.path);
1180 free(url);
1181 strbuf_release(&out_buffer.buf);
1182 strbuf_release(&in_buffer);
1183 curl_slist_free_all(dav_headers);
1186 static void get_remote_object_list(unsigned char parent)
1188 char path[] = "objects/XX/";
1189 static const char hex[] = "0123456789abcdef";
1190 unsigned int val = parent;
1192 path[8] = hex[val >> 4];
1193 path[9] = hex[val & 0xf];
1194 remote_dir_exists[val] = 0;
1195 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1196 process_ls_object, &val);
1199 static int locking_available(void)
1201 struct active_request_slot *slot;
1202 struct slot_results results;
1203 struct strbuf in_buffer = STRBUF_INIT;
1204 struct buffer out_buffer = { STRBUF_INIT, 0 };
1205 struct curl_slist *dav_headers = http_copy_default_headers();
1206 struct xml_ctx ctx;
1207 int lock_flags = 0;
1208 char *escaped;
1210 escaped = xml_entities(repo->url);
1211 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1212 free(escaped);
1214 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1215 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1217 slot = get_active_slot();
1218 slot->results = &results;
1219 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1220 &out_buffer, fwrite_buffer);
1221 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1222 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1224 if (start_active_slot(slot)) {
1225 run_active_slot(slot);
1226 if (results.curl_result == CURLE_OK) {
1227 XML_Parser parser = XML_ParserCreate(NULL);
1228 enum XML_Status result;
1229 ctx.name = xcalloc(10, 1);
1230 ctx.len = 0;
1231 ctx.cdata = NULL;
1232 ctx.userFunc = handle_lockprop_ctx;
1233 ctx.userData = &lock_flags;
1234 XML_SetUserData(parser, &ctx);
1235 XML_SetElementHandler(parser, xml_start_tag,
1236 xml_end_tag);
1237 result = XML_Parse(parser, in_buffer.buf,
1238 in_buffer.len, 1);
1239 free(ctx.name);
1241 if (result != XML_STATUS_OK) {
1242 fprintf(stderr, "XML error: %s\n",
1243 XML_ErrorString(
1244 XML_GetErrorCode(parser)));
1245 lock_flags = 0;
1247 XML_ParserFree(parser);
1248 if (!lock_flags)
1249 error("no DAV locking support on %s",
1250 repo->url);
1252 } else {
1253 error("Cannot access URL %s, return code %d",
1254 repo->url, results.curl_result);
1255 lock_flags = 0;
1257 } else {
1258 error("Unable to start PROPFIND request on %s", repo->url);
1261 strbuf_release(&out_buffer.buf);
1262 strbuf_release(&in_buffer);
1263 curl_slist_free_all(dav_headers);
1265 return lock_flags;
1268 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1270 struct object_list *entry = xmalloc(sizeof(struct object_list));
1271 entry->item = obj;
1272 entry->next = *p;
1273 *p = entry;
1274 return &entry->next;
1277 static struct object_list **process_blob(struct blob *blob,
1278 struct object_list **p)
1280 struct object *obj = &blob->object;
1282 obj->flags |= LOCAL;
1284 if (obj->flags & (UNINTERESTING | SEEN))
1285 return p;
1287 obj->flags |= SEEN;
1288 return add_one_object(obj, p);
1291 static struct object_list **process_tree(struct tree *tree,
1292 struct object_list **p)
1294 struct object *obj = &tree->object;
1295 struct tree_desc desc;
1296 struct name_entry entry;
1298 obj->flags |= LOCAL;
1300 if (obj->flags & (UNINTERESTING | SEEN))
1301 return p;
1302 if (parse_tree(tree) < 0)
1303 die("bad tree object %s", oid_to_hex(&obj->oid));
1305 obj->flags |= SEEN;
1306 p = add_one_object(obj, p);
1308 init_tree_desc(&desc, tree->buffer, tree->size);
1310 while (tree_entry(&desc, &entry))
1311 switch (object_type(entry.mode)) {
1312 case OBJ_TREE:
1313 p = process_tree(lookup_tree(the_repository, &entry.oid),
1315 break;
1316 case OBJ_BLOB:
1317 p = process_blob(lookup_blob(the_repository, &entry.oid),
1319 break;
1320 default:
1321 /* Subproject commit - not in this repository */
1322 break;
1325 free_tree_buffer(tree);
1326 return p;
1329 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1331 int i;
1332 struct commit *commit;
1333 struct object_list **p = &objects;
1334 int count = 0;
1336 while ((commit = get_revision(revs)) != NULL) {
1337 p = process_tree(get_commit_tree(commit), p);
1338 commit->object.flags |= LOCAL;
1339 if (!(commit->object.flags & UNINTERESTING))
1340 count += add_send_request(&commit->object, lock);
1343 for (i = 0; i < revs->pending.nr; i++) {
1344 struct object_array_entry *entry = revs->pending.objects + i;
1345 struct object *obj = entry->item;
1346 const char *name = entry->name;
1348 if (obj->flags & (UNINTERESTING | SEEN))
1349 continue;
1350 if (obj->type == OBJ_TAG) {
1351 obj->flags |= SEEN;
1352 p = add_one_object(obj, p);
1353 continue;
1355 if (obj->type == OBJ_TREE) {
1356 p = process_tree((struct tree *)obj, p);
1357 continue;
1359 if (obj->type == OBJ_BLOB) {
1360 p = process_blob((struct blob *)obj, p);
1361 continue;
1363 die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name);
1366 while (objects) {
1367 if (!(objects->item->flags & UNINTERESTING))
1368 count += add_send_request(objects->item, lock);
1369 objects = objects->next;
1372 return count;
1375 static int update_remote(const struct object_id *oid, struct remote_lock *lock)
1377 struct active_request_slot *slot;
1378 struct slot_results results;
1379 struct buffer out_buffer = { STRBUF_INIT, 0 };
1380 struct curl_slist *dav_headers;
1382 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1384 strbuf_addf(&out_buffer.buf, "%s\n", oid_to_hex(oid));
1386 slot = get_active_slot();
1387 slot->results = &results;
1388 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1389 &out_buffer, fwrite_null);
1390 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1392 if (start_active_slot(slot)) {
1393 run_active_slot(slot);
1394 strbuf_release(&out_buffer.buf);
1395 if (results.curl_result != CURLE_OK) {
1396 fprintf(stderr,
1397 "PUT error: curl result=%d, HTTP code=%ld\n",
1398 results.curl_result, results.http_code);
1399 /* We should attempt recovery? */
1400 return 0;
1402 } else {
1403 strbuf_release(&out_buffer.buf);
1404 fprintf(stderr, "Unable to start PUT request\n");
1405 return 0;
1408 return 1;
1411 static struct ref *remote_refs;
1413 static void one_remote_ref(const char *refname)
1415 struct ref *ref;
1416 struct object *obj;
1418 ref = alloc_ref(refname);
1420 if (http_fetch_ref(repo->url, ref) != 0) {
1421 fprintf(stderr,
1422 "Unable to fetch ref %s from %s\n",
1423 refname, repo->url);
1424 free(ref);
1425 return;
1429 * Fetch a copy of the object if it doesn't exist locally - it
1430 * may be required for updating server info later.
1432 if (repo->can_update_info_refs && !has_object_file(&ref->old_oid)) {
1433 obj = lookup_unknown_object(the_repository, &ref->old_oid);
1434 fprintf(stderr, " fetch %s for %s\n",
1435 oid_to_hex(&ref->old_oid), refname);
1436 add_fetch_request(obj);
1439 ref->next = remote_refs;
1440 remote_refs = ref;
1443 static void get_dav_remote_heads(void)
1445 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1448 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1450 struct strbuf *buf = (struct strbuf *)ls->userData;
1451 struct object *o;
1452 struct ref *ref;
1454 ref = alloc_ref(ls->dentry_name);
1456 if (http_fetch_ref(repo->url, ref) != 0) {
1457 fprintf(stderr,
1458 "Unable to fetch ref %s from %s\n",
1459 ls->dentry_name, repo->url);
1460 aborted = 1;
1461 free(ref);
1462 return;
1465 o = parse_object(the_repository, &ref->old_oid);
1466 if (!o) {
1467 fprintf(stderr,
1468 "Unable to parse object %s for remote ref %s\n",
1469 oid_to_hex(&ref->old_oid), ls->dentry_name);
1470 aborted = 1;
1471 free(ref);
1472 return;
1475 strbuf_addf(buf, "%s\t%s\n",
1476 oid_to_hex(&ref->old_oid), ls->dentry_name);
1478 if (o->type == OBJ_TAG) {
1479 o = deref_tag(the_repository, o, ls->dentry_name, 0);
1480 if (o)
1481 strbuf_addf(buf, "%s\t%s^{}\n",
1482 oid_to_hex(&o->oid), ls->dentry_name);
1484 free(ref);
1487 static void update_remote_info_refs(struct remote_lock *lock)
1489 struct buffer buffer = { STRBUF_INIT, 0 };
1490 struct active_request_slot *slot;
1491 struct slot_results results;
1492 struct curl_slist *dav_headers;
1494 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1495 add_remote_info_ref, &buffer.buf);
1496 if (!aborted) {
1497 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1499 slot = get_active_slot();
1500 slot->results = &results;
1501 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1502 &buffer, fwrite_null);
1503 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1505 if (start_active_slot(slot)) {
1506 run_active_slot(slot);
1507 if (results.curl_result != CURLE_OK) {
1508 fprintf(stderr,
1509 "PUT error: curl result=%d, HTTP code=%ld\n",
1510 results.curl_result, results.http_code);
1514 strbuf_release(&buffer.buf);
1517 static int remote_exists(const char *path)
1519 char *url = xstrfmt("%s%s", repo->url, path);
1520 int ret;
1523 switch (http_get_strbuf(url, NULL, NULL)) {
1524 case HTTP_OK:
1525 ret = 1;
1526 break;
1527 case HTTP_MISSING_TARGET:
1528 ret = 0;
1529 break;
1530 case HTTP_ERROR:
1531 error("unable to access '%s': %s", url, curl_errorstr);
1532 /* fallthrough */
1533 default:
1534 ret = -1;
1536 free(url);
1537 return ret;
1540 static void fetch_symref(const char *path, char **symref, struct object_id *oid)
1542 char *url = xstrfmt("%s%s", repo->url, path);
1543 struct strbuf buffer = STRBUF_INIT;
1544 const char *name;
1546 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1547 die("Couldn't get %s for remote symref\n%s", url,
1548 curl_errorstr);
1549 free(url);
1551 FREE_AND_NULL(*symref);
1552 oidclr(oid);
1554 if (buffer.len == 0)
1555 return;
1557 /* Cut off trailing newline. */
1558 strbuf_rtrim(&buffer);
1560 /* If it's a symref, set the refname; otherwise try for a sha1 */
1561 if (skip_prefix(buffer.buf, "ref: ", &name)) {
1562 *symref = xmemdupz(name, buffer.len - (name - buffer.buf));
1563 } else {
1564 get_oid_hex(buffer.buf, oid);
1567 strbuf_release(&buffer);
1570 static int verify_merge_base(struct object_id *head_oid, struct ref *remote)
1572 struct commit *head = lookup_commit_or_die(head_oid, "HEAD");
1573 struct commit *branch = lookup_commit_or_die(&remote->old_oid,
1574 remote->name);
1576 return in_merge_bases(branch, head);
1579 static int delete_remote_branch(const char *pattern, int force)
1581 struct ref *refs = remote_refs;
1582 struct ref *remote_ref = NULL;
1583 struct object_id head_oid;
1584 char *symref = NULL;
1585 int match;
1586 int patlen = strlen(pattern);
1587 int i;
1588 struct active_request_slot *slot;
1589 struct slot_results results;
1590 char *url;
1592 /* Find the remote branch(es) matching the specified branch name */
1593 for (match = 0; refs; refs = refs->next) {
1594 char *name = refs->name;
1595 int namelen = strlen(name);
1596 if (namelen < patlen ||
1597 memcmp(name + namelen - patlen, pattern, patlen))
1598 continue;
1599 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1600 continue;
1601 match++;
1602 remote_ref = refs;
1604 if (match == 0)
1605 return error("No remote branch matches %s", pattern);
1606 if (match != 1)
1607 return error("More than one remote branch matches %s",
1608 pattern);
1611 * Remote HEAD must be a symref (not exactly foolproof; a remote
1612 * symlink to a symref will look like a symref)
1614 fetch_symref("HEAD", &symref, &head_oid);
1615 if (!symref)
1616 return error("Remote HEAD is not a symref");
1618 /* Remote branch must not be the remote HEAD */
1619 for (i = 0; symref && i < MAXDEPTH; i++) {
1620 if (!strcmp(remote_ref->name, symref))
1621 return error("Remote branch %s is the current HEAD",
1622 remote_ref->name);
1623 fetch_symref(symref, &symref, &head_oid);
1626 /* Run extra sanity checks if delete is not forced */
1627 if (!force) {
1628 /* Remote HEAD must resolve to a known object */
1629 if (symref)
1630 return error("Remote HEAD symrefs too deep");
1631 if (is_null_oid(&head_oid))
1632 return error("Unable to resolve remote HEAD");
1633 if (!has_object_file(&head_oid))
1634 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", oid_to_hex(&head_oid));
1636 /* Remote branch must resolve to a known object */
1637 if (is_null_oid(&remote_ref->old_oid))
1638 return error("Unable to resolve remote branch %s",
1639 remote_ref->name);
1640 if (!has_object_file(&remote_ref->old_oid))
1641 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));
1643 /* Remote branch must be an ancestor of remote HEAD */
1644 if (!verify_merge_base(&head_oid, remote_ref)) {
1645 return error("The branch '%s' is not an ancestor "
1646 "of your current HEAD.\n"
1647 "If you are sure you want to delete it,"
1648 " run:\n\t'git http-push -D %s %s'",
1649 remote_ref->name, repo->url, pattern);
1653 /* Send delete request */
1654 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1655 if (dry_run)
1656 return 0;
1657 url = xstrfmt("%s%s", repo->url, remote_ref->name);
1658 slot = get_active_slot();
1659 slot->results = &results;
1660 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1661 if (start_active_slot(slot)) {
1662 run_active_slot(slot);
1663 free(url);
1664 if (results.curl_result != CURLE_OK)
1665 return error("DELETE request failed (%d/%ld)",
1666 results.curl_result, results.http_code);
1667 } else {
1668 free(url);
1669 return error("Unable to start DELETE request");
1672 return 0;
1675 static void run_request_queue(void)
1677 is_running_queue = 1;
1678 fill_active_slots();
1679 add_fill_function(NULL, fill_active_slot);
1680 do {
1681 finish_all_active_slots();
1682 fill_active_slots();
1683 } while (request_queue_head && !aborted);
1685 is_running_queue = 0;
1688 int cmd_main(int argc, const char **argv)
1690 struct transfer_request *request;
1691 struct transfer_request *next_request;
1692 struct refspec rs = REFSPEC_INIT_PUSH;
1693 struct remote_lock *ref_lock = NULL;
1694 struct remote_lock *info_ref_lock = NULL;
1695 int delete_branch = 0;
1696 int force_delete = 0;
1697 int objects_to_send;
1698 int rc = 0;
1699 int i;
1700 int new_refs;
1701 struct ref *ref, *local_refs;
1703 CALLOC_ARRAY(repo, 1);
1705 argv++;
1706 for (i = 1; i < argc; i++, argv++) {
1707 const char *arg = *argv;
1709 if (*arg == '-') {
1710 if (!strcmp(arg, "--all")) {
1711 push_all = MATCH_REFS_ALL;
1712 continue;
1714 if (!strcmp(arg, "--force")) {
1715 force_all = 1;
1716 continue;
1718 if (!strcmp(arg, "--dry-run")) {
1719 dry_run = 1;
1720 continue;
1722 if (!strcmp(arg, "--helper-status")) {
1723 helper_status = 1;
1724 continue;
1726 if (!strcmp(arg, "--verbose")) {
1727 push_verbosely = 1;
1728 http_is_verbose = 1;
1729 continue;
1731 if (!strcmp(arg, "-d")) {
1732 delete_branch = 1;
1733 continue;
1735 if (!strcmp(arg, "-D")) {
1736 delete_branch = 1;
1737 force_delete = 1;
1738 continue;
1740 if (!strcmp(arg, "-h"))
1741 usage(http_push_usage);
1743 if (!repo->url) {
1744 char *path = strstr(arg, "//");
1745 str_end_url_with_slash(arg, &repo->url);
1746 repo->path_len = strlen(repo->url);
1747 if (path) {
1748 repo->path = strchr(path+2, '/');
1749 if (repo->path)
1750 repo->path_len = strlen(repo->path);
1752 continue;
1754 refspec_appendn(&rs, argv, argc - i);
1755 break;
1758 if (!repo->url)
1759 usage(http_push_usage);
1761 if (delete_branch && rs.nr != 1)
1762 die("You must specify only one branch name when deleting a remote branch");
1764 setup_git_directory();
1766 memset(remote_dir_exists, -1, 256);
1768 http_init(NULL, repo->url, 1);
1770 is_running_queue = 0;
1772 /* Verify DAV compliance/lock support */
1773 if (!locking_available()) {
1774 rc = 1;
1775 goto cleanup;
1778 sigchain_push_common(remove_locks_on_signal);
1780 /* Check whether the remote has server info files */
1781 repo->can_update_info_refs = 0;
1782 repo->has_info_refs = remote_exists("info/refs");
1783 repo->has_info_packs = remote_exists("objects/info/packs");
1784 if (repo->has_info_refs) {
1785 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1786 if (info_ref_lock)
1787 repo->can_update_info_refs = 1;
1788 else {
1789 error("cannot lock existing info/refs");
1790 rc = 1;
1791 goto cleanup;
1794 if (repo->has_info_packs)
1795 fetch_indices();
1797 /* Get a list of all local and remote heads to validate refspecs */
1798 local_refs = get_local_heads();
1799 fprintf(stderr, "Fetching remote heads...\n");
1800 get_dav_remote_heads();
1801 run_request_queue();
1803 /* Remove a remote branch if -d or -D was specified */
1804 if (delete_branch) {
1805 const char *branch = rs.items[i].src;
1806 if (delete_remote_branch(branch, force_delete) == -1) {
1807 fprintf(stderr, "Unable to delete remote branch %s\n",
1808 branch);
1809 if (helper_status)
1810 printf("error %s cannot remove\n", branch);
1812 goto cleanup;
1815 /* match them up */
1816 if (match_push_refs(local_refs, &remote_refs, &rs, push_all)) {
1817 rc = -1;
1818 goto cleanup;
1820 if (!remote_refs) {
1821 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1822 if (helper_status)
1823 printf("error null no match\n");
1824 rc = 0;
1825 goto cleanup;
1828 new_refs = 0;
1829 for (ref = remote_refs; ref; ref = ref->next) {
1830 struct rev_info revs;
1831 struct strvec commit_argv = STRVEC_INIT;
1833 if (!ref->peer_ref)
1834 continue;
1836 if (is_null_oid(&ref->peer_ref->new_oid)) {
1837 if (delete_remote_branch(ref->name, 1) == -1) {
1838 error("Could not remove %s", ref->name);
1839 if (helper_status)
1840 printf("error %s cannot remove\n", ref->name);
1841 rc = -4;
1843 else if (helper_status)
1844 printf("ok %s\n", ref->name);
1845 new_refs++;
1846 continue;
1849 if (oideq(&ref->old_oid, &ref->peer_ref->new_oid)) {
1850 if (push_verbosely)
1851 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1852 if (helper_status)
1853 printf("ok %s up to date\n", ref->name);
1854 continue;
1857 if (!force_all &&
1858 !is_null_oid(&ref->old_oid) &&
1859 !ref->force) {
1860 if (!has_object_file(&ref->old_oid) ||
1861 !ref_newer(&ref->peer_ref->new_oid,
1862 &ref->old_oid)) {
1864 * We do not have the remote ref, or
1865 * we know that the remote ref is not
1866 * an ancestor of what we are trying to
1867 * push. Either way this can be losing
1868 * commits at the remote end and likely
1869 * we were not up to date to begin with.
1871 error("remote '%s' is not an ancestor of\n"
1872 "local '%s'.\n"
1873 "Maybe you are not up-to-date and "
1874 "need to pull first?",
1875 ref->name,
1876 ref->peer_ref->name);
1877 if (helper_status)
1878 printf("error %s non-fast forward\n", ref->name);
1879 rc = -2;
1880 continue;
1883 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1884 new_refs++;
1886 fprintf(stderr, "updating '%s'", ref->name);
1887 if (strcmp(ref->name, ref->peer_ref->name))
1888 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1889 fprintf(stderr, "\n from %s\n to %s\n",
1890 oid_to_hex(&ref->old_oid), oid_to_hex(&ref->new_oid));
1891 if (dry_run) {
1892 if (helper_status)
1893 printf("ok %s\n", ref->name);
1894 continue;
1897 /* Lock remote branch ref */
1898 ref_lock = lock_remote(ref->name, LOCK_TIME);
1899 if (!ref_lock) {
1900 fprintf(stderr, "Unable to lock remote branch %s\n",
1901 ref->name);
1902 if (helper_status)
1903 printf("error %s lock error\n", ref->name);
1904 rc = 1;
1905 continue;
1908 /* Set up revision info for this refspec */
1909 strvec_push(&commit_argv, ""); /* ignored */
1910 strvec_push(&commit_argv, "--objects");
1911 strvec_push(&commit_argv, oid_to_hex(&ref->new_oid));
1912 if (!push_all && !is_null_oid(&ref->old_oid))
1913 strvec_pushf(&commit_argv, "^%s",
1914 oid_to_hex(&ref->old_oid));
1915 repo_init_revisions(the_repository, &revs, setup_git_directory());
1916 setup_revisions(commit_argv.nr, commit_argv.v, &revs, NULL);
1917 revs.edge_hint = 0; /* just in case */
1919 /* Generate a list of objects that need to be pushed */
1920 pushing = 0;
1921 if (prepare_revision_walk(&revs))
1922 die("revision walk setup failed");
1923 mark_edges_uninteresting(&revs, NULL, 0);
1924 objects_to_send = get_delta(&revs, ref_lock);
1925 finish_all_active_slots();
1927 /* Push missing objects to remote, this would be a
1928 convenient time to pack them first if appropriate. */
1929 pushing = 1;
1930 if (objects_to_send)
1931 fprintf(stderr, " sending %d objects\n",
1932 objects_to_send);
1934 run_request_queue();
1936 /* Update the remote branch if all went well */
1937 if (aborted || !update_remote(&ref->new_oid, ref_lock))
1938 rc = 1;
1940 if (!rc)
1941 fprintf(stderr, " done\n");
1942 if (helper_status)
1943 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1944 unlock_remote(ref_lock);
1945 check_locks();
1946 strvec_clear(&commit_argv);
1947 release_revisions(&revs);
1950 /* Update remote server info if appropriate */
1951 if (repo->has_info_refs && new_refs) {
1952 if (info_ref_lock && repo->can_update_info_refs) {
1953 fprintf(stderr, "Updating remote server info\n");
1954 if (!dry_run)
1955 update_remote_info_refs(info_ref_lock);
1956 } else {
1957 fprintf(stderr, "Unable to update server info\n");
1961 cleanup:
1962 if (info_ref_lock)
1963 unlock_remote(info_ref_lock);
1964 free(repo);
1966 http_cleanup();
1968 request = request_queue_head;
1969 while (request != NULL) {
1970 next_request = request->next;
1971 release_request(request);
1972 request = next_request;
1975 return rc;