Merge branch 'hm/paint-hits-in-log-grep'
[git/debian.git] / http-push.c
blob3309aaf004a4db175bc4c0b94b5c63efebcb30e3
1 #include "cache.h"
2 #include "repository.h"
3 #include "commit.h"
4 #include "tag.h"
5 #include "blob.h"
6 #include "http.h"
7 #include "refs.h"
8 #include "diff.h"
9 #include "revision.h"
10 #include "exec-cmd.h"
11 #include "remote.h"
12 #include "list-objects.h"
13 #include "sigchain.h"
14 #include "strvec.h"
15 #include "packfile.h"
16 #include "object-store.h"
17 #include "commit-reach.h"
19 #ifdef EXPAT_NEEDS_XMLPARSE_H
20 #include <xmlparse.h>
21 #else
22 #include <expat.h>
23 #endif
25 static const char http_push_usage[] =
26 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
28 #ifndef XML_STATUS_OK
29 enum XML_Status {
30 XML_STATUS_OK = 1,
31 XML_STATUS_ERROR = 0
33 #define XML_STATUS_OK 1
34 #define XML_STATUS_ERROR 0
35 #endif
37 #define PREV_BUF_SIZE 4096
39 /* DAV methods */
40 #define DAV_LOCK "LOCK"
41 #define DAV_MKCOL "MKCOL"
42 #define DAV_MOVE "MOVE"
43 #define DAV_PROPFIND "PROPFIND"
44 #define DAV_PUT "PUT"
45 #define DAV_UNLOCK "UNLOCK"
46 #define DAV_DELETE "DELETE"
48 /* DAV lock flags */
49 #define DAV_PROP_LOCKWR (1u << 0)
50 #define DAV_PROP_LOCKEX (1u << 1)
51 #define DAV_LOCK_OK (1u << 2)
53 /* DAV XML properties */
54 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
55 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
56 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
57 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
58 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
59 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
60 #define DAV_PROPFIND_RESP ".multistatus.response"
61 #define DAV_PROPFIND_NAME ".multistatus.response.href"
62 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
64 /* DAV request body templates */
65 #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>"
66 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
67 #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>"
69 #define LOCK_TIME 600
70 #define LOCK_REFRESH 30
72 /* Remember to update object flag allocation in object.h */
73 #define LOCAL (1u<<11)
74 #define REMOTE (1u<<12)
75 #define FETCHING (1u<<13)
76 #define PUSHING (1u<<14)
78 /* We allow "recursive" symbolic refs. Only within reason, though */
79 #define MAXDEPTH 5
81 static int pushing;
82 static int aborted;
83 static signed char remote_dir_exists[256];
85 static int push_verbosely;
86 static int push_all = MATCH_REFS_NONE;
87 static int force_all;
88 static int dry_run;
89 static int helper_status;
91 static struct object_list *objects;
93 struct repo {
94 char *url;
95 char *path;
96 int path_len;
97 int has_info_refs;
98 int can_update_info_refs;
99 int has_info_packs;
100 struct packed_git *packs;
101 struct remote_lock *locks;
104 static struct repo *repo;
106 enum transfer_state {
107 NEED_FETCH,
108 RUN_FETCH_LOOSE,
109 RUN_FETCH_PACKED,
110 NEED_PUSH,
111 RUN_MKCOL,
112 RUN_PUT,
113 RUN_MOVE,
114 ABORTED,
115 COMPLETE
118 struct transfer_request {
119 struct object *obj;
120 struct packed_git *target;
121 char *url;
122 char *dest;
123 struct remote_lock *lock;
124 struct curl_slist *headers;
125 struct buffer buffer;
126 enum transfer_state state;
127 CURLcode curl_result;
128 char errorstr[CURL_ERROR_SIZE];
129 long http_code;
130 void *userData;
131 struct active_request_slot *slot;
132 struct transfer_request *next;
135 static struct transfer_request *request_queue_head;
137 struct xml_ctx {
138 char *name;
139 int len;
140 char *cdata;
141 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
142 void *userData;
145 struct remote_lock {
146 char *url;
147 char *owner;
148 char *token;
149 char tmpfile_suffix[GIT_MAX_HEXSZ + 1];
150 time_t start_time;
151 long timeout;
152 int refreshing;
153 struct remote_lock *next;
156 /* Flags that control remote_ls processing */
157 #define PROCESS_FILES (1u << 0)
158 #define PROCESS_DIRS (1u << 1)
159 #define RECURSIVE (1u << 2)
161 /* Flags that remote_ls passes to callback functions */
162 #define IS_DIR (1u << 0)
164 struct remote_ls_ctx {
165 char *path;
166 void (*userFunc)(struct remote_ls_ctx *ls);
167 void *userData;
168 int flags;
169 char *dentry_name;
170 int dentry_flags;
171 struct remote_ls_ctx *parent;
174 /* get_dav_token_headers options */
175 enum dav_header_flag {
176 DAV_HEADER_IF = (1u << 0),
177 DAV_HEADER_LOCK = (1u << 1),
178 DAV_HEADER_TIMEOUT = (1u << 2)
181 static char *xml_entities(const char *s)
183 struct strbuf buf = STRBUF_INIT;
184 strbuf_addstr_xml_quoted(&buf, s);
185 return strbuf_detach(&buf, NULL);
188 static void curl_setup_http_get(CURL *curl, const char *url,
189 const char *custom_req)
191 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
192 curl_easy_setopt(curl, CURLOPT_URL, url);
193 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
194 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
197 static void curl_setup_http(CURL *curl, const char *url,
198 const char *custom_req, struct buffer *buffer,
199 curl_write_callback write_fn)
201 curl_easy_setopt(curl, CURLOPT_PUT, 1);
202 curl_easy_setopt(curl, CURLOPT_URL, url);
203 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
204 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
205 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
206 curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
207 curl_easy_setopt(curl, CURLOPT_IOCTLDATA, buffer);
208 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
209 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
210 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
211 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
214 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
216 struct strbuf buf = STRBUF_INIT;
217 struct curl_slist *dav_headers = http_copy_default_headers();
219 if (options & DAV_HEADER_IF) {
220 strbuf_addf(&buf, "If: (<%s>)", lock->token);
221 dav_headers = curl_slist_append(dav_headers, buf.buf);
222 strbuf_reset(&buf);
224 if (options & DAV_HEADER_LOCK) {
225 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
226 dav_headers = curl_slist_append(dav_headers, buf.buf);
227 strbuf_reset(&buf);
229 if (options & DAV_HEADER_TIMEOUT) {
230 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
231 dav_headers = curl_slist_append(dav_headers, buf.buf);
232 strbuf_reset(&buf);
234 strbuf_release(&buf);
236 return dav_headers;
239 static void finish_request(struct transfer_request *request);
240 static void release_request(struct transfer_request *request);
242 static void process_response(void *callback_data)
244 struct transfer_request *request =
245 (struct transfer_request *)callback_data;
247 finish_request(request);
250 static void start_fetch_loose(struct transfer_request *request)
252 struct active_request_slot *slot;
253 struct http_object_request *obj_req;
255 obj_req = new_http_object_request(repo->url, &request->obj->oid);
256 if (obj_req == NULL) {
257 request->state = ABORTED;
258 return;
261 slot = obj_req->slot;
262 slot->callback_func = process_response;
263 slot->callback_data = request;
264 request->slot = slot;
265 request->userData = obj_req;
267 /* Try to get the request started, abort the request on error */
268 request->state = RUN_FETCH_LOOSE;
269 if (!start_active_slot(slot)) {
270 fprintf(stderr, "Unable to start GET request\n");
271 repo->can_update_info_refs = 0;
272 release_http_object_request(obj_req);
273 release_request(request);
277 static void start_mkcol(struct transfer_request *request)
279 char *hex = oid_to_hex(&request->obj->oid);
280 struct active_request_slot *slot;
282 request->url = get_remote_object_url(repo->url, hex, 1);
284 slot = get_active_slot();
285 slot->callback_func = process_response;
286 slot->callback_data = request;
287 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
288 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
290 if (start_active_slot(slot)) {
291 request->slot = slot;
292 request->state = RUN_MKCOL;
293 } else {
294 request->state = ABORTED;
295 FREE_AND_NULL(request->url);
299 static void start_fetch_packed(struct transfer_request *request)
301 struct packed_git *target;
303 struct transfer_request *check_request = request_queue_head;
304 struct http_pack_request *preq;
306 target = find_sha1_pack(request->obj->oid.hash, repo->packs);
307 if (!target) {
308 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", oid_to_hex(&request->obj->oid));
309 repo->can_update_info_refs = 0;
310 release_request(request);
311 return;
313 close_pack_index(target);
314 request->target = target;
316 fprintf(stderr, "Fetching pack %s\n",
317 hash_to_hex(target->hash));
318 fprintf(stderr, " which contains %s\n", oid_to_hex(&request->obj->oid));
320 preq = new_http_pack_request(target->hash, repo->url);
321 if (preq == NULL) {
322 repo->can_update_info_refs = 0;
323 return;
326 /* Make sure there isn't another open request for this pack */
327 while (check_request) {
328 if (check_request->state == RUN_FETCH_PACKED &&
329 !strcmp(check_request->url, preq->url)) {
330 release_http_pack_request(preq);
331 release_request(request);
332 return;
334 check_request = check_request->next;
337 preq->slot->callback_func = process_response;
338 preq->slot->callback_data = request;
339 request->slot = preq->slot;
340 request->userData = preq;
342 /* Try to get the request started, abort the request on error */
343 request->state = RUN_FETCH_PACKED;
344 if (!start_active_slot(preq->slot)) {
345 fprintf(stderr, "Unable to start GET request\n");
346 release_http_pack_request(preq);
347 repo->can_update_info_refs = 0;
348 release_request(request);
352 static void start_put(struct transfer_request *request)
354 char *hex = oid_to_hex(&request->obj->oid);
355 struct active_request_slot *slot;
356 struct strbuf buf = STRBUF_INIT;
357 enum object_type type;
358 char hdr[50];
359 void *unpacked;
360 unsigned long len;
361 int hdrlen;
362 ssize_t size;
363 git_zstream stream;
365 unpacked = read_object_file(&request->obj->oid, &type, &len);
366 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(type), (uintmax_t)len) + 1;
368 /* Set it up */
369 git_deflate_init(&stream, zlib_compression_level);
370 size = git_deflate_bound(&stream, len + hdrlen);
371 strbuf_init(&request->buffer.buf, size);
372 request->buffer.posn = 0;
374 /* Compress it */
375 stream.next_out = (unsigned char *)request->buffer.buf.buf;
376 stream.avail_out = size;
378 /* First header.. */
379 stream.next_in = (void *)hdr;
380 stream.avail_in = hdrlen;
381 while (git_deflate(&stream, 0) == Z_OK)
382 ; /* nothing */
384 /* Then the data itself.. */
385 stream.next_in = unpacked;
386 stream.avail_in = len;
387 while (git_deflate(&stream, Z_FINISH) == Z_OK)
388 ; /* nothing */
389 git_deflate_end(&stream);
390 free(unpacked);
392 request->buffer.buf.len = stream.total_out;
394 strbuf_addstr(&buf, "Destination: ");
395 append_remote_object_url(&buf, repo->url, hex, 0);
396 request->dest = strbuf_detach(&buf, NULL);
398 append_remote_object_url(&buf, repo->url, hex, 0);
399 strbuf_add(&buf, request->lock->tmpfile_suffix, the_hash_algo->hexsz + 1);
400 request->url = strbuf_detach(&buf, NULL);
402 slot = get_active_slot();
403 slot->callback_func = process_response;
404 slot->callback_data = request;
405 curl_setup_http(slot->curl, request->url, DAV_PUT,
406 &request->buffer, fwrite_null);
408 if (start_active_slot(slot)) {
409 request->slot = slot;
410 request->state = RUN_PUT;
411 } else {
412 request->state = ABORTED;
413 FREE_AND_NULL(request->url);
417 static void start_move(struct transfer_request *request)
419 struct active_request_slot *slot;
420 struct curl_slist *dav_headers = http_copy_default_headers();
422 slot = get_active_slot();
423 slot->callback_func = process_response;
424 slot->callback_data = request;
425 curl_setup_http_get(slot->curl, request->url, DAV_MOVE);
426 dav_headers = curl_slist_append(dav_headers, request->dest);
427 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
428 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
430 if (start_active_slot(slot)) {
431 request->slot = slot;
432 request->state = RUN_MOVE;
433 } else {
434 request->state = ABORTED;
435 FREE_AND_NULL(request->url);
439 static int refresh_lock(struct remote_lock *lock)
441 struct active_request_slot *slot;
442 struct slot_results results;
443 struct curl_slist *dav_headers;
444 int rc = 0;
446 lock->refreshing = 1;
448 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
450 slot = get_active_slot();
451 slot->results = &results;
452 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
453 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
455 if (start_active_slot(slot)) {
456 run_active_slot(slot);
457 if (results.curl_result != CURLE_OK) {
458 fprintf(stderr, "LOCK HTTP error %ld\n",
459 results.http_code);
460 } else {
461 lock->start_time = time(NULL);
462 rc = 1;
466 lock->refreshing = 0;
467 curl_slist_free_all(dav_headers);
469 return rc;
472 static void check_locks(void)
474 struct remote_lock *lock = repo->locks;
475 time_t current_time = time(NULL);
476 int time_remaining;
478 while (lock) {
479 time_remaining = lock->start_time + lock->timeout -
480 current_time;
481 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
482 if (!refresh_lock(lock)) {
483 fprintf(stderr,
484 "Unable to refresh lock for %s\n",
485 lock->url);
486 aborted = 1;
487 return;
490 lock = lock->next;
494 static void release_request(struct transfer_request *request)
496 struct transfer_request *entry = request_queue_head;
498 if (request == request_queue_head) {
499 request_queue_head = request->next;
500 } else {
501 while (entry && entry->next != request)
502 entry = entry->next;
503 if (entry)
504 entry->next = request->next;
507 free(request->url);
508 free(request);
511 static void finish_request(struct transfer_request *request)
513 struct http_pack_request *preq;
514 struct http_object_request *obj_req;
516 request->curl_result = request->slot->curl_result;
517 request->http_code = request->slot->http_code;
518 request->slot = NULL;
520 /* Keep locks active */
521 check_locks();
523 if (request->headers != NULL)
524 curl_slist_free_all(request->headers);
526 /* URL is reused for MOVE after PUT and used during FETCH */
527 if (request->state != RUN_PUT && request->state != RUN_FETCH_PACKED) {
528 FREE_AND_NULL(request->url);
531 if (request->state == RUN_MKCOL) {
532 if (request->curl_result == CURLE_OK ||
533 request->http_code == 405) {
534 remote_dir_exists[request->obj->oid.hash[0]] = 1;
535 start_put(request);
536 } else {
537 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
538 oid_to_hex(&request->obj->oid),
539 request->curl_result, request->http_code);
540 request->state = ABORTED;
541 aborted = 1;
543 } else if (request->state == RUN_PUT) {
544 if (request->curl_result == CURLE_OK) {
545 start_move(request);
546 } else {
547 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
548 oid_to_hex(&request->obj->oid),
549 request->curl_result, request->http_code);
550 request->state = ABORTED;
551 aborted = 1;
553 } else if (request->state == RUN_MOVE) {
554 if (request->curl_result == CURLE_OK) {
555 if (push_verbosely)
556 fprintf(stderr, " sent %s\n",
557 oid_to_hex(&request->obj->oid));
558 request->obj->flags |= REMOTE;
559 release_request(request);
560 } else {
561 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
562 oid_to_hex(&request->obj->oid),
563 request->curl_result, request->http_code);
564 request->state = ABORTED;
565 aborted = 1;
567 } else if (request->state == RUN_FETCH_LOOSE) {
568 obj_req = (struct http_object_request *)request->userData;
570 if (finish_http_object_request(obj_req) == 0)
571 if (obj_req->rename == 0)
572 request->obj->flags |= (LOCAL | REMOTE);
574 /* Try fetching packed if necessary */
575 if (request->obj->flags & LOCAL) {
576 release_http_object_request(obj_req);
577 release_request(request);
578 } else
579 start_fetch_packed(request);
581 } else if (request->state == RUN_FETCH_PACKED) {
582 int fail = 1;
583 if (request->curl_result != CURLE_OK) {
584 fprintf(stderr, "Unable to get pack file %s\n%s",
585 request->url, curl_errorstr);
586 } else {
587 preq = (struct http_pack_request *)request->userData;
589 if (preq) {
590 if (finish_http_pack_request(preq) == 0)
591 fail = 0;
592 release_http_pack_request(preq);
595 if (fail)
596 repo->can_update_info_refs = 0;
597 else
598 http_install_packfile(request->target, &repo->packs);
599 release_request(request);
603 static int is_running_queue;
604 static int fill_active_slot(void *unused)
606 struct transfer_request *request;
608 if (aborted || !is_running_queue)
609 return 0;
611 for (request = request_queue_head; request; request = request->next) {
612 if (request->state == NEED_FETCH) {
613 start_fetch_loose(request);
614 return 1;
615 } else if (pushing && request->state == NEED_PUSH) {
616 if (remote_dir_exists[request->obj->oid.hash[0]] == 1) {
617 start_put(request);
618 } else {
619 start_mkcol(request);
621 return 1;
624 return 0;
627 static void get_remote_object_list(unsigned char parent);
629 static void add_fetch_request(struct object *obj)
631 struct transfer_request *request;
633 check_locks();
636 * Don't fetch the object if it's known to exist locally
637 * or is already in the request queue
639 if (remote_dir_exists[obj->oid.hash[0]] == -1)
640 get_remote_object_list(obj->oid.hash[0]);
641 if (obj->flags & (LOCAL | FETCHING))
642 return;
644 obj->flags |= FETCHING;
645 request = xmalloc(sizeof(*request));
646 request->obj = obj;
647 request->url = NULL;
648 request->lock = NULL;
649 request->headers = NULL;
650 request->state = NEED_FETCH;
651 request->next = request_queue_head;
652 request_queue_head = request;
654 fill_active_slots();
655 step_active_slots();
658 static int add_send_request(struct object *obj, struct remote_lock *lock)
660 struct transfer_request *request;
661 struct packed_git *target;
663 /* Keep locks active */
664 check_locks();
667 * Don't push the object if it's known to exist on the remote
668 * or is already in the request queue
670 if (remote_dir_exists[obj->oid.hash[0]] == -1)
671 get_remote_object_list(obj->oid.hash[0]);
672 if (obj->flags & (REMOTE | PUSHING))
673 return 0;
674 target = find_sha1_pack(obj->oid.hash, repo->packs);
675 if (target) {
676 obj->flags |= REMOTE;
677 return 0;
680 obj->flags |= PUSHING;
681 request = xmalloc(sizeof(*request));
682 request->obj = obj;
683 request->url = NULL;
684 request->lock = lock;
685 request->headers = NULL;
686 request->state = NEED_PUSH;
687 request->next = request_queue_head;
688 request_queue_head = request;
690 fill_active_slots();
691 step_active_slots();
693 return 1;
696 static int fetch_indices(void)
698 int ret;
700 if (push_verbosely)
701 fprintf(stderr, "Getting pack list\n");
703 switch (http_get_info_packs(repo->url, &repo->packs)) {
704 case HTTP_OK:
705 case HTTP_MISSING_TARGET:
706 ret = 0;
707 break;
708 default:
709 ret = -1;
712 return ret;
715 static void one_remote_object(const struct object_id *oid)
717 struct object *obj;
719 obj = lookup_object(the_repository, oid);
720 if (!obj)
721 obj = parse_object(the_repository, oid);
723 /* Ignore remote objects that don't exist locally */
724 if (!obj)
725 return;
727 obj->flags |= REMOTE;
728 if (!object_list_contains(objects, obj))
729 object_list_insert(obj, &objects);
732 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
734 int *lock_flags = (int *)ctx->userData;
736 if (tag_closed) {
737 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
738 if ((*lock_flags & DAV_PROP_LOCKEX) &&
739 (*lock_flags & DAV_PROP_LOCKWR)) {
740 *lock_flags |= DAV_LOCK_OK;
742 *lock_flags &= DAV_LOCK_OK;
743 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
744 *lock_flags |= DAV_PROP_LOCKWR;
745 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
746 *lock_flags |= DAV_PROP_LOCKEX;
751 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
753 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
754 git_hash_ctx hash_ctx;
755 unsigned char lock_token_hash[GIT_MAX_RAWSZ];
757 if (tag_closed && ctx->cdata) {
758 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
759 lock->owner = xstrdup(ctx->cdata);
760 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
761 const char *arg;
762 if (skip_prefix(ctx->cdata, "Second-", &arg))
763 lock->timeout = strtol(arg, NULL, 10);
764 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
765 lock->token = xstrdup(ctx->cdata);
767 the_hash_algo->init_fn(&hash_ctx);
768 the_hash_algo->update_fn(&hash_ctx, lock->token, strlen(lock->token));
769 the_hash_algo->final_fn(lock_token_hash, &hash_ctx);
771 lock->tmpfile_suffix[0] = '_';
772 memcpy(lock->tmpfile_suffix + 1, hash_to_hex(lock_token_hash), the_hash_algo->hexsz);
777 static void one_remote_ref(const char *refname);
779 static void
780 xml_start_tag(void *userData, const char *name, const char **atts)
782 struct xml_ctx *ctx = (struct xml_ctx *)userData;
783 const char *c = strchr(name, ':');
784 int old_namelen, new_len;
786 if (c == NULL)
787 c = name;
788 else
789 c++;
791 old_namelen = strlen(ctx->name);
792 new_len = old_namelen + strlen(c) + 2;
794 if (new_len > ctx->len) {
795 ctx->name = xrealloc(ctx->name, new_len);
796 ctx->len = new_len;
798 xsnprintf(ctx->name + old_namelen, ctx->len - old_namelen, ".%s", c);
800 FREE_AND_NULL(ctx->cdata);
802 ctx->userFunc(ctx, 0);
805 static void
806 xml_end_tag(void *userData, const char *name)
808 struct xml_ctx *ctx = (struct xml_ctx *)userData;
809 const char *c = strchr(name, ':');
810 char *ep;
812 ctx->userFunc(ctx, 1);
814 if (c == NULL)
815 c = name;
816 else
817 c++;
819 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
820 *ep = 0;
823 static void
824 xml_cdata(void *userData, const XML_Char *s, int len)
826 struct xml_ctx *ctx = (struct xml_ctx *)userData;
827 free(ctx->cdata);
828 ctx->cdata = xmemdupz(s, len);
831 static struct remote_lock *lock_remote(const char *path, long timeout)
833 struct active_request_slot *slot;
834 struct slot_results results;
835 struct buffer out_buffer = { STRBUF_INIT, 0 };
836 struct strbuf in_buffer = STRBUF_INIT;
837 char *url;
838 char *ep;
839 char timeout_header[25];
840 struct remote_lock *lock = NULL;
841 struct curl_slist *dav_headers = http_copy_default_headers();
842 struct xml_ctx ctx;
843 char *escaped;
845 url = xstrfmt("%s%s", repo->url, path);
847 /* Make sure leading directories exist for the remote ref */
848 ep = strchr(url + strlen(repo->url) + 1, '/');
849 while (ep) {
850 char saved_character = ep[1];
851 ep[1] = '\0';
852 slot = get_active_slot();
853 slot->results = &results;
854 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
855 if (start_active_slot(slot)) {
856 run_active_slot(slot);
857 if (results.curl_result != CURLE_OK &&
858 results.http_code != 405) {
859 fprintf(stderr,
860 "Unable to create branch path %s\n",
861 url);
862 free(url);
863 return NULL;
865 } else {
866 fprintf(stderr, "Unable to start MKCOL request\n");
867 free(url);
868 return NULL;
870 ep[1] = saved_character;
871 ep = strchr(ep + 1, '/');
874 escaped = xml_entities(ident_default_email());
875 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
876 free(escaped);
878 xsnprintf(timeout_header, sizeof(timeout_header), "Timeout: Second-%ld", timeout);
879 dav_headers = curl_slist_append(dav_headers, timeout_header);
880 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
882 slot = get_active_slot();
883 slot->results = &results;
884 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
885 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
886 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
888 CALLOC_ARRAY(lock, 1);
889 lock->timeout = -1;
891 if (start_active_slot(slot)) {
892 run_active_slot(slot);
893 if (results.curl_result == CURLE_OK) {
894 XML_Parser parser = XML_ParserCreate(NULL);
895 enum XML_Status result;
896 ctx.name = xcalloc(10, 1);
897 ctx.len = 0;
898 ctx.cdata = NULL;
899 ctx.userFunc = handle_new_lock_ctx;
900 ctx.userData = lock;
901 XML_SetUserData(parser, &ctx);
902 XML_SetElementHandler(parser, xml_start_tag,
903 xml_end_tag);
904 XML_SetCharacterDataHandler(parser, xml_cdata);
905 result = XML_Parse(parser, in_buffer.buf,
906 in_buffer.len, 1);
907 free(ctx.name);
908 if (result != XML_STATUS_OK) {
909 fprintf(stderr, "XML error: %s\n",
910 XML_ErrorString(
911 XML_GetErrorCode(parser)));
912 lock->timeout = -1;
914 XML_ParserFree(parser);
915 } else {
916 fprintf(stderr,
917 "error: curl result=%d, HTTP code=%ld\n",
918 results.curl_result, results.http_code);
920 } else {
921 fprintf(stderr, "Unable to start LOCK request\n");
924 curl_slist_free_all(dav_headers);
925 strbuf_release(&out_buffer.buf);
926 strbuf_release(&in_buffer);
928 if (lock->token == NULL || lock->timeout <= 0) {
929 free(lock->token);
930 free(lock->owner);
931 free(url);
932 FREE_AND_NULL(lock);
933 } else {
934 lock->url = url;
935 lock->start_time = time(NULL);
936 lock->next = repo->locks;
937 repo->locks = lock;
940 return lock;
943 static int unlock_remote(struct remote_lock *lock)
945 struct active_request_slot *slot;
946 struct slot_results results;
947 struct remote_lock *prev = repo->locks;
948 struct curl_slist *dav_headers;
949 int rc = 0;
951 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
953 slot = get_active_slot();
954 slot->results = &results;
955 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
956 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
958 if (start_active_slot(slot)) {
959 run_active_slot(slot);
960 if (results.curl_result == CURLE_OK)
961 rc = 1;
962 else
963 fprintf(stderr, "UNLOCK HTTP error %ld\n",
964 results.http_code);
965 } else {
966 fprintf(stderr, "Unable to start UNLOCK request\n");
969 curl_slist_free_all(dav_headers);
971 if (repo->locks == lock) {
972 repo->locks = lock->next;
973 } else {
974 while (prev && prev->next != lock)
975 prev = prev->next;
976 if (prev)
977 prev->next = lock->next;
980 free(lock->owner);
981 free(lock->url);
982 free(lock->token);
983 free(lock);
985 return rc;
988 static void remove_locks(void)
990 struct remote_lock *lock = repo->locks;
992 fprintf(stderr, "Removing remote locks...\n");
993 while (lock) {
994 struct remote_lock *next = lock->next;
995 unlock_remote(lock);
996 lock = next;
1000 static void remove_locks_on_signal(int signo)
1002 remove_locks();
1003 sigchain_pop(signo);
1004 raise(signo);
1007 static void remote_ls(const char *path, int flags,
1008 void (*userFunc)(struct remote_ls_ctx *ls),
1009 void *userData);
1011 /* extract hex from sharded "xx/x{38}" filename */
1012 static int get_oid_hex_from_objpath(const char *path, struct object_id *oid)
1014 oid->algo = hash_algo_by_ptr(the_hash_algo);
1016 if (strlen(path) != the_hash_algo->hexsz + 1)
1017 return -1;
1019 if (hex_to_bytes(oid->hash, path, 1))
1020 return -1;
1021 path += 2;
1022 path++; /* skip '/' */
1024 return hex_to_bytes(oid->hash + 1, path, the_hash_algo->rawsz - 1);
1027 static void process_ls_object(struct remote_ls_ctx *ls)
1029 unsigned int *parent = (unsigned int *)ls->userData;
1030 const char *path = ls->dentry_name;
1031 struct object_id oid;
1033 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1034 remote_dir_exists[*parent] = 1;
1035 return;
1038 if (!skip_prefix(path, "objects/", &path) ||
1039 get_oid_hex_from_objpath(path, &oid))
1040 return;
1042 one_remote_object(&oid);
1045 static void process_ls_ref(struct remote_ls_ctx *ls)
1047 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1048 fprintf(stderr, " %s\n", ls->dentry_name);
1049 return;
1052 if (!(ls->dentry_flags & IS_DIR))
1053 one_remote_ref(ls->dentry_name);
1056 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1058 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1060 if (tag_closed) {
1061 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1062 if (ls->dentry_flags & IS_DIR) {
1064 /* ensure collection names end with slash */
1065 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1067 if (ls->flags & PROCESS_DIRS) {
1068 ls->userFunc(ls);
1070 if (strcmp(ls->dentry_name, ls->path) &&
1071 ls->flags & RECURSIVE) {
1072 remote_ls(ls->dentry_name,
1073 ls->flags,
1074 ls->userFunc,
1075 ls->userData);
1077 } else if (ls->flags & PROCESS_FILES) {
1078 ls->userFunc(ls);
1080 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1081 char *path = ctx->cdata;
1082 if (*ctx->cdata == 'h') {
1083 path = strstr(path, "//");
1084 if (path) {
1085 path = strchr(path+2, '/');
1088 if (path) {
1089 const char *url = repo->url;
1090 if (repo->path)
1091 url = repo->path;
1092 if (strncmp(path, url, repo->path_len))
1093 error("Parsed path '%s' does not match url: '%s'",
1094 path, url);
1095 else {
1096 path += repo->path_len;
1097 ls->dentry_name = xstrdup(path);
1100 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1101 ls->dentry_flags |= IS_DIR;
1103 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1104 FREE_AND_NULL(ls->dentry_name);
1105 ls->dentry_flags = 0;
1110 * NEEDSWORK: remote_ls() ignores info/refs on the remote side. But it
1111 * should _only_ heed the information from that file, instead of trying to
1112 * determine the refs from the remote file system (badly: it does not even
1113 * know about packed-refs).
1115 static void remote_ls(const char *path, int flags,
1116 void (*userFunc)(struct remote_ls_ctx *ls),
1117 void *userData)
1119 char *url = xstrfmt("%s%s", repo->url, path);
1120 struct active_request_slot *slot;
1121 struct slot_results results;
1122 struct strbuf in_buffer = STRBUF_INIT;
1123 struct buffer out_buffer = { STRBUF_INIT, 0 };
1124 struct curl_slist *dav_headers = http_copy_default_headers();
1125 struct xml_ctx ctx;
1126 struct remote_ls_ctx ls;
1128 ls.flags = flags;
1129 ls.path = xstrdup(path);
1130 ls.dentry_name = NULL;
1131 ls.dentry_flags = 0;
1132 ls.userData = userData;
1133 ls.userFunc = userFunc;
1135 strbuf_addstr(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1137 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1138 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1140 slot = get_active_slot();
1141 slot->results = &results;
1142 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1143 &out_buffer, fwrite_buffer);
1144 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1145 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1147 if (start_active_slot(slot)) {
1148 run_active_slot(slot);
1149 if (results.curl_result == CURLE_OK) {
1150 XML_Parser parser = XML_ParserCreate(NULL);
1151 enum XML_Status result;
1152 ctx.name = xcalloc(10, 1);
1153 ctx.len = 0;
1154 ctx.cdata = NULL;
1155 ctx.userFunc = handle_remote_ls_ctx;
1156 ctx.userData = &ls;
1157 XML_SetUserData(parser, &ctx);
1158 XML_SetElementHandler(parser, xml_start_tag,
1159 xml_end_tag);
1160 XML_SetCharacterDataHandler(parser, xml_cdata);
1161 result = XML_Parse(parser, in_buffer.buf,
1162 in_buffer.len, 1);
1163 free(ctx.name);
1165 if (result != XML_STATUS_OK) {
1166 fprintf(stderr, "XML error: %s\n",
1167 XML_ErrorString(
1168 XML_GetErrorCode(parser)));
1170 XML_ParserFree(parser);
1172 } else {
1173 fprintf(stderr, "Unable to start PROPFIND request\n");
1176 free(ls.path);
1177 free(url);
1178 strbuf_release(&out_buffer.buf);
1179 strbuf_release(&in_buffer);
1180 curl_slist_free_all(dav_headers);
1183 static void get_remote_object_list(unsigned char parent)
1185 char path[] = "objects/XX/";
1186 static const char hex[] = "0123456789abcdef";
1187 unsigned int val = parent;
1189 path[8] = hex[val >> 4];
1190 path[9] = hex[val & 0xf];
1191 remote_dir_exists[val] = 0;
1192 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1193 process_ls_object, &val);
1196 static int locking_available(void)
1198 struct active_request_slot *slot;
1199 struct slot_results results;
1200 struct strbuf in_buffer = STRBUF_INIT;
1201 struct buffer out_buffer = { STRBUF_INIT, 0 };
1202 struct curl_slist *dav_headers = http_copy_default_headers();
1203 struct xml_ctx ctx;
1204 int lock_flags = 0;
1205 char *escaped;
1207 escaped = xml_entities(repo->url);
1208 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1209 free(escaped);
1211 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1212 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1214 slot = get_active_slot();
1215 slot->results = &results;
1216 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1217 &out_buffer, fwrite_buffer);
1218 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1219 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, &in_buffer);
1221 if (start_active_slot(slot)) {
1222 run_active_slot(slot);
1223 if (results.curl_result == CURLE_OK) {
1224 XML_Parser parser = XML_ParserCreate(NULL);
1225 enum XML_Status result;
1226 ctx.name = xcalloc(10, 1);
1227 ctx.len = 0;
1228 ctx.cdata = NULL;
1229 ctx.userFunc = handle_lockprop_ctx;
1230 ctx.userData = &lock_flags;
1231 XML_SetUserData(parser, &ctx);
1232 XML_SetElementHandler(parser, xml_start_tag,
1233 xml_end_tag);
1234 result = XML_Parse(parser, in_buffer.buf,
1235 in_buffer.len, 1);
1236 free(ctx.name);
1238 if (result != XML_STATUS_OK) {
1239 fprintf(stderr, "XML error: %s\n",
1240 XML_ErrorString(
1241 XML_GetErrorCode(parser)));
1242 lock_flags = 0;
1244 XML_ParserFree(parser);
1245 if (!lock_flags)
1246 error("no DAV locking support on %s",
1247 repo->url);
1249 } else {
1250 error("Cannot access URL %s, return code %d",
1251 repo->url, results.curl_result);
1252 lock_flags = 0;
1254 } else {
1255 error("Unable to start PROPFIND request on %s", repo->url);
1258 strbuf_release(&out_buffer.buf);
1259 strbuf_release(&in_buffer);
1260 curl_slist_free_all(dav_headers);
1262 return lock_flags;
1265 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1267 struct object_list *entry = xmalloc(sizeof(struct object_list));
1268 entry->item = obj;
1269 entry->next = *p;
1270 *p = entry;
1271 return &entry->next;
1274 static struct object_list **process_blob(struct blob *blob,
1275 struct object_list **p)
1277 struct object *obj = &blob->object;
1279 obj->flags |= LOCAL;
1281 if (obj->flags & (UNINTERESTING | SEEN))
1282 return p;
1284 obj->flags |= SEEN;
1285 return add_one_object(obj, p);
1288 static struct object_list **process_tree(struct tree *tree,
1289 struct object_list **p)
1291 struct object *obj = &tree->object;
1292 struct tree_desc desc;
1293 struct name_entry entry;
1295 obj->flags |= LOCAL;
1297 if (obj->flags & (UNINTERESTING | SEEN))
1298 return p;
1299 if (parse_tree(tree) < 0)
1300 die("bad tree object %s", oid_to_hex(&obj->oid));
1302 obj->flags |= SEEN;
1303 p = add_one_object(obj, p);
1305 init_tree_desc(&desc, tree->buffer, tree->size);
1307 while (tree_entry(&desc, &entry))
1308 switch (object_type(entry.mode)) {
1309 case OBJ_TREE:
1310 p = process_tree(lookup_tree(the_repository, &entry.oid),
1312 break;
1313 case OBJ_BLOB:
1314 p = process_blob(lookup_blob(the_repository, &entry.oid),
1316 break;
1317 default:
1318 /* Subproject commit - not in this repository */
1319 break;
1322 free_tree_buffer(tree);
1323 return p;
1326 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1328 int i;
1329 struct commit *commit;
1330 struct object_list **p = &objects;
1331 int count = 0;
1333 while ((commit = get_revision(revs)) != NULL) {
1334 p = process_tree(get_commit_tree(commit), p);
1335 commit->object.flags |= LOCAL;
1336 if (!(commit->object.flags & UNINTERESTING))
1337 count += add_send_request(&commit->object, lock);
1340 for (i = 0; i < revs->pending.nr; i++) {
1341 struct object_array_entry *entry = revs->pending.objects + i;
1342 struct object *obj = entry->item;
1343 const char *name = entry->name;
1345 if (obj->flags & (UNINTERESTING | SEEN))
1346 continue;
1347 if (obj->type == OBJ_TAG) {
1348 obj->flags |= SEEN;
1349 p = add_one_object(obj, p);
1350 continue;
1352 if (obj->type == OBJ_TREE) {
1353 p = process_tree((struct tree *)obj, p);
1354 continue;
1356 if (obj->type == OBJ_BLOB) {
1357 p = process_blob((struct blob *)obj, p);
1358 continue;
1360 die("unknown pending object %s (%s)", oid_to_hex(&obj->oid), name);
1363 while (objects) {
1364 if (!(objects->item->flags & UNINTERESTING))
1365 count += add_send_request(objects->item, lock);
1366 objects = objects->next;
1369 return count;
1372 static int update_remote(const struct object_id *oid, struct remote_lock *lock)
1374 struct active_request_slot *slot;
1375 struct slot_results results;
1376 struct buffer out_buffer = { STRBUF_INIT, 0 };
1377 struct curl_slist *dav_headers;
1379 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1381 strbuf_addf(&out_buffer.buf, "%s\n", oid_to_hex(oid));
1383 slot = get_active_slot();
1384 slot->results = &results;
1385 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1386 &out_buffer, fwrite_null);
1387 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1389 if (start_active_slot(slot)) {
1390 run_active_slot(slot);
1391 strbuf_release(&out_buffer.buf);
1392 if (results.curl_result != CURLE_OK) {
1393 fprintf(stderr,
1394 "PUT error: curl result=%d, HTTP code=%ld\n",
1395 results.curl_result, results.http_code);
1396 /* We should attempt recovery? */
1397 return 0;
1399 } else {
1400 strbuf_release(&out_buffer.buf);
1401 fprintf(stderr, "Unable to start PUT request\n");
1402 return 0;
1405 return 1;
1408 static struct ref *remote_refs;
1410 static void one_remote_ref(const char *refname)
1412 struct ref *ref;
1413 struct object *obj;
1415 ref = alloc_ref(refname);
1417 if (http_fetch_ref(repo->url, ref) != 0) {
1418 fprintf(stderr,
1419 "Unable to fetch ref %s from %s\n",
1420 refname, repo->url);
1421 free(ref);
1422 return;
1426 * Fetch a copy of the object if it doesn't exist locally - it
1427 * may be required for updating server info later.
1429 if (repo->can_update_info_refs && !has_object_file(&ref->old_oid)) {
1430 obj = lookup_unknown_object(the_repository, &ref->old_oid);
1431 fprintf(stderr, " fetch %s for %s\n",
1432 oid_to_hex(&ref->old_oid), refname);
1433 add_fetch_request(obj);
1436 ref->next = remote_refs;
1437 remote_refs = ref;
1440 static void get_dav_remote_heads(void)
1442 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1445 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1447 struct strbuf *buf = (struct strbuf *)ls->userData;
1448 struct object *o;
1449 struct ref *ref;
1451 ref = alloc_ref(ls->dentry_name);
1453 if (http_fetch_ref(repo->url, ref) != 0) {
1454 fprintf(stderr,
1455 "Unable to fetch ref %s from %s\n",
1456 ls->dentry_name, repo->url);
1457 aborted = 1;
1458 free(ref);
1459 return;
1462 o = parse_object(the_repository, &ref->old_oid);
1463 if (!o) {
1464 fprintf(stderr,
1465 "Unable to parse object %s for remote ref %s\n",
1466 oid_to_hex(&ref->old_oid), ls->dentry_name);
1467 aborted = 1;
1468 free(ref);
1469 return;
1472 strbuf_addf(buf, "%s\t%s\n",
1473 oid_to_hex(&ref->old_oid), ls->dentry_name);
1475 if (o->type == OBJ_TAG) {
1476 o = deref_tag(the_repository, o, ls->dentry_name, 0);
1477 if (o)
1478 strbuf_addf(buf, "%s\t%s^{}\n",
1479 oid_to_hex(&o->oid), ls->dentry_name);
1481 free(ref);
1484 static void update_remote_info_refs(struct remote_lock *lock)
1486 struct buffer buffer = { STRBUF_INIT, 0 };
1487 struct active_request_slot *slot;
1488 struct slot_results results;
1489 struct curl_slist *dav_headers;
1491 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1492 add_remote_info_ref, &buffer.buf);
1493 if (!aborted) {
1494 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1496 slot = get_active_slot();
1497 slot->results = &results;
1498 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1499 &buffer, fwrite_null);
1500 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1502 if (start_active_slot(slot)) {
1503 run_active_slot(slot);
1504 if (results.curl_result != CURLE_OK) {
1505 fprintf(stderr,
1506 "PUT error: curl result=%d, HTTP code=%ld\n",
1507 results.curl_result, results.http_code);
1511 strbuf_release(&buffer.buf);
1514 static int remote_exists(const char *path)
1516 char *url = xstrfmt("%s%s", repo->url, path);
1517 int ret;
1520 switch (http_get_strbuf(url, NULL, NULL)) {
1521 case HTTP_OK:
1522 ret = 1;
1523 break;
1524 case HTTP_MISSING_TARGET:
1525 ret = 0;
1526 break;
1527 case HTTP_ERROR:
1528 error("unable to access '%s': %s", url, curl_errorstr);
1529 /* fallthrough */
1530 default:
1531 ret = -1;
1533 free(url);
1534 return ret;
1537 static void fetch_symref(const char *path, char **symref, struct object_id *oid)
1539 char *url = xstrfmt("%s%s", repo->url, path);
1540 struct strbuf buffer = STRBUF_INIT;
1541 const char *name;
1543 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1544 die("Couldn't get %s for remote symref\n%s", url,
1545 curl_errorstr);
1546 free(url);
1548 FREE_AND_NULL(*symref);
1549 oidclr(oid);
1551 if (buffer.len == 0)
1552 return;
1554 /* Cut off trailing newline. */
1555 strbuf_rtrim(&buffer);
1557 /* If it's a symref, set the refname; otherwise try for a sha1 */
1558 if (skip_prefix(buffer.buf, "ref: ", &name)) {
1559 *symref = xmemdupz(name, buffer.len - (name - buffer.buf));
1560 } else {
1561 get_oid_hex(buffer.buf, oid);
1564 strbuf_release(&buffer);
1567 static int verify_merge_base(struct object_id *head_oid, struct ref *remote)
1569 struct commit *head = lookup_commit_or_die(head_oid, "HEAD");
1570 struct commit *branch = lookup_commit_or_die(&remote->old_oid,
1571 remote->name);
1573 return in_merge_bases(branch, head);
1576 static int delete_remote_branch(const char *pattern, int force)
1578 struct ref *refs = remote_refs;
1579 struct ref *remote_ref = NULL;
1580 struct object_id head_oid;
1581 char *symref = NULL;
1582 int match;
1583 int patlen = strlen(pattern);
1584 int i;
1585 struct active_request_slot *slot;
1586 struct slot_results results;
1587 char *url;
1589 /* Find the remote branch(es) matching the specified branch name */
1590 for (match = 0; refs; refs = refs->next) {
1591 char *name = refs->name;
1592 int namelen = strlen(name);
1593 if (namelen < patlen ||
1594 memcmp(name + namelen - patlen, pattern, patlen))
1595 continue;
1596 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1597 continue;
1598 match++;
1599 remote_ref = refs;
1601 if (match == 0)
1602 return error("No remote branch matches %s", pattern);
1603 if (match != 1)
1604 return error("More than one remote branch matches %s",
1605 pattern);
1608 * Remote HEAD must be a symref (not exactly foolproof; a remote
1609 * symlink to a symref will look like a symref)
1611 fetch_symref("HEAD", &symref, &head_oid);
1612 if (!symref)
1613 return error("Remote HEAD is not a symref");
1615 /* Remote branch must not be the remote HEAD */
1616 for (i = 0; symref && i < MAXDEPTH; i++) {
1617 if (!strcmp(remote_ref->name, symref))
1618 return error("Remote branch %s is the current HEAD",
1619 remote_ref->name);
1620 fetch_symref(symref, &symref, &head_oid);
1623 /* Run extra sanity checks if delete is not forced */
1624 if (!force) {
1625 /* Remote HEAD must resolve to a known object */
1626 if (symref)
1627 return error("Remote HEAD symrefs too deep");
1628 if (is_null_oid(&head_oid))
1629 return error("Unable to resolve remote HEAD");
1630 if (!has_object_file(&head_oid))
1631 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", oid_to_hex(&head_oid));
1633 /* Remote branch must resolve to a known object */
1634 if (is_null_oid(&remote_ref->old_oid))
1635 return error("Unable to resolve remote branch %s",
1636 remote_ref->name);
1637 if (!has_object_file(&remote_ref->old_oid))
1638 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));
1640 /* Remote branch must be an ancestor of remote HEAD */
1641 if (!verify_merge_base(&head_oid, remote_ref)) {
1642 return error("The branch '%s' is not an ancestor "
1643 "of your current HEAD.\n"
1644 "If you are sure you want to delete it,"
1645 " run:\n\t'git http-push -D %s %s'",
1646 remote_ref->name, repo->url, pattern);
1650 /* Send delete request */
1651 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1652 if (dry_run)
1653 return 0;
1654 url = xstrfmt("%s%s", repo->url, remote_ref->name);
1655 slot = get_active_slot();
1656 slot->results = &results;
1657 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1658 if (start_active_slot(slot)) {
1659 run_active_slot(slot);
1660 free(url);
1661 if (results.curl_result != CURLE_OK)
1662 return error("DELETE request failed (%d/%ld)",
1663 results.curl_result, results.http_code);
1664 } else {
1665 free(url);
1666 return error("Unable to start DELETE request");
1669 return 0;
1672 static void run_request_queue(void)
1674 is_running_queue = 1;
1675 fill_active_slots();
1676 add_fill_function(NULL, fill_active_slot);
1677 do {
1678 finish_all_active_slots();
1679 fill_active_slots();
1680 } while (request_queue_head && !aborted);
1682 is_running_queue = 0;
1685 int cmd_main(int argc, const char **argv)
1687 struct transfer_request *request;
1688 struct transfer_request *next_request;
1689 struct refspec rs = REFSPEC_INIT_PUSH;
1690 struct remote_lock *ref_lock = NULL;
1691 struct remote_lock *info_ref_lock = NULL;
1692 struct rev_info revs;
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 strvec commit_argv = STRVEC_INIT;
1830 if (!ref->peer_ref)
1831 continue;
1833 if (is_null_oid(&ref->peer_ref->new_oid)) {
1834 if (delete_remote_branch(ref->name, 1) == -1) {
1835 error("Could not remove %s", ref->name);
1836 if (helper_status)
1837 printf("error %s cannot remove\n", ref->name);
1838 rc = -4;
1840 else if (helper_status)
1841 printf("ok %s\n", ref->name);
1842 new_refs++;
1843 continue;
1846 if (oideq(&ref->old_oid, &ref->peer_ref->new_oid)) {
1847 if (push_verbosely)
1848 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1849 if (helper_status)
1850 printf("ok %s up to date\n", ref->name);
1851 continue;
1854 if (!force_all &&
1855 !is_null_oid(&ref->old_oid) &&
1856 !ref->force) {
1857 if (!has_object_file(&ref->old_oid) ||
1858 !ref_newer(&ref->peer_ref->new_oid,
1859 &ref->old_oid)) {
1861 * We do not have the remote ref, or
1862 * we know that the remote ref is not
1863 * an ancestor of what we are trying to
1864 * push. Either way this can be losing
1865 * commits at the remote end and likely
1866 * we were not up to date to begin with.
1868 error("remote '%s' is not an ancestor of\n"
1869 "local '%s'.\n"
1870 "Maybe you are not up-to-date and "
1871 "need to pull first?",
1872 ref->name,
1873 ref->peer_ref->name);
1874 if (helper_status)
1875 printf("error %s non-fast forward\n", ref->name);
1876 rc = -2;
1877 continue;
1880 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1881 new_refs++;
1883 fprintf(stderr, "updating '%s'", ref->name);
1884 if (strcmp(ref->name, ref->peer_ref->name))
1885 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1886 fprintf(stderr, "\n from %s\n to %s\n",
1887 oid_to_hex(&ref->old_oid), oid_to_hex(&ref->new_oid));
1888 if (dry_run) {
1889 if (helper_status)
1890 printf("ok %s\n", ref->name);
1891 continue;
1894 /* Lock remote branch ref */
1895 ref_lock = lock_remote(ref->name, LOCK_TIME);
1896 if (ref_lock == NULL) {
1897 fprintf(stderr, "Unable to lock remote branch %s\n",
1898 ref->name);
1899 if (helper_status)
1900 printf("error %s lock error\n", ref->name);
1901 rc = 1;
1902 continue;
1905 /* Set up revision info for this refspec */
1906 strvec_push(&commit_argv, ""); /* ignored */
1907 strvec_push(&commit_argv, "--objects");
1908 strvec_push(&commit_argv, oid_to_hex(&ref->new_oid));
1909 if (!push_all && !is_null_oid(&ref->old_oid))
1910 strvec_pushf(&commit_argv, "^%s",
1911 oid_to_hex(&ref->old_oid));
1912 repo_init_revisions(the_repository, &revs, setup_git_directory());
1913 setup_revisions(commit_argv.nr, commit_argv.v, &revs, NULL);
1914 revs.edge_hint = 0; /* just in case */
1916 /* Generate a list of objects that need to be pushed */
1917 pushing = 0;
1918 if (prepare_revision_walk(&revs))
1919 die("revision walk setup failed");
1920 mark_edges_uninteresting(&revs, NULL, 0);
1921 objects_to_send = get_delta(&revs, ref_lock);
1922 finish_all_active_slots();
1924 /* Push missing objects to remote, this would be a
1925 convenient time to pack them first if appropriate. */
1926 pushing = 1;
1927 if (objects_to_send)
1928 fprintf(stderr, " sending %d objects\n",
1929 objects_to_send);
1931 run_request_queue();
1933 /* Update the remote branch if all went well */
1934 if (aborted || !update_remote(&ref->new_oid, ref_lock))
1935 rc = 1;
1937 if (!rc)
1938 fprintf(stderr, " done\n");
1939 if (helper_status)
1940 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1941 unlock_remote(ref_lock);
1942 check_locks();
1943 strvec_clear(&commit_argv);
1946 /* Update remote server info if appropriate */
1947 if (repo->has_info_refs && new_refs) {
1948 if (info_ref_lock && repo->can_update_info_refs) {
1949 fprintf(stderr, "Updating remote server info\n");
1950 if (!dry_run)
1951 update_remote_info_refs(info_ref_lock);
1952 } else {
1953 fprintf(stderr, "Unable to update server info\n");
1957 cleanup:
1958 if (info_ref_lock)
1959 unlock_remote(info_ref_lock);
1960 free(repo);
1962 http_cleanup();
1964 request = request_queue_head;
1965 while (request != NULL) {
1966 next_request = request->next;
1967 release_request(request);
1968 request = next_request;
1971 return rc;