phttpget.c revision 150427
1/*- 2 * Copyright 2005 Colin Percival 3 * All rights reserved 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted providing that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 22 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 23 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 * POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27#include <sys/cdefs.h> 28__FBSDID("$FreeBSD: head/usr.sbin/portsnap/phttpget/phttpget.c 150427 2005-09-21 18:42:56Z cperciva $"); 29 30#include <sys/types.h> 31#include <sys/time.h> 32#include <sys/socket.h> 33 34#include <ctype.h> 35#include <err.h> 36#include <errno.h> 37#include <fcntl.h> 38#include <limits.h> 39#include <netdb.h> 40#include <stdio.h> 41#include <stdlib.h> 42#include <string.h> 43#include <sysexits.h> 44#include <unistd.h> 45 46static const char * env_HTTP_PROXY; 47static const char * env_HTTP_USER_AGENT; 48static const char * proxyport; 49 50static struct timeval timo = { 15, 0}; 51 52static void 53usage(void) 54{ 55 56 fprintf(stderr, "usage: phttpget server [file ...]\n"); 57 exit(EX_USAGE); 58} 59 60static void 61readenv(void) 62{ 63 char * p; 64 65 env_HTTP_PROXY = getenv("HTTP_PROXY"); 66 if (env_HTTP_PROXY != NULL) { 67 if (strncmp(env_HTTP_PROXY, "http://", 7) == 0) 68 env_HTTP_PROXY += 7; 69 p = strchr(env_HTTP_PROXY, '/'); 70 if (p != NULL) 71 *p = 0; 72 p = strchr(env_HTTP_PROXY, ':'); 73 if (p != NULL) { 74 *p = 0; 75 proxyport = p + 1; 76 } else 77 proxyport = "3128"; 78 } 79 80 env_HTTP_USER_AGENT = getenv("HTTP_USER_AGENT"); 81 if (env_HTTP_USER_AGENT == NULL) 82 env_HTTP_USER_AGENT = "phttpget/0.1"; 83} 84 85static int 86makerequest(char ** buf, char * path, char * server, int connclose) 87{ 88 int buflen; 89 90 buflen = asprintf(buf, 91 "GET %s%s/%s HTTP/1.1\r\n" 92 "Host: %s\r\n" 93 "User-Agent: %s\r\n" 94 "%s" 95 "\r\n", 96 env_HTTP_PROXY ? "http://" : "", 97 env_HTTP_PROXY ? server : "", 98 path, server, env_HTTP_USER_AGENT, 99 connclose ? "Connection: Close\r\n" : ""); 100 if (buflen == -1) 101 err(1, "asprintf"); 102 return(buflen); 103} 104 105static int 106readln(int sd, char * resbuf, int * resbuflen, int * resbufpos) 107{ 108 ssize_t len; 109 110 while (strnstr(resbuf + *resbufpos, "\r\n", 111 *resbuflen - *resbufpos) == NULL) { 112 /* Move buffered data to the start of the buffer */ 113 if (*resbufpos != 0) { 114 memmove(resbuf, resbuf + *resbufpos, 115 *resbuflen - *resbufpos); 116 *resbuflen -= *resbufpos; 117 *resbufpos = 0; 118 } 119 120 /* If the buffer is full, complain */ 121 if (*resbuflen == BUFSIZ) 122 return -1; 123 124 /* Read more data into the buffer */ 125 len = recv(sd, resbuf + *resbuflen, BUFSIZ - *resbuflen, 0); 126 if ((len == -1) && (errno != EINTR)) 127 return -1; 128 129 if (len != -1) 130 *resbuflen += len; 131 } 132 133 return 0; 134} 135 136static int 137copybytes(int sd, int fd, off_t copylen, char * resbuf, int * resbuflen, 138 int * resbufpos) 139{ 140 ssize_t len; 141 142 while (copylen) { 143 /* Write data from resbuf to fd */ 144 len = *resbuflen - *resbufpos; 145 if (copylen < len) 146 len = copylen; 147 if (len > 0) { 148 if (fd != -1) 149 len = write(fd, resbuf + *resbufpos, len); 150 if (len == -1) 151 err(1, "write"); 152 *resbufpos += len; 153 copylen -= len; 154 continue; 155 } 156 157 /* Read more data into buffer */ 158 len = recv(sd, resbuf, BUFSIZ, 0); 159 if (len == -1) { 160 if (errno == EINTR) 161 continue; 162 return -1; 163 } else if (len == 0) { 164 return -2; 165 } else { 166 *resbuflen = len; 167 *resbufpos = 0; 168 } 169 } 170 171 return 0; 172} 173 174int 175main(int argc, char *argv[]) 176{ 177 struct addrinfo hints; /* Hints to getaddrinfo */ 178 struct addrinfo *res; /* Pointer to server address being used */ 179 struct addrinfo *res0; /* Pointer to server addresses */ 180 char * resbuf = NULL; /* Response buffer */ 181 int resbufpos = 0; /* Response buffer position */ 182 int resbuflen = 0; /* Response buffer length */ 183 char * eolp; /* Pointer to "\r\n" within resbuf */ 184 char * hln; /* Pointer within header line */ 185 char * servername; /* Name of server */ 186 char * fname = NULL; /* Name of downloaded file */ 187 char * reqbuf = NULL; /* Request buffer */ 188 int reqbufpos = 0; /* Request buffer position */ 189 int reqbuflen = 0; /* Request buffer length */ 190 ssize_t len; /* Length sent or received */ 191 int nreq = 0; /* Number of next request to send */ 192 int nres = 0; /* Number of next reply to receive */ 193 int pipelined = 0; /* != 0 if connection in pipelined mode. */ 194 int sd = -1; /* Socket descriptor */ 195 int sdflags = 0; /* Flags on the socket sd */ 196 int fd = -1; /* Descriptor for download target file */ 197 int error; /* Error code */ 198 int statuscode; /* HTTP Status code */ 199 off_t contentlength; /* Value from Content-Length header */ 200 int chunked; /* != if transfer-encoding is chunked */ 201 off_t clen; /* Chunk length */ 202 int firstreq = 0; /* # of first request for this connection */ 203 204 /* Check that the arguments are sensible */ 205 if (argc < 2) 206 usage(); 207 208 /* Read important environment variables */ 209 readenv(); 210 211 /* Get server name and adjust arg[cv] to point at file names */ 212 servername = argv[1]; 213 argv += 2; 214 argc -= 2; 215 216 /* Allocate response buffer */ 217 resbuf = malloc(BUFSIZ); 218 if (resbuf == NULL) 219 err(1, "malloc"); 220 221 /* Look up server */ 222 memset(&hints, 0, sizeof(hints)); 223 hints.ai_family = PF_UNSPEC; 224 hints.ai_socktype = SOCK_STREAM; 225 error = getaddrinfo(env_HTTP_PROXY ? env_HTTP_PROXY : servername, 226 env_HTTP_PROXY ? proxyport : "http", &hints, &res0); 227 if (error) 228 errx(1, "%s: host = %s, port = %s", 229 env_HTTP_PROXY ? env_HTTP_PROXY : servername, 230 env_HTTP_PROXY ? proxyport : "http", 231 gai_strerror(error)); 232 if (res0 == NULL) 233 errx(1, "could not look up %s", servername); 234 res = res0; 235 236 /* Do the fetching */ 237 while (nres < argc) { 238 /* Make sure we have a connected socket */ 239 for (; sd == -1; res = res->ai_next) { 240 /* No addresses left to try :-( */ 241 if (res == NULL) 242 errx(1, "Could not connect to %s", servername); 243 244 /* Create a socket... */ 245 sd = socket(res->ai_family, res->ai_socktype, 246 res->ai_protocol); 247 if (sd == -1) 248 continue; 249 250 /* ... set 15-second timeouts ... */ 251 setsockopt(sd, SOL_SOCKET, SO_SNDTIMEO, 252 (void *)&timo, (socklen_t)sizeof(timo)); 253 setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, 254 (void *)&timo, (socklen_t)sizeof(timo)); 255 256 /* ... and connect to the server. */ 257 if(connect(sd, res->ai_addr, res->ai_addrlen)) { 258 close(sd); 259 sd = -1; 260 continue; 261 } 262 263 firstreq = nres; 264 } 265 266 /* 267 * If in pipelined HTTP mode, put socket into non-blocking 268 * mode, since we're probably going to want to try to send 269 * several HTTP requests. 270 */ 271 if (pipelined) { 272 sdflags = fcntl(sd, F_GETFL); 273 if (fcntl(sd, F_SETFL, sdflags | O_NONBLOCK) == -1) 274 err(1, "fcntl"); 275 } 276 277 /* Construct requests and/or send them without blocking */ 278 while ((nreq < argc) && ((reqbuf == NULL) || pipelined)) { 279 /* If not in the middle of a request, make one */ 280 if (reqbuf == NULL) { 281 reqbuflen = makerequest(&reqbuf, argv[nreq], 282 servername, (nreq == argc - 1)); 283 reqbufpos = 0; 284 } 285 286 /* If in pipelined mode, try to send the request */ 287 if (pipelined) { 288 while (reqbufpos < reqbuflen) { 289 len = send(sd, reqbuf + reqbufpos, 290 reqbuflen - reqbufpos, 0); 291 if (len == -1) 292 break; 293 reqbufpos += len; 294 } 295 if (reqbufpos < reqbuflen) { 296 if (errno != EAGAIN) 297 goto conndied; 298 break; 299 } else { 300 free(reqbuf); 301 reqbuf = NULL; 302 nreq++; 303 } 304 } 305 } 306 307 /* Put connection back into blocking mode */ 308 if (pipelined) { 309 if (fcntl(sd, F_SETFL, sdflags) == -1) 310 err(1, "fcntl"); 311 } 312 313 /* Do we need to blocking-send a request? */ 314 if (nres == nreq) { 315 while (reqbufpos < reqbuflen) { 316 len = send(sd, reqbuf + reqbufpos, 317 reqbuflen - reqbufpos, 0); 318 if (len == -1) 319 goto conndied; 320 reqbufpos += len; 321 } 322 free(reqbuf); 323 reqbuf = NULL; 324 nreq++; 325 } 326 327 /* Scan through the response processing headers. */ 328 statuscode = 0; 329 contentlength = -1; 330 chunked = 0; 331 do { 332 /* Get a header line */ 333 error = readln(sd, resbuf, &resbuflen, &resbufpos); 334 if (error) 335 goto conndied; 336 hln = resbuf + resbufpos; 337 eolp = strnstr(hln, "\r\n", resbuflen - resbufpos); 338 resbufpos = (eolp - resbuf) + 2; 339 *eolp = '\0'; 340 341 /* Make sure it doesn't contain a NUL character */ 342 if (strchr(hln, '\0') != eolp) 343 goto conndied; 344 345 if (statuscode == 0) { 346 /* The first line MUST be HTTP/1.x xxx ... */ 347 if ((strncmp(hln, "HTTP/1.", 7) != 0) || 348 ! isdigit(hln[7])) 349 goto conndied; 350 351 /* 352 * If the minor version number isn't zero, 353 * then we can assume that pipelining our 354 * requests is OK -- as long as we don't 355 * see a "Connection: close" line later 356 * and we either have a Content-Length or 357 * Transfer-Encoding: chunked header to 358 * tell us the length. 359 */ 360 if (hln[7] != '0') 361 pipelined = 1; 362 363 /* Skip over the minor version number */ 364 hln = strchr(hln + 7, ' '); 365 if (hln == NULL) 366 goto conndied; 367 else 368 hln++; 369 370 /* Read the status code */ 371 while (isdigit(*hln)) { 372 statuscode = statuscode * 10 + 373 *hln - '0'; 374 hln++; 375 } 376 377 if (statuscode < 100 || statuscode > 599) 378 goto conndied; 379 380 /* Ignore the rest of the line */ 381 continue; 382 } 383 384 /* Check for "Connection: close" header */ 385 if (strncmp(hln, "Connection:", 11) == 0) { 386 hln += 11; 387 if (strstr(hln, "close") != NULL) 388 pipelined = 0; 389 390 /* Next header... */ 391 continue; 392 } 393 394 /* Check for "Content-Length:" header */ 395 if (strncmp(hln, "Content-Length:", 15) == 0) { 396 hln += 15; 397 contentlength = 0; 398 399 /* Find the start of the length */ 400 while (!isdigit(*hln) && (*hln != '\0')) 401 hln++; 402 403 /* Compute the length */ 404 while (isdigit(*hln)) { 405 if (contentlength >= OFF_MAX / 10) { 406 /* Nasty people... */ 407 goto conndied; 408 } 409 contentlength = contentlength * 10 + 410 *hln - '0'; 411 hln++; 412 } 413 414 /* Next header... */ 415 continue; 416 } 417 418 /* Check for "Transfer-Encoding: chunked" header */ 419 if (strncmp(hln, "Transfer-Encoding:", 18) == 0) { 420 hln += 18; 421 if (strstr(hln, "chunked") != NULL) 422 chunked = 1; 423 424 /* Next header... */ 425 continue; 426 } 427 428 /* We blithely ignore any other header lines */ 429 430 /* No more header lines */ 431 if (strlen(hln) == 0) { 432 /* 433 * If the status code was 1xx, then there will 434 * be a real header later. Servers may emit 435 * 1xx header blocks at will, but since we 436 * don't expect one, we should just ignore it. 437 */ 438 if (100 <= statuscode && statuscode <= 199) { 439 statuscode = 0; 440 continue; 441 } 442 443 /* End of header; message body follows */ 444 break; 445 } 446 } while (1); 447 448 /* No message body for 204 or 304 */ 449 if (statuscode == 204 || statuscode == 304) { 450 nres++; 451 continue; 452 } 453 454 /* 455 * There should be a message body coming, but we only want 456 * to send it to a file if the status code is 200 457 */ 458 if (statuscode == 200) { 459 /* Generate a file name for the download */ 460 fname = strrchr(argv[nres], '/'); 461 if (fname == NULL) 462 fname = argv[nres]; 463 else 464 fname++; 465 if (strlen(fname) == 0) 466 errx(1, "Cannot obtain file name from %s\n", 467 argv[nres]); 468 469 fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY, 0644); 470 if (fd == -1) 471 errx(1, "open(%s)", fname); 472 }; 473 474 /* Read the message and send data to fd if appropriate */ 475 if (chunked) { 476 /* Handle a chunked-encoded entity */ 477 478 /* Read chunks */ 479 do { 480 error = readln(sd, resbuf, &resbuflen, 481 &resbufpos); 482 if (error) 483 goto conndied; 484 hln = resbuf + resbufpos; 485 eolp = strstr(hln, "\r\n"); 486 resbufpos = (eolp - resbuf) + 2; 487 488 clen = 0; 489 while (isxdigit(*hln)) { 490 if (clen >= OFF_MAX / 16) { 491 /* Nasty people... */ 492 goto conndied; 493 } 494 if (isdigit(*hln)) 495 clen = clen * 16 + *hln - '0'; 496 else 497 clen = clen * 16 + 10 + 498 tolower(*hln) - 'a'; 499 hln++; 500 } 501 502 error = copybytes(sd, fd, clen, resbuf, 503 &resbuflen, &resbufpos); 504 if (error) { 505 goto conndied; 506 } 507 } while (clen != 0); 508 509 /* Read trailer and final CRLF */ 510 do { 511 error = readln(sd, resbuf, &resbuflen, 512 &resbufpos); 513 if (error) 514 goto conndied; 515 hln = resbuf + resbufpos; 516 eolp = strstr(hln, "\r\n"); 517 resbufpos = (eolp - resbuf) + 2; 518 } while (hln != eolp); 519 } else if (contentlength != -1) { 520 error = copybytes(sd, fd, contentlength, resbuf, 521 &resbuflen, &resbufpos); 522 if (error) 523 goto conndied; 524 } else { 525 /* 526 * Not chunked, and no content length header. 527 * Read everything until the server closes the 528 * socket. 529 */ 530 error = copybytes(sd, fd, OFF_MAX, resbuf, 531 &resbuflen, &resbufpos); 532 if (error == -1) 533 goto conndied; 534 pipelined = 0; 535 } 536 537 if (fd != -1) { 538 close(fd); 539 fd = -1; 540 } 541 542 fprintf(stderr, "http://%s/%s: %d ", servername, argv[nres], 543 statuscode); 544 if (statuscode == 200) 545 fprintf(stderr, "OK\n"); 546 else if (statuscode < 300) 547 fprintf(stderr, "Successful (ignored)\n"); 548 else if (statuscode < 400) 549 fprintf(stderr, "Redirection (ignored)\n"); 550 else 551 fprintf(stderr, "Error (ignored)\n"); 552 553 /* We've finished this file! */ 554 nres++; 555 556 /* 557 * If necessary, clean up this connection so that we 558 * can start a new one. 559 */ 560 if (pipelined == 0) 561 goto cleanupconn; 562 continue; 563 564conndied: 565 /* 566 * Something went wrong -- our connection died, the server 567 * sent us garbage, etc. If this happened on the first 568 * request we sent over this connection, give up. Otherwise, 569 * close this connection, open a new one, and reissue the 570 * request. 571 */ 572 if (nres == firstreq) 573 errx(1, "Connection failure"); 574 575cleanupconn: 576 /* 577 * Clean up our connection and keep on going 578 */ 579 shutdown(sd, SHUT_RDWR); 580 close(sd); 581 sd = -1; 582 if (fd != -1) { 583 close(fd); 584 fd = -1; 585 } 586 if (reqbuf != NULL) { 587 free(reqbuf); 588 reqbuf = NULL; 589 } 590 nreq = nres; 591 res = res0; 592 pipelined = 0; 593 resbufpos = resbuflen = 0; 594 continue; 595 } 596 597 free(resbuf); 598 freeaddrinfo(res0); 599 600 return 0; 601} 602