Merge branch 'jc/cvsimport'
[git/git.git] / http-push.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "pack.h"
4 #include "fetch.h"
5 #include "tag.h"
6 #include "blob.h"
7 #include "http.h"
8 #include "refs.h"
9 #include "revision.h"
10 #include "exec_cmd.h"
11
12 #include <expat.h>
13
14 static const char http_push_usage[] =
15 "git-http-push [--all] [--force] [--verbose] <remote> [<head>...]\n";
16
17 #ifndef XML_STATUS_OK
18 enum XML_Status {
19 XML_STATUS_OK = 1,
20 XML_STATUS_ERROR = 0
21 };
22 #define XML_STATUS_OK 1
23 #define XML_STATUS_ERROR 0
24 #endif
25
26 #define PREV_BUF_SIZE 4096
27 #define RANGE_HEADER_SIZE 30
28
29 /* DAV methods */
30 #define DAV_LOCK "LOCK"
31 #define DAV_MKCOL "MKCOL"
32 #define DAV_MOVE "MOVE"
33 #define DAV_PROPFIND "PROPFIND"
34 #define DAV_PUT "PUT"
35 #define DAV_UNLOCK "UNLOCK"
36 #define DAV_DELETE "DELETE"
37
38 /* DAV lock flags */
39 #define DAV_PROP_LOCKWR (1u << 0)
40 #define DAV_PROP_LOCKEX (1u << 1)
41 #define DAV_LOCK_OK (1u << 2)
42
43 /* DAV XML properties */
44 #define DAV_CTX_LOCKENTRY ".multistatus.response.propstat.prop.supportedlock.lockentry"
45 #define DAV_CTX_LOCKTYPE_WRITE ".multistatus.response.propstat.prop.supportedlock.lockentry.locktype.write"
46 #define DAV_CTX_LOCKTYPE_EXCLUSIVE ".multistatus.response.propstat.prop.supportedlock.lockentry.lockscope.exclusive"
47 #define DAV_ACTIVELOCK_OWNER ".prop.lockdiscovery.activelock.owner.href"
48 #define DAV_ACTIVELOCK_TIMEOUT ".prop.lockdiscovery.activelock.timeout"
49 #define DAV_ACTIVELOCK_TOKEN ".prop.lockdiscovery.activelock.locktoken.href"
50 #define DAV_PROPFIND_RESP ".multistatus.response"
51 #define DAV_PROPFIND_NAME ".multistatus.response.href"
52 #define DAV_PROPFIND_COLLECTION ".multistatus.response.propstat.prop.resourcetype.collection"
53
54 /* DAV request body templates */
55 #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>"
56 #define PROPFIND_ALL_REQUEST "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n<D:allprop/>\n</D:propfind>"
57 #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>"
58
59 #define LOCK_TIME 600
60 #define LOCK_REFRESH 30
61
62 /* bits #0-4 in revision.h */
63
64 #define LOCAL (1u << 5)
65 #define REMOTE (1u << 6)
66 #define FETCHING (1u << 7)
67 #define PUSHING (1u << 8)
68
69 /* We allow "recursive" symbolic refs. Only within reason, though */
70 #define MAXDEPTH 5
71
72 static int pushing = 0;
73 static int aborted = 0;
74 static signed char remote_dir_exists[256];
75
76 static struct curl_slist *no_pragma_header;
77 static struct curl_slist *default_headers;
78
79 static int push_verbosely = 0;
80 static int push_all = 0;
81 static int force_all = 0;
82
83 static struct object_list *objects = NULL;
84
85 struct repo
86 {
87 char *url;
88 int path_len;
89 int has_info_refs;
90 int can_update_info_refs;
91 int has_info_packs;
92 struct packed_git *packs;
93 struct remote_lock *locks;
94 };
95
96 static struct repo *remote = NULL;
97
98 enum transfer_state {
99 NEED_FETCH,
100 RUN_FETCH_LOOSE,
101 RUN_FETCH_PACKED,
102 NEED_PUSH,
103 RUN_MKCOL,
104 RUN_PUT,
105 RUN_MOVE,
106 ABORTED,
107 COMPLETE,
108 };
109
110 struct transfer_request
111 {
112 struct object *obj;
113 char *url;
114 char *dest;
115 struct remote_lock *lock;
116 struct curl_slist *headers;
117 struct buffer buffer;
118 char filename[PATH_MAX];
119 char tmpfile[PATH_MAX];
120 int local_fileno;
121 FILE *local_stream;
122 enum transfer_state state;
123 CURLcode curl_result;
124 char errorstr[CURL_ERROR_SIZE];
125 long http_code;
126 unsigned char real_sha1[20];
127 SHA_CTX c;
128 z_stream stream;
129 int zret;
130 int rename;
131 void *userData;
132 struct active_request_slot *slot;
133 struct transfer_request *next;
134 };
135
136 static struct transfer_request *request_queue_head = NULL;
137
138 struct xml_ctx
139 {
140 char *name;
141 int len;
142 char *cdata;
143 void (*userFunc)(struct xml_ctx *ctx, int tag_closed);
144 void *userData;
145 };
146
147 struct remote_lock
148 {
149 char *url;
150 char *owner;
151 char *token;
152 time_t start_time;
153 long timeout;
154 int refreshing;
155 struct remote_lock *next;
156 };
157
158 /* Flags that control remote_ls processing */
159 #define PROCESS_FILES (1u << 0)
160 #define PROCESS_DIRS (1u << 1)
161 #define RECURSIVE (1u << 2)
162
163 /* Flags that remote_ls passes to callback functions */
164 #define IS_DIR (1u << 0)
165
166 struct remote_ls_ctx
167 {
168 char *path;
169 void (*userFunc)(struct remote_ls_ctx *ls);
170 void *userData;
171 int flags;
172 char *dentry_name;
173 int dentry_flags;
174 struct remote_ls_ctx *parent;
175 };
176
177 static void finish_request(struct transfer_request *request);
178 static void release_request(struct transfer_request *request);
179
180 static void process_response(void *callback_data)
181 {
182 struct transfer_request *request =
183 (struct transfer_request *)callback_data;
184
185 finish_request(request);
186 }
187
188 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
189 void *data)
190 {
191 unsigned char expn[4096];
192 size_t size = eltsize * nmemb;
193 int posn = 0;
194 struct transfer_request *request = (struct transfer_request *)data;
195 do {
196 ssize_t retval = write(request->local_fileno,
197 ptr + posn, size - posn);
198 if (retval < 0)
199 return posn;
200 posn += retval;
201 } while (posn < size);
202
203 request->stream.avail_in = size;
204 request->stream.next_in = ptr;
205 do {
206 request->stream.next_out = expn;
207 request->stream.avail_out = sizeof(expn);
208 request->zret = inflate(&request->stream, Z_SYNC_FLUSH);
209 SHA1_Update(&request->c, expn,
210 sizeof(expn) - request->stream.avail_out);
211 } while (request->stream.avail_in && request->zret == Z_OK);
212 data_received++;
213 return size;
214 }
215
216 static void start_fetch_loose(struct transfer_request *request)
217 {
218 char *hex = sha1_to_hex(request->obj->sha1);
219 char *filename;
220 char prevfile[PATH_MAX];
221 char *url;
222 char *posn;
223 int prevlocal;
224 unsigned char prev_buf[PREV_BUF_SIZE];
225 ssize_t prev_read = 0;
226 long prev_posn = 0;
227 char range[RANGE_HEADER_SIZE];
228 struct curl_slist *range_header = NULL;
229 struct active_request_slot *slot;
230
231 filename = sha1_file_name(request->obj->sha1);
232 snprintf(request->filename, sizeof(request->filename), "%s", filename);
233 snprintf(request->tmpfile, sizeof(request->tmpfile),
234 "%s.temp", filename);
235
236 snprintf(prevfile, sizeof(prevfile), "%s.prev", request->filename);
237 unlink(prevfile);
238 rename(request->tmpfile, prevfile);
239 unlink(request->tmpfile);
240
241 if (request->local_fileno != -1)
242 error("fd leakage in start: %d", request->local_fileno);
243 request->local_fileno = open(request->tmpfile,
244 O_WRONLY | O_CREAT | O_EXCL, 0666);
245 /* This could have failed due to the "lazy directory creation";
246 * try to mkdir the last path component.
247 */
248 if (request->local_fileno < 0 && errno == ENOENT) {
249 char *dir = strrchr(request->tmpfile, '/');
250 if (dir) {
251 *dir = 0;
252 mkdir(request->tmpfile, 0777);
253 *dir = '/';
254 }
255 request->local_fileno = open(request->tmpfile,
256 O_WRONLY | O_CREAT | O_EXCL, 0666);
257 }
258
259 if (request->local_fileno < 0) {
260 request->state = ABORTED;
261 error("Couldn't create temporary file %s for %s: %s",
262 request->tmpfile, request->filename, strerror(errno));
263 return;
264 }
265
266 memset(&request->stream, 0, sizeof(request->stream));
267
268 inflateInit(&request->stream);
269
270 SHA1_Init(&request->c);
271
272 url = xmalloc(strlen(remote->url) + 50);
273 request->url = xmalloc(strlen(remote->url) + 50);
274 strcpy(url, remote->url);
275 posn = url + strlen(remote->url);
276 strcpy(posn, "objects/");
277 posn += 8;
278 memcpy(posn, hex, 2);
279 posn += 2;
280 *(posn++) = '/';
281 strcpy(posn, hex + 2);
282 strcpy(request->url, url);
283
284 /* If a previous temp file is present, process what was already
285 fetched. */
286 prevlocal = open(prevfile, O_RDONLY);
287 if (prevlocal != -1) {
288 do {
289 prev_read = read(prevlocal, prev_buf, PREV_BUF_SIZE);
290 if (prev_read>0) {
291 if (fwrite_sha1_file(prev_buf,
292 1,
293 prev_read,
294 request) == prev_read) {
295 prev_posn += prev_read;
296 } else {
297 prev_read = -1;
298 }
299 }
300 } while (prev_read > 0);
301 close(prevlocal);
302 }
303 unlink(prevfile);
304
305 /* Reset inflate/SHA1 if there was an error reading the previous temp
306 file; also rewind to the beginning of the local file. */
307 if (prev_read == -1) {
308 memset(&request->stream, 0, sizeof(request->stream));
309 inflateInit(&request->stream);
310 SHA1_Init(&request->c);
311 if (prev_posn>0) {
312 prev_posn = 0;
313 lseek(request->local_fileno, SEEK_SET, 0);
314 ftruncate(request->local_fileno, 0);
315 }
316 }
317
318 slot = get_active_slot();
319 slot->callback_func = process_response;
320 slot->callback_data = request;
321 request->slot = slot;
322
323 curl_easy_setopt(slot->curl, CURLOPT_FILE, request);
324 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
325 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
326 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
327 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
328
329 /* If we have successfully processed data from a previous fetch
330 attempt, only fetch the data we don't already have. */
331 if (prev_posn>0) {
332 if (push_verbosely)
333 fprintf(stderr,
334 "Resuming fetch of object %s at byte %ld\n",
335 hex, prev_posn);
336 sprintf(range, "Range: bytes=%ld-", prev_posn);
337 range_header = curl_slist_append(range_header, range);
338 curl_easy_setopt(slot->curl,
339 CURLOPT_HTTPHEADER, range_header);
340 }
341
342 /* Try to get the request started, abort the request on error */
343 request->state = RUN_FETCH_LOOSE;
344 if (!start_active_slot(slot)) {
345 fprintf(stderr, "Unable to start GET request\n");
346 remote->can_update_info_refs = 0;
347 release_request(request);
348 }
349 }
350
351 static void start_fetch_packed(struct transfer_request *request)
352 {
353 char *url;
354 struct packed_git *target;
355 FILE *packfile;
356 char *filename;
357 long prev_posn = 0;
358 char range[RANGE_HEADER_SIZE];
359 struct curl_slist *range_header = NULL;
360
361 struct transfer_request *check_request = request_queue_head;
362 struct active_request_slot *slot;
363
364 target = find_sha1_pack(request->obj->sha1, remote->packs);
365 if (!target) {
366 fprintf(stderr, "Unable to fetch %s, will not be able to update server info refs\n", sha1_to_hex(request->obj->sha1));
367 remote->can_update_info_refs = 0;
368 release_request(request);
369 return;
370 }
371
372 fprintf(stderr, "Fetching pack %s\n", sha1_to_hex(target->sha1));
373 fprintf(stderr, " which contains %s\n", sha1_to_hex(request->obj->sha1));
374
375 filename = sha1_pack_name(target->sha1);
376 snprintf(request->filename, sizeof(request->filename), "%s", filename);
377 snprintf(request->tmpfile, sizeof(request->tmpfile),
378 "%s.temp", filename);
379
380 url = xmalloc(strlen(remote->url) + 64);
381 sprintf(url, "%sobjects/pack/pack-%s.pack",
382 remote->url, sha1_to_hex(target->sha1));
383
384 /* Make sure there isn't another open request for this pack */
385 while (check_request) {
386 if (check_request->state == RUN_FETCH_PACKED &&
387 !strcmp(check_request->url, url)) {
388 free(url);
389 release_request(request);
390 return;
391 }
392 check_request = check_request->next;
393 }
394
395 packfile = fopen(request->tmpfile, "a");
396 if (!packfile) {
397 fprintf(stderr, "Unable to open local file %s for pack",
398 filename);
399 remote->can_update_info_refs = 0;
400 free(url);
401 return;
402 }
403
404 slot = get_active_slot();
405 slot->callback_func = process_response;
406 slot->callback_data = request;
407 request->slot = slot;
408 request->local_stream = packfile;
409 request->userData = target;
410
411 request->url = url;
412 curl_easy_setopt(slot->curl, CURLOPT_FILE, packfile);
413 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
414 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
415 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
416 slot->local = packfile;
417
418 /* If there is data present from a previous transfer attempt,
419 resume where it left off */
420 prev_posn = ftell(packfile);
421 if (prev_posn>0) {
422 if (push_verbosely)
423 fprintf(stderr,
424 "Resuming fetch of pack %s at byte %ld\n",
425 sha1_to_hex(target->sha1), prev_posn);
426 sprintf(range, "Range: bytes=%ld-", prev_posn);
427 range_header = curl_slist_append(range_header, range);
428 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
429 }
430
431 /* Try to get the request started, abort the request on error */
432 request->state = RUN_FETCH_PACKED;
433 if (!start_active_slot(slot)) {
434 fprintf(stderr, "Unable to start GET request\n");
435 remote->can_update_info_refs = 0;
436 release_request(request);
437 }
438 }
439
440 static void start_mkcol(struct transfer_request *request)
441 {
442 char *hex = sha1_to_hex(request->obj->sha1);
443 struct active_request_slot *slot;
444 char *posn;
445
446 request->url = xmalloc(strlen(remote->url) + 13);
447 strcpy(request->url, remote->url);
448 posn = request->url + strlen(remote->url);
449 strcpy(posn, "objects/");
450 posn += 8;
451 memcpy(posn, hex, 2);
452 posn += 2;
453 strcpy(posn, "/");
454
455 slot = get_active_slot();
456 slot->callback_func = process_response;
457 slot->callback_data = request;
458 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
459 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
460 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, request->errorstr);
461 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
462 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
463
464 if (start_active_slot(slot)) {
465 request->slot = slot;
466 request->state = RUN_MKCOL;
467 } else {
468 request->state = ABORTED;
469 free(request->url);
470 request->url = NULL;
471 }
472 }
473
474 static void start_put(struct transfer_request *request)
475 {
476 char *hex = sha1_to_hex(request->obj->sha1);
477 struct active_request_slot *slot;
478 char *posn;
479 char type[20];
480 char hdr[50];
481 void *unpacked;
482 unsigned long len;
483 int hdrlen;
484 ssize_t size;
485 z_stream stream;
486
487 unpacked = read_sha1_file(request->obj->sha1, type, &len);
488 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
489
490 /* Set it up */
491 memset(&stream, 0, sizeof(stream));
492 deflateInit(&stream, Z_BEST_COMPRESSION);
493 size = deflateBound(&stream, len + hdrlen);
494 request->buffer.buffer = xmalloc(size);
495
496 /* Compress it */
497 stream.next_out = request->buffer.buffer;
498 stream.avail_out = size;
499
500 /* First header.. */
501 stream.next_in = (void *)hdr;
502 stream.avail_in = hdrlen;
503 while (deflate(&stream, 0) == Z_OK)
504 /* nothing */;
505
506 /* Then the data itself.. */
507 stream.next_in = unpacked;
508 stream.avail_in = len;
509 while (deflate(&stream, Z_FINISH) == Z_OK)
510 /* nothing */;
511 deflateEnd(&stream);
512 free(unpacked);
513
514 request->buffer.size = stream.total_out;
515 request->buffer.posn = 0;
516
517 request->url = xmalloc(strlen(remote->url) +
518 strlen(request->lock->token) + 51);
519 strcpy(request->url, remote->url);
520 posn = request->url + strlen(remote->url);
521 strcpy(posn, "objects/");
522 posn += 8;
523 memcpy(posn, hex, 2);
524 posn += 2;
525 *(posn++) = '/';
526 strcpy(posn, hex + 2);
527 request->dest = xmalloc(strlen(request->url) + 14);
528 sprintf(request->dest, "Destination: %s", request->url);
529 posn += 38;
530 *(posn++) = '.';
531 strcpy(posn, request->lock->token);
532
533 slot = get_active_slot();
534 slot->callback_func = process_response;
535 slot->callback_data = request;
536 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &request->buffer);
537 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, request->buffer.size);
538 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
539 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
540 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
541 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
542 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
543 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
544 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
545
546 if (start_active_slot(slot)) {
547 request->slot = slot;
548 request->state = RUN_PUT;
549 } else {
550 request->state = ABORTED;
551 free(request->url);
552 request->url = NULL;
553 }
554 }
555
556 static void start_move(struct transfer_request *request)
557 {
558 struct active_request_slot *slot;
559 struct curl_slist *dav_headers = NULL;
560
561 slot = get_active_slot();
562 slot->callback_func = process_response;
563 slot->callback_data = request;
564 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1); /* undo PUT setup */
565 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MOVE);
566 dav_headers = curl_slist_append(dav_headers, request->dest);
567 dav_headers = curl_slist_append(dav_headers, "Overwrite: T");
568 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
569 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
570 curl_easy_setopt(slot->curl, CURLOPT_URL, request->url);
571
572 if (start_active_slot(slot)) {
573 request->slot = slot;
574 request->state = RUN_MOVE;
575 } else {
576 request->state = ABORTED;
577 free(request->url);
578 request->url = NULL;
579 }
580 }
581
582 static int refresh_lock(struct remote_lock *lock)
583 {
584 struct active_request_slot *slot;
585 struct slot_results results;
586 char *if_header;
587 char timeout_header[25];
588 struct curl_slist *dav_headers = NULL;
589 int rc = 0;
590
591 lock->refreshing = 1;
592
593 if_header = xmalloc(strlen(lock->token) + 25);
594 sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock->token);
595 sprintf(timeout_header, "Timeout: Second-%ld", lock->timeout);
596 dav_headers = curl_slist_append(dav_headers, if_header);
597 dav_headers = curl_slist_append(dav_headers, timeout_header);
598
599 slot = get_active_slot();
600 slot->results = &results;
601 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
602 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
603 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
604 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
605 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
606
607 if (start_active_slot(slot)) {
608 run_active_slot(slot);
609 if (results.curl_result != CURLE_OK) {
610 fprintf(stderr, "LOCK HTTP error %ld\n",
611 results.http_code);
612 } else {
613 lock->start_time = time(NULL);
614 rc = 1;
615 }
616 }
617
618 lock->refreshing = 0;
619 curl_slist_free_all(dav_headers);
620 free(if_header);
621
622 return rc;
623 }
624
625 static void check_locks()
626 {
627 struct remote_lock *lock = remote->locks;
628 time_t current_time = time(NULL);
629 int time_remaining;
630
631 while (lock) {
632 time_remaining = lock->start_time + lock->timeout -
633 current_time;
634 if (!lock->refreshing && time_remaining < LOCK_REFRESH) {
635 if (!refresh_lock(lock)) {
636 fprintf(stderr,
637 "Unable to refresh lock for %s\n",
638 lock->url);
639 aborted = 1;
640 return;
641 }
642 }
643 lock = lock->next;
644 }
645 }
646
647 static void release_request(struct transfer_request *request)
648 {
649 struct transfer_request *entry = request_queue_head;
650
651 if (request == request_queue_head) {
652 request_queue_head = request->next;
653 } else {
654 while (entry->next != NULL && entry->next != request)
655 entry = entry->next;
656 if (entry->next == request)
657 entry->next = entry->next->next;
658 }
659
660 if (request->local_fileno != -1)
661 close(request->local_fileno);
662 if (request->local_stream)
663 fclose(request->local_stream);
664 if (request->url != NULL)
665 free(request->url);
666 free(request);
667 }
668
669 static void finish_request(struct transfer_request *request)
670 {
671 struct stat st;
672 struct packed_git *target;
673 struct packed_git **lst;
674
675 request->curl_result = request->slot->curl_result;
676 request->http_code = request->slot->http_code;
677 request->slot = NULL;
678
679 /* Keep locks active */
680 check_locks();
681
682 if (request->headers != NULL)
683 curl_slist_free_all(request->headers);
684
685 /* URL is reused for MOVE after PUT */
686 if (request->state != RUN_PUT) {
687 free(request->url);
688 request->url = NULL;
689 }
690
691 if (request->state == RUN_MKCOL) {
692 if (request->curl_result == CURLE_OK ||
693 request->http_code == 405) {
694 remote_dir_exists[request->obj->sha1[0]] = 1;
695 start_put(request);
696 } else {
697 fprintf(stderr, "MKCOL %s failed, aborting (%d/%ld)\n",
698 sha1_to_hex(request->obj->sha1),
699 request->curl_result, request->http_code);
700 request->state = ABORTED;
701 aborted = 1;
702 }
703 } else if (request->state == RUN_PUT) {
704 if (request->curl_result == CURLE_OK) {
705 start_move(request);
706 } else {
707 fprintf(stderr, "PUT %s failed, aborting (%d/%ld)\n",
708 sha1_to_hex(request->obj->sha1),
709 request->curl_result, request->http_code);
710 request->state = ABORTED;
711 aborted = 1;
712 }
713 } else if (request->state == RUN_MOVE) {
714 if (request->curl_result == CURLE_OK) {
715 if (push_verbosely)
716 fprintf(stderr, " sent %s\n",
717 sha1_to_hex(request->obj->sha1));
718 request->obj->flags |= REMOTE;
719 release_request(request);
720 } else {
721 fprintf(stderr, "MOVE %s failed, aborting (%d/%ld)\n",
722 sha1_to_hex(request->obj->sha1),
723 request->curl_result, request->http_code);
724 request->state = ABORTED;
725 aborted = 1;
726 }
727 } else if (request->state == RUN_FETCH_LOOSE) {
728 fchmod(request->local_fileno, 0444);
729 close(request->local_fileno); request->local_fileno = -1;
730
731 if (request->curl_result != CURLE_OK &&
732 request->http_code != 416) {
733 if (stat(request->tmpfile, &st) == 0) {
734 if (st.st_size == 0)
735 unlink(request->tmpfile);
736 }
737 } else {
738 if (request->http_code == 416)
739 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
740
741 inflateEnd(&request->stream);
742 SHA1_Final(request->real_sha1, &request->c);
743 if (request->zret != Z_STREAM_END) {
744 unlink(request->tmpfile);
745 } else if (memcmp(request->obj->sha1, request->real_sha1, 20)) {
746 unlink(request->tmpfile);
747 } else {
748 request->rename =
749 move_temp_to_file(
750 request->tmpfile,
751 request->filename);
752 if (request->rename == 0) {
753 request->obj->flags |= (LOCAL | REMOTE);
754 }
755 }
756 }
757
758 /* Try fetching packed if necessary */
759 if (request->obj->flags & LOCAL)
760 release_request(request);
761 else
762 start_fetch_packed(request);
763
764 } else if (request->state == RUN_FETCH_PACKED) {
765 if (request->curl_result != CURLE_OK) {
766 fprintf(stderr, "Unable to get pack file %s\n%s",
767 request->url, curl_errorstr);
768 remote->can_update_info_refs = 0;
769 } else {
770 fclose(request->local_stream);
771 request->local_stream = NULL;
772 if (!move_temp_to_file(request->tmpfile,
773 request->filename)) {
774 target = (struct packed_git *)request->userData;
775 lst = &remote->packs;
776 while (*lst != target)
777 lst = &((*lst)->next);
778 *lst = (*lst)->next;
779
780 if (!verify_pack(target, 0))
781 install_packed_git(target);
782 else
783 remote->can_update_info_refs = 0;
784 }
785 }
786 release_request(request);
787 }
788 }
789
790 void fill_active_slots(void)
791 {
792 struct transfer_request *request = request_queue_head;
793 struct transfer_request *next;
794 struct active_request_slot *slot = active_queue_head;
795 int num_transfers;
796
797 if (aborted)
798 return;
799
800 while (active_requests < max_requests && request != NULL) {
801 next = request->next;
802 if (request->state == NEED_FETCH) {
803 start_fetch_loose(request);
804 } else if (pushing && request->state == NEED_PUSH) {
805 if (remote_dir_exists[request->obj->sha1[0]] == 1) {
806 start_put(request);
807 } else {
808 start_mkcol(request);
809 }
810 curl_multi_perform(curlm, &num_transfers);
811 }
812 request = next;
813 }
814
815 while (slot != NULL) {
816 if (!slot->in_use && slot->curl != NULL) {
817 curl_easy_cleanup(slot->curl);
818 slot->curl = NULL;
819 }
820 slot = slot->next;
821 }
822 }
823
824 static void get_remote_object_list(unsigned char parent);
825
826 static void add_fetch_request(struct object *obj)
827 {
828 struct transfer_request *request;
829
830 check_locks();
831
832 /*
833 * Don't fetch the object if it's known to exist locally
834 * or is already in the request queue
835 */
836 if (remote_dir_exists[obj->sha1[0]] == -1)
837 get_remote_object_list(obj->sha1[0]);
838 if (obj->flags & (LOCAL | FETCHING))
839 return;
840
841 obj->flags |= FETCHING;
842 request = xmalloc(sizeof(*request));
843 request->obj = obj;
844 request->url = NULL;
845 request->lock = NULL;
846 request->headers = NULL;
847 request->local_fileno = -1;
848 request->local_stream = NULL;
849 request->state = NEED_FETCH;
850 request->next = request_queue_head;
851 request_queue_head = request;
852
853 fill_active_slots();
854 step_active_slots();
855 }
856
857 static int add_send_request(struct object *obj, struct remote_lock *lock)
858 {
859 struct transfer_request *request = request_queue_head;
860 struct packed_git *target;
861
862 /* Keep locks active */
863 check_locks();
864
865 /*
866 * Don't push the object if it's known to exist on the remote
867 * or is already in the request queue
868 */
869 if (remote_dir_exists[obj->sha1[0]] == -1)
870 get_remote_object_list(obj->sha1[0]);
871 if (obj->flags & (REMOTE | PUSHING))
872 return 0;
873 target = find_sha1_pack(obj->sha1, remote->packs);
874 if (target) {
875 obj->flags |= REMOTE;
876 return 0;
877 }
878
879 obj->flags |= PUSHING;
880 request = xmalloc(sizeof(*request));
881 request->obj = obj;
882 request->url = NULL;
883 request->lock = lock;
884 request->headers = NULL;
885 request->local_fileno = -1;
886 request->local_stream = NULL;
887 request->state = NEED_PUSH;
888 request->next = request_queue_head;
889 request_queue_head = request;
890
891 fill_active_slots();
892 step_active_slots();
893
894 return 1;
895 }
896
897 static int fetch_index(unsigned char *sha1)
898 {
899 char *hex = sha1_to_hex(sha1);
900 char *filename;
901 char *url;
902 char tmpfile[PATH_MAX];
903 long prev_posn = 0;
904 char range[RANGE_HEADER_SIZE];
905 struct curl_slist *range_header = NULL;
906
907 FILE *indexfile;
908 struct active_request_slot *slot;
909 struct slot_results results;
910
911 /* Don't use the index if the pack isn't there */
912 url = xmalloc(strlen(remote->url) + 64);
913 sprintf(url, "%sobjects/pack/pack-%s.pack", remote->url, hex);
914 slot = get_active_slot();
915 slot->results = &results;
916 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
917 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
918 if (start_active_slot(slot)) {
919 run_active_slot(slot);
920 if (results.curl_result != CURLE_OK) {
921 free(url);
922 return error("Unable to verify pack %s is available",
923 hex);
924 }
925 } else {
926 return error("Unable to start request");
927 }
928
929 if (has_pack_index(sha1))
930 return 0;
931
932 if (push_verbosely)
933 fprintf(stderr, "Getting index for pack %s\n", hex);
934
935 sprintf(url, "%sobjects/pack/pack-%s.idx", remote->url, hex);
936
937 filename = sha1_pack_index_name(sha1);
938 snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
939 indexfile = fopen(tmpfile, "a");
940 if (!indexfile)
941 return error("Unable to open local file %s for pack index",
942 filename);
943
944 slot = get_active_slot();
945 slot->results = &results;
946 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
947 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
948 curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
949 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
950 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
951 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
952 slot->local = indexfile;
953
954 /* If there is data present from a previous transfer attempt,
955 resume where it left off */
956 prev_posn = ftell(indexfile);
957 if (prev_posn>0) {
958 if (push_verbosely)
959 fprintf(stderr,
960 "Resuming fetch of index for pack %s at byte %ld\n",
961 hex, prev_posn);
962 sprintf(range, "Range: bytes=%ld-", prev_posn);
963 range_header = curl_slist_append(range_header, range);
964 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
965 }
966
967 if (start_active_slot(slot)) {
968 run_active_slot(slot);
969 if (results.curl_result != CURLE_OK) {
970 free(url);
971 fclose(indexfile);
972 return error("Unable to get pack index %s\n%s", url,
973 curl_errorstr);
974 }
975 } else {
976 free(url);
977 fclose(indexfile);
978 return error("Unable to start request");
979 }
980
981 free(url);
982 fclose(indexfile);
983
984 return move_temp_to_file(tmpfile, filename);
985 }
986
987 static int setup_index(unsigned char *sha1)
988 {
989 struct packed_git *new_pack;
990
991 if (fetch_index(sha1))
992 return -1;
993
994 new_pack = parse_pack_index(sha1);
995 new_pack->next = remote->packs;
996 remote->packs = new_pack;
997 return 0;
998 }
999
1000 static int fetch_indices(void)
1001 {
1002 unsigned char sha1[20];
1003 char *url;
1004 struct buffer buffer;
1005 char *data;
1006 int i = 0;
1007
1008 struct active_request_slot *slot;
1009 struct slot_results results;
1010
1011 data = xmalloc(4096);
1012 memset(data, 0, 4096);
1013 buffer.size = 4096;
1014 buffer.posn = 0;
1015 buffer.buffer = data;
1016
1017 if (push_verbosely)
1018 fprintf(stderr, "Getting pack list\n");
1019
1020 url = xmalloc(strlen(remote->url) + 20);
1021 sprintf(url, "%sobjects/info/packs", remote->url);
1022
1023 slot = get_active_slot();
1024 slot->results = &results;
1025 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1026 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1027 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1028 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1029 if (start_active_slot(slot)) {
1030 run_active_slot(slot);
1031 if (results.curl_result != CURLE_OK) {
1032 free(buffer.buffer);
1033 free(url);
1034 if (results.http_code == 404)
1035 return 0;
1036 else
1037 return error("%s", curl_errorstr);
1038 }
1039 } else {
1040 free(buffer.buffer);
1041 free(url);
1042 return error("Unable to start request");
1043 }
1044 free(url);
1045
1046 data = buffer.buffer;
1047 while (i < buffer.posn) {
1048 switch (data[i]) {
1049 case 'P':
1050 i++;
1051 if (i + 52 < buffer.posn &&
1052 !strncmp(data + i, " pack-", 6) &&
1053 !strncmp(data + i + 46, ".pack\n", 6)) {
1054 get_sha1_hex(data + i + 6, sha1);
1055 setup_index(sha1);
1056 i += 51;
1057 break;
1058 }
1059 default:
1060 while (data[i] != '\n')
1061 i++;
1062 }
1063 i++;
1064 }
1065
1066 free(buffer.buffer);
1067 return 0;
1068 }
1069
1070 static inline int needs_quote(int ch)
1071 {
1072 switch (ch) {
1073 case '/': case '-': case '.':
1074 case 'A'...'Z': case 'a'...'z': case '0'...'9':
1075 return 0;
1076 default:
1077 return 1;
1078 }
1079 }
1080
1081 static inline int hex(int v)
1082 {
1083 if (v < 10) return '0' + v;
1084 else return 'A' + v - 10;
1085 }
1086
1087 static char *quote_ref_url(const char *base, const char *ref)
1088 {
1089 const char *cp;
1090 char *dp, *qref;
1091 int len, baselen, ch;
1092
1093 baselen = strlen(base);
1094 len = baselen + 1;
1095 for (cp = ref; (ch = *cp) != 0; cp++, len++)
1096 if (needs_quote(ch))
1097 len += 2; /* extra two hex plus replacement % */
1098 qref = xmalloc(len);
1099 memcpy(qref, base, baselen);
1100 for (cp = ref, dp = qref + baselen; (ch = *cp) != 0; cp++) {
1101 if (needs_quote(ch)) {
1102 *dp++ = '%';
1103 *dp++ = hex((ch >> 4) & 0xF);
1104 *dp++ = hex(ch & 0xF);
1105 }
1106 else
1107 *dp++ = ch;
1108 }
1109 *dp = 0;
1110
1111 return qref;
1112 }
1113
1114 int fetch_ref(char *ref, unsigned char *sha1)
1115 {
1116 char *url;
1117 char hex[42];
1118 struct buffer buffer;
1119 char *base = remote->url;
1120 struct active_request_slot *slot;
1121 struct slot_results results;
1122 buffer.size = 41;
1123 buffer.posn = 0;
1124 buffer.buffer = hex;
1125 hex[41] = '\0';
1126
1127 url = quote_ref_url(base, ref);
1128 slot = get_active_slot();
1129 slot->results = &results;
1130 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
1131 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1132 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
1133 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1134 if (start_active_slot(slot)) {
1135 run_active_slot(slot);
1136 if (results.curl_result != CURLE_OK)
1137 return error("Couldn't get %s for %s\n%s",
1138 url, ref, curl_errorstr);
1139 } else {
1140 return error("Unable to start request");
1141 }
1142
1143 hex[40] = '\0';
1144 get_sha1_hex(hex, sha1);
1145 return 0;
1146 }
1147
1148 static void one_remote_object(const char *hex)
1149 {
1150 unsigned char sha1[20];
1151 struct object *obj;
1152
1153 if (get_sha1_hex(hex, sha1) != 0)
1154 return;
1155
1156 obj = lookup_object(sha1);
1157 if (!obj)
1158 obj = parse_object(sha1);
1159
1160 /* Ignore remote objects that don't exist locally */
1161 if (!obj)
1162 return;
1163
1164 obj->flags |= REMOTE;
1165 if (!object_list_contains(objects, obj))
1166 add_object(obj, &objects, NULL, "");
1167 }
1168
1169 static void handle_lockprop_ctx(struct xml_ctx *ctx, int tag_closed)
1170 {
1171 int *lock_flags = (int *)ctx->userData;
1172
1173 if (tag_closed) {
1174 if (!strcmp(ctx->name, DAV_CTX_LOCKENTRY)) {
1175 if ((*lock_flags & DAV_PROP_LOCKEX) &&
1176 (*lock_flags & DAV_PROP_LOCKWR)) {
1177 *lock_flags |= DAV_LOCK_OK;
1178 }
1179 *lock_flags &= DAV_LOCK_OK;
1180 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_WRITE)) {
1181 *lock_flags |= DAV_PROP_LOCKWR;
1182 } else if (!strcmp(ctx->name, DAV_CTX_LOCKTYPE_EXCLUSIVE)) {
1183 *lock_flags |= DAV_PROP_LOCKEX;
1184 }
1185 }
1186 }
1187
1188 static void handle_new_lock_ctx(struct xml_ctx *ctx, int tag_closed)
1189 {
1190 struct remote_lock *lock = (struct remote_lock *)ctx->userData;
1191
1192 if (tag_closed && ctx->cdata) {
1193 if (!strcmp(ctx->name, DAV_ACTIVELOCK_OWNER)) {
1194 lock->owner = xmalloc(strlen(ctx->cdata) + 1);
1195 strcpy(lock->owner, ctx->cdata);
1196 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TIMEOUT)) {
1197 if (!strncmp(ctx->cdata, "Second-", 7))
1198 lock->timeout =
1199 strtol(ctx->cdata + 7, NULL, 10);
1200 } else if (!strcmp(ctx->name, DAV_ACTIVELOCK_TOKEN)) {
1201 if (!strncmp(ctx->cdata, "opaquelocktoken:", 16)) {
1202 lock->token = xmalloc(strlen(ctx->cdata) - 15);
1203 strcpy(lock->token, ctx->cdata + 16);
1204 }
1205 }
1206 }
1207 }
1208
1209 static void one_remote_ref(char *refname);
1210
1211 static void
1212 xml_start_tag(void *userData, const char *name, const char **atts)
1213 {
1214 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1215 const char *c = index(name, ':');
1216 int new_len;
1217
1218 if (c == NULL)
1219 c = name;
1220 else
1221 c++;
1222
1223 new_len = strlen(ctx->name) + strlen(c) + 2;
1224
1225 if (new_len > ctx->len) {
1226 ctx->name = xrealloc(ctx->name, new_len);
1227 ctx->len = new_len;
1228 }
1229 strcat(ctx->name, ".");
1230 strcat(ctx->name, c);
1231
1232 if (ctx->cdata) {
1233 free(ctx->cdata);
1234 ctx->cdata = NULL;
1235 }
1236
1237 ctx->userFunc(ctx, 0);
1238 }
1239
1240 static void
1241 xml_end_tag(void *userData, const char *name)
1242 {
1243 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1244 const char *c = index(name, ':');
1245 char *ep;
1246
1247 ctx->userFunc(ctx, 1);
1248
1249 if (c == NULL)
1250 c = name;
1251 else
1252 c++;
1253
1254 ep = ctx->name + strlen(ctx->name) - strlen(c) - 1;
1255 *ep = 0;
1256 }
1257
1258 static void
1259 xml_cdata(void *userData, const XML_Char *s, int len)
1260 {
1261 struct xml_ctx *ctx = (struct xml_ctx *)userData;
1262 if (ctx->cdata)
1263 free(ctx->cdata);
1264 ctx->cdata = xcalloc(len+1, 1);
1265 strncpy(ctx->cdata, s, len);
1266 }
1267
1268 static struct remote_lock *lock_remote(char *path, long timeout)
1269 {
1270 struct active_request_slot *slot;
1271 struct slot_results results;
1272 struct buffer out_buffer;
1273 struct buffer in_buffer;
1274 char *out_data;
1275 char *in_data;
1276 char *url;
1277 char *ep;
1278 char timeout_header[25];
1279 struct remote_lock *lock = NULL;
1280 XML_Parser parser = XML_ParserCreate(NULL);
1281 enum XML_Status result;
1282 struct curl_slist *dav_headers = NULL;
1283 struct xml_ctx ctx;
1284
1285 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1286 sprintf(url, "%s%s", remote->url, path);
1287
1288 /* Make sure leading directories exist for the remote ref */
1289 ep = strchr(url + strlen(remote->url) + 11, '/');
1290 while (ep) {
1291 *ep = 0;
1292 slot = get_active_slot();
1293 slot->results = &results;
1294 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1295 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1296 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_MKCOL);
1297 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1298 if (start_active_slot(slot)) {
1299 run_active_slot(slot);
1300 if (results.curl_result != CURLE_OK &&
1301 results.http_code != 405) {
1302 fprintf(stderr,
1303 "Unable to create branch path %s\n",
1304 url);
1305 free(url);
1306 return NULL;
1307 }
1308 } else {
1309 fprintf(stderr, "Unable to start MKCOL request\n");
1310 free(url);
1311 return NULL;
1312 }
1313 *ep = '/';
1314 ep = strchr(ep + 1, '/');
1315 }
1316
1317 out_buffer.size = strlen(LOCK_REQUEST) + strlen(git_default_email) - 2;
1318 out_data = xmalloc(out_buffer.size + 1);
1319 snprintf(out_data, out_buffer.size + 1, LOCK_REQUEST, git_default_email);
1320 out_buffer.posn = 0;
1321 out_buffer.buffer = out_data;
1322
1323 in_buffer.size = 4096;
1324 in_data = xmalloc(in_buffer.size);
1325 in_buffer.posn = 0;
1326 in_buffer.buffer = in_data;
1327
1328 sprintf(timeout_header, "Timeout: Second-%ld", timeout);
1329 dav_headers = curl_slist_append(dav_headers, timeout_header);
1330 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1331
1332 slot = get_active_slot();
1333 slot->results = &results;
1334 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1335 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1336 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1337 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1338 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1339 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1340 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1341 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_LOCK);
1342 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1343
1344 lock = xcalloc(1, sizeof(*lock));
1345 lock->timeout = -1;
1346
1347 if (start_active_slot(slot)) {
1348 run_active_slot(slot);
1349 if (results.curl_result == CURLE_OK) {
1350 ctx.name = xcalloc(10, 1);
1351 ctx.len = 0;
1352 ctx.cdata = NULL;
1353 ctx.userFunc = handle_new_lock_ctx;
1354 ctx.userData = lock;
1355 XML_SetUserData(parser, &ctx);
1356 XML_SetElementHandler(parser, xml_start_tag,
1357 xml_end_tag);
1358 XML_SetCharacterDataHandler(parser, xml_cdata);
1359 result = XML_Parse(parser, in_buffer.buffer,
1360 in_buffer.posn, 1);
1361 free(ctx.name);
1362 if (result != XML_STATUS_OK) {
1363 fprintf(stderr, "XML error: %s\n",
1364 XML_ErrorString(
1365 XML_GetErrorCode(parser)));
1366 lock->timeout = -1;
1367 }
1368 }
1369 } else {
1370 fprintf(stderr, "Unable to start LOCK request\n");
1371 }
1372
1373 curl_slist_free_all(dav_headers);
1374 free(out_data);
1375 free(in_data);
1376
1377 if (lock->token == NULL || lock->timeout <= 0) {
1378 if (lock->token != NULL)
1379 free(lock->token);
1380 if (lock->owner != NULL)
1381 free(lock->owner);
1382 free(url);
1383 free(lock);
1384 lock = NULL;
1385 } else {
1386 lock->url = url;
1387 lock->start_time = time(NULL);
1388 lock->next = remote->locks;
1389 remote->locks = lock;
1390 }
1391
1392 return lock;
1393 }
1394
1395 static int unlock_remote(struct remote_lock *lock)
1396 {
1397 struct active_request_slot *slot;
1398 struct slot_results results;
1399 struct remote_lock *prev = remote->locks;
1400 char *lock_token_header;
1401 struct curl_slist *dav_headers = NULL;
1402 int rc = 0;
1403
1404 lock_token_header = xmalloc(strlen(lock->token) + 31);
1405 sprintf(lock_token_header, "Lock-Token: <opaquelocktoken:%s>",
1406 lock->token);
1407 dav_headers = curl_slist_append(dav_headers, lock_token_header);
1408
1409 slot = get_active_slot();
1410 slot->results = &results;
1411 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1412 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1413 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_UNLOCK);
1414 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1415
1416 if (start_active_slot(slot)) {
1417 run_active_slot(slot);
1418 if (results.curl_result == CURLE_OK)
1419 rc = 1;
1420 else
1421 fprintf(stderr, "UNLOCK HTTP error %ld\n",
1422 results.http_code);
1423 } else {
1424 fprintf(stderr, "Unable to start UNLOCK request\n");
1425 }
1426
1427 curl_slist_free_all(dav_headers);
1428 free(lock_token_header);
1429
1430 if (remote->locks == lock) {
1431 remote->locks = lock->next;
1432 } else {
1433 while (prev && prev->next != lock)
1434 prev = prev->next;
1435 if (prev)
1436 prev->next = prev->next->next;
1437 }
1438
1439 if (lock->owner != NULL)
1440 free(lock->owner);
1441 free(lock->url);
1442 free(lock->token);
1443 free(lock);
1444
1445 return rc;
1446 }
1447
1448 static void remote_ls(const char *path, int flags,
1449 void (*userFunc)(struct remote_ls_ctx *ls),
1450 void *userData);
1451
1452 static void process_ls_object(struct remote_ls_ctx *ls)
1453 {
1454 unsigned int *parent = (unsigned int *)ls->userData;
1455 char *path = ls->dentry_name;
1456 char *obj_hex;
1457
1458 if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
1459 remote_dir_exists[*parent] = 1;
1460 return;
1461 }
1462
1463 if (strlen(path) != 49)
1464 return;
1465 path += 8;
1466 obj_hex = xmalloc(strlen(path));
1467 strncpy(obj_hex, path, 2);
1468 strcpy(obj_hex + 2, path + 3);
1469 one_remote_object(obj_hex);
1470 free(obj_hex);
1471 }
1472
1473 static void process_ls_ref(struct remote_ls_ctx *ls)
1474 {
1475 if (!strcmp(ls->path, ls->dentry_name) && (ls->dentry_flags & IS_DIR)) {
1476 fprintf(stderr, " %s\n", ls->dentry_name);
1477 return;
1478 }
1479
1480 if (!(ls->dentry_flags & IS_DIR))
1481 one_remote_ref(ls->dentry_name);
1482 }
1483
1484 static void handle_remote_ls_ctx(struct xml_ctx *ctx, int tag_closed)
1485 {
1486 struct remote_ls_ctx *ls = (struct remote_ls_ctx *)ctx->userData;
1487
1488 if (tag_closed) {
1489 if (!strcmp(ctx->name, DAV_PROPFIND_RESP) && ls->dentry_name) {
1490 if (ls->dentry_flags & IS_DIR) {
1491 if (ls->flags & PROCESS_DIRS) {
1492 ls->userFunc(ls);
1493 }
1494 if (strcmp(ls->dentry_name, ls->path) &&
1495 ls->flags & RECURSIVE) {
1496 remote_ls(ls->dentry_name,
1497 ls->flags,
1498 ls->userFunc,
1499 ls->userData);
1500 }
1501 } else if (ls->flags & PROCESS_FILES) {
1502 ls->userFunc(ls);
1503 }
1504 } else if (!strcmp(ctx->name, DAV_PROPFIND_NAME) && ctx->cdata) {
1505 ls->dentry_name = xmalloc(strlen(ctx->cdata) -
1506 remote->path_len + 1);
1507 strcpy(ls->dentry_name, ctx->cdata + remote->path_len);
1508 } else if (!strcmp(ctx->name, DAV_PROPFIND_COLLECTION)) {
1509 ls->dentry_flags |= IS_DIR;
1510 }
1511 } else if (!strcmp(ctx->name, DAV_PROPFIND_RESP)) {
1512 if (ls->dentry_name) {
1513 free(ls->dentry_name);
1514 }
1515 ls->dentry_name = NULL;
1516 ls->dentry_flags = 0;
1517 }
1518 }
1519
1520 static void remote_ls(const char *path, int flags,
1521 void (*userFunc)(struct remote_ls_ctx *ls),
1522 void *userData)
1523 {
1524 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
1525 struct active_request_slot *slot;
1526 struct slot_results results;
1527 struct buffer in_buffer;
1528 struct buffer out_buffer;
1529 char *in_data;
1530 char *out_data;
1531 XML_Parser parser = XML_ParserCreate(NULL);
1532 enum XML_Status result;
1533 struct curl_slist *dav_headers = NULL;
1534 struct xml_ctx ctx;
1535 struct remote_ls_ctx ls;
1536
1537 ls.flags = flags;
1538 ls.path = strdup(path);
1539 ls.dentry_name = NULL;
1540 ls.dentry_flags = 0;
1541 ls.userData = userData;
1542 ls.userFunc = userFunc;
1543
1544 sprintf(url, "%s%s", remote->url, path);
1545
1546 out_buffer.size = strlen(PROPFIND_ALL_REQUEST);
1547 out_data = xmalloc(out_buffer.size + 1);
1548 snprintf(out_data, out_buffer.size + 1, PROPFIND_ALL_REQUEST);
1549 out_buffer.posn = 0;
1550 out_buffer.buffer = out_data;
1551
1552 in_buffer.size = 4096;
1553 in_data = xmalloc(in_buffer.size);
1554 in_buffer.posn = 0;
1555 in_buffer.buffer = in_data;
1556
1557 dav_headers = curl_slist_append(dav_headers, "Depth: 1");
1558 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1559
1560 slot = get_active_slot();
1561 slot->results = &results;
1562 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1563 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1564 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1565 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1566 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1567 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1568 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1569 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1570 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1571
1572 if (start_active_slot(slot)) {
1573 run_active_slot(slot);
1574 if (results.curl_result == CURLE_OK) {
1575 ctx.name = xcalloc(10, 1);
1576 ctx.len = 0;
1577 ctx.cdata = NULL;
1578 ctx.userFunc = handle_remote_ls_ctx;
1579 ctx.userData = &ls;
1580 XML_SetUserData(parser, &ctx);
1581 XML_SetElementHandler(parser, xml_start_tag,
1582 xml_end_tag);
1583 XML_SetCharacterDataHandler(parser, xml_cdata);
1584 result = XML_Parse(parser, in_buffer.buffer,
1585 in_buffer.posn, 1);
1586 free(ctx.name);
1587
1588 if (result != XML_STATUS_OK) {
1589 fprintf(stderr, "XML error: %s\n",
1590 XML_ErrorString(
1591 XML_GetErrorCode(parser)));
1592 }
1593 }
1594 } else {
1595 fprintf(stderr, "Unable to start PROPFIND request\n");
1596 }
1597
1598 free(ls.path);
1599 free(url);
1600 free(out_data);
1601 free(in_buffer.buffer);
1602 curl_slist_free_all(dav_headers);
1603 }
1604
1605 static void get_remote_object_list(unsigned char parent)
1606 {
1607 char path[] = "objects/XX/";
1608 static const char hex[] = "0123456789abcdef";
1609 unsigned int val = parent;
1610
1611 path[8] = hex[val >> 4];
1612 path[9] = hex[val & 0xf];
1613 remote_dir_exists[val] = 0;
1614 remote_ls(path, (PROCESS_FILES | PROCESS_DIRS),
1615 process_ls_object, &val);
1616 }
1617
1618 static int locking_available(void)
1619 {
1620 struct active_request_slot *slot;
1621 struct slot_results results;
1622 struct buffer in_buffer;
1623 struct buffer out_buffer;
1624 char *in_data;
1625 char *out_data;
1626 XML_Parser parser = XML_ParserCreate(NULL);
1627 enum XML_Status result;
1628 struct curl_slist *dav_headers = NULL;
1629 struct xml_ctx ctx;
1630 int lock_flags = 0;
1631
1632 out_buffer.size =
1633 strlen(PROPFIND_SUPPORTEDLOCK_REQUEST) +
1634 strlen(remote->url) - 2;
1635 out_data = xmalloc(out_buffer.size + 1);
1636 snprintf(out_data, out_buffer.size + 1,
1637 PROPFIND_SUPPORTEDLOCK_REQUEST, remote->url);
1638 out_buffer.posn = 0;
1639 out_buffer.buffer = out_data;
1640
1641 in_buffer.size = 4096;
1642 in_data = xmalloc(in_buffer.size);
1643 in_buffer.posn = 0;
1644 in_buffer.buffer = in_data;
1645
1646 dav_headers = curl_slist_append(dav_headers, "Depth: 0");
1647 dav_headers = curl_slist_append(dav_headers, "Content-Type: text/xml");
1648
1649 slot = get_active_slot();
1650 slot->results = &results;
1651 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1652 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1653 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1654 curl_easy_setopt(slot->curl, CURLOPT_FILE, &in_buffer);
1655 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
1656 curl_easy_setopt(slot->curl, CURLOPT_URL, remote->url);
1657 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1658 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PROPFIND);
1659 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1660
1661 if (start_active_slot(slot)) {
1662 run_active_slot(slot);
1663 if (results.curl_result == CURLE_OK) {
1664 ctx.name = xcalloc(10, 1);
1665 ctx.len = 0;
1666 ctx.cdata = NULL;
1667 ctx.userFunc = handle_lockprop_ctx;
1668 ctx.userData = &lock_flags;
1669 XML_SetUserData(parser, &ctx);
1670 XML_SetElementHandler(parser, xml_start_tag,
1671 xml_end_tag);
1672 result = XML_Parse(parser, in_buffer.buffer,
1673 in_buffer.posn, 1);
1674 free(ctx.name);
1675
1676 if (result != XML_STATUS_OK) {
1677 fprintf(stderr, "XML error: %s\n",
1678 XML_ErrorString(
1679 XML_GetErrorCode(parser)));
1680 lock_flags = 0;
1681 }
1682 }
1683 } else {
1684 fprintf(stderr, "Unable to start PROPFIND request\n");
1685 }
1686
1687 free(out_data);
1688 free(in_buffer.buffer);
1689 curl_slist_free_all(dav_headers);
1690
1691 return lock_flags;
1692 }
1693
1694 static struct object_list **process_blob(struct blob *blob,
1695 struct object_list **p,
1696 struct name_path *path,
1697 const char *name)
1698 {
1699 struct object *obj = &blob->object;
1700
1701 obj->flags |= LOCAL;
1702
1703 if (obj->flags & (UNINTERESTING | SEEN))
1704 return p;
1705
1706 obj->flags |= SEEN;
1707 return add_object(obj, p, path, name);
1708 }
1709
1710 static struct object_list **process_tree(struct tree *tree,
1711 struct object_list **p,
1712 struct name_path *path,
1713 const char *name)
1714 {
1715 struct object *obj = &tree->object;
1716 struct tree_entry_list *entry;
1717 struct name_path me;
1718
1719 obj->flags |= LOCAL;
1720
1721 if (obj->flags & (UNINTERESTING | SEEN))
1722 return p;
1723 if (parse_tree(tree) < 0)
1724 die("bad tree object %s", sha1_to_hex(obj->sha1));
1725
1726 obj->flags |= SEEN;
1727 p = add_object(obj, p, NULL, name);
1728 me.up = path;
1729 me.elem = name;
1730 me.elem_len = strlen(name);
1731 entry = tree->entries;
1732 tree->entries = NULL;
1733 while (entry) {
1734 struct tree_entry_list *next = entry->next;
1735 if (entry->directory)
1736 p = process_tree(entry->item.tree, p, &me, entry->name);
1737 else
1738 p = process_blob(entry->item.blob, p, &me, entry->name);
1739 free(entry);
1740 entry = next;
1741 }
1742 return p;
1743 }
1744
1745 static int get_delta(struct rev_info *revs, struct remote_lock *lock)
1746 {
1747 struct commit *commit;
1748 struct object_list **p = &objects, *pending;
1749 int count = 0;
1750
1751 while ((commit = get_revision(revs)) != NULL) {
1752 p = process_tree(commit->tree, p, NULL, "");
1753 commit->object.flags |= LOCAL;
1754 if (!(commit->object.flags & UNINTERESTING))
1755 count += add_send_request(&commit->object, lock);
1756 }
1757
1758 for (pending = revs->pending_objects; pending; pending = pending->next) {
1759 struct object *obj = pending->item;
1760 const char *name = pending->name;
1761
1762 if (obj->flags & (UNINTERESTING | SEEN))
1763 continue;
1764 if (obj->type == tag_type) {
1765 obj->flags |= SEEN;
1766 p = add_object(obj, p, NULL, name);
1767 continue;
1768 }
1769 if (obj->type == tree_type) {
1770 p = process_tree((struct tree *)obj, p, NULL, name);
1771 continue;
1772 }
1773 if (obj->type == blob_type) {
1774 p = process_blob((struct blob *)obj, p, NULL, name);
1775 continue;
1776 }
1777 die("unknown pending object %s (%s)", sha1_to_hex(obj->sha1), name);
1778 }
1779
1780 while (objects) {
1781 if (!(objects->item->flags & UNINTERESTING))
1782 count += add_send_request(objects->item, lock);
1783 objects = objects->next;
1784 }
1785
1786 return count;
1787 }
1788
1789 static int update_remote(unsigned char *sha1, struct remote_lock *lock)
1790 {
1791 struct active_request_slot *slot;
1792 struct slot_results results;
1793 char *out_data;
1794 char *if_header;
1795 struct buffer out_buffer;
1796 struct curl_slist *dav_headers = NULL;
1797 int i;
1798
1799 if_header = xmalloc(strlen(lock->token) + 25);
1800 sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock->token);
1801 dav_headers = curl_slist_append(dav_headers, if_header);
1802
1803 out_buffer.size = 41;
1804 out_data = xmalloc(out_buffer.size + 1);
1805 i = snprintf(out_data, out_buffer.size + 1, "%s\n", sha1_to_hex(sha1));
1806 if (i != out_buffer.size) {
1807 fprintf(stderr, "Unable to initialize PUT request body\n");
1808 return 0;
1809 }
1810 out_buffer.posn = 0;
1811 out_buffer.buffer = out_data;
1812
1813 slot = get_active_slot();
1814 slot->results = &results;
1815 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &out_buffer);
1816 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, out_buffer.size);
1817 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
1818 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
1819 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
1820 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
1821 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
1822 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
1823 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
1824
1825 if (start_active_slot(slot)) {
1826 run_active_slot(slot);
1827 free(out_data);
1828 free(if_header);
1829 if (results.curl_result != CURLE_OK) {
1830 fprintf(stderr,
1831 "PUT error: curl result=%d, HTTP code=%ld\n",
1832 results.curl_result, results.http_code);
1833 /* We should attempt recovery? */
1834 return 0;
1835 }
1836 } else {
1837 free(out_data);
1838 free(if_header);
1839 fprintf(stderr, "Unable to start PUT request\n");
1840 return 0;
1841 }
1842
1843 return 1;
1844 }
1845
1846 static struct ref *local_refs, **local_tail;
1847 static struct ref *remote_refs, **remote_tail;
1848
1849 static int one_local_ref(const char *refname, const unsigned char *sha1)
1850 {
1851 struct ref *ref;
1852 int len = strlen(refname) + 1;
1853 ref = xcalloc(1, sizeof(*ref) + len);
1854 memcpy(ref->new_sha1, sha1, 20);
1855 memcpy(ref->name, refname, len);
1856 *local_tail = ref;
1857 local_tail = &ref->next;
1858 return 0;
1859 }
1860
1861 static void one_remote_ref(char *refname)
1862 {
1863 struct ref *ref;
1864 unsigned char remote_sha1[20];
1865 struct object *obj;
1866 int len = strlen(refname) + 1;
1867
1868 if (fetch_ref(refname, remote_sha1) != 0) {
1869 fprintf(stderr,
1870 "Unable to fetch ref %s from %s\n",
1871 refname, remote->url);
1872 return;
1873 }
1874
1875 /*
1876 * Fetch a copy of the object if it doesn't exist locally - it
1877 * may be required for updating server info later.
1878 */
1879 if (remote->can_update_info_refs && !has_sha1_file(remote_sha1)) {
1880 obj = lookup_unknown_object(remote_sha1);
1881 if (obj) {
1882 fprintf(stderr, " fetch %s for %s\n",
1883 sha1_to_hex(remote_sha1), refname);
1884 add_fetch_request(obj);
1885 }
1886 }
1887
1888 ref = xcalloc(1, sizeof(*ref) + len);
1889 memcpy(ref->old_sha1, remote_sha1, 20);
1890 memcpy(ref->name, refname, len);
1891 *remote_tail = ref;
1892 remote_tail = &ref->next;
1893 }
1894
1895 static void get_local_heads(void)
1896 {
1897 local_tail = &local_refs;
1898 for_each_ref(one_local_ref);
1899 }
1900
1901 static void get_dav_remote_heads(void)
1902 {
1903 remote_tail = &remote_refs;
1904 remote_ls("refs/", (PROCESS_FILES | PROCESS_DIRS | RECURSIVE), process_ls_ref, NULL);
1905 }
1906
1907 static int is_zero_sha1(const unsigned char *sha1)
1908 {
1909 int i;
1910
1911 for (i = 0; i < 20; i++) {
1912 if (*sha1++)
1913 return 0;
1914 }
1915 return 1;
1916 }
1917
1918 static void unmark_and_free(struct commit_list *list, unsigned int mark)
1919 {
1920 while (list) {
1921 struct commit_list *temp = list;
1922 temp->item->object.flags &= ~mark;
1923 list = temp->next;
1924 free(temp);
1925 }
1926 }
1927
1928 static int ref_newer(const unsigned char *new_sha1,
1929 const unsigned char *old_sha1)
1930 {
1931 struct object *o;
1932 struct commit *old, *new;
1933 struct commit_list *list, *used;
1934 int found = 0;
1935
1936 /* Both new and old must be commit-ish and new is descendant of
1937 * old. Otherwise we require --force.
1938 */
1939 o = deref_tag(parse_object(old_sha1), NULL, 0);
1940 if (!o || o->type != commit_type)
1941 return 0;
1942 old = (struct commit *) o;
1943
1944 o = deref_tag(parse_object(new_sha1), NULL, 0);
1945 if (!o || o->type != commit_type)
1946 return 0;
1947 new = (struct commit *) o;
1948
1949 if (parse_commit(new) < 0)
1950 return 0;
1951
1952 used = list = NULL;
1953 commit_list_insert(new, &list);
1954 while (list) {
1955 new = pop_most_recent_commit(&list, TMP_MARK);
1956 commit_list_insert(new, &used);
1957 if (new == old) {
1958 found = 1;
1959 break;
1960 }
1961 }
1962 unmark_and_free(list, TMP_MARK);
1963 unmark_and_free(used, TMP_MARK);
1964 return found;
1965 }
1966
1967 static void mark_edge_parents_uninteresting(struct commit *commit)
1968 {
1969 struct commit_list *parents;
1970
1971 for (parents = commit->parents; parents; parents = parents->next) {
1972 struct commit *parent = parents->item;
1973 if (!(parent->object.flags & UNINTERESTING))
1974 continue;
1975 mark_tree_uninteresting(parent->tree);
1976 }
1977 }
1978
1979 static void mark_edges_uninteresting(struct commit_list *list)
1980 {
1981 for ( ; list; list = list->next) {
1982 struct commit *commit = list->item;
1983
1984 if (commit->object.flags & UNINTERESTING) {
1985 mark_tree_uninteresting(commit->tree);
1986 continue;
1987 }
1988 mark_edge_parents_uninteresting(commit);
1989 }
1990 }
1991
1992 static void add_remote_info_ref(struct remote_ls_ctx *ls)
1993 {
1994 struct buffer *buf = (struct buffer *)ls->userData;
1995 unsigned char remote_sha1[20];
1996 struct object *o;
1997 int len;
1998 char *ref_info;
1999
2000 if (fetch_ref(ls->dentry_name, remote_sha1) != 0) {
2001 fprintf(stderr,
2002 "Unable to fetch ref %s from %s\n",
2003 ls->dentry_name, remote->url);
2004 aborted = 1;
2005 return;
2006 }
2007
2008 o = parse_object(remote_sha1);
2009 if (!o) {
2010 fprintf(stderr,
2011 "Unable to parse object %s for remote ref %s\n",
2012 sha1_to_hex(remote_sha1), ls->dentry_name);
2013 aborted = 1;
2014 return;
2015 }
2016
2017 len = strlen(ls->dentry_name) + 42;
2018 ref_info = xcalloc(len + 1, 1);
2019 sprintf(ref_info, "%s %s\n",
2020 sha1_to_hex(remote_sha1), ls->dentry_name);
2021 fwrite_buffer(ref_info, 1, len, buf);
2022 free(ref_info);
2023
2024 if (o->type == tag_type) {
2025 o = deref_tag(o, ls->dentry_name, 0);
2026 if (o) {
2027 len = strlen(ls->dentry_name) + 45;
2028 ref_info = xcalloc(len + 1, 1);
2029 sprintf(ref_info, "%s %s^{}\n",
2030 sha1_to_hex(o->sha1), ls->dentry_name);
2031 fwrite_buffer(ref_info, 1, len, buf);
2032 free(ref_info);
2033 }
2034 }
2035 }
2036
2037 static void update_remote_info_refs(struct remote_lock *lock)
2038 {
2039 struct buffer buffer;
2040 struct active_request_slot *slot;
2041 struct slot_results results;
2042 char *if_header;
2043 struct curl_slist *dav_headers = NULL;
2044
2045 buffer.buffer = xmalloc(4096);
2046 memset(buffer.buffer, 0, 4096);
2047 buffer.size = 4096;
2048 buffer.posn = 0;
2049 remote_ls("refs/", (PROCESS_FILES | RECURSIVE),
2050 add_remote_info_ref, &buffer);
2051 if (!aborted) {
2052 if_header = xmalloc(strlen(lock->token) + 25);
2053 sprintf(if_header, "If: (<opaquelocktoken:%s>)", lock->token);
2054 dav_headers = curl_slist_append(dav_headers, if_header);
2055
2056 slot = get_active_slot();
2057 slot->results = &results;
2058 curl_easy_setopt(slot->curl, CURLOPT_INFILE, &buffer);
2059 curl_easy_setopt(slot->curl, CURLOPT_INFILESIZE, buffer.posn);
2060 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, fread_buffer);
2061 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2062 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_PUT);
2063 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, dav_headers);
2064 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 1);
2065 curl_easy_setopt(slot->curl, CURLOPT_PUT, 1);
2066 curl_easy_setopt(slot->curl, CURLOPT_URL, lock->url);
2067
2068 buffer.posn = 0;
2069
2070 if (start_active_slot(slot)) {
2071 run_active_slot(slot);
2072 if (results.curl_result != CURLE_OK) {
2073 fprintf(stderr,
2074 "PUT error: curl result=%d, HTTP code=%ld\n",
2075 results.curl_result, results.http_code);
2076 }
2077 }
2078 free(if_header);
2079 }
2080 free(buffer.buffer);
2081 }
2082
2083 static int remote_exists(const char *path)
2084 {
2085 char *url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2086 struct active_request_slot *slot;
2087 struct slot_results results;
2088
2089 sprintf(url, "%s%s", remote->url, path);
2090
2091 slot = get_active_slot();
2092 slot->results = &results;
2093 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2094 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2095
2096 if (start_active_slot(slot)) {
2097 run_active_slot(slot);
2098 if (results.http_code == 404)
2099 return 0;
2100 else if (results.curl_result == CURLE_OK)
2101 return 1;
2102 else
2103 fprintf(stderr, "HEAD HTTP error %ld\n", results.http_code);
2104 } else {
2105 fprintf(stderr, "Unable to start HEAD request\n");
2106 }
2107
2108 return -1;
2109 }
2110
2111 static void fetch_symref(char *path, char **symref, unsigned char *sha1)
2112 {
2113 char *url;
2114 struct buffer buffer;
2115 struct active_request_slot *slot;
2116 struct slot_results results;
2117
2118 url = xmalloc(strlen(remote->url) + strlen(path) + 1);
2119 sprintf(url, "%s%s", remote->url, path);
2120
2121 buffer.size = 4096;
2122 buffer.posn = 0;
2123 buffer.buffer = xmalloc(buffer.size);
2124
2125 slot = get_active_slot();
2126 slot->results = &results;
2127 curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
2128 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
2129 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
2130 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2131 if (start_active_slot(slot)) {
2132 run_active_slot(slot);
2133 if (results.curl_result != CURLE_OK) {
2134 die("Couldn't get %s for remote symref\n%s",
2135 url, curl_errorstr);
2136 }
2137 } else {
2138 die("Unable to start remote symref request");
2139 }
2140 free(url);
2141
2142 if (*symref != NULL)
2143 free(*symref);
2144 *symref = NULL;
2145 memset(sha1, 0, 20);
2146
2147 if (buffer.posn == 0)
2148 return;
2149
2150 /* If it's a symref, set the refname; otherwise try for a sha1 */
2151 if (!strncmp((char *)buffer.buffer, "ref: ", 5)) {
2152 *symref = xcalloc(buffer.posn - 5, 1);
2153 strncpy(*symref, (char *)buffer.buffer + 5, buffer.posn - 6);
2154 } else {
2155 get_sha1_hex(buffer.buffer, sha1);
2156 }
2157
2158 free(buffer.buffer);
2159 }
2160
2161 static int verify_merge_base(unsigned char *head_sha1, unsigned char *branch_sha1)
2162 {
2163 int pipe_fd[2];
2164 pid_t merge_base_pid;
2165 char line[PATH_MAX + 20];
2166 unsigned char merge_sha1[20];
2167 int verified = 0;
2168
2169 if (pipe(pipe_fd) < 0)
2170 die("Verify merge base: pipe failed");
2171
2172 merge_base_pid = fork();
2173 if (!merge_base_pid) {
2174 static const char *args[] = {
2175 "merge-base",
2176 "-a",
2177 NULL,
2178 NULL,
2179 NULL
2180 };
2181 args[2] = strdup(sha1_to_hex(head_sha1));
2182 args[3] = sha1_to_hex(branch_sha1);
2183
2184 dup2(pipe_fd[1], 1);
2185 close(pipe_fd[0]);
2186 close(pipe_fd[1]);
2187 execv_git_cmd(args);
2188 die("merge-base setup failed");
2189 }
2190 if (merge_base_pid < 0)
2191 die("merge-base fork failed");
2192
2193 dup2(pipe_fd[0], 0);
2194 close(pipe_fd[0]);
2195 close(pipe_fd[1]);
2196 while (fgets(line, sizeof(line), stdin) != NULL) {
2197 if (get_sha1_hex(line, merge_sha1))
2198 die("expected sha1, got garbage:\n %s", line);
2199 if (!memcmp(branch_sha1, merge_sha1, 20)) {
2200 verified = 1;
2201 break;
2202 }
2203 }
2204
2205 return verified;
2206 }
2207
2208 static int delete_remote_branch(char *pattern, int force)
2209 {
2210 struct ref *refs = remote_refs;
2211 struct ref *remote_ref = NULL;
2212 unsigned char head_sha1[20];
2213 char *symref = NULL;
2214 int match;
2215 int patlen = strlen(pattern);
2216 int i;
2217 struct active_request_slot *slot;
2218 struct slot_results results;
2219 char *url;
2220
2221 /* Find the remote branch(es) matching the specified branch name */
2222 for (match = 0; refs; refs = refs->next) {
2223 char *name = refs->name;
2224 int namelen = strlen(name);
2225 if (namelen < patlen ||
2226 memcmp(name + namelen - patlen, pattern, patlen))
2227 continue;
2228 if (namelen != patlen && name[namelen - patlen - 1] != '/')
2229 continue;
2230 match++;
2231 remote_ref = refs;
2232 }
2233 if (match == 0)
2234 return error("No remote branch matches %s", pattern);
2235 if (match != 1)
2236 return error("More than one remote branch matches %s",
2237 pattern);
2238
2239 /*
2240 * Remote HEAD must be a symref (not exactly foolproof; a remote
2241 * symlink to a symref will look like a symref)
2242 */
2243 fetch_symref("HEAD", &symref, head_sha1);
2244 if (!symref)
2245 return error("Remote HEAD is not a symref");
2246
2247 /* Remote branch must not be the remote HEAD */
2248 for (i=0; symref && i<MAXDEPTH; i++) {
2249 if (!strcmp(remote_ref->name, symref))
2250 return error("Remote branch %s is the current HEAD",
2251 remote_ref->name);
2252 fetch_symref(symref, &symref, head_sha1);
2253 }
2254
2255 /* Run extra sanity checks if delete is not forced */
2256 if (!force) {
2257 /* Remote HEAD must resolve to a known object */
2258 if (symref)
2259 return error("Remote HEAD symrefs too deep");
2260 if (is_zero_sha1(head_sha1))
2261 return error("Unable to resolve remote HEAD");
2262 if (!has_sha1_file(head_sha1))
2263 return error("Remote HEAD resolves to object %s\nwhich does not exist locally, perhaps you need to fetch?", sha1_to_hex(head_sha1));
2264
2265 /* Remote branch must resolve to a known object */
2266 if (is_zero_sha1(remote_ref->old_sha1))
2267 return error("Unable to resolve remote branch %s",
2268 remote_ref->name);
2269 if (!has_sha1_file(remote_ref->old_sha1))
2270 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));
2271
2272 /* Remote branch must be an ancestor of remote HEAD */
2273 if (!verify_merge_base(head_sha1, remote_ref->old_sha1)) {
2274 return error("The branch '%s' is not a strict subset of your current HEAD.\nIf you are sure you want to delete it, run:\n\t'git http-push -D %s %s'", remote_ref->name, remote->url, pattern);
2275 }
2276 }
2277
2278 /* Send delete request */
2279 fprintf(stderr, "Removing remote branch '%s'\n", remote_ref->name);
2280 url = xmalloc(strlen(remote->url) + strlen(remote_ref->name) + 1);
2281 sprintf(url, "%s%s", remote->url, remote_ref->name);
2282 slot = get_active_slot();
2283 slot->results = &results;
2284 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2285 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_null);
2286 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2287 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, DAV_DELETE);
2288 if (start_active_slot(slot)) {
2289 run_active_slot(slot);
2290 free(url);
2291 if (results.curl_result != CURLE_OK)
2292 return error("DELETE request failed (%d/%ld)\n",
2293 results.curl_result, results.http_code);
2294 } else {
2295 free(url);
2296 return error("Unable to start DELETE request");
2297 }
2298
2299 return 0;
2300 }
2301
2302 int main(int argc, char **argv)
2303 {
2304 struct transfer_request *request;
2305 struct transfer_request *next_request;
2306 int nr_refspec = 0;
2307 char **refspec = NULL;
2308 struct remote_lock *ref_lock = NULL;
2309 struct remote_lock *info_ref_lock = NULL;
2310 struct rev_info revs;
2311 int delete_branch = 0;
2312 int force_delete = 0;
2313 int objects_to_send;
2314 int rc = 0;
2315 int i;
2316 int new_refs;
2317 struct ref *ref;
2318
2319 setup_git_directory();
2320 setup_ident();
2321
2322 remote = xcalloc(sizeof(*remote), 1);
2323
2324 argv++;
2325 for (i = 1; i < argc; i++, argv++) {
2326 char *arg = *argv;
2327
2328 if (*arg == '-') {
2329 if (!strcmp(arg, "--all")) {
2330 push_all = 1;
2331 continue;
2332 }
2333 if (!strcmp(arg, "--force")) {
2334 force_all = 1;
2335 continue;
2336 }
2337 if (!strcmp(arg, "--verbose")) {
2338 push_verbosely = 1;
2339 continue;
2340 }
2341 if (!strcmp(arg, "-d")) {
2342 delete_branch = 1;
2343 continue;
2344 }
2345 if (!strcmp(arg, "-D")) {
2346 delete_branch = 1;
2347 force_delete = 1;
2348 continue;
2349 }
2350 }
2351 if (!remote->url) {
2352 char *path = strstr(arg, "//");
2353 remote->url = arg;
2354 if (path) {
2355 path = index(path+2, '/');
2356 if (path)
2357 remote->path_len = strlen(path);
2358 }
2359 continue;
2360 }
2361 refspec = argv;
2362 nr_refspec = argc - i;
2363 break;
2364 }
2365
2366 if (!remote->url)
2367 usage(http_push_usage);
2368
2369 if (delete_branch && nr_refspec != 1)
2370 die("You must specify only one branch name when deleting a remote branch");
2371
2372 memset(remote_dir_exists, -1, 256);
2373
2374 http_init();
2375
2376 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
2377 default_headers = curl_slist_append(default_headers, "Range:");
2378 default_headers = curl_slist_append(default_headers, "Destination:");
2379 default_headers = curl_slist_append(default_headers, "If:");
2380 default_headers = curl_slist_append(default_headers,
2381 "Pragma: no-cache");
2382
2383 /* Verify DAV compliance/lock support */
2384 if (!locking_available()) {
2385 fprintf(stderr, "Error: no DAV locking support on remote repo %s\n", remote->url);
2386 rc = 1;
2387 goto cleanup;
2388 }
2389
2390 /* Check whether the remote has server info files */
2391 remote->can_update_info_refs = 0;
2392 remote->has_info_refs = remote_exists("info/refs");
2393 remote->has_info_packs = remote_exists("objects/info/packs");
2394 if (remote->has_info_refs) {
2395 info_ref_lock = lock_remote("info/refs", LOCK_TIME);
2396 if (info_ref_lock)
2397 remote->can_update_info_refs = 1;
2398 }
2399 if (remote->has_info_packs)
2400 fetch_indices();
2401
2402 /* Get a list of all local and remote heads to validate refspecs */
2403 get_local_heads();
2404 fprintf(stderr, "Fetching remote heads...\n");
2405 get_dav_remote_heads();
2406
2407 /* Remove a remote branch if -d or -D was specified */
2408 if (delete_branch) {
2409 if (delete_remote_branch(refspec[0], force_delete) == -1)
2410 fprintf(stderr, "Unable to delete remote branch %s\n",
2411 refspec[0]);
2412 goto cleanup;
2413 }
2414
2415 /* match them up */
2416 if (!remote_tail)
2417 remote_tail = &remote_refs;
2418 if (match_refs(local_refs, remote_refs, &remote_tail,
2419 nr_refspec, refspec, push_all))
2420 return -1;
2421 if (!remote_refs) {
2422 fprintf(stderr, "No refs in common and none specified; doing nothing.\n");
2423 return 0;
2424 }
2425
2426 new_refs = 0;
2427 for (ref = remote_refs; ref; ref = ref->next) {
2428 char old_hex[60], *new_hex;
2429 const char *commit_argv[4];
2430 int commit_argc;
2431 char *new_sha1_hex, *old_sha1_hex;
2432
2433 if (!ref->peer_ref)
2434 continue;
2435 if (!memcmp(ref->old_sha1, ref->peer_ref->new_sha1, 20)) {
2436 if (push_verbosely || 1)
2437 fprintf(stderr, "'%s': up-to-date\n", ref->name);
2438 continue;
2439 }
2440
2441 if (!force_all &&
2442 !is_zero_sha1(ref->old_sha1) &&
2443 !ref->force) {
2444 if (!has_sha1_file(ref->old_sha1) ||
2445 !ref_newer(ref->peer_ref->new_sha1,
2446 ref->old_sha1)) {
2447 /* We do not have the remote ref, or
2448 * we know that the remote ref is not
2449 * an ancestor of what we are trying to
2450 * push. Either way this can be losing
2451 * commits at the remote end and likely
2452 * we were not up to date to begin with.
2453 */
2454 error("remote '%s' is not a strict "
2455 "subset of local ref '%s'. "
2456 "maybe you are not up-to-date and "
2457 "need to pull first?",
2458 ref->name,
2459 ref->peer_ref->name);
2460 rc = -2;
2461 continue;
2462 }
2463 }
2464 memcpy(ref->new_sha1, ref->peer_ref->new_sha1, 20);
2465 if (is_zero_sha1(ref->new_sha1)) {
2466 error("cannot happen anymore");
2467 rc = -3;
2468 continue;
2469 }
2470 new_refs++;
2471 strcpy(old_hex, sha1_to_hex(ref->old_sha1));
2472 new_hex = sha1_to_hex(ref->new_sha1);
2473
2474 fprintf(stderr, "updating '%s'", ref->name);
2475 if (strcmp(ref->name, ref->peer_ref->name))
2476 fprintf(stderr, " using '%s'", ref->peer_ref->name);
2477 fprintf(stderr, "\n from %s\n to %s\n", old_hex, new_hex);
2478
2479
2480 /* Lock remote branch ref */
2481 ref_lock = lock_remote(ref->name, LOCK_TIME);
2482 if (ref_lock == NULL) {
2483 fprintf(stderr, "Unable to lock remote branch %s\n",
2484 ref->name);
2485 rc = 1;
2486 continue;
2487 }
2488
2489 /* Set up revision info for this refspec */
2490 commit_argc = 3;
2491 new_sha1_hex = strdup(sha1_to_hex(ref->new_sha1));
2492 old_sha1_hex = NULL;
2493 commit_argv[1] = "--objects";
2494 commit_argv[2] = new_sha1_hex;
2495 if (!push_all && !is_zero_sha1(ref->old_sha1)) {
2496 old_sha1_hex = xmalloc(42);
2497 sprintf(old_sha1_hex, "^%s",
2498 sha1_to_hex(ref->old_sha1));
2499 commit_argv[3] = old_sha1_hex;
2500 commit_argc++;
2501 }
2502 setup_revisions(commit_argc, commit_argv, &revs, NULL);
2503 free(new_sha1_hex);
2504 if (old_sha1_hex) {
2505 free(old_sha1_hex);
2506 commit_argv[1] = NULL;
2507 }
2508
2509 /* Generate a list of objects that need to be pushed */
2510 pushing = 0;
2511 prepare_revision_walk(&revs);
2512 mark_edges_uninteresting(revs.commits);
2513 objects_to_send = get_delta(&revs, ref_lock);
2514 finish_all_active_slots();
2515
2516 /* Push missing objects to remote, this would be a
2517 convenient time to pack them first if appropriate. */
2518 pushing = 1;
2519 if (objects_to_send)
2520 fprintf(stderr, " sending %d objects\n",
2521 objects_to_send);
2522 fill_active_slots();
2523 finish_all_active_slots();
2524
2525 /* Update the remote branch if all went well */
2526 if (aborted || !update_remote(ref->new_sha1, ref_lock)) {
2527 rc = 1;
2528 goto unlock;
2529 }
2530
2531 unlock:
2532 if (!rc)
2533 fprintf(stderr, " done\n");
2534 unlock_remote(ref_lock);
2535 check_locks();
2536 }
2537
2538 /* Update remote server info if appropriate */
2539 if (remote->has_info_refs && new_refs) {
2540 if (info_ref_lock && remote->can_update_info_refs) {
2541 fprintf(stderr, "Updating remote server info\n");
2542 update_remote_info_refs(info_ref_lock);
2543 } else {
2544 fprintf(stderr, "Unable to update server info\n");
2545 }
2546 }
2547 if (info_ref_lock)
2548 unlock_remote(info_ref_lock);
2549
2550 cleanup:
2551 free(remote);
2552
2553 curl_slist_free_all(no_pragma_header);
2554 curl_slist_free_all(default_headers);
2555
2556 http_cleanup();
2557
2558 request = request_queue_head;
2559 while (request != NULL) {
2560 next_request = request->next;
2561 release_request(request);
2562 request = next_request;
2563 }
2564
2565 return rc;
2566 }