zlib: initialize git_zstream in git_deflate_init{,_gzip,_raw}
[git/mjg.git] / http-push.c
blob8f473b35de30bda806354c90a37c02ffba9c00cc
1 #include "cache.h"
2 #include "commit.h"
3 #include "tag.h"
4 #include "blob.h"
5 #include "http.h"
6 #include "refs.h"
7 #include "diff.h"
8 #include "revision.h"
9 #include "exec_cmd.h"
10 #include "remote.h"
11 #include "list-objects.h"
12 #include "sigchain.h"
14 #ifdef EXPAT_NEEDS_XMLPARSE_H
15 #include <xmlparse.h>
16 #else
17 #include <expat.h>
18 #endif
20 static const char http_push_usage[] =
21 "git http-push [--all] [--dry-run] [--force] [--verbose] <remote> [<head>...]\n";
23 #ifndef XML_STATUS_OK
24 enum XML_Status {
25 XML_STATUS_OK = 1,
26 XML_STATUS_ERROR = 0
28 #define XML_STATUS_OK 1
29 #define XML_STATUS_ERROR 0
30 #endif
32 #define PREV_BUF_SIZE 4096
34 /* DAV methods */
35 #define DAV_LOCK "LOCK"
36 #define DAV_MKCOL "MKCOL"
37 #define DAV_MOVE "MOVE"
38 #define DAV_PROPFIND "PROPFIND"
39 #define DAV_PUT "PUT"
40 #define DAV_UNLOCK "UNLOCK"
41 #define DAV_DELETE "DELETE"
43 /* DAV lock flags */
44 #define DAV_PROP_LOCKWR (1u << 0)
45 #define DAV_PROP_LOCKEX (1u << 1)
46 #define DAV_LOCK_OK (1u << 2)
48 /* DAV XML properties */
49 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
50 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
51 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
52 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
53 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
54 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
55 #define DAV_PROPFIND_RESP ".multistatus.response"
56 #define DAV_PROPFIND_NAME ".multistatus.response.href"
57 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
59 /* DAV request body templates */
60 #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>"
61 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
62 #define LOCK_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:lockinfo xmlns:D=\"DAV:\">\n<D:lockscope><D:exclusive/></D:lockscope>\n<D:locktype><D:write/></D:locktype>\n<D:owner>\n<D:href>mailto:%s</D:href>\n</D:owner>\n</D:lockinfo>"
64 #define LOCK_TIME 600
65 #define LOCK_REFRESH 30
67 /* Remember to update object flag allocation in object.h */
68 #define LOCAL (1u<<16)
69 #define REMOTE (1u<<17)
70 #define FETCHING (1u<<18)
71 #define PUSHING (1u<<19)
73 /* We allow "recursive" symbolic refs. Only within reason, though */
74 #define MAXDEPTH 5
76 static int pushing;
77 static int aborted;
78 static signed char remote_dir_exists[256];
80 static int push_verbosely;
81 static int push_all = MATCH_REFS_NONE;
82 static int force_all;
83 static int dry_run;
84 static int helper_status;
86 static struct object_list *objects;
88 struct repo {
89 char *url;
90 char *path;
91 int path_len;
92 int has_info_refs;
93 int can_update_info_refs;
94 int has_info_packs;
95 struct packed_git *packs;
96 struct remote_lock *locks;
99 static struct repo *repo;
101 enum transfer_state {
102 NEED_FETCH,
103 RUN_FETCH_LOOSE,
104 RUN_FETCH_PACKED,
105 NEED_PUSH,
106 RUN_MKCOL,
107 RUN_PUT,
108 RUN_MOVE,
109 ABORTED,
110 COMPLETE
113 struct transfer_request {
114 struct object *obj;
115 char *url;
116 char *dest;
117 struct remote_lock *lock;
118 struct curl_slist *headers;
119 struct buffer buffer;
120 enum transfer_state state;
121 CURLcode curl_result;
122 char errorstr[CURL_ERROR_SIZE];
123 long http_code;
124 void *userData;
125 struct active_request_slot *slot;
126 struct transfer_request *next;
129 static struct transfer_request *request_queue_head;
131 struct xml_ctx {
132 char *name;
133 int len;
134 char *cdata;
135 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
136 void *userData;
139 struct remote_lock {
140 char *url;
141 char *owner;
142 char *token;
143 char tmpfile_suffix[41];
144 time_t start_time;
145 long timeout;
146 int refreshing;
147 struct remote_lock *next;
150 /* Flags that control remote_ls processing */
151 #define PROCESS_FILES (1u << 0)
152 #define PROCESS_DIRS (1u << 1)
153 #define RECURSIVE (1u << 2)
155 /* Flags that remote_ls passes to callback functions */
156 #define IS_DIR (1u << 0)
158 struct remote_ls_ctx {
159 char *path;
160 void (*userFunc)(struct remote_ls_ctx *ls);
161 void *userData;
162 int flags;
163 char *dentry_name;
164 int dentry_flags;
165 struct remote_ls_ctx *parent;
168 /* get_dav_token_headers options */
169 enum dav_header_flag {
170 DAV_HEADER_IF = (1u << 0),
171 DAV_HEADER_LOCK = (1u << 1),
172 DAV_HEADER_TIMEOUT = (1u << 2)
175 static char *xml_entities(const char *s)
177 struct strbuf buf = STRBUF_INIT;
178 strbuf_addstr_xml_quoted(&buf, s);
179 return strbuf_detach(&buf, NULL);
182 static void curl_setup_http_get(CURL *curl, const char *url,
183 const char *custom_req)
185 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
186 curl_easy_setopt(curl, CURLOPT_URL, url);
187 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
188 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_null);
191 static void curl_setup_http(CURL *curl, const char *url,
192 const char *custom_req, struct buffer *buffer,
193 curl_write_callback write_fn)
195 curl_easy_setopt(curl, CURLOPT_PUT, 1);
196 curl_easy_setopt(curl, CURLOPT_URL, url);
197 curl_easy_setopt(curl, CURLOPT_INFILE, buffer);
198 curl_easy_setopt(curl, CURLOPT_INFILESIZE, buffer->buf.len);
199 curl_easy_setopt(curl, CURLOPT_READFUNCTION, fread_buffer);
200 #ifndef NO_CURL_IOCTL
201 curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_buffer);
202 curl_easy_setopt(curl, CURLOPT_IOCTLDATA, buffer);
203 #endif
204 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
205 curl_easy_setopt(curl, CURLOPT_NOBODY, 0);
206 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
207 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
210 static struct curl_slist *get_dav_token_headers(struct remote_lock *lock, enum dav_header_flag options)
212 struct strbuf buf = STRBUF_INIT;
213 struct curl_slist *dav_headers = NULL;
215 if (options & DAV_HEADER_IF) {
216 strbuf_addf(&buf, "If: (<%s>)", lock->token);
217 dav_headers = curl_slist_append(dav_headers, buf.buf);
218 strbuf_reset(&buf);
220 if (options & DAV_HEADER_LOCK) {
221 strbuf_addf(&buf, "Lock-Token: <%s>", lock->token);
222 dav_headers = curl_slist_append(dav_headers, buf.buf);
223 strbuf_reset(&buf);
225 if (options & DAV_HEADER_TIMEOUT) {
226 strbuf_addf(&buf, "Timeout: Second-%ld", lock->timeout);
227 dav_headers = curl_slist_append(dav_headers, buf.buf);
228 strbuf_reset(&buf);
230 strbuf_release(&buf);
232 return dav_headers;
235 static void finish_request(struct transfer_request *request);
236 static void release_request(struct transfer_request *request);
238 static void process_response(void *callback_data)
240 struct transfer_request *request =
241 (struct transfer_request *)callback_data;
243 finish_request(request);
246 #ifdef USE_CURL_MULTI
248 static void start_fetch_loose(struct transfer_request *request)
250 struct active_request_slot *slot;
251 struct http_object_request *obj_req;
253 obj_req = new_http_object_request(repo->url, request->obj->sha1);
254 if (obj_req == NULL) {
255 request->state = ABORTED;
256 return;
259 slot = obj_req->slot;
260 slot->callback_func = process_response;
261 slot->callback_data = request;
262 request->slot = slot;
263 request->userData = obj_req;
265 /* Try to get the request started, abort the request on error */
266 request->state = RUN_FETCH_LOOSE;
267 if (!start_active_slot(slot)) {
268 fprintf(stderr, "Unable to start GET request\n");
269 repo->can_update_info_refs = 0;
270 release_http_object_request(obj_req);
271 release_request(request);
275 static void start_mkcol(struct transfer_request *request)
277 char *hex = sha1_to_hex(request->obj->sha1);
278 struct active_request_slot *slot;
280 request->url = get_remote_object_url(repo->url, hex, 1);
282 slot = get_active_slot();
283 slot->callback_func = process_response;
284 slot->callback_data = request;
285 curl_setup_http_get(slot->curl, request->url, DAV_MKCOL);
286 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
288 if (start_active_slot(slot)) {
289 request->slot = slot;
290 request->state = RUN_MKCOL;
291 } else {
292 request->state = ABORTED;
293 free(request->url);
294 request->url = NULL;
297 #endif
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->sha1, repo->packs);
307 if (!target) {
308 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
309 repo->can_update_info_refs = 0;
310 release_request(request);
311 return;
314 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
315 fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
317 preq = new_http_pack_request(target, repo->url);
318 if (preq == NULL) {
319 release_http_pack_request(preq);
320 repo->can_update_info_refs = 0;
321 return;
323 preq->lst = &repo->packs;
325 /* Make sure there isn't another open request for this pack */
326 while (check_request) {
327 if (check_request->state == RUN_FETCH_PACKED &&
328 !strcmp(check_request->url, preq->url)) {
329 release_http_pack_request(preq);
330 release_request(request);
331 return;
333 check_request = check_request->next;
336 preq->slot->callback_func = process_response;
337 preq->slot->callback_data = request;
338 request->slot = preq->slot;
339 request->userData = preq;
341 /* Try to get the request started, abort the request on error */
342 request->state = RUN_FETCH_PACKED;
343 if (!start_active_slot(preq->slot)) {
344 fprintf(stderr, "Unable to start GET request\n");
345 release_http_pack_request(preq);
346 repo->can_update_info_refs = 0;
347 release_request(request);
351 static void start_put(struct transfer_request *request)
353 char *hex = sha1_to_hex(request->obj->sha1);
354 struct active_request_slot *slot;
355 struct strbuf buf = STRBUF_INIT;
356 enum object_type type;
357 char hdr[50];
358 void *unpacked;
359 unsigned long len;
360 int hdrlen;
361 ssize_t size;
362 git_zstream stream;
364 unpacked = read_sha1_file(request->obj->sha1, &type, &len);
365 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
367 /* Set it up */
368 git_deflate_init(&stream, zlib_compression_level);
369 size = git_deflate_bound(&stream, len + hdrlen);
370 strbuf_init(&request->buffer.buf, size);
371 request->buffer.posn = 0;
373 /* Compress it */
374 stream.next_out = (unsigned char *)request->buffer.buf.buf;
375 stream.avail_out = size;
377 /* First header.. */
378 stream.next_in = (void *)hdr;
379 stream.avail_in = hdrlen;
380 while (git_deflate(&stream, 0) == Z_OK)
381 ; /* nothing */
383 /* Then the data itself.. */
384 stream.next_in = unpacked;
385 stream.avail_in = len;
386 while (git_deflate(&stream, Z_FINISH) == Z_OK)
387 ; /* nothing */
388 git_deflate_end(&stream);
389 free(unpacked);
391 request->buffer.buf.len = stream.total_out;
393 strbuf_addstr(&buf, "Destination: ");
394 append_remote_object_url(&buf, repo->url, hex, 0);
395 request->dest = strbuf_detach(&buf, NULL);
397 append_remote_object_url(&buf, repo->url, hex, 0);
398 strbuf_add(&buf, request->lock->tmpfile_suffix, 41);
399 request->url = strbuf_detach(&buf, NULL);
401 slot = get_active_slot();
402 slot->callback_func = process_response;
403 slot->callback_data = request;
404 curl_setup_http(slot->curl, request->url, DAV_PUT,
405 &request->buffer, fwrite_null);
407 if (start_active_slot(slot)) {
408 request->slot = slot;
409 request->state = RUN_PUT;
410 } else {
411 request->state = ABORTED;
412 free(request->url);
413 request->url = NULL;
417 static void start_move(struct transfer_request *request)
419 struct active_request_slot *slot;
420 struct curl_slist *dav_headers = NULL;
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(request->url);
436 request->url = NULL;
440 static int refresh_lock(struct remote_lock *lock)
442 struct active_request_slot *slot;
443 struct slot_results results;
444 struct curl_slist *dav_headers;
445 int rc = 0;
447 lock->refreshing = 1;
449 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF | DAV_HEADER_TIMEOUT);
451 slot = get_active_slot();
452 slot->results = &results;
453 curl_setup_http_get(slot->curl, lock->url, DAV_LOCK);
454 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
456 if (start_active_slot(slot)) {
457 run_active_slot(slot);
458 if (results.curl_result != CURLE_OK) {
459 fprintf(stderr, "LOCK HTTP error %ld\n",
460 results.http_code);
461 } else {
462 lock->start_time = time(NULL);
463 rc = 1;
467 lock->refreshing = 0;
468 curl_slist_free_all(dav_headers);
470 return rc;
473 static void check_locks(void)
475 struct remote_lock *lock = repo->locks;
476 time_t current_time = time(NULL);
477 int time_remaining;
479 while (lock) {
480 time_remaining = lock->start_time + lock->timeout -
481 current_time;
482 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
483 if (!refresh_lock(lock)) {
484 fprintf(stderr,
485 "Unable to refresh lock for %s\n",
486 lock->url);
487 aborted = 1;
488 return;
491 lock = lock->next;
495 static void release_request(struct transfer_request *request)
497 struct transfer_request *entry = request_queue_head;
499 if (request == request_queue_head) {
500 request_queue_head = request->next;
501 } else {
502 while (entry->next != NULL && entry->next != request)
503 entry = entry->next;
504 if (entry->next == request)
505 entry->next = entry->next->next;
508 free(request->url);
509 free(request);
512 static void finish_request(struct transfer_request *request)
514 struct http_pack_request *preq;
515 struct http_object_request *obj_req;
517 request->curl_result = request->slot->curl_result;
518 request->http_code = request->slot->http_code;
519 request->slot = NULL;
521 /* Keep locks active */
522 check_locks();
524 if (request->headers != NULL)
525 curl_slist_free_all(request->headers);
527 /* URL is reused for MOVE after PUT */
528 if (request->state != RUN_PUT) {
529 free(request->url);
530 request->url = NULL;
533 if (request->state == RUN_MKCOL) {
534 if (request->curl_result == CURLE_OK ||
535 request->http_code == 405) {
536 remote_dir_exists[request->obj->sha1[0]] = 1;
537 start_put(request);
538 } else {
539 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
540 sha1_to_hex(request->obj->sha1),
541 request->curl_result, request->http_code);
542 request->state = ABORTED;
543 aborted = 1;
545 } else if (request->state == RUN_PUT) {
546 if (request->curl_result == CURLE_OK) {
547 start_move(request);
548 } else {
549 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
550 sha1_to_hex(request->obj->sha1),
551 request->curl_result, request->http_code);
552 request->state = ABORTED;
553 aborted = 1;
555 } else if (request->state == RUN_MOVE) {
556 if (request->curl_result == CURLE_OK) {
557 if (push_verbosely)
558 fprintf(stderr, " sent %s\n",
559 sha1_to_hex(request->obj->sha1));
560 request->obj->flags |= REMOTE;
561 release_request(request);
562 } else {
563 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
564 sha1_to_hex(request->obj->sha1),
565 request->curl_result, request->http_code);
566 request->state = ABORTED;
567 aborted = 1;
569 } else if (request->state == RUN_FETCH_LOOSE) {
570 obj_req = (struct http_object_request *)request->userData;
572 if (finish_http_object_request(obj_req) == 0)
573 if (obj_req->rename == 0)
574 request->obj->flags |= (LOCAL | REMOTE);
576 /* Try fetching packed if necessary */
577 if (request->obj->flags & LOCAL) {
578 release_http_object_request(obj_req);
579 release_request(request);
580 } else
581 start_fetch_packed(request);
583 } else if (request->state == RUN_FETCH_PACKED) {
584 int fail = 1;
585 if (request->curl_result != CURLE_OK) {
586 fprintf(stderr, "Unable to get pack file %s\n%s",
587 request->url, curl_errorstr);
588 } else {
589 preq = (struct http_pack_request *)request->userData;
591 if (preq) {
592 if (finish_http_pack_request(preq) == 0)
593 fail = 0;
594 release_http_pack_request(preq);
597 if (fail)
598 repo->can_update_info_refs = 0;
599 release_request(request);
603 #ifdef USE_CURL_MULTI
604 static int is_running_queue;
605 static int fill_active_slot(void *unused)
607 struct transfer_request *request;
609 if (aborted || !is_running_queue)
610 return 0;
612 for (request = request_queue_head; request; request = request->next) {
613 if (request->state == NEED_FETCH) {
614 start_fetch_loose(request);
615 return 1;
616 } else if (pushing && request->state == NEED_PUSH) {
617 if (remote_dir_exists[request->obj->sha1[0]] == 1) {
618 start_put(request);
619 } else {
620 start_mkcol(request);
622 return 1;
625 return 0;
627 #endif
629 static void get_remote_object_list(unsigned char parent);
631 static void add_fetch_request(struct object *obj)
633 struct transfer_request *request;
635 check_locks();
638 * Don't fetch the object if it's known to exist locally
639 * or is already in the request queue
641 if (remote_dir_exists[obj->sha1[0]] == -1)
642 get_remote_object_list(obj->sha1[0]);
643 if (obj->flags & (LOCAL | FETCHING))
644 return;
646 obj->flags |= FETCHING;
647 request = xmalloc(sizeof(*request));
648 request->obj = obj;
649 request->url = NULL;
650 request->lock = NULL;
651 request->headers = NULL;
652 request->state = NEED_FETCH;
653 request->next = request_queue_head;
654 request_queue_head = request;
656 #ifdef USE_CURL_MULTI
657 fill_active_slots();
658 step_active_slots();
659 #endif
662 static int add_send_request(struct object *obj, struct remote_lock *lock)
664 struct transfer_request *request;
665 struct packed_git *target;
667 /* Keep locks active */
668 check_locks();
671 * Don't push the object if it's known to exist on the remote
672 * or is already in the request queue
674 if (remote_dir_exists[obj->sha1[0]] == -1)
675 get_remote_object_list(obj->sha1[0]);
676 if (obj->flags & (REMOTE | PUSHING))
677 return 0;
678 target = find_sha1_pack(obj->sha1, repo->packs);
679 if (target) {
680 obj->flags |= REMOTE;
681 return 0;
684 obj->flags |= PUSHING;
685 request = xmalloc(sizeof(*request));
686 request->obj = obj;
687 request->url = NULL;
688 request->lock = lock;
689 request->headers = NULL;
690 request->state = NEED_PUSH;
691 request->next = request_queue_head;
692 request_queue_head = request;
694 #ifdef USE_CURL_MULTI
695 fill_active_slots();
696 step_active_slots();
697 #endif
699 return 1;
702 static int fetch_indices(void)
704 int ret;
706 if (push_verbosely)
707 fprintf(stderr, "Getting pack list\n");
709 switch (http_get_info_packs(repo->url, &repo->packs)) {
710 case HTTP_OK:
711 case HTTP_MISSING_TARGET:
712 ret = 0;
713 break;
714 default:
715 ret = -1;
718 return ret;
721 static void one_remote_object(const char *hex)
723 unsigned char sha1[20];
724 struct object *obj;
726 if (get_sha1_hex(hex, sha1) != 0)
727 return;
729 obj = lookup_object(sha1);
730 if (!obj)
731 obj = parse_object(sha1);
733 /* Ignore remote objects that don't exist locally */
734 if (!obj)
735 return;
737 obj->flags |= REMOTE;
738 if (!object_list_contains(objects, obj))
739 object_list_insert(obj, &objects);
742 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
744 int *lock_flags = (int *)ctx->userData;
746 if (tag_closed) {
747 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
748 if ((*lock_flags & DAV_PROP_LOCKEX) &&
749 (*lock_flags & DAV_PROP_LOCKWR)) {
750 *lock_flags |= DAV_LOCK_OK;
752 *lock_flags &= DAV_LOCK_OK;
753 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
754 *lock_flags |= DAV_PROP_LOCKWR;
755 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
756 *lock_flags |= DAV_PROP_LOCKEX;
761 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
763 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
764 git_SHA_CTX sha_ctx;
765 unsigned char lock_token_sha1[20];
767 if (tag_closed && ctx->cdata) {
768 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
769 lock->owner = xmalloc(strlen(ctx->cdata) + 1);
770 strcpy(lock->owner, ctx->cdata);
771 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
772 if (starts_with(ctx->cdata, "Second-"))
773 lock->timeout =
774 strtol(ctx->cdata + 7, NULL, 10);
775 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
776 lock->token = xmalloc(strlen(ctx->cdata) + 1);
777 strcpy(lock->token, ctx->cdata);
779 git_SHA1_Init(&sha_ctx);
780 git_SHA1_Update(&sha_ctx, lock->token, strlen(lock->token));
781 git_SHA1_Final(lock_token_sha1, &sha_ctx);
783 lock->tmpfile_suffix[0] = '_';
784 memcpy(lock->tmpfile_suffix + 1, sha1_to_hex(lock_token_sha1), 40);
789 static void one_remote_ref(const char *refname);
791 static void
792 xml_start_tag(void *userData, const char *name, const char **atts)
794 struct xml_ctx *ctx = (struct xml_ctx *)userData;
795 const char *c = strchr(name, ':');
796 int new_len;
798 if (c == NULL)
799 c = name;
800 else
801 c++;
803 new_len = strlen(ctx->name) + strlen(c) + 2;
805 if (new_len > ctx->len) {
806 ctx->name = xrealloc(ctx->name, new_len);
807 ctx->len = new_len;
809 strcat(ctx->name, ".");
810 strcat(ctx->name, c);
812 free(ctx->cdata);
813 ctx->cdata = NULL;
815 ctx->userFunc(ctx, 0);
818 static void
819 xml_end_tag(void *userData, const char *name)
821 struct xml_ctx *ctx = (struct xml_ctx *)userData;
822 const char *c = strchr(name, ':');
823 char *ep;
825 ctx->userFunc(ctx, 1);
827 if (c == NULL)
828 c = name;
829 else
830 c++;
832 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
833 *ep = 0;
836 static void
837 xml_cdata(void *userData, const XML_Char *s, int len)
839 struct xml_ctx *ctx = (struct xml_ctx *)userData;
840 free(ctx->cdata);
841 ctx->cdata = xmemdupz(s, len);
844 static struct remote_lock *lock_remote(const char *path, long timeout)
846 struct active_request_slot *slot;
847 struct slot_results results;
848 struct buffer out_buffer = { STRBUF_INIT, 0 };
849 struct strbuf in_buffer = STRBUF_INIT;
850 char *url;
851 char *ep;
852 char timeout_header[25];
853 struct remote_lock *lock = NULL;
854 struct curl_slist *dav_headers = NULL;
855 struct xml_ctx ctx;
856 char *escaped;
858 url = xmalloc(strlen(repo->url) + strlen(path) + 1);
859 sprintf(url, "%s%s", repo->url, path);
861 /* Make sure leading directories exist for the remote ref */
862 ep = strchr(url + strlen(repo->url) + 1, '/');
863 while (ep) {
864 char saved_character = ep[1];
865 ep[1] = '\0';
866 slot = get_active_slot();
867 slot->results = &results;
868 curl_setup_http_get(slot->curl, url, DAV_MKCOL);
869 if (start_active_slot(slot)) {
870 run_active_slot(slot);
871 if (results.curl_result != CURLE_OK &&
872 results.http_code != 405) {
873 fprintf(stderr,
874 "Unable to create branch path %s\n",
875 url);
876 free(url);
877 return NULL;
879 } else {
880 fprintf(stderr, "Unable to start MKCOL request\n");
881 free(url);
882 return NULL;
884 ep[1] = saved_character;
885 ep = strchr(ep + 1, '/');
888 escaped = xml_entities(ident_default_email());
889 strbuf_addf(&out_buffer.buf, LOCK_REQUEST, escaped);
890 free(escaped);
892 sprintf(timeout_header, "Timeout: Second-%ld", timeout);
893 dav_headers = curl_slist_append(dav_headers, timeout_header);
894 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
896 slot = get_active_slot();
897 slot->results = &results;
898 curl_setup_http(slot->curl, url, DAV_LOCK, &out_buffer, fwrite_buffer);
899 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
900 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
902 lock = xcalloc(1, sizeof(*lock));
903 lock->timeout = -1;
905 if (start_active_slot(slot)) {
906 run_active_slot(slot);
907 if (results.curl_result == CURLE_OK) {
908 XML_Parser parser = XML_ParserCreate(NULL);
909 enum XML_Status result;
910 ctx.name = xcalloc(10, 1);
911 ctx.len = 0;
912 ctx.cdata = NULL;
913 ctx.userFunc = handle_new_lock_ctx;
914 ctx.userData = lock;
915 XML_SetUserData(parser, &ctx);
916 XML_SetElementHandler(parser, xml_start_tag,
917 xml_end_tag);
918 XML_SetCharacterDataHandler(parser, xml_cdata);
919 result = XML_Parse(parser, in_buffer.buf,
920 in_buffer.len, 1);
921 free(ctx.name);
922 if (result != XML_STATUS_OK) {
923 fprintf(stderr, "XML error: %s\n",
924 XML_ErrorString(
925 XML_GetErrorCode(parser)));
926 lock->timeout = -1;
928 XML_ParserFree(parser);
930 } else {
931 fprintf(stderr, "Unable to start LOCK request\n");
934 curl_slist_free_all(dav_headers);
935 strbuf_release(&out_buffer.buf);
936 strbuf_release(&in_buffer);
938 if (lock->token == NULL || lock->timeout <= 0) {
939 free(lock->token);
940 free(lock->owner);
941 free(url);
942 free(lock);
943 lock = NULL;
944 } else {
945 lock->url = url;
946 lock->start_time = time(NULL);
947 lock->next = repo->locks;
948 repo->locks = lock;
951 return lock;
954 static int unlock_remote(struct remote_lock *lock)
956 struct active_request_slot *slot;
957 struct slot_results results;
958 struct remote_lock *prev = repo->locks;
959 struct curl_slist *dav_headers;
960 int rc = 0;
962 dav_headers = get_dav_token_headers(lock, DAV_HEADER_LOCK);
964 slot = get_active_slot();
965 slot->results = &results;
966 curl_setup_http_get(slot->curl, lock->url, DAV_UNLOCK);
967 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
969 if (start_active_slot(slot)) {
970 run_active_slot(slot);
971 if (results.curl_result == CURLE_OK)
972 rc = 1;
973 else
974 fprintf(stderr, "UNLOCK HTTP error %ld\n",
975 results.http_code);
976 } else {
977 fprintf(stderr, "Unable to start UNLOCK request\n");
980 curl_slist_free_all(dav_headers);
982 if (repo->locks == lock) {
983 repo->locks = lock->next;
984 } else {
985 while (prev && prev->next != lock)
986 prev = prev->next;
987 if (prev)
988 prev->next = prev->next->next;
991 free(lock->owner);
992 free(lock->url);
993 free(lock->token);
994 free(lock);
996 return rc;
999 static void remove_locks(void)
1001 struct remote_lock *lock = repo->locks;
1003 fprintf(stderr, "Removing remote locks...\n");
1004 while (lock) {
1005 struct remote_lock *next = lock->next;
1006 unlock_remote(lock);
1007 lock = next;
1011 static void remove_locks_on_signal(int signo)
1013 remove_locks();
1014 sigchain_pop(signo);
1015 raise(signo);
1018 static void remote_ls(const char *path, int flags,
1019 void (*userFunc)(struct remote_ls_ctx *ls),
1020 void *userData);
1022 static void process_ls_object(struct remote_ls_ctx *ls)
1024 unsigned int *parent = (unsigned int *)ls->userData;
1025 char *path = ls->dentry_name;
1026 char *obj_hex;
1028 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1029 remote_dir_exists[*parent] = 1;
1030 return;
1033 if (strlen(path) != 49)
1034 return;
1035 path += 8;
1036 obj_hex = xmalloc(strlen(path));
1037 /* NB: path is not null-terminated, can not use strlcpy here */
1038 memcpy(obj_hex, path, 2);
1039 strcpy(obj_hex + 2, path + 3);
1040 one_remote_object(obj_hex);
1041 free(obj_hex);
1044 static void process_ls_ref(struct remote_ls_ctx *ls)
1046 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1047 fprintf(stderr, " %s\n", ls->dentry_name);
1048 return;
1051 if (!(ls->dentry_flags & IS_DIR))
1052 one_remote_ref(ls->dentry_name);
1055 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1057 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1059 if (tag_closed) {
1060 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1061 if (ls->dentry_flags & IS_DIR) {
1063 /* ensure collection names end with slash */
1064 str_end_url_with_slash(ls->dentry_name, &ls->dentry_name);
1066 if (ls->flags & PROCESS_DIRS) {
1067 ls->userFunc(ls);
1069 if (strcmp(ls->dentry_name, ls->path) &&
1070 ls->flags & RECURSIVE) {
1071 remote_ls(ls->dentry_name,
1072 ls->flags,
1073 ls->userFunc,
1074 ls->userData);
1076 } else if (ls->flags & PROCESS_FILES) {
1077 ls->userFunc(ls);
1079 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1080 char *path = ctx->cdata;
1081 if (*ctx->cdata == 'h') {
1082 path = strstr(path, "//");
1083 if (path) {
1084 path = strchr(path+2, '/');
1087 if (path) {
1088 const char *url = repo->url;
1089 if (repo->path)
1090 url = repo->path;
1091 if (strncmp(path, url, repo->path_len))
1092 error("Parsed path '%s' does not match url: '%s'",
1093 path, url);
1094 else {
1095 path += repo->path_len;
1096 ls->dentry_name = xstrdup(path);
1099 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1100 ls->dentry_flags |= IS_DIR;
1102 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1103 free(ls->dentry_name);
1104 ls->dentry_name = NULL;
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 = xmalloc(strlen(repo->url) + strlen(path) + 1);
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 = NULL;
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 sprintf(url, "%s%s", repo->url, path);
1137 strbuf_addf(&out_buffer.buf, PROPFIND_ALL_REQUEST);
1139 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1140 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1142 slot = get_active_slot();
1143 slot->results = &results;
1144 curl_setup_http(slot->curl, url, DAV_PROPFIND,
1145 &out_buffer, fwrite_buffer);
1146 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1147 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1149 if (start_active_slot(slot)) {
1150 run_active_slot(slot);
1151 if (results.curl_result == CURLE_OK) {
1152 XML_Parser parser = XML_ParserCreate(NULL);
1153 enum XML_Status result;
1154 ctx.name = xcalloc(10, 1);
1155 ctx.len = 0;
1156 ctx.cdata = NULL;
1157 ctx.userFunc = handle_remote_ls_ctx;
1158 ctx.userData = &ls;
1159 XML_SetUserData(parser, &ctx);
1160 XML_SetElementHandler(parser, xml_start_tag,
1161 xml_end_tag);
1162 XML_SetCharacterDataHandler(parser, xml_cdata);
1163 result = XML_Parse(parser, in_buffer.buf,
1164 in_buffer.len, 1);
1165 free(ctx.name);
1167 if (result != XML_STATUS_OK) {
1168 fprintf(stderr, "XML error: %s\n",
1169 XML_ErrorString(
1170 XML_GetErrorCode(parser)));
1172 XML_ParserFree(parser);
1174 } else {
1175 fprintf(stderr, "Unable to start PROPFIND request\n");
1178 free(ls.path);
1179 free(url);
1180 strbuf_release(&out_buffer.buf);
1181 strbuf_release(&in_buffer);
1182 curl_slist_free_all(dav_headers);
1185 static void get_remote_object_list(unsigned char parent)
1187 char path[] = "objects/XX/";
1188 static const char hex[] = "0123456789abcdef";
1189 unsigned int val = parent;
1191 path[8] = hex[val >> 4];
1192 path[9] = hex[val & 0xf];
1193 remote_dir_exists[val] = 0;
1194 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1195 process_ls_object, &val);
1198 static int locking_available(void)
1200 struct active_request_slot *slot;
1201 struct slot_results results;
1202 struct strbuf in_buffer = STRBUF_INIT;
1203 struct buffer out_buffer = { STRBUF_INIT, 0 };
1204 struct curl_slist *dav_headers = NULL;
1205 struct xml_ctx ctx;
1206 int lock_flags = 0;
1207 char *escaped;
1209 escaped = xml_entities(repo->url);
1210 strbuf_addf(&out_buffer.buf, PROPFIND_SUPPORTEDLOCK_REQUEST, escaped);
1211 free(escaped);
1213 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1214 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1216 slot = get_active_slot();
1217 slot->results = &results;
1218 curl_setup_http(slot->curl, repo->url, DAV_PROPFIND,
1219 &out_buffer, fwrite_buffer);
1220 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1221 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1223 if (start_active_slot(slot)) {
1224 run_active_slot(slot);
1225 if (results.curl_result == CURLE_OK) {
1226 XML_Parser parser = XML_ParserCreate(NULL);
1227 enum XML_Status result;
1228 ctx.name = xcalloc(10, 1);
1229 ctx.len = 0;
1230 ctx.cdata = NULL;
1231 ctx.userFunc = handle_lockprop_ctx;
1232 ctx.userData = &lock_flags;
1233 XML_SetUserData(parser, &ctx);
1234 XML_SetElementHandler(parser, xml_start_tag,
1235 xml_end_tag);
1236 result = XML_Parse(parser, in_buffer.buf,
1237 in_buffer.len, 1);
1238 free(ctx.name);
1240 if (result != XML_STATUS_OK) {
1241 fprintf(stderr, "XML error: %s\n",
1242 XML_ErrorString(
1243 XML_GetErrorCode(parser)));
1244 lock_flags = 0;
1246 XML_ParserFree(parser);
1247 if (!lock_flags)
1248 error("no DAV locking support on %s",
1249 repo->url);
1251 } else {
1252 error("Cannot access URL %s, return code %d",
1253 repo->url, results.curl_result);
1254 lock_flags = 0;
1256 } else {
1257 error("Unable to start PROPFIND request on %s", repo->url);
1260 strbuf_release(&out_buffer.buf);
1261 strbuf_release(&in_buffer);
1262 curl_slist_free_all(dav_headers);
1264 return lock_flags;
1267 static struct object_list **add_one_object(struct object *obj, struct object_list **p)
1269 struct object_list *entry = xmalloc(sizeof(struct object_list));
1270 entry->item = obj;
1271 entry->next = *p;
1272 *p = entry;
1273 return &entry->next;
1276 static struct object_list **process_blob(struct blob *blob,
1277 struct object_list **p,
1278 struct name_path *path,
1279 const char *name)
1281 struct object *obj = &blob->object;
1283 obj->flags |= LOCAL;
1285 if (obj->flags & (UNINTERESTING | SEEN))
1286 return p;
1288 obj->flags |= SEEN;
1289 return add_one_object(obj, p);
1292 static struct object_list **process_tree(struct tree *tree,
1293 struct object_list **p,
1294 struct name_path *path,
1295 const char *name)
1297 struct object *obj = &tree->object;
1298 struct tree_desc desc;
1299 struct name_entry entry;
1300 struct name_path me;
1302 obj->flags |= LOCAL;
1304 if (obj->flags & (UNINTERESTING | SEEN))
1305 return p;
1306 if (parse_tree(tree) < 0)
1307 die("bad tree object %s", sha1_to_hex(obj->sha1));
1309 obj->flags |= SEEN;
1310 name = xstrdup(name);
1311 p = add_one_object(obj, p);
1312 me.up = path;
1313 me.elem = name;
1314 me.elem_len = strlen(name);
1316 init_tree_desc(&desc, tree->buffer, tree->size);
1318 while (tree_entry(&desc, &entry))
1319 switch (object_type(entry.mode)) {
1320 case OBJ_TREE:
1321 p = process_tree(lookup_tree(entry.sha1), p, &me, name);
1322 break;
1323 case OBJ_BLOB:
1324 p = process_blob(lookup_blob(entry.sha1), p, &me, name);
1325 break;
1326 default:
1327 /* Subproject commit - not in this repository */
1328 break;
1331 free_tree_buffer(tree);
1332 return p;
1335 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1337 int i;
1338 struct commit *commit;
1339 struct object_list **p = &objects;
1340 int count = 0;
1342 while ((commit = get_revision(revs)) != NULL) {
1343 p = process_tree(commit->tree, p, NULL, "");
1344 commit->object.flags |= LOCAL;
1345 if (!(commit->object.flags & UNINTERESTING))
1346 count += add_send_request(&commit->object, lock);
1349 for (i = 0; i < revs->pending.nr; i++) {
1350 struct object_array_entry *entry = revs->pending.objects + i;
1351 struct object *obj = entry->item;
1352 const char *name = entry->name;
1354 if (obj->flags & (UNINTERESTING | SEEN))
1355 continue;
1356 if (obj->type == OBJ_TAG) {
1357 obj->flags |= SEEN;
1358 p = add_one_object(obj, p);
1359 continue;
1361 if (obj->type == OBJ_TREE) {
1362 p = process_tree((struct tree *)obj, p, NULL, name);
1363 continue;
1365 if (obj->type == OBJ_BLOB) {
1366 p = process_blob((struct blob *)obj, p, NULL, name);
1367 continue;
1369 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1372 while (objects) {
1373 if (!(objects->item->flags & UNINTERESTING))
1374 count += add_send_request(objects->item, lock);
1375 objects = objects->next;
1378 return count;
1381 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1383 struct active_request_slot *slot;
1384 struct slot_results results;
1385 struct buffer out_buffer = { STRBUF_INIT, 0 };
1386 struct curl_slist *dav_headers;
1388 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1390 strbuf_addf(&out_buffer.buf, "%s\n", sha1_to_hex(sha1));
1392 slot = get_active_slot();
1393 slot->results = &results;
1394 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1395 &out_buffer, fwrite_null);
1396 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1398 if (start_active_slot(slot)) {
1399 run_active_slot(slot);
1400 strbuf_release(&out_buffer.buf);
1401 if (results.curl_result != CURLE_OK) {
1402 fprintf(stderr,
1403 "PUT error: curl result=%d, HTTP code=%ld\n",
1404 results.curl_result, results.http_code);
1405 /* We should attempt recovery? */
1406 return 0;
1408 } else {
1409 strbuf_release(&out_buffer.buf);
1410 fprintf(stderr, "Unable to start PUT request\n");
1411 return 0;
1414 return 1;
1417 static struct ref *remote_refs;
1419 static void one_remote_ref(const char *refname)
1421 struct ref *ref;
1422 struct object *obj;
1424 ref = alloc_ref(refname);
1426 if (http_fetch_ref(repo->url, ref) != 0) {
1427 fprintf(stderr,
1428 "Unable to fetch ref %s from %s\n",
1429 refname, repo->url);
1430 free(ref);
1431 return;
1435 * Fetch a copy of the object if it doesn't exist locally - it
1436 * may be required for updating server info later.
1438 if (repo->can_update_info_refs && !has_sha1_file(ref->old_sha1)) {
1439 obj = lookup_unknown_object(ref->old_sha1);
1440 if (obj) {
1441 fprintf(stderr, " fetch %s for %s\n",
1442 sha1_to_hex(ref->old_sha1), refname);
1443 add_fetch_request(obj);
1447 ref->next = remote_refs;
1448 remote_refs = ref;
1451 static void get_dav_remote_heads(void)
1453 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1456 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1458 struct strbuf *buf = (struct strbuf *)ls->userData;
1459 struct object *o;
1460 int len;
1461 char *ref_info;
1462 struct ref *ref;
1464 ref = alloc_ref(ls->dentry_name);
1466 if (http_fetch_ref(repo->url, ref) != 0) {
1467 fprintf(stderr,
1468 "Unable to fetch ref %s from %s\n",
1469 ls->dentry_name, repo->url);
1470 aborted = 1;
1471 free(ref);
1472 return;
1475 o = parse_object(ref->old_sha1);
1476 if (!o) {
1477 fprintf(stderr,
1478 "Unable to parse object %s for remote ref %s\n",
1479 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1480 aborted = 1;
1481 free(ref);
1482 return;
1485 len = strlen(ls->dentry_name) + 42;
1486 ref_info = xcalloc(len + 1, 1);
1487 sprintf(ref_info, "%s %s\n",
1488 sha1_to_hex(ref->old_sha1), ls->dentry_name);
1489 fwrite_buffer(ref_info, 1, len, buf);
1490 free(ref_info);
1492 if (o->type == OBJ_TAG) {
1493 o = deref_tag(o, ls->dentry_name, 0);
1494 if (o) {
1495 len = strlen(ls->dentry_name) + 45;
1496 ref_info = xcalloc(len + 1, 1);
1497 sprintf(ref_info, "%s %s^{}\n",
1498 sha1_to_hex(o->sha1), ls->dentry_name);
1499 fwrite_buffer(ref_info, 1, len, buf);
1500 free(ref_info);
1503 free(ref);
1506 static void update_remote_info_refs(struct remote_lock *lock)
1508 struct buffer buffer = { STRBUF_INIT, 0 };
1509 struct active_request_slot *slot;
1510 struct slot_results results;
1511 struct curl_slist *dav_headers;
1513 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
1514 add_remote_info_ref, &buffer.buf);
1515 if (!aborted) {
1516 dav_headers = get_dav_token_headers(lock, DAV_HEADER_IF);
1518 slot = get_active_slot();
1519 slot->results = &results;
1520 curl_setup_http(slot->curl, lock->url, DAV_PUT,
1521 &buffer, fwrite_null);
1522 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1524 if (start_active_slot(slot)) {
1525 run_active_slot(slot);
1526 if (results.curl_result != CURLE_OK) {
1527 fprintf(stderr,
1528 "PUT error: curl result=%d, HTTP code=%ld\n",
1529 results.curl_result, results.http_code);
1533 strbuf_release(&buffer.buf);
1536 static int remote_exists(const char *path)
1538 char *url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1539 int ret;
1541 sprintf(url, "%s%s", repo->url, path);
1543 switch (http_get_strbuf(url, NULL, NULL)) {
1544 case HTTP_OK:
1545 ret = 1;
1546 break;
1547 case HTTP_MISSING_TARGET:
1548 ret = 0;
1549 break;
1550 case HTTP_ERROR:
1551 error("unable to access '%s': %s", url, curl_errorstr);
1552 default:
1553 ret = -1;
1555 free(url);
1556 return ret;
1559 static void fetch_symref(const char *path, char **symref, unsigned char *sha1)
1561 char *url;
1562 struct strbuf buffer = STRBUF_INIT;
1564 url = xmalloc(strlen(repo->url) + strlen(path) + 1);
1565 sprintf(url, "%s%s", repo->url, path);
1567 if (http_get_strbuf(url, &buffer, NULL) != HTTP_OK)
1568 die("Couldn't get %s for remote symref\n%s", url,
1569 curl_errorstr);
1570 free(url);
1572 free(*symref);
1573 *symref = NULL;
1574 hashclr(sha1);
1576 if (buffer.len == 0)
1577 return;
1579 /* If it's a symref, set the refname; otherwise try for a sha1 */
1580 if (starts_with((char *)buffer.buf, "ref: ")) {
1581 *symref = xmemdupz((char *)buffer.buf + 5, buffer.len - 6);
1582 } else {
1583 get_sha1_hex(buffer.buf, sha1);
1586 strbuf_release(&buffer);
1589 static int verify_merge_base(unsigned char *head_sha1, struct ref *remote)
1591 struct commit *head = lookup_commit_or_die(head_sha1, "HEAD");
1592 struct commit *branch = lookup_commit_or_die(remote->old_sha1, remote->name);
1594 return in_merge_bases(branch, head);
1597 static int delete_remote_branch(const char *pattern, int force)
1599 struct ref *refs = remote_refs;
1600 struct ref *remote_ref = NULL;
1601 unsigned char head_sha1[20];
1602 char *symref = NULL;
1603 int match;
1604 int patlen = strlen(pattern);
1605 int i;
1606 struct active_request_slot *slot;
1607 struct slot_results results;
1608 char *url;
1610 /* Find the remote branch(es) matching the specified branch name */
1611 for (match = 0; refs; refs = refs->next) {
1612 char *name = refs->name;
1613 int namelen = strlen(name);
1614 if (namelen < patlen ||
1615 memcmp(name + namelen - patlen, pattern, patlen))
1616 continue;
1617 if (namelen != patlen && name[namelen - patlen - 1] != '/')
1618 continue;
1619 match++;
1620 remote_ref = refs;
1622 if (match == 0)
1623 return error("No remote branch matches %s", pattern);
1624 if (match != 1)
1625 return error("More than one remote branch matches %s",
1626 pattern);
1629 * Remote HEAD must be a symref (not exactly foolproof; a remote
1630 * symlink to a symref will look like a symref)
1632 fetch_symref("HEAD", &symref, head_sha1);
1633 if (!symref)
1634 return error("Remote HEAD is not a symref");
1636 /* Remote branch must not be the remote HEAD */
1637 for (i = 0; symref && i < MAXDEPTH; i++) {
1638 if (!strcmp(remote_ref->name, symref))
1639 return error("Remote branch %s is the current HEAD",
1640 remote_ref->name);
1641 fetch_symref(symref, &symref, head_sha1);
1644 /* Run extra sanity checks if delete is not forced */
1645 if (!force) {
1646 /* Remote HEAD must resolve to a known object */
1647 if (symref)
1648 return error("Remote HEAD symrefs too deep");
1649 if (is_null_sha1(head_sha1))
1650 return error("Unable to resolve remote HEAD");
1651 if (!has_sha1_file(head_sha1))
1652 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
1654 /* Remote branch must resolve to a known object */
1655 if (is_null_sha1(remote_ref->old_sha1))
1656 return error("Unable to resolve remote branch %s",
1657 remote_ref->name);
1658 if (!has_sha1_file(remote_ref->old_sha1))
1659 return error("Remote branch %s resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", remote_ref->name, sha1_to_hex(remote_ref->old_sha1));
1661 /* Remote branch must be an ancestor of remote HEAD */
1662 if (!verify_merge_base(head_sha1, remote_ref)) {
1663 return error("The branch '%s' is not an ancestor "
1664 "of your current HEAD.\n"
1665 "If you are sure you want to delete it,"
1666 " run:\n\t'git http-push -D %s %s'",
1667 remote_ref->name, repo->url, pattern);
1671 /* Send delete request */
1672 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
1673 if (dry_run)
1674 return 0;
1675 url = xmalloc(strlen(repo->url) + strlen(remote_ref->name) + 1);
1676 sprintf(url, "%s%s", repo->url, remote_ref->name);
1677 slot = get_active_slot();
1678 slot->results = &results;
1679 curl_setup_http_get(slot->curl, url, DAV_DELETE);
1680 if (start_active_slot(slot)) {
1681 run_active_slot(slot);
1682 free(url);
1683 if (results.curl_result != CURLE_OK)
1684 return error("DELETE request failed (%d/%ld)",
1685 results.curl_result, results.http_code);
1686 } else {
1687 free(url);
1688 return error("Unable to start DELETE request");
1691 return 0;
1694 static void run_request_queue(void)
1696 #ifdef USE_CURL_MULTI
1697 is_running_queue = 1;
1698 fill_active_slots();
1699 add_fill_function(NULL, fill_active_slot);
1700 #endif
1701 do {
1702 finish_all_active_slots();
1703 #ifdef USE_CURL_MULTI
1704 fill_active_slots();
1705 #endif
1706 } while (request_queue_head && !aborted);
1708 #ifdef USE_CURL_MULTI
1709 is_running_queue = 0;
1710 #endif
1713 int main(int argc, char **argv)
1715 struct transfer_request *request;
1716 struct transfer_request *next_request;
1717 int nr_refspec = 0;
1718 char **refspec = NULL;
1719 struct remote_lock *ref_lock = NULL;
1720 struct remote_lock *info_ref_lock = NULL;
1721 struct rev_info revs;
1722 int delete_branch = 0;
1723 int force_delete = 0;
1724 int objects_to_send;
1725 int rc = 0;
1726 int i;
1727 int new_refs;
1728 struct ref *ref, *local_refs;
1730 git_setup_gettext();
1732 git_extract_argv0_path(argv[0]);
1734 repo = xcalloc(1, sizeof(*repo));
1736 argv++;
1737 for (i = 1; i < argc; i++, argv++) {
1738 char *arg = *argv;
1740 if (*arg == '-') {
1741 if (!strcmp(arg, "--all")) {
1742 push_all = MATCH_REFS_ALL;
1743 continue;
1745 if (!strcmp(arg, "--force")) {
1746 force_all = 1;
1747 continue;
1749 if (!strcmp(arg, "--dry-run")) {
1750 dry_run = 1;
1751 continue;
1753 if (!strcmp(arg, "--helper-status")) {
1754 helper_status = 1;
1755 continue;
1757 if (!strcmp(arg, "--verbose")) {
1758 push_verbosely = 1;
1759 http_is_verbose = 1;
1760 continue;
1762 if (!strcmp(arg, "-d")) {
1763 delete_branch = 1;
1764 continue;
1766 if (!strcmp(arg, "-D")) {
1767 delete_branch = 1;
1768 force_delete = 1;
1769 continue;
1771 if (!strcmp(arg, "-h"))
1772 usage(http_push_usage);
1774 if (!repo->url) {
1775 char *path = strstr(arg, "//");
1776 str_end_url_with_slash(arg, &repo->url);
1777 repo->path_len = strlen(repo->url);
1778 if (path) {
1779 repo->path = strchr(path+2, '/');
1780 if (repo->path)
1781 repo->path_len = strlen(repo->path);
1783 continue;
1785 refspec = argv;
1786 nr_refspec = argc - i;
1787 break;
1790 #ifndef USE_CURL_MULTI
1791 die("git-push is not available for http/https repository when not compiled with USE_CURL_MULTI");
1792 #endif
1794 if (!repo->url)
1795 usage(http_push_usage);
1797 if (delete_branch && nr_refspec != 1)
1798 die("You must specify only one branch name when deleting a remote branch");
1800 setup_git_directory();
1802 memset(remote_dir_exists, -1, 256);
1804 http_init(NULL, repo->url, 1);
1806 #ifdef USE_CURL_MULTI
1807 is_running_queue = 0;
1808 #endif
1810 /* Verify DAV compliance/lock support */
1811 if (!locking_available()) {
1812 rc = 1;
1813 goto cleanup;
1816 sigchain_push_common(remove_locks_on_signal);
1818 /* Check whether the remote has server info files */
1819 repo->can_update_info_refs = 0;
1820 repo->has_info_refs = remote_exists("info/refs");
1821 repo->has_info_packs = remote_exists("objects/info/packs");
1822 if (repo->has_info_refs) {
1823 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
1824 if (info_ref_lock)
1825 repo->can_update_info_refs = 1;
1826 else {
1827 error("cannot lock existing info/refs");
1828 rc = 1;
1829 goto cleanup;
1832 if (repo->has_info_packs)
1833 fetch_indices();
1835 /* Get a list of all local and remote heads to validate refspecs */
1836 local_refs = get_local_heads();
1837 fprintf(stderr, "Fetching remote heads...\n");
1838 get_dav_remote_heads();
1839 run_request_queue();
1841 /* Remove a remote branch if -d or -D was specified */
1842 if (delete_branch) {
1843 if (delete_remote_branch(refspec[0], force_delete) == -1) {
1844 fprintf(stderr, "Unable to delete remote branch %s\n",
1845 refspec[0]);
1846 if (helper_status)
1847 printf("error %s cannot remove\n", refspec[0]);
1849 goto cleanup;
1852 /* match them up */
1853 if (match_push_refs(local_refs, &remote_refs,
1854 nr_refspec, (const char **) refspec, push_all)) {
1855 rc = -1;
1856 goto cleanup;
1858 if (!remote_refs) {
1859 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
1860 if (helper_status)
1861 printf("error null no match\n");
1862 rc = 0;
1863 goto cleanup;
1866 new_refs = 0;
1867 for (ref = remote_refs; ref; ref = ref->next) {
1868 char old_hex[60], *new_hex;
1869 const char *commit_argv[5];
1870 int commit_argc;
1871 char *new_sha1_hex, *old_sha1_hex;
1873 if (!ref->peer_ref)
1874 continue;
1876 if (is_null_sha1(ref->peer_ref->new_sha1)) {
1877 if (delete_remote_branch(ref->name, 1) == -1) {
1878 error("Could not remove %s", ref->name);
1879 if (helper_status)
1880 printf("error %s cannot remove\n", ref->name);
1881 rc = -4;
1883 else if (helper_status)
1884 printf("ok %s\n", ref->name);
1885 new_refs++;
1886 continue;
1889 if (!hashcmp(ref->old_sha1, ref->peer_ref->new_sha1)) {
1890 if (push_verbosely)
1891 fprintf(stderr, "'%s': up-to-date\n", ref->name);
1892 if (helper_status)
1893 printf("ok %s up to date\n", ref->name);
1894 continue;
1897 if (!force_all &&
1898 !is_null_sha1(ref->old_sha1) &&
1899 !ref->force) {
1900 if (!has_sha1_file(ref->old_sha1) ||
1901 !ref_newer(ref->peer_ref->new_sha1,
1902 ref->old_sha1)) {
1904 * We do not have the remote ref, or
1905 * we know that the remote ref is not
1906 * an ancestor of what we are trying to
1907 * push. Either way this can be losing
1908 * commits at the remote end and likely
1909 * we were not up to date to begin with.
1911 error("remote '%s' is not an ancestor of\n"
1912 "local '%s'.\n"
1913 "Maybe you are not up-to-date and "
1914 "need to pull first?",
1915 ref->name,
1916 ref->peer_ref->name);
1917 if (helper_status)
1918 printf("error %s non-fast forward\n", ref->name);
1919 rc = -2;
1920 continue;
1923 hashcpy(ref->new_sha1, ref->peer_ref->new_sha1);
1924 new_refs++;
1925 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
1926 new_hex = sha1_to_hex(ref->new_sha1);
1928 fprintf(stderr, "updating '%s'", ref->name);
1929 if (strcmp(ref->name, ref->peer_ref->name))
1930 fprintf(stderr, " using '%s'", ref->peer_ref->name);
1931 fprintf(stderr, "\n from %s\n to %s\n", old_hex, new_hex);
1932 if (dry_run) {
1933 if (helper_status)
1934 printf("ok %s\n", ref->name);
1935 continue;
1938 /* Lock remote branch ref */
1939 ref_lock = lock_remote(ref->name, LOCK_TIME);
1940 if (ref_lock == NULL) {
1941 fprintf(stderr, "Unable to lock remote branch %s\n",
1942 ref->name);
1943 if (helper_status)
1944 printf("error %s lock error\n", ref->name);
1945 rc = 1;
1946 continue;
1949 /* Set up revision info for this refspec */
1950 commit_argc = 3;
1951 new_sha1_hex = xstrdup(sha1_to_hex(ref->new_sha1));
1952 old_sha1_hex = NULL;
1953 commit_argv[1] = "--objects";
1954 commit_argv[2] = new_sha1_hex;
1955 if (!push_all && !is_null_sha1(ref->old_sha1)) {
1956 old_sha1_hex = xmalloc(42);
1957 sprintf(old_sha1_hex, "^%s",
1958 sha1_to_hex(ref->old_sha1));
1959 commit_argv[3] = old_sha1_hex;
1960 commit_argc++;
1962 commit_argv[commit_argc] = NULL;
1963 init_revisions(&revs, setup_git_directory());
1964 setup_revisions(commit_argc, commit_argv, &revs, NULL);
1965 revs.edge_hint = 0; /* just in case */
1966 free(new_sha1_hex);
1967 if (old_sha1_hex) {
1968 free(old_sha1_hex);
1969 commit_argv[1] = NULL;
1972 /* Generate a list of objects that need to be pushed */
1973 pushing = 0;
1974 if (prepare_revision_walk(&revs))
1975 die("revision walk setup failed");
1976 mark_edges_uninteresting(&revs, NULL);
1977 objects_to_send = get_delta(&revs, ref_lock);
1978 finish_all_active_slots();
1980 /* Push missing objects to remote, this would be a
1981 convenient time to pack them first if appropriate. */
1982 pushing = 1;
1983 if (objects_to_send)
1984 fprintf(stderr, " sending %d objects\n",
1985 objects_to_send);
1987 run_request_queue();
1989 /* Update the remote branch if all went well */
1990 if (aborted || !update_remote(ref->new_sha1, ref_lock))
1991 rc = 1;
1993 if (!rc)
1994 fprintf(stderr, " done\n");
1995 if (helper_status)
1996 printf("%s %s\n", !rc ? "ok" : "error", ref->name);
1997 unlock_remote(ref_lock);
1998 check_locks();
2001 /* Update remote server info if appropriate */
2002 if (repo->has_info_refs && new_refs) {
2003 if (info_ref_lock && repo->can_update_info_refs) {
2004 fprintf(stderr, "Updating remote server info\n");
2005 if (!dry_run)
2006 update_remote_info_refs(info_ref_lock);
2007 } else {
2008 fprintf(stderr, "Unable to update server info\n");
2012 cleanup:
2013 if (info_ref_lock)
2014 unlock_remote(info_ref_lock);
2015 free(repo);
2017 http_cleanup();
2019 request = request_queue_head;
2020 while (request != NULL) {
2021 next_request = request->next;
2022 release_request(request);
2023 request = next_request;
2026 return rc;