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