httpclient.c 38.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "common.h"
#include "git2.h"
#include "http_parser.h"
#include "vector.h"
#include "trace.h"
#include "httpclient.h"
#include "http.h"
15 16 17
#include "auth.h"
#include "auth_negotiate.h"
#include "auth_ntlm.h"
18
#include "git2/sys/credential.h"
19 20 21 22 23 24
#include "net.h"
#include "stream.h"
#include "streams/socket.h"
#include "streams/tls.h"
#include "auth.h"

25
static git_http_auth_scheme auth_schemes[] = {
26 27 28
	{ GIT_HTTP_AUTH_NEGOTIATE, "Negotiate", GIT_CREDENTIAL_DEFAULT, git_http_auth_negotiate },
	{ GIT_HTTP_AUTH_NTLM, "NTLM", GIT_CREDENTIAL_USERPASS_PLAINTEXT, git_http_auth_ntlm },
	{ GIT_HTTP_AUTH_BASIC, "Basic", GIT_CREDENTIAL_USERPASS_PLAINTEXT, git_http_auth_basic },
29 30
};

31 32 33 34 35 36 37 38 39 40 41 42
/*
 * Use a 16kb read buffer to match the maximum size of a TLS packet.  This
 * is critical for compatibility with SecureTransport, which will always do
 * a network read on every call, even if it has data buffered to return to
 * you.  That buffered data may be the _end_ of a keep-alive response, so
 * if SecureTransport performs another network read, it will wait until the
 * server ultimately times out before it returns that buffered data to you.
 * Since SecureTransport only reads a single TLS packet at a time, by
 * calling it with a read buffer that is the maximum size of a TLS packet,
 * we ensure that it will never buffer.
 */
#define GIT_READ_BUFFER_SIZE (16 * 1024)
43 44 45 46

typedef struct {
	git_net_url url;
	git_stream *stream;
47 48 49

	git_vector auth_challenges;
	git_http_auth_context *auth_context;
50 51 52
} git_http_server;

typedef enum {
53 54 55 56 57
	PROXY = 1,
	SERVER
} git_http_server_t;

typedef enum {
58
	NONE = 0,
59
	SENDING_REQUEST,
60 61
	SENDING_BODY,
	SENT_REQUEST,
62
	HAS_EARLY_RESPONSE,
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	READING_RESPONSE,
	READING_BODY,
	DONE
} http_client_state;

/* Parser state */
typedef enum {
	PARSE_HEADER_NONE = 0,
	PARSE_HEADER_NAME,
	PARSE_HEADER_VALUE,
	PARSE_HEADER_COMPLETE
} parse_header_state;

typedef enum {
	PARSE_STATUS_OK,
78
	PARSE_STATUS_NO_OUTPUT,
79 80 81 82 83 84 85 86
	PARSE_STATUS_ERROR
} parse_status;

typedef struct {
	git_http_client *client;
	git_http_response *response;

	/* Temporary buffers to avoid extra mallocs */
87 88
	git_str parse_header_name;
	git_str parse_header_value;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

	/* Parser state */
	int error;
	parse_status parse_status;

	/* Headers parsing */
	parse_header_state parse_header_state;

	/* Body parsing */
	char *output_buf;       /* Caller's output buffer */
	size_t output_size;     /* Size of caller's output buffer */
	size_t output_written;  /* Bytes we've written to output buffer */
} http_parser_context;

/* HTTP client connection */
struct git_http_client {
	git_http_client_options opts;

107 108
	/* Are we writing to the proxy or server, and state of the client. */
	git_http_server_t current_server;
109 110 111 112 113 114 115 116 117
	http_client_state state;

	http_parser parser;

	git_http_server server;
	git_http_server proxy;

	unsigned request_count;
	unsigned connected : 1,
118
	         proxy_connected : 1,
119 120
	         keepalive : 1,
	         request_chunked : 1;
121 122

	/* Temporary buffers to avoid extra mallocs */
123 124
	git_str request_msg;
	git_str read_buf;
125 126 127 128

	/* A subset of information from the request */
	size_t request_body_len,
	       request_body_remain;
129 130 131 132 133 134

	/*
	 * When state == HAS_EARLY_RESPONSE, the response of our proxy
	 * that we have buffered and will deliver during read_response.
	 */
	git_http_response early_response;
135 136 137 138
};

bool git_http_response_is_redirect(git_http_response *response)
{
139 140 141 142 143
	return (response->status == GIT_HTTP_MOVED_PERMANENTLY ||
	        response->status == GIT_HTTP_FOUND ||
	        response->status == GIT_HTTP_SEE_OTHER ||
		response->status == GIT_HTTP_TEMPORARY_REDIRECT ||
		response->status == GIT_HTTP_PERMANENT_REDIRECT);
144 145 146 147
}

void git_http_response_dispose(git_http_response *response)
{
148 149
	if (!response)
		return;
150 151 152 153 154 155 156 157 158 159

	git__free(response->content_type);
	git__free(response->location);

	memset(response, 0, sizeof(git_http_response));
}

static int on_header_complete(http_parser *parser)
{
	http_parser_context *ctx = (http_parser_context *) parser->data;
160
	git_http_client *client = ctx->client;
161 162
	git_http_response *response = ctx->response;

163 164
	git_str *name = &ctx->parse_header_name;
	git_str *value = &ctx->parse_header_value;
165 166 167

	if (!strcasecmp("Content-Type", name->ptr)) {
		if (response->content_type) {
168
			git_error_set(GIT_ERROR_HTTP,
169 170 171 172 173 174 175 176 177 178 179
			              "multiple content-type headers");
			return -1;
		}

		response->content_type =
			git__strndup(value->ptr, value->size);
		GIT_ERROR_CHECK_ALLOC(ctx->response->content_type);
	} else if (!strcasecmp("Content-Length", name->ptr)) {
		int64_t len;

		if (response->content_length) {
180
			git_error_set(GIT_ERROR_HTTP,
181 182 183 184 185 186
			              "multiple content-length headers");
			return -1;
		}

		if (git__strntol64(&len, value->ptr, value->size,
		                   NULL, 10) < 0 || len < 0) {
187
			git_error_set(GIT_ERROR_HTTP,
188 189 190 191 192
			              "invalid content-length");
			return -1;
		}

		response->content_length = (size_t)len;
193 194 195
	} else if (!strcasecmp("Transfer-Encoding", name->ptr) &&
	           !strcasecmp("chunked", value->ptr)) {
			ctx->response->chunked = 1;
196
	} else if (!strcasecmp("Proxy-Authenticate", git_str_cstr(name))) {
197 198 199 200 201 202 203 204 205 206 207
		char *dup = git__strndup(value->ptr, value->size);
		GIT_ERROR_CHECK_ALLOC(dup);

		if (git_vector_insert(&client->proxy.auth_challenges, dup) < 0)
			return -1;
	} else if (!strcasecmp("WWW-Authenticate", name->ptr)) {
		char *dup = git__strndup(value->ptr, value->size);
		GIT_ERROR_CHECK_ALLOC(dup);

		if (git_vector_insert(&client->server.auth_challenges, dup) < 0)
			return -1;
208 209
	} else if (!strcasecmp("Location", name->ptr)) {
		if (response->location) {
210
			git_error_set(GIT_ERROR_HTTP,
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
				"multiple location headers");
			return -1;
		}

		response->location = git__strndup(value->ptr, value->size);
		GIT_ERROR_CHECK_ALLOC(response->location);
	}

	return 0;
}

static int on_header_field(http_parser *parser, const char *str, size_t len)
{
	http_parser_context *ctx = (http_parser_context *) parser->data;

	switch (ctx->parse_header_state) {
	/*
	 * We last saw a header value, process the name/value pair and
	 * get ready to handle this new name.
	 */
	case PARSE_HEADER_VALUE:
		if (on_header_complete(parser) < 0)
			return ctx->parse_status = PARSE_STATUS_ERROR;

235 236
		git_str_clear(&ctx->parse_header_name);
		git_str_clear(&ctx->parse_header_value);
237 238 239 240 241 242
		/* Fall through */

	case PARSE_HEADER_NONE:
	case PARSE_HEADER_NAME:
		ctx->parse_header_state = PARSE_HEADER_NAME;

243
		if (git_str_put(&ctx->parse_header_name, str, len) < 0)
244 245 246 247 248
			return ctx->parse_status = PARSE_STATUS_ERROR;

		break;

	default:
249
		git_error_set(GIT_ERROR_HTTP,
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
		              "header name seen at unexpected time");
		return ctx->parse_status = PARSE_STATUS_ERROR;
	}

	return 0;
}

static int on_header_value(http_parser *parser, const char *str, size_t len)
{
	http_parser_context *ctx = (http_parser_context *) parser->data;

	switch (ctx->parse_header_state) {
	case PARSE_HEADER_NAME:
	case PARSE_HEADER_VALUE:
		ctx->parse_header_state = PARSE_HEADER_VALUE;

266
		if (git_str_put(&ctx->parse_header_value, str, len) < 0)
267 268 269 270 271
			return ctx->parse_status = PARSE_STATUS_ERROR;

		break;

	default:
272
		git_error_set(GIT_ERROR_HTTP,
273 274 275 276 277 278 279
		              "header value seen at unexpected time");
		return ctx->parse_status = PARSE_STATUS_ERROR;
	}

	return 0;
}

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
GIT_INLINE(bool) challenge_matches_scheme(
	const char *challenge,
	git_http_auth_scheme *scheme)
{
	const char *scheme_name = scheme->name;
	size_t scheme_len = strlen(scheme_name);

	if (!strncasecmp(challenge, scheme_name, scheme_len) &&
	    (challenge[scheme_len] == '\0' || challenge[scheme_len] == ' '))
		return true;

	return false;
}

static git_http_auth_scheme *scheme_for_challenge(const char *challenge)
{
	size_t i;

	for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) {
		if (challenge_matches_scheme(challenge, &auth_schemes[i]))
			return &auth_schemes[i];
	}

	return NULL;
}

GIT_INLINE(void) collect_authinfo(
	unsigned int *schemetypes,
	unsigned int *credtypes,
	git_vector *challenges)
{
	git_http_auth_scheme *scheme;
	const char *challenge;
	size_t i;

	*schemetypes = 0;
	*credtypes = 0;

	git_vector_foreach(challenges, i, challenge) {
		if ((scheme = scheme_for_challenge(challenge)) != NULL) {
			*schemetypes |= scheme->type;
			*credtypes |= scheme->credtypes;
		}
	}
}

static int resend_needed(git_http_client *client, git_http_response *response)
{
	git_http_auth_context *auth_context;

330
	if (response->status == GIT_HTTP_STATUS_UNAUTHORIZED &&
331 332 333 334 335
	    (auth_context = client->server.auth_context) &&
	    auth_context->is_complete &&
	    !auth_context->is_complete(auth_context))
		return 1;

336
	if (response->status == GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
337 338 339 340 341 342 343 344
	    (auth_context = client->proxy.auth_context) &&
	    auth_context->is_complete &&
	    !auth_context->is_complete(auth_context))
		return 1;

	return 0;
}

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
static int on_headers_complete(http_parser *parser)
{
	http_parser_context *ctx = (http_parser_context *) parser->data;

	/* Finalize the last seen header */
	switch (ctx->parse_header_state) {
	case PARSE_HEADER_VALUE:
		if (on_header_complete(parser) < 0)
			return ctx->parse_status = PARSE_STATUS_ERROR;

		/* Fall through */

	case PARSE_HEADER_NONE:
		ctx->parse_header_state = PARSE_HEADER_COMPLETE;
		break;

	default:
362
		git_error_set(GIT_ERROR_HTTP,
363 364 365 366 367 368 369
		              "header completion at unexpected time");
		return ctx->parse_status = PARSE_STATUS_ERROR;
	}

	ctx->response->status = parser->status_code;
	ctx->client->keepalive = http_should_keep_alive(parser);

370 371 372 373 374 375 376 377 378 379 380
	/* Prepare for authentication */
	collect_authinfo(&ctx->response->server_auth_schemetypes,
	                 &ctx->response->server_auth_credtypes,
	                 &ctx->client->server.auth_challenges);
	collect_authinfo(&ctx->response->proxy_auth_schemetypes,
	                 &ctx->response->proxy_auth_credtypes,
	                 &ctx->client->proxy.auth_challenges);

	ctx->response->resend_credentials = resend_needed(ctx->client,
	                                                  ctx->response);

381 382 383
	/* Stop parsing. */
	http_parser_pause(parser, 1);

384 385 386 387 388
	if (ctx->response->content_type || ctx->response->chunked)
		ctx->client->state = READING_BODY;
	else
		ctx->client->state = DONE;

389 390 391 392 393 394 395 396
	return 0;
}

static int on_body(http_parser *parser, const char *buf, size_t len)
{
	http_parser_context *ctx = (http_parser_context *) parser->data;
	size_t max_len;

397
	/* Saw data when we expected not to (eg, in consume_response_body) */
398
	if (ctx->output_buf == NULL || ctx->output_size == 0) {
399 400 401 402
		ctx->parse_status = PARSE_STATUS_NO_OUTPUT;
		return 0;
	}

403
	GIT_ASSERT(ctx->output_size >= ctx->output_written);
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

	max_len = min(ctx->output_size - ctx->output_written, len);
	max_len = min(max_len, INT_MAX);

	memcpy(ctx->output_buf + ctx->output_written, buf, max_len);
	ctx->output_written += max_len;

	return 0;
}

static int on_message_complete(http_parser *parser)
{
	http_parser_context *ctx = (http_parser_context *) parser->data;

	ctx->client->state = DONE;
	return 0;
}

GIT_INLINE(int) stream_write(
	git_http_server *server,
	const char *data,
	size_t len)
{
	git_trace(GIT_TRACE_TRACE,
	          "Sending request:\n%.*s", (int)len, data);

	return git_stream__write_full(server->stream, data, len, 0);
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
GIT_INLINE(int) client_write_request(git_http_client *client)
{
	git_stream *stream = client->current_server == PROXY ?
		             client->proxy.stream : client->server.stream;

	git_trace(GIT_TRACE_TRACE,
	          "Sending request:\n%.*s",
	          (int)client->request_msg.size, client->request_msg.ptr);

	return git_stream__write_full(stream,
				      client->request_msg.ptr,
	                              client->request_msg.size,
				      0);
}

448
static const char *name_for_method(git_http_method method)
449 450 451 452 453 454
{
	switch (method) {
	case GIT_HTTP_METHOD_GET:
		return "GET";
	case GIT_HTTP_METHOD_POST:
		return "POST";
455 456
	case GIT_HTTP_METHOD_CONNECT:
		return "CONNECT";
457 458 459 460 461
	}

	return NULL;
}

462 463 464 465 466 467 468 469
/*
 * Find the scheme that is suitable for the given credentials, based on the
 * server's auth challenges.
 */
static bool best_scheme_and_challenge(
	git_http_auth_scheme **scheme_out,
	const char **challenge_out,
	git_vector *challenges,
470
	git_credential *credentials)
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
{
	const char *challenge;
	size_t i, j;

	for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) {
		git_vector_foreach(challenges, j, challenge) {
			git_http_auth_scheme *scheme = &auth_schemes[i];

			if (challenge_matches_scheme(challenge, scheme) &&
			    (scheme->credtypes & credentials->credtype)) {
				*scheme_out = scheme;
				*challenge_out = challenge;
				return true;
			}
		}
	}

	return false;
}

/*
 * Find the challenge from the server for our current auth context.
 */
static const char *challenge_for_context(
	git_vector *challenges,
	git_http_auth_context *auth_ctx)
{
	const char *challenge;
	size_t i, j;

	for (i = 0; i < ARRAY_SIZE(auth_schemes); i++) {
		if (auth_schemes[i].type == auth_ctx->type) {
			git_http_auth_scheme *scheme = &auth_schemes[i];

			git_vector_foreach(challenges, j, challenge) {
				if (challenge_matches_scheme(challenge, scheme))
					return challenge;
			}
		}
	}

	return NULL;
}

static const char *init_auth_context(
	git_http_server *server,
	git_vector *challenges,
518
	git_credential *credentials)
519 520 521 522 523 524
{
	git_http_auth_scheme *scheme;
	const char *challenge;
	int error;

	if (!best_scheme_and_challenge(&scheme, &challenge, challenges, credentials)) {
525
		git_error_set(GIT_ERROR_HTTP, "could not find appropriate mechanism for credentials");
526 527 528 529 530 531
		return NULL;
	}

	error = scheme->init_context(&server->auth_context, &server->url);

	if (error == GIT_PASSTHROUGH) {
532
		git_error_set(GIT_ERROR_HTTP, "'%s' authentication is not supported", scheme->name);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
		return NULL;
	}

	return challenge;
}

static void free_auth_context(git_http_server *server)
{
	if (!server->auth_context)
		return;

	if (server->auth_context->free)
		server->auth_context->free(server->auth_context);

	server->auth_context = NULL;
}

static int apply_credentials(
551
	git_str *buf,
552 553
	git_http_server *server,
	const char *header_name,
554
	git_credential *credentials)
555 556 557 558
{
	git_http_auth_context *auth = server->auth_context;
	git_vector *challenges = &server->auth_challenges;
	const char *challenge;
559
	git_str token = GIT_STR_INIT;
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
	int error = 0;

	/* We've started a new request without creds; free the context. */
	if (auth && !credentials) {
		free_auth_context(server);
		return 0;
	}

	/* We haven't authenticated, nor were we asked to.  Nothing to do. */
	if (!auth && !git_vector_length(challenges))
		return 0;

	if (!auth) {
		challenge = init_auth_context(server, challenges, credentials);
		auth = server->auth_context;

		if (!challenge || !auth) {
			error = -1;
			goto done;
		}
	} else if (auth->set_challenge) {
		challenge = challenge_for_context(challenges, auth);
	}

	if (auth->set_challenge && challenge &&
	    (error = auth->set_challenge(auth, challenge)) < 0)
		goto done;

	if ((error = auth->next_token(&token, auth, credentials)) < 0)
		goto done;

	if (auth->is_complete && auth->is_complete(auth)) {
		/*
		 * If we're done with an auth mechanism with connection affinity,
		 * we don't need to send any more headers and can dispose the context.
		 */
		if (auth->connection_affinity)
			free_auth_context(server);
	} else if (!token.size) {
599 600
		git_error_set(GIT_ERROR_HTTP, "failed to respond to authentication challenge");
		error = GIT_EAUTH;
601 602 603 604
		goto done;
	}

	if (token.size > 0)
605
		error = git_str_printf(buf, "%s: %s\r\n", header_name, token.ptr);
606 607

done:
608
	git_str_dispose(&token);
609 610 611 612
	return error;
}

GIT_INLINE(int) apply_server_credentials(
613
	git_str *buf,
614 615 616 617 618 619 620 621 622 623
	git_http_client *client,
	git_http_request *request)
{
	return apply_credentials(buf,
	                         &client->server,
	                         "Authorization",
	                         request->credentials);
}

GIT_INLINE(int) apply_proxy_credentials(
624
	git_str *buf,
625 626 627 628 629 630 631 632 633
	git_http_client *client,
	git_http_request *request)
{
	return apply_credentials(buf,
	                         &client->proxy,
	                         "Proxy-Authorization",
	                         request->proxy_credentials);
}

634
static int puts_host_and_port(git_str *buf, git_net_url *url, bool force_port)
635 636 637 638
{
	bool ipv6 = git_net_url_is_ipv6(url);

	if (ipv6)
639
		git_str_putc(buf, '[');
640

641
	git_str_puts(buf, url->host);
642 643

	if (ipv6)
644
		git_str_putc(buf, ']');
645 646

	if (force_port || !git_net_url_is_default_port(url)) {
647 648
		git_str_putc(buf, ':');
		git_str_puts(buf, url->port);
649 650
	}

651
	return git_str_oom(buf) ? -1 : 0;
652 653
}

654 655 656 657
static int generate_connect_request(
	git_http_client *client,
	git_http_request *request)
{
658
	git_str *buf;
659 660
	int error;

661
	git_str_clear(&client->request_msg);
662 663
	buf = &client->request_msg;

664
	git_str_puts(buf, "CONNECT ");
665
	puts_host_and_port(buf, &client->server.url, true);
666
	git_str_puts(buf, " HTTP/1.1\r\n");
667

668
	git_str_puts(buf, "User-Agent: ");
669
	git_http__user_agent(buf);
670
	git_str_puts(buf, "\r\n");
671

672
	git_str_puts(buf, "Host: ");
673
	puts_host_and_port(buf, &client->server.url, true);
674
	git_str_puts(buf, "\r\n");
675 676 677 678

	if ((error = apply_proxy_credentials(buf, client, request) < 0))
		return -1;

679
	git_str_puts(buf, "\r\n");
680

681
	return git_str_oom(buf) ? -1 : 0;
682 683
}

684 685 686 687 688
static bool use_connect_proxy(git_http_client *client)
{
    return client->proxy.url.host && !strcmp(client->server.url.scheme, "https");
}

689 690 691 692
static int generate_request(
	git_http_client *client,
	git_http_request *request)
{
693
	git_str *buf;
694
	size_t i;
695
	int error;
696

697 698
	GIT_ASSERT_ARG(client);
	GIT_ASSERT_ARG(request);
699

700
	git_str_clear(&client->request_msg);
701 702
	buf = &client->request_msg;

703
	/* GET|POST path HTTP/1.1 */
704 705
	git_str_puts(buf, name_for_method(request->method));
	git_str_putc(buf, ' ');
706

707 708 709 710 711
	if (request->proxy && strcmp(request->url->scheme, "https"))
		git_net_url_fmt(buf, request->url);
	else
		git_net_url_fmt_path(buf, request->url);

712
	git_str_puts(buf, " HTTP/1.1\r\n");
713

714
	git_str_puts(buf, "User-Agent: ");
715
	git_http__user_agent(buf);
716
	git_str_puts(buf, "\r\n");
717

718
	git_str_puts(buf, "Host: ");
719
	puts_host_and_port(buf, request->url, false);
720
	git_str_puts(buf, "\r\n");
721 722

	if (request->accept)
723
		git_str_printf(buf, "Accept: %s\r\n", request->accept);
724
	else
725
		git_str_puts(buf, "Accept: */*\r\n");
726 727

	if (request->content_type)
728
		git_str_printf(buf, "Content-Type: %s\r\n",
729 730 731
			request->content_type);

	if (request->chunked)
732
		git_str_puts(buf, "Transfer-Encoding: chunked\r\n");
733 734

	if (request->content_length > 0)
735
		git_str_printf(buf, "Content-Length: %"PRIuZ "\r\n",
736 737 738
			request->content_length);

	if (request->expect_continue)
739
		git_str_printf(buf, "Expect: 100-continue\r\n");
740

741
	if ((error = apply_server_credentials(buf, client, request)) < 0 ||
742 743
	    (!use_connect_proxy(client) &&
			(error = apply_proxy_credentials(buf, client, request)) < 0))
744 745
		return error;

746 747 748 749 750
	if (request->custom_headers) {
		for (i = 0; i < request->custom_headers->count; i++) {
			const char *hdr = request->custom_headers->strings[i];

			if (hdr)
751
				git_str_printf(buf, "%s\r\n", hdr);
752 753 754
		}
	}

755
	git_str_puts(buf, "\r\n");
756

757
	if (git_str_oom(buf))
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
		return -1;

	return 0;
}

static int check_certificate(
	git_stream *stream,
	git_net_url *url,
	int is_valid,
	git_transport_certificate_check_cb cert_cb,
	void *cert_cb_payload)
{
	git_cert *cert;
	git_error_state last_error = {0};
	int error;

	if ((error = git_stream_certificate(&cert, stream)) < 0)
		return error;

	git_error_state_capture(&last_error, GIT_ECERTIFICATE);

	error = cert_cb(cert, is_valid, url->host, cert_cb_payload);

	if (error == GIT_PASSTHROUGH && !is_valid)
		return git_error_state_restore(&last_error);
	else if (error == GIT_PASSTHROUGH)
		error = 0;
	else if (error && !git_error_last())
786
		git_error_set(GIT_ERROR_HTTP,
787 788 789 790 791 792
		              "user rejected certificate for %s", url->host);

	git_error_state_free(&last_error);
	return error;
}

793 794
static int server_connect_stream(
	git_http_server *server,
795 796 797 798 799
	git_transport_certificate_check_cb cert_cb,
	void *cb_payload)
{
	int error;

800
	GIT_ERROR_CHECK_VERSION(server->stream, GIT_STREAM_VERSION, "git_stream");
801

802
	error = git_stream_connect(server->stream);
803 804 805 806

	if (error && error != GIT_ECERTIFICATE)
		return error;

807 808
	if (git_stream_is_encrypted(server->stream) && cert_cb != NULL)
		error = check_certificate(server->stream, &server->url, !error,
809 810 811 812 813
		                          cert_cb, cb_payload);

	return error;
}

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
static void reset_auth_connection(git_http_server *server)
{
	/*
	 * If we've authenticated and we're doing "normal"
	 * authentication with a request affinity (Basic, Digest)
	 * then we want to _keep_ our context, since authentication
	 * survives even through non-keep-alive connections.  If
	 * we've authenticated and we're doing connection-based
	 * authentication (NTLM, Negotiate) - indicated by the presence
	 * of an `is_complete` callback - then we need to restart
	 * authentication on a new connection.
	 */

	if (server->auth_context &&
	    server->auth_context->connection_affinity)
		free_auth_context(server);
}

832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
/*
 * Updates the server data structure with the new URL; returns 1 if the server
 * has changed and we need to reconnect, returns 0 otherwise.
 */
GIT_INLINE(int) server_setup_from_url(
	git_http_server *server,
	git_net_url *url)
{
	if (!server->url.scheme || strcmp(server->url.scheme, url->scheme) ||
	    !server->url.host || strcmp(server->url.host, url->host) ||
	    !server->url.port || strcmp(server->url.port, url->port)) {
		git__free(server->url.scheme);
		git__free(server->url.host);
		git__free(server->url.port);

		server->url.scheme = git__strdup(url->scheme);
		GIT_ERROR_CHECK_ALLOC(server->url.scheme);

		server->url.host = git__strdup(url->host);
		GIT_ERROR_CHECK_ALLOC(server->url.host);

		server->url.port = git__strdup(url->port);
		GIT_ERROR_CHECK_ALLOC(server->url.port);

		return 1;
	}

	return 0;
}

862 863 864 865 866 867
static void reset_parser(git_http_client *client)
{
	http_parser_init(&client->parser, HTTP_RESPONSE);
}

static int setup_hosts(
868 869 870 871 872
	git_http_client *client,
	git_http_request *request)
{
	int ret, diff = 0;

873 874 875 876
	GIT_ASSERT_ARG(client);
	GIT_ASSERT_ARG(request);

	GIT_ASSERT(request->url);
877 878 879 880 881 882 883 884 885 886 887 888

	if ((ret = server_setup_from_url(&client->server, request->url)) < 0)
		return ret;

	diff |= ret;

	if (request->proxy &&
	    (ret = server_setup_from_url(&client->proxy, request->proxy)) < 0)
		return ret;

	diff |= ret;

889 890 891 892
	if (diff) {
		free_auth_context(&client->server);
		free_auth_context(&client->proxy);

893
		client->connected = 0;
894
	}
895 896 897 898

	return 0;
}

899
GIT_INLINE(int) server_create_stream(git_http_server *server)
900
{
901 902 903 904 905 906 907
	git_net_url *url = &server->url;

	if (strcasecmp(url->scheme, "https") == 0)
		return git_tls_stream_new(&server->stream, url->host, url->port);
	else if (strcasecmp(url->scheme, "http") == 0)
		return git_socket_stream_new(&server->stream, url->host, url->port);

908
	git_error_set(GIT_ERROR_HTTP, "unknown http scheme '%s'", url->scheme);
909
	return -1;
910 911
}

912 913 914 915 916 917 918 919 920 921 922
GIT_INLINE(void) save_early_response(
	git_http_client *client,
	git_http_response *response)
{
	/* Buffer the response so we can return it in read_response */
	client->state = HAS_EARLY_RESPONSE;

	memcpy(&client->early_response, response, sizeof(git_http_response));
	memset(response, 0, sizeof(git_http_response));
}

923 924 925
static int proxy_connect(
	git_http_client *client,
	git_http_request *request)
926
{
927
	git_http_response response = {0};
928 929
	int error;

930
	if (!client->proxy_connected || !client->keepalive) {
931
		git_trace(GIT_TRACE_DEBUG, "Connecting to proxy %s port %s",
932
			  client->proxy.url.host, client->proxy.url.port);
933

934 935 936 937 938
		if ((error = server_create_stream(&client->proxy)) < 0 ||
		    (error = server_connect_stream(&client->proxy,
			client->opts.proxy_certificate_check_cb,
			client->opts.proxy_certificate_check_payload)) < 0)
			goto done;
939

940
		client->proxy_connected = 1;
941 942
	}

943 944
	client->current_server = PROXY;
	client->state = SENDING_REQUEST;
945

946 947 948
	if ((error = generate_connect_request(client, request)) < 0 ||
	    (error = client_write_request(client)) < 0)
		goto done;
949

950
	client->state = SENT_REQUEST;
951

952 953 954
	if ((error = git_http_client_read_response(&response, client)) < 0 ||
	    (error = git_http_client_skip_body(client)) < 0)
		goto done;
955

956
	GIT_ASSERT(client->state == DONE);
957

958
	if (response.status == GIT_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
959
		save_early_response(client, &response);
960 961 962

		error = GIT_RETRY;
		goto done;
963
	} else if (response.status != GIT_HTTP_STATUS_OK) {
964
		git_error_set(GIT_ERROR_HTTP, "proxy returned unexpected status: %d", response.status);
965
		error = -1;
966
		goto done;
967 968
	}

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
	reset_parser(client);
	client->state = NONE;

done:
	git_http_response_dispose(&response);
	return error;
}

static int server_connect(git_http_client *client)
{
	git_net_url *url = &client->server.url;
	git_transport_certificate_check_cb cert_cb;
	void *cert_payload;
	int error;

	client->current_server = SERVER;

	if (client->proxy.stream)
		error = git_tls_stream_wrap(&client->server.stream, client->proxy.stream, url->host);
	else
		error = server_create_stream(&client->server);

991
	if (error < 0)
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
		goto done;

	cert_cb = client->opts.server_certificate_check_cb;
	cert_payload = client->opts.server_certificate_check_payload;

	error = server_connect_stream(&client->server, cert_cb, cert_payload);

done:
	return error;
}

GIT_INLINE(void) close_stream(git_http_server *server)
{
	if (server->stream) {
		git_stream_close(server->stream);
		git_stream_free(server->stream);
		server->stream = NULL;
	}
}

static int http_client_connect(
	git_http_client *client,
	git_http_request *request)
{
	bool use_proxy = false;
	int error;

	if ((error = setup_hosts(client, request)) < 0)
1020 1021
		goto on_error;

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	/* We're connected to our destination server; no need to reconnect */
	if (client->connected && client->keepalive &&
	    (client->state == NONE || client->state == DONE))
		return 0;

	client->connected = 0;
	client->request_count = 0;

	close_stream(&client->server);
	reset_auth_connection(&client->server);

	reset_parser(client);

	/* Reconnect to the proxy if necessary. */
1036
	use_proxy = use_connect_proxy(client);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

	if (use_proxy) {
		if (!client->proxy_connected || !client->keepalive ||
		    (client->state != NONE && client->state != DONE)) {
			close_stream(&client->proxy);
			reset_auth_connection(&client->proxy);

			client->proxy_connected = 0;
		}

		if ((error = proxy_connect(client, request)) < 0)
			goto on_error;
	}

1051
	git_trace(GIT_TRACE_DEBUG, "Connecting to remote %s port %s",
1052 1053 1054
	          client->server.url.host, client->server.url.port);

	if ((error = server_connect(client)) < 0)
1055 1056 1057
		goto on_error;

	client->connected = 1;
1058
	return error;
1059 1060

on_error:
1061 1062
	if (error != GIT_RETRY)
		close_stream(&client->proxy);
1063

1064
	close_stream(&client->server);
1065 1066 1067 1068 1069
	return error;
}

GIT_INLINE(int) client_read(git_http_client *client)
{
1070
	http_parser_context *parser_context = client->parser.data;
1071
	git_stream *stream;
1072 1073 1074 1075
	char *buf = client->read_buf.ptr + client->read_buf.size;
	size_t max_len;
	ssize_t read_len;

1076 1077 1078
	stream = client->current_server == PROXY ?
		client->proxy.stream : client->server.stream;

1079
	/*
1080
	 * We use a git_str for convenience, but statically allocate it and
1081 1082 1083 1084 1085 1086
	 * don't resize.  Limit our consumption to INT_MAX since calling
	 * functions use an int return type to return number of bytes read.
	 */
	max_len = client->read_buf.asize - client->read_buf.size;
	max_len = min(max_len, INT_MAX);

1087 1088 1089
	if (parser_context->output_size)
		max_len = min(max_len, parser_context->output_size);

1090
	if (max_len == 0) {
1091
		git_error_set(GIT_ERROR_HTTP, "no room in output buffer");
1092 1093 1094
		return -1;
	}

1095
	read_len = git_stream_read(stream, buf, max_len);
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

	if (read_len >= 0) {
		client->read_buf.size += read_len;

		git_trace(GIT_TRACE_TRACE, "Received:\n%.*s",
		          (int)read_len, buf);
	}

	return (int)read_len;
}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
static bool parser_settings_initialized;
static http_parser_settings parser_settings;

GIT_INLINE(http_parser_settings *) http_client_parser_settings(void)
{
	if (!parser_settings_initialized) {
		parser_settings.on_header_field = on_header_field;
		parser_settings.on_header_value = on_header_value;
		parser_settings.on_headers_complete = on_headers_complete;
		parser_settings.on_body = on_body;
		parser_settings.on_message_complete = on_message_complete;

		parser_settings_initialized = true;
	}

	return &parser_settings;
}

1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
GIT_INLINE(int) client_read_and_parse(git_http_client *client)
{
	http_parser *parser = &client->parser;
	http_parser_context *ctx = (http_parser_context *) parser->data;
	unsigned char http_errno;
	int read_len;
	size_t parsed_len;

	/*
	 * If we have data in our read buffer, that means we stopped early
	 * when parsing headers.  Use the data in the read buffer instead of
	 * reading more from the socket.
	 */
	if (!client->read_buf.size && (read_len = client_read(client)) < 0)
		return read_len;

	parsed_len = http_parser_execute(parser,
		http_client_parser_settings(),
		client->read_buf.ptr,
		client->read_buf.size);
	http_errno = client->parser.http_errno;

	if (parsed_len > INT_MAX) {
1148
		git_error_set(GIT_ERROR_HTTP, "unexpectedly large parse");
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
		return -1;
	}

	if (ctx->parse_status == PARSE_STATUS_ERROR) {
		client->connected = 0;
		return ctx->error ? ctx->error : -1;
	}

	/*
	 * If we finished reading the headers or body, we paused parsing.
	 * Otherwise the parser will start filling the body, or even parse
	 * a new response if the server pipelined us multiple responses.
	 * (This can happen in response to an expect/continue request,
	 * where the server gives you a 100 and 200 simultaneously.)
	 */
	if (http_errno == HPE_PAUSED) {
		/*
		 * http-parser has a "feature" where it will not deliver the
		 * final byte when paused in a callback.  Consume that byte.
		 * https://github.com/nodejs/http-parser/issues/97
		 */
1170
		GIT_ASSERT(client->read_buf.size > parsed_len);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181

		http_parser_pause(parser, 0);

		parsed_len += http_parser_execute(parser,
			http_client_parser_settings(),
			client->read_buf.ptr + parsed_len,
			1);
	}

	/* Most failures will be reported in http_errno */
	else if (parser->http_errno != HPE_OK) {
1182
		git_error_set(GIT_ERROR_HTTP, "http parser error: %s",
1183 1184 1185 1186 1187 1188
		              http_errno_description(http_errno));
		return -1;
	}

	/* Otherwise we should have consumed the entire buffer. */
	else if (parsed_len != client->read_buf.size) {
1189
		git_error_set(GIT_ERROR_HTTP,
1190 1191 1192 1193 1194 1195 1196
		              "http parser did not consume entire buffer: %s",
			      http_errno_description(http_errno));
		return -1;
	}

	/* recv returned 0, the server hung up on us */
	else if (!parsed_len) {
1197
		git_error_set(GIT_ERROR_HTTP, "unexpected EOF");
1198 1199 1200
		return -1;
	}

1201
	git_str_consume_bytes(&client->read_buf, parsed_len);
1202 1203 1204 1205

	return (int)parsed_len;
}

1206 1207 1208
/*
 * See if we've consumed the entire response body.  If the client was
 * reading the body but did not consume it entirely, it's possible that
1209 1210 1211 1212 1213
 * they knew that the stream had finished (in a git response, seeing a
 * final flush) and stopped reading.  But if the response was chunked,
 * we may have not consumed the final chunk marker.  Consume it to
 * ensure that we don't have it waiting in our socket.  If there's
 * more than just a chunk marker, close the connection.
1214 1215 1216 1217 1218 1219 1220 1221
 */
static void complete_response_body(git_http_client *client)
{
	http_parser_context parser_context = {0};

	/* If we're not keeping alive, don't bother. */
	if (!client->keepalive) {
		client->connected = 0;
1222
		goto done;
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	}

	parser_context.client = client;
	client->parser.data = &parser_context;

	/* If there was an error, just close the connection. */
	if (client_read_and_parse(client) < 0 ||
	    parser_context.error != HPE_OK ||
	    (parser_context.parse_status != PARSE_STATUS_OK &&
	     parser_context.parse_status != PARSE_STATUS_NO_OUTPUT)) {
		git_error_clear();
		client->connected = 0;
	}
1236 1237

done:
1238
	git_str_clear(&client->read_buf);
1239 1240 1241 1242 1243 1244
}

int git_http_client_send_request(
	git_http_client *client,
	git_http_request *request)
{
1245
	git_http_response response = {0};
1246 1247
	int error = -1;

1248 1249
	GIT_ASSERT_ARG(client);
	GIT_ASSERT_ARG(request);
1250 1251 1252 1253 1254

	/* If the client did not finish reading, clean up the stream. */
	if (client->state == READING_BODY)
		complete_response_body(client);

1255 1256 1257
	/* If we're waiting for proxy auth, don't sending more requests. */
	if (client->state == HAS_EARLY_RESPONSE)
		return 0;
1258 1259

	if (git_trace_level() >= GIT_TRACE_DEBUG) {
1260
		git_str url = GIT_STR_INIT;
1261 1262 1263 1264
		git_net_url_fmt(&url, request->url);
		git_trace(GIT_TRACE_DEBUG, "Sending %s request to %s",
		          name_for_method(request->method),
		          url.ptr ? url.ptr : "<invalid>");
1265
		git_str_dispose(&url);
1266 1267
	}

1268
	if ((error = http_client_connect(client, request)) < 0 ||
1269
	    (error = generate_request(client, request)) < 0 ||
1270
	    (error = client_write_request(client)) < 0)
1271 1272
		goto done;

1273 1274 1275 1276 1277 1278 1279 1280 1281
	client->state = SENT_REQUEST;

	if (request->expect_continue) {
		if ((error = git_http_client_read_response(&response, client)) < 0 ||
		    (error = git_http_client_skip_body(client)) < 0)
			goto done;

		error = 0;

1282
		if (response.status != GIT_HTTP_STATUS_CONTINUE) {
1283 1284 1285 1286 1287
			save_early_response(client, &response);
			goto done;
		}
	}

1288 1289 1290 1291 1292 1293 1294
	if (request->content_length || request->chunked) {
		client->state = SENDING_BODY;
		client->request_body_len = request->content_length;
		client->request_body_remain = request->content_length;
		client->request_chunked = request->chunked;
	}

1295 1296
	reset_parser(client);

1297
done:
1298 1299 1300
	if (error == GIT_RETRY)
		error = 0;

1301
	git_http_response_dispose(&response);
1302 1303 1304
	return error;
}

1305 1306 1307 1308 1309 1310
bool git_http_client_has_response(git_http_client *client)
{
	return (client->state == HAS_EARLY_RESPONSE ||
	        client->state > SENT_REQUEST);
}

1311 1312 1313 1314 1315 1316
int git_http_client_send_body(
	git_http_client *client,
	const char *buffer,
	size_t buffer_len)
{
	git_http_server *server;
1317
	git_str hdr = GIT_STR_INIT;
1318 1319
	int error;

1320
	GIT_ASSERT_ARG(client);
1321 1322 1323 1324 1325 1326

	/* If we're waiting for proxy auth, don't sending more requests. */
	if (client->state == HAS_EARLY_RESPONSE)
		return 0;

	if (client->state != SENDING_BODY) {
1327
		git_error_set(GIT_ERROR_HTTP, "client is in invalid state");
1328 1329
		return -1;
	}
1330 1331 1332 1333 1334 1335 1336

	if (!buffer_len)
		return 0;

	server = &client->server;

	if (client->request_body_len) {
1337
		GIT_ASSERT(buffer_len <= client->request_body_remain);
1338 1339 1340 1341 1342 1343

		if ((error = stream_write(server, buffer, buffer_len)) < 0)
			goto done;

		client->request_body_remain -= buffer_len;
	} else {
1344
		if ((error = git_str_printf(&hdr, "%" PRIxZ "\r\n", buffer_len)) < 0 ||
1345 1346 1347 1348 1349 1350 1351
		    (error = stream_write(server, hdr.ptr, hdr.size)) < 0 ||
		    (error = stream_write(server, buffer, buffer_len)) < 0 ||
		    (error = stream_write(server, "\r\n", 2)) < 0)
			goto done;
	}

done:
1352
	git_str_dispose(&hdr);
1353 1354 1355 1356 1357 1358 1359
	return error;
}

static int complete_request(git_http_client *client)
{
	int error = 0;

1360 1361
	GIT_ASSERT_ARG(client);
	GIT_ASSERT(client->state == SENDING_BODY);
1362 1363

	if (client->request_body_len && client->request_body_remain) {
1364
		git_error_set(GIT_ERROR_HTTP, "truncated write");
1365 1366 1367 1368 1369
		error = -1;
	} else if (client->request_chunked) {
		error = stream_write(&client->server, "0\r\n\r\n", 5);
	}

1370
	client->state = SENT_REQUEST;
1371 1372 1373
	return error;
}

1374 1375 1376 1377 1378 1379 1380
int git_http_client_read_response(
	git_http_response *response,
	git_http_client *client)
{
	http_parser_context parser_context = {0};
	int error;

1381 1382
	GIT_ASSERT_ARG(response);
	GIT_ASSERT_ARG(client);
1383 1384

	if (client->state == SENDING_BODY) {
1385 1386
		if ((error = complete_request(client)) < 0)
			goto done;
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
	}

	if (client->state == HAS_EARLY_RESPONSE) {
		memcpy(response, &client->early_response, sizeof(git_http_response));
		memset(&client->early_response, 0, sizeof(git_http_response));
		client->state = DONE;
		return 0;
	}

	if (client->state != SENT_REQUEST) {
1397
		git_error_set(GIT_ERROR_HTTP, "client is in invalid state");
1398 1399
		error = -1;
		goto done;
1400 1401
	}

1402 1403
	git_http_response_dispose(response);

1404 1405 1406 1407 1408
	if (client->current_server == PROXY) {
		git_vector_free_deep(&client->proxy.auth_challenges);
	} else if(client->current_server == SERVER) {
		git_vector_free_deep(&client->server.auth_challenges);
	}
1409

1410
	client->state = READING_RESPONSE;
1411
	client->keepalive = 0;
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
	client->parser.data = &parser_context;

	parser_context.client = client;
	parser_context.response = response;

	while (client->state == READING_RESPONSE) {
		if ((error = client_read_and_parse(client)) < 0)
			goto done;
	}

1422
	GIT_ASSERT(client->state == READING_BODY || client->state == DONE);
1423 1424

done:
1425 1426
	git_str_dispose(&parser_context.parse_header_name);
	git_str_dispose(&parser_context.parse_header_value);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442

	return error;
}

int git_http_client_read_body(
	git_http_client *client,
	char *buffer,
	size_t buffer_size)
{
	http_parser_context parser_context = {0};
	int error = 0;

	if (client->state == DONE)
		return 0;

	if (client->state != READING_BODY) {
1443
		git_error_set(GIT_ERROR_HTTP, "client is in invalid state");
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
		return -1;
	}

	/*
	 * Now we'll read from the socket and http_parser will pipeline the
	 * data directly to the client.
	 */

	parser_context.client = client;
	parser_context.output_buf = buffer;
	parser_context.output_size = buffer_size;

	client->parser.data = &parser_context;

	/*
1459 1460 1461 1462 1463
	 * Clients expect to get a non-zero amount of data from us,
	 * so we either block until we have data to return, until we
	 * hit EOF or there's an error.  Do this in a loop, since we
	 * may end up reading only some stream metadata (like chunk
	 * information).
1464 1465 1466 1467 1468 1469
	 */
	while (!parser_context.output_written) {
		error = client_read_and_parse(client);

		if (error <= 0)
			goto done;
1470 1471 1472

		if (client->state == DONE)
			break;
1473 1474
	}

1475
	GIT_ASSERT(parser_context.output_written <= INT_MAX);
1476 1477 1478 1479 1480 1481 1482 1483 1484
	error = (int)parser_context.output_written;

done:
	if (error < 0)
		client->connected = 0;

	return error;
}

1485 1486 1487 1488 1489 1490 1491 1492 1493
int git_http_client_skip_body(git_http_client *client)
{
	http_parser_context parser_context = {0};
	int error;

	if (client->state == DONE)
		return 0;

	if (client->state != READING_BODY) {
1494
		git_error_set(GIT_ERROR_HTTP, "client is in invalid state");
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
		return -1;
	}

	parser_context.client = client;
	client->parser.data = &parser_context;

	do {
		error = client_read_and_parse(client);

		if (parser_context.error != HPE_OK ||
		    (parser_context.parse_status != PARSE_STATUS_OK &&
		     parser_context.parse_status != PARSE_STATUS_NO_OUTPUT)) {
1507
			git_error_set(GIT_ERROR_HTTP,
1508 1509 1510
			              "unexpected data handled in callback");
			error = -1;
		}
1511
	} while (error >= 0 && client->state != DONE);
1512 1513 1514 1515 1516 1517 1518

	if (error < 0)
		client->connected = 0;

	return error;
}

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
/*
 * Create an http_client capable of communicating with the given remote
 * host.
 */
int git_http_client_new(
	git_http_client **out,
	git_http_client_options *opts)
{
	git_http_client *client;

1529
	GIT_ASSERT_ARG(out);
1530 1531 1532 1533

	client = git__calloc(1, sizeof(git_http_client));
	GIT_ERROR_CHECK_ALLOC(client);

1534
	git_str_init(&client->read_buf, GIT_READ_BUFFER_SIZE);
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	GIT_ERROR_CHECK_ALLOC(client->read_buf.ptr);

	if (opts)
		memcpy(&client->opts, opts, sizeof(git_http_client_options));

	*out = client;
	return 0;
}

GIT_INLINE(void) http_server_close(git_http_server *server)
{
	if (server->stream) {
		git_stream_close(server->stream);
		git_stream_free(server->stream);
		server->stream = NULL;
	}

	git_net_url_dispose(&server->url);
1553 1554 1555

	git_vector_free_deep(&server->auth_challenges);
	free_auth_context(server);
1556 1557 1558 1559 1560 1561 1562
}

static void http_client_close(git_http_client *client)
{
	http_server_close(&client->server);
	http_server_close(&client->proxy);

1563
	git_str_dispose(&client->request_msg);
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576

	client->state = 0;
	client->request_count = 0;
	client->connected = 0;
	client->keepalive = 0;
}

void git_http_client_free(git_http_client *client)
{
	if (!client)
		return;

	http_client_close(client);
1577
	git_str_dispose(&client->read_buf);
1578 1579
	git__free(client);
}