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