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