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