]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side.cc
debug levels
[thirdparty/squid.git] / src / client_side.cc
CommitLineData
3c66d057 1
dd11e0b7 2/*
5d679edb 3 * $Id: client_side.cc,v 1.402 1998/09/24 20:41:19 rousskov Exp $
dd11e0b7 4 *
5 * DEBUG: section 33 Client-side Routines
6 * AUTHOR: Duane Wessels
7 *
42c04c16 8 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
e25c139f 9 * ----------------------------------------------------------
dd11e0b7 10 *
11 * Squid is the result of efforts by numerous individuals from the
12 * Internet community. Development is led by Duane Wessels of the
e25c139f 13 * National Laboratory for Applied Network Research and funded by the
14 * National Science Foundation. Squid is Copyrighted (C) 1998 by
15 * Duane Wessels and the University of California San Diego. Please
16 * see the COPYRIGHT file for full details. Squid incorporates
17 * software developed and/or copyrighted by other sources. Please see
18 * the CREDITS file for full details.
dd11e0b7 19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
cbdec147 32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 33 *
dd11e0b7 34 */
f88bb09c 35
36#include "squid.h"
37
5cafc1d6 38#if IPF_TRANSPARENT
39#if HAVE_SYS_IOCTL_H
40#include <sys/ioctl.h>
41#endif
42#include <netinet/tcp.h>
43#include <net/if.h>
44#include <ip_compat.h>
45#include <ip_fil.h>
46#include <ip_nat.h>
47#endif
48
49
50
5492ad1d 51#if LINGERING_CLOSE
52#define comm_close comm_lingering_close
53#endif
54
7a2f978b 55static const char *const crlf = "\r\n";
f715bd3a 56static const char *const proxy_auth_challenge_fmt = "Basic realm=\"%s\"";
7a2f978b 57
58#define REQUEST_BUF_SIZE 4096
59#define FAILURE_MODE_TIME 300
60
61/* Local functions */
62
fc5d6f7f 63static CWCB clientWriteComplete;
7a2f978b 64static PF clientReadRequest;
65static PF connStateFree;
66static PF requestTimeout;
7a2f978b 67static int CheckQuickAbort2(const clientHttpRequest *);
1b02b5be 68static int clientCheckTransferDone(clientHttpRequest *);
7a2f978b 69static void CheckQuickAbort(clientHttpRequest *);
88aad2e5 70static void checkFailureRatio(err_type, hier_code);
fb63215a 71static void clientProcessMiss(clientHttpRequest *);
eeb423fb 72static void clientBuildReplyHeader(clientHttpRequest * http, HttpReply * rep);
99edd1c3 73static clientHttpRequest *parseHttpRequestAbort(ConnStateData * conn, const char *uri);
7a2f978b 74static clientHttpRequest *parseHttpRequest(ConnStateData *, method_t *, int *, char **, size_t *);
582b6456 75static RH clientRedirectDone;
1b02b5be 76static STCB clientHandleIMSReply;
f5b8bbc4 77static int clientGetsOldEntry(StoreEntry * new, StoreEntry * old, request_t * request);
78static int checkAccelOnly(clientHttpRequest *);
7c1d4010 79static int clientOnlyIfCached(clientHttpRequest * http);
7a2f978b 80static STCB clientSendMoreData;
81static STCB clientCacheHit;
99edd1c3 82static void clientInterpretRequestHeaders(clientHttpRequest *);
fb63215a 83static void clientProcessRequest(clientHttpRequest *);
84static void clientProcessExpired(void *data);
038eb4ed 85static void clientProcessOnlyIfCachedMiss(clientHttpRequest * http);
cb69b4c7 86static HttpReply *clientConstructProxyAuthReply(clientHttpRequest * http);
50ddd7a4 87static int clientCachable(clientHttpRequest * http);
88static int clientHierarchical(clientHttpRequest * http);
efb9218c 89static int clientCheckContentLength(request_t * r);
ba4f8e5a 90static int httpAcceptDefer(void);
49d3fcb0 91static log_type clientProcessRequest2(clientHttpRequest * http);
ea6f43cd 92
38d7734b 93static int
382d851a 94checkAccelOnly(clientHttpRequest * http)
38d7734b 95{
96 /* return TRUE if someone makes a proxy request to us and
97 * we are in httpd-accel only mode */
f1dc9b30 98 if (!Config2.Accel.on)
38d7734b 99 return 0;
17a0a4ee 100 if (Config.onoff.accel_with_proxy)
38d7734b 101 return 0;
382d851a 102 if (http->request->protocol == PROTO_CACHEOBJ)
38d7734b 103 return 0;
77ed547a 104 if (http->flags.accel)
38d7734b 105 return 0;
106 return 1;
107}
108
b8d8561b 109void
382d851a 110clientAccessCheck(void *data)
f88bb09c 111{
382d851a 112 clientHttpRequest *http = data;
113 ConnStateData *conn = http->conn;
99edd1c3 114 const char *browser;
17a0a4ee 115 if (Config.onoff.ident_lookup && conn->ident.state == IDENT_NONE) {
425ad52e 116 identStart(-1, conn, clientAccessCheck, http);
ba1d2afa 117 return;
118 }
382d851a 119 if (checkAccelOnly(http)) {
120 clientAccessCheckDone(0, http);
75e88d56 121 return;
f88bb09c 122 }
99edd1c3 123 browser = httpHeaderGetStr(&http->request->header, HDR_USER_AGENT);
f1dc9b30 124 http->acl_checklist = aclChecklistCreate(Config.accessList.http,
382d851a 125 http->request,
126 conn->peer.sin_addr,
75e88d56 127 browser,
382d851a 128 conn->ident.ident);
129 aclNBCheck(http->acl_checklist, clientAccessCheckDone, http);
f88bb09c 130}
131
7c1d4010 132/*
133 * returns true if client specified that the object must come from the cache
134 * witout contacting origin server
135 */
136static int
137clientOnlyIfCached(clientHttpRequest * http)
138{
139 const request_t *r = http->request;
140 assert(r);
ea285003 141 return r->cache_control &&
8e092300 142 EBIT_TEST(r->cache_control->mask, CC_ONLY_IF_CACHED);
7c1d4010 143}
144
cb69b4c7 145static HttpReply *
ee1679df 146clientConstructProxyAuthReply(clientHttpRequest * http)
cb69b4c7 147{
148 ErrorState *err = errorCon(ERR_CACHE_ACCESS_DENIED, HTTP_PROXY_AUTHENTICATION_REQUIRED);
149 HttpReply *rep;
150 err->request = requestLink(http->request);
151 rep = errorBuildReply(err);
152 errorStateFree(err);
153 /* add Authenticate header */
f715bd3a 154 httpHeaderPutStrf(&rep->header, HDR_PROXY_AUTHENTICATE, proxy_auth_challenge_fmt, Config.proxyAuthRealm);
cb69b4c7 155 return rep;
156}
fc5d6f7f 157
23d92c64 158StoreEntry *
92695e5e 159clientCreateStoreEntry(clientHttpRequest * h, method_t m, request_flags flags)
79e0dc20 160{
161 StoreEntry *e;
40defb17 162 /*
163 * For erroneous requests, we might not have a h->request,
164 * so make a fake one.
165 */
99edd1c3 166 if (h->request == NULL)
167 h->request = requestLink(requestCreate(m, PROTO_NONE, NULL));
23d92c64 168 e = storeCreateEntry(h->uri, h->log_uri, flags, m);
79e0dc20 169 storeClientListAdd(e, h);
447e176b 170#if DELAY_POOLS
171 delaySetStoreClient(e, h, h->request->delay_id);
172#endif
cc27d775 173 storeClientCopy(e, 0, 0, CLIENT_SOCK_SZ, memAllocate(MEM_CLIENT_SOCK_BUF), clientSendMoreData, h);
79e0dc20 174 return e;
175}
176
177
b8d8561b 178void
75e88d56 179clientAccessCheckDone(int answer, void *data)
f88bb09c 180{
382d851a 181 clientHttpRequest *http = data;
02922e76 182 int page_id = -1;
9b312a19 183 ErrorState *err = NULL;
23d92c64 184 debug(33, 5) ("clientAccessCheckDone: '%s' answer=%d\n", http->uri, answer);
382d851a 185 http->acl_checklist = NULL;
fc5d6f7f 186 if (answer == ACCESS_ALLOWED) {
9b5d1d21 187 safe_free(http->uri);
188 http->uri = xstrdup(urlCanonical(http->request));
ce66013b 189 assert(http->redirect_state == REDIRECT_NONE);
382d851a 190 http->redirect_state = REDIRECT_PENDING;
191 redirectStart(http, clientRedirectDone, http);
fc5d6f7f 192 } else if (answer == ACCESS_REQ_PROXY_AUTH) {
fc5d6f7f 193 http->log_type = LOG_TCP_DENIED;
92695e5e 194 http->entry = clientCreateStoreEntry(http, http->request->method, null_request_flags);
def67559 195 /* create appropriate response */
196 http->entry->mem_obj->reply = clientConstructProxyAuthReply(http);
197 httpReplySwapOut(http->entry->mem_obj->reply, http->entry);
0254527a 198 storeComplete(http->entry);
f88bb09c 199 } else {
23d92c64 200 debug(33, 5) ("Access Denied: %s\n", http->uri);
901e234d 201 debug(33, 5) ("AclMatchedName = %s\n",
6f47fbc7 202 AclMatchedName ? AclMatchedName : "<null>");
79a15e0a 203 http->log_type = LOG_TCP_DENIED;
92695e5e 204 http->entry = clientCreateStoreEntry(http, http->request->method, null_request_flags);
02922e76 205 page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName);
206 /* NOTE: don't use HTTP_UNAUTHORIZED because then the
207 * stupid browser wants us to authenticate */
208 err = errorCon(ERR_ACCESS_DENIED, HTTP_FORBIDDEN);
209 err->request = requestLink(http->request);
210 err->src_addr = http->conn->peer.sin_addr;
211 if (page_id > 0)
212 err->page_id = page_id;
213 errorAppendEntry(http->entry, err);
f88bb09c 214 }
215}
216
b8d8561b 217static void
218clientRedirectDone(void *data, char *result)
f88bb09c 219{
382d851a 220 clientHttpRequest *http = data;
c0cdaf99 221 request_t *new_request = NULL;
382d851a 222 request_t *old_request = http->request;
23d92c64 223 debug(33, 5) ("clientRedirectDone: '%s' result=%s\n", http->uri,
f88bb09c 224 result ? result : "NULL");
ce66013b 225 assert(http->redirect_state == REDIRECT_PENDING);
382d851a 226 http->redirect_state = REDIRECT_DONE;
77ed547a 227 if (result && strcmp(result, http->uri))
20cc1450 228 new_request = urlParse(old_request->method, result);
c0cdaf99 229 if (new_request) {
23d92c64 230 safe_free(http->uri);
9b5d1d21 231 http->uri = xstrdup(urlCanonical(new_request));
20cc1450 232 new_request->http_ver = old_request->http_ver;
2246b732 233 httpHeaderAppend(&new_request->header, &old_request->header);
77ed547a 234 new_request->client_addr = old_request->client_addr;
92695e5e 235 new_request->flags.redirected = 1;
6cf028ab 236 if (old_request->body) {
237 new_request->body = xmalloc(old_request->body_sz);
238 xmemcpy(new_request->body, old_request->body, old_request->body_sz);
239 new_request->body_sz = old_request->body_sz;
240 }
20cc1450 241 requestUnlink(old_request);
382d851a 242 http->request = requestLink(new_request);
f88bb09c 243 }
99edd1c3 244 clientInterpretRequestHeaders(http);
23d92c64 245 fd_note(http->conn->fd, http->uri);
fb63215a 246 clientProcessRequest(http);
e81957b7 247}
248
fb63215a 249static void
250clientProcessExpired(void *data)
620da955 251{
382d851a 252 clientHttpRequest *http = data;
23d92c64 253 char *url = http->uri;
620da955 254 StoreEntry *entry = NULL;
23d92c64 255 debug(33, 3) ("clientProcessExpired: '%s'\n", http->uri);
b9d34cc1 256 assert(http->entry->lastmod >= 0);
7c1d4010 257 /*
258 * check if we are allowed to contact other servers
259 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
6106c6fc 260 * a stale entry *if* it matches client requirements
7c1d4010 261 */
262 if (clientOnlyIfCached(http)) {
263 clientProcessOnlyIfCachedMiss(http);
264 return;
265 }
92695e5e 266 http->request->flags.refresh = 1;
382d851a 267 http->old_entry = http->entry;
620da955 268 entry = storeCreateEntry(url,
23d92c64 269 http->log_uri,
382d851a 270 http->request->flags,
271 http->request->method);
620da955 272 /* NOTE, don't call storeLockObject(), storeCreateEntry() does it */
fe96bbe6 273 storeClientListAdd(entry, http);
274 storeClientListAdd(http->old_entry, http);
447e176b 275#if DELAY_POOLS
276 delaySetStoreClient(entry, http, http->request->delay_id);
277 delaySetStoreClient(http->old_entry, http, http->request->delay_id);
278#endif
382d851a 279 entry->lastmod = http->old_entry->lastmod;
1c3e77cd 280 debug(33, 5) ("clientProcessExpired: lastmod %d\n", (int) entry->lastmod);
d1a43e28 281 entry->refcount++; /* EXPIRED CASE */
382d851a 282 http->entry = entry;
283 http->out.offset = 0;
d1061d2b 284 fwdStart(http->conn->fd, http->entry, http->request,
285 http->conn->peer.sin_addr);
f990cccc 286 /* Register with storage manager to receive updates when data comes in. */
0e473d70 287 if (entry->store_status == STORE_ABORTED)
6cf028ab 288 debug(33, 0) ("clientProcessExpired: entry->swap_status == STORE_ABORTED\n");
d89d1fb6 289 storeClientCopy(entry,
fe96bbe6 290 http->out.offset,
d89d1fb6 291 http->out.offset,
cc27d775 292 CLIENT_SOCK_SZ,
293 memAllocate(MEM_CLIENT_SOCK_BUF),
1b02b5be 294 clientHandleIMSReply,
d89d1fb6 295 http);
620da955 296}
297
91f4d519 298static int
299clientGetsOldEntry(StoreEntry * new_entry, StoreEntry * old_entry, request_t * request)
300{
71a8a965 301 const http_status status = new_entry->mem_obj->reply->sline.status;
302 if (0 == status) {
303 debug(33, 5) ("clientGetsOldEntry: YES, broken HTTP reply\n");
304 return 1;
305 }
91f4d519 306 /* If the reply is anything but "Not Modified" then
307 * we must forward it to the client */
71a8a965 308 if (HTTP_NOT_MODIFIED != status) {
cb69b4c7 309 debug(33, 5) ("clientGetsOldEntry: NO, reply=%d\n", status);
91f4d519 310 return 0;
311 }
312 /* If the client did not send IMS in the request, then it
313 * must get the old object, not this "Not Modified" reply */
92695e5e 314 if (!request->flags.ims) {
a3d5953d 315 debug(33, 5) ("clientGetsOldEntry: YES, no client IMS\n");
91f4d519 316 return 1;
317 }
318 /* If the client IMS time is prior to the entry LASTMOD time we
319 * need to send the old object */
320 if (modifiedSince(old_entry, request)) {
5f6ac48b 321 debug(33, 5) ("clientGetsOldEntry: YES, modified since %d\n",
1afe05c5 322 (int) request->ims);
91f4d519 323 return 1;
324 }
a3d5953d 325 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
91f4d519 326 return 0;
327}
328
329
52d4522b 330static void
1b02b5be 331clientHandleIMSReply(void *data, char *buf, ssize_t size)
620da955 332{
382d851a 333 clientHttpRequest *http = data;
382d851a 334 StoreEntry *entry = http->entry;
620da955 335 MemObject *mem = entry->mem_obj;
9fb13bb6 336 const char *url = storeUrl(entry);
e92d33a5 337 int unlink_request = 0;
76cff1d4 338 StoreEntry *oldentry;
49d3fcb0 339 int recopy = 1;
71a8a965 340 const http_status status = mem->reply->sline.status;
93f9abd0 341 debug(33, 3) ("clientHandleIMSReply: %s, %d bytes\n", url, (int) size);
6801f8a8 342 if (size < 0 && entry->store_status != STORE_ABORTED)
343 storeAbort(entry, 1);
344 if (entry->store_status == STORE_ABORTED) {
1b02b5be 345 debug(33, 3) ("clientHandleIMSReply: ABORTED '%s'\n", url);
c54e9052 346 /* We have an existing entry, but failed to validate it */
accc6d47 347 /* Its okay to send the old one anyway */
348 http->log_type = LOG_TCP_REFRESH_FAIL_HIT;
349 storeUnregister(entry, http);
350 storeUnlockObject(entry);
351 entry = http->entry = http->old_entry;
352 entry->refcount++;
71a8a965 353 } else if (STORE_PENDING == entry->store_status && 0 == status) {
1b02b5be 354 debug(33, 3) ("clientHandleIMSReply: Incomplete headers for '%s'\n", url);
cc27d775 355 if (size >= CLIENT_SOCK_SZ) {
4455552a 356 /* will not get any bigger than that */
357 debug(33, 3) ("clientHandleIMSReply: Reply is too large '%s', using old entry\n", url);
878570db 358 /* use old entry, this repeats the code abovez */
4455552a 359 http->log_type = LOG_TCP_REFRESH_FAIL_HIT;
360 storeUnregister(entry, http);
743eebfa 361 storeUnlockObject(entry);
4455552a 362 entry = http->entry = http->old_entry;
363 entry->refcount++;
878570db 364 /* continue */
4455552a 365 } else {
4455552a 366 storeClientCopy(entry,
367 http->out.offset + size,
368 http->out.offset,
cc27d775 369 CLIENT_SOCK_SZ,
49d3fcb0 370 buf,
4455552a 371 clientHandleIMSReply,
372 http);
878570db 373 return;
4455552a 374 }
382d851a 375 } else if (clientGetsOldEntry(entry, http->old_entry, http->request)) {
620da955 376 /* We initiated the IMS request, the client is not expecting
76cff1d4 377 * 304, so put the good one back. First, make sure the old entry
378 * headers have been loaded from disk. */
382d851a 379 oldentry = http->old_entry;
382d851a 380 http->log_type = LOG_TCP_REFRESH_HIT;
d89d1fb6 381 if (oldentry->mem_obj->request == NULL) {
382 oldentry->mem_obj->request = requestLink(mem->request);
383 unlink_request = 1;
e92d33a5 384 }
64763c37 385 /* Don't memcpy() the whole reply structure here. For example,
386 * www.thegist.com (Netscape/1.13) returns a content-length for
387 * 304's which seems to be the length of the 304 HEADERS!!! and
388 * not the body they refer to. */
71a8a965 389 httpReplyUpdateOnNotModified(oldentry->mem_obj->reply, mem->reply);
d89d1fb6 390 storeTimestampsSet(oldentry);
382d851a 391 storeUnregister(entry, http);
6d54aea8 392 storeUnlockObject(entry);
382d851a 393 entry = http->entry = oldentry;
41fad779 394 entry->timestamp = squid_curtime;
657266fe 395 if (unlink_request) {
e92d33a5 396 requestUnlink(entry->mem_obj->request);
657266fe 397 entry->mem_obj->request = NULL;
398 }
620da955 399 } else {
400 /* the client can handle this reply, whatever it is */
382d851a 401 http->log_type = LOG_TCP_REFRESH_MISS;
71a8a965 402 if (HTTP_NOT_MODIFIED == mem->reply->sline.status) {
382d851a 403 http->old_entry->timestamp = squid_curtime;
404 http->old_entry->refcount++;
405 http->log_type = LOG_TCP_REFRESH_HIT;
d1a43e28 406 }
382d851a 407 storeUnregister(http->old_entry, http);
408 storeUnlockObject(http->old_entry);
49d3fcb0 409 recopy = 0;
620da955 410 }
382d851a 411 http->old_entry = NULL; /* done with old_entry */
49d3fcb0 412 assert(entry->store_status != STORE_ABORTED);
413 if (recopy) {
414 storeClientCopy(entry,
415 http->out.offset,
416 http->out.offset,
cc27d775 417 CLIENT_SOCK_SZ,
49d3fcb0 418 buf,
419 clientSendMoreData,
420 http);
421 } else {
422 clientSendMoreData(data, buf, size);
6cf028ab 423 }
620da955 424}
91f4d519 425
426int
304d07cb 427modifiedSince(StoreEntry * entry, request_t * request)
91f4d519 428{
429 int object_length;
430 MemObject *mem = entry->mem_obj;
1c3e77cd 431 time_t mod_time = entry->lastmod;
9fb13bb6 432 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry));
1c3e77cd 433 if (mod_time < 0)
434 mod_time = entry->timestamp;
0cdcddb9 435 debug(33, 3) ("modifiedSince: mod_time = %d\n", (int) mod_time);
1c3e77cd 436 if (mod_time < 0)
91f4d519 437 return 1;
438 /* Find size of the object */
038eb4ed 439 object_length = mem->reply->content_length;
cb69b4c7 440 if (object_length < 0)
07304bf9 441 object_length = contentLen(entry);
1c3e77cd 442 if (mod_time > request->ims) {
a3d5953d 443 debug(33, 3) ("--> YES: entry newer than client\n");
91f4d519 444 return 1;
1c3e77cd 445 } else if (mod_time < request->ims) {
a3d5953d 446 debug(33, 3) ("--> NO: entry older than client\n");
91f4d519 447 return 0;
448 } else if (request->imslen < 0) {
a3d5953d 449 debug(33, 3) ("--> NO: same LMT, no client length\n");
91f4d519 450 return 0;
451 } else if (request->imslen == object_length) {
a3d5953d 452 debug(33, 3) ("--> NO: same LMT, same length\n");
91f4d519 453 return 0;
454 } else {
a3d5953d 455 debug(33, 3) ("--> YES: same LMT, different length\n");
91f4d519 456 return 1;
457 }
458}
b3b64e58 459
a90eae18 460void
382d851a 461clientPurgeRequest(clientHttpRequest * http)
a90eae18 462{
a90eae18 463 StoreEntry *entry;
9b312a19 464 ErrorState *err = NULL;
8d6da567 465 HttpReply *r;
9b312a19 466 debug(33, 3) ("Config.onoff.enable_purge = %d\n", Config.onoff.enable_purge);
17a0a4ee 467 if (!Config.onoff.enable_purge) {
79a15e0a 468 http->log_type = LOG_TCP_DENIED;
fe40a877 469 err = errorCon(ERR_ACCESS_DENIED, HTTP_FORBIDDEN);
9b312a19 470 err->request = requestLink(http->request);
471 err->src_addr = http->conn->peer.sin_addr;
92695e5e 472 http->entry = clientCreateStoreEntry(http, http->request->method, null_request_flags);
79e0dc20 473 errorAppendEntry(http->entry, err);
a90eae18 474 return;
475 }
382d851a 476 http->log_type = LOG_TCP_MISS;
2f9aa365 477 if ((entry = storeGetPublic(http->uri, METHOD_GET)) == NULL) {
9b312a19 478 http->http_code = HTTP_NOT_FOUND;
a90eae18 479 } else {
480 storeRelease(entry);
9b312a19 481 http->http_code = HTTP_OK;
a90eae18 482 }
49d3fcb0 483 debug(33, 4) ("clientPurgeRequest: Not modified '%s'\n",
afa9f1cd 484 storeUrl(entry));
485 /*
486 * Make a new entry to hold the reply to be written
487 * to the client.
488 */
92695e5e 489 http->entry = clientCreateStoreEntry(http, http->request->method, null_request_flags);
8d6da567 490 httpReplyReset(r = http->entry->mem_obj->reply);
491 httpReplySetHeaders(r, 1.0, http->http_code, NULL, NULL, 0, 0, -1);
492 httpReplySwapOut(r, http->entry);
afa9f1cd 493 storeComplete(http->entry);
a90eae18 494}
e33ba616 495
496int
ea3a2a69 497checkNegativeHit(StoreEntry * e)
e33ba616 498{
d46a87a8 499 if (!EBIT_TEST(e->flags, ENTRY_NEGCACHED))
ea3a2a69 500 return 0;
501 if (e->expires <= squid_curtime)
502 return 0;
503 if (e->store_status != STORE_OK)
504 return 0;
505 return 1;
e33ba616 506}
7a2f978b 507
a7c05555 508void
0e473d70 509clientUpdateCounters(clientHttpRequest * http)
a7c05555 510{
ee1679df 511 int svc_time = tvSubMsec(http->start, current_time);
b4e7f82d 512 ping_data *i;
39edba21 513 HierarchyLogEntry *H;
0e473d70 514 Counter.client_http.requests++;
d8b83480 515 if (isTcpHit(http->log_type))
0e473d70 516 Counter.client_http.hits++;
0e473d70 517 if (http->request->err_type != ERR_NONE)
518 Counter.client_http.errors++;
12cf1be2 519 statHistCount(&Counter.client_http.all_svc_time, svc_time);
ee1679df 520 /*
521 * The idea here is not to be complete, but to get service times
522 * for only well-defined types. For example, we don't include
523 * LOG_TCP_REFRESH_FAIL_HIT because its not really a cache hit
524 * (we *tried* to validate it, but failed).
525 */
526 switch (http->log_type) {
7c9c84ad 527 case LOG_TCP_REFRESH_HIT:
528 statHistCount(&Counter.client_http.nh_svc_time, svc_time);
529 break;
ee1679df 530 case LOG_TCP_IMS_HIT:
12cf1be2 531 statHistCount(&Counter.client_http.nm_svc_time, svc_time);
ee1679df 532 break;
533 case LOG_TCP_HIT:
534 case LOG_TCP_MEM_HIT:
12cf1be2 535 statHistCount(&Counter.client_http.hit_svc_time, svc_time);
ee1679df 536 break;
537 case LOG_TCP_MISS:
538 case LOG_TCP_CLIENT_REFRESH_MISS:
12cf1be2 539 statHistCount(&Counter.client_http.miss_svc_time, svc_time);
ee1679df 540 break;
541 default:
542 /* make compiler warnings go away */
543 break;
544 }
39edba21 545 H = &http->request->hier;
69c95dd3 546 switch (H->alg) {
547 case PEER_SA_DIGEST:
17b6e784 548 Counter.cd.times_used++;
69c95dd3 549 break;
550 case PEER_SA_ICP:
551 Counter.icp.times_used++;
b4e7f82d 552 i = &H->ping;
69c95dd3 553 if (0 != i->stop.tv_sec && 0 != i->start.tv_sec)
554 statHistCount(&Counter.icp.query_svc_time,
555 tvSubUsec(i->start, i->stop));
556 if (i->timeout)
557 Counter.icp.query_timeouts++;
558 break;
559 case PEER_SA_NETDB:
560 Counter.netdb.times_used++;
561 break;
562 default:
563 break;
17b6e784 564 }
a7c05555 565}
566
7a2f978b 567static void
568httpRequestFree(void *data)
569{
570 clientHttpRequest *http = data;
571 clientHttpRequest **H;
572 ConnStateData *conn = http->conn;
573 StoreEntry *entry = http->entry;
574 request_t *request = http->request;
575 MemObject *mem = NULL;
93f9abd0 576 debug(33, 3) ("httpRequestFree: %s\n", storeUrl(entry));
1b02b5be 577 if (!clientCheckTransferDone(http)) {
7a2f978b 578 if (entry)
579 storeUnregister(entry, http); /* unregister BEFORE abort */
580 CheckQuickAbort(http);
581 entry = http->entry; /* reset, IMS might have changed it */
582 if (entry && entry->ping_status == PING_WAITING)
583 storeReleaseRequest(entry);
7a2f978b 584 }
585 assert(http->log_type < LOG_TYPE_MAX);
586 if (entry)
587 mem = entry->mem_obj;
588 if (http->out.size || http->log_type) {
728da2ee 589 http->al.icp.opcode = ICP_INVALID;
ef65d6ca 590 http->al.url = http->log_uri;
591 debug(33, 9) ("httpRequestFree: al.url='%s'\n", http->al.url);
7a2f978b 592 if (mem) {
cb69b4c7 593 http->al.http.code = mem->reply->sline.status;
038eb4ed 594 http->al.http.content_type = strBuf(mem->reply->content_type);
7a2f978b 595 }
596 http->al.cache.caddr = conn->log_addr;
597 http->al.cache.size = http->out.size;
598 http->al.cache.code = http->log_type;
599 http->al.cache.msec = tvSubMsec(http->start, current_time);
def67559 600 if (request->user_ident[0])
601 http->al.cache.ident = request->user_ident;
602 else
603 http->al.cache.ident = conn->ident.ident;
7a2f978b 604 if (request) {
2246b732 605 Packer p;
606 MemBuf mb;
607 memBufDefInit(&mb);
608 packerToMemInit(&p, &mb);
609 httpHeaderPackInto(&request->header, &p);
7a2f978b 610 http->al.http.method = request->method;
2246b732 611 http->al.headers.request = xstrdup(mb.buf);
7a2f978b 612 http->al.hier = request->hier;
2246b732 613 packerClean(&p);
614 memBufClean(&mb);
7a2f978b 615 }
616 accessLogLog(&http->al);
a7c05555 617 clientUpdateCounters(http);
6f47fbc7 618 clientdbUpdate(conn->peer.sin_addr, http->log_type, PROTO_HTTP, http->out.size);
7a2f978b 619 }
7a2f978b 620 if (http->acl_checklist)
621 aclChecklistFree(http->acl_checklist);
88aad2e5 622 if (request)
c24fca87 623 checkFailureRatio(request->err_type, http->al.hier.code);
23d92c64 624 safe_free(http->uri);
625 safe_free(http->log_uri);
2246b732 626 safe_free(http->al.headers.request);
7a2f978b 627 safe_free(http->al.headers.reply);
d192d11f 628 stringClean(&http->range_iter.boundary);
7a2f978b 629 if (entry) {
630 http->entry = NULL;
631 storeUnregister(entry, http);
632 storeUnlockObject(entry);
633 }
634 /* old_entry might still be set if we didn't yet get the reply
1b02b5be 635 * code in clientHandleIMSReply() */
7a2f978b 636 if (http->old_entry) {
637 storeUnregister(http->old_entry, http);
638 storeUnlockObject(http->old_entry);
639 http->old_entry = NULL;
640 }
641 requestUnlink(http->request);
642 assert(http != http->next);
643 assert(http->conn->chr != NULL);
644 H = &http->conn->chr;
645 while (*H) {
646 if (*H == http)
647 break;
648 H = &(*H)->next;
649 }
650 assert(*H != NULL);
651 *H = http->next;
652 http->next = NULL;
653 cbdataFree(http);
654}
655
656/* This is a handler normally called by comm_close() */
657static void
658connStateFree(int fd, void *data)
659{
660 ConnStateData *connState = data;
661 clientHttpRequest *http;
93f9abd0 662 debug(33, 3) ("connStateFree: FD %d\n", fd);
7a2f978b 663 assert(connState != NULL);
79d39a72 664 while ((http = connState->chr) != NULL) {
7a2f978b 665 assert(http->conn == connState);
666 assert(connState->chr != connState->chr->next);
667 httpRequestFree(http);
668 }
669 if (connState->ident.fd > -1)
670 comm_close(connState->ident.fd);
671 safe_free(connState->in.buf);
59c4d35b 672 /* XXX account connState->in.buf */
7a2f978b 673 pconnHistCount(0, connState->nrequests);
674 cbdataFree(connState);
675}
676
677static void
99edd1c3 678clientInterpretRequestHeaders(clientHttpRequest * http)
7a2f978b 679{
680 request_t *request = http->request;
99edd1c3 681 const HttpHeader *req_hdr = &request->header;
682#if USE_USERAGENT_LOG
683 const char *str;
684#endif
99edd1c3 685 request->imslen = -1;
686 request->ims = httpHeaderGetTime(req_hdr, HDR_IF_MODIFIED_SINCE);
687 if (request->ims > 0)
92695e5e 688 request->flags.ims = 1;
99edd1c3 689 if (httpHeaderHas(req_hdr, HDR_PRAGMA)) {
690 String s = httpHeaderGetList(req_hdr, HDR_PRAGMA);
465dc415 691 if (strListIsMember(&s, "no-cache", ',')) {
9f60cfdf 692#if HTTP_VIOLATIONS
cbe3a719 693 if (Config.onoff.reload_into_ims)
92695e5e 694 request->flags.nocache_hack = 1;
cbe3a719 695 else if (refresh_nocache_hack)
92695e5e 696 request->flags.nocache_hack = 1;
465dc415 697 else
9f60cfdf 698#endif
92695e5e 699 request->flags.nocache = 1;
465dc415 700 }
99edd1c3 701 stringClean(&s);
7a2f978b 702 }
4b315324 703 /* ignore range header in non-GETs */
704 if (request->method == METHOD_GET) {
705 request->range = httpHeaderGetRange(req_hdr);
706 if (request->range)
92695e5e 707 request->flags.range = 1;
4b315324 708 }
99edd1c3 709 if (httpHeaderHas(req_hdr, HDR_AUTHORIZATION))
92695e5e 710 request->flags.auth = 1;
7a2f978b 711 if (request->login[0] != '\0')
92695e5e 712 request->flags.auth = 1;
99edd1c3 713 if (httpMsgIsPersistent(request->http_ver, req_hdr))
92695e5e 714 request->flags.proxy_keepalive = 1;
99edd1c3 715 if (httpHeaderHas(req_hdr, HDR_VIA)) {
716 String s = httpHeaderGetList(req_hdr, HDR_VIA);
edf3ffdc 717 /* ThisCache cannot be a member of Via header, "1.0 ThisCache" can */
718 if (strListIsSubstr(&s, ThisCache, ',')) {
9330543e 719 debug(33, 1) ("WARNING: Forwarding loop detected for '%s'\n",
720 http->uri);
721 debug(33, 1) ("--> %s\n", strBuf(s));
92695e5e 722 request->flags.loopdetect = 1;
7a2f978b 723 }
d21f1c54 724#if FORW_VIA_DB
ea285003 725 fvdbCountVia(strBuf(s));
d21f1c54 726#endif
99edd1c3 727 stringClean(&s);
d21f1c54 728 }
7a2f978b 729#if USE_USERAGENT_LOG
99edd1c3 730 if ((str = httpHeaderGetStr(req_hdr, HDR_USER_AGENT)))
731 logUserAgent(fqdnFromAddr(http->conn->peer.sin_addr), str);
d21f1c54 732#endif
733#if FORW_VIA_DB
99edd1c3 734 if (httpHeaderHas(req_hdr, HDR_X_FORWARDED_FOR)) {
735 String s = httpHeaderGetList(req_hdr, HDR_X_FORWARDED_FOR);
736 fvdbCountForw(strBuf(s));
737 stringClean(&s);
738 }
7a2f978b 739#endif
99edd1c3 740 request->cache_control = httpHeaderGetCc(req_hdr);
7a2f978b 741 if (request->method == METHOD_TRACE) {
99edd1c3 742 request->max_forwards = httpHeaderGetInt(req_hdr, HDR_MAX_FORWARDS);
7a2f978b 743 }
50ddd7a4 744 if (clientCachable(http))
92695e5e 745 request->flags.cachable = 1;
50ddd7a4 746 if (clientHierarchical(http))
92695e5e 747 request->flags.hierarchical = 1;
95e36d02 748#if DELAY_POOLS
749 if (delayClient(http)) {
750 debug(33, 5) ("clientInterpretRequestHeaders: delay request class %d position %d\n",
447e176b 751 request->delay_id >> 16,
752 request->delay_id & 0xFFFF);
95e36d02 753 }
754#endif
99edd1c3 755 debug(33, 5) ("clientInterpretRequestHeaders: REQ_NOCACHE = %s\n",
92695e5e 756 request->flags.nocache ? "SET" : "NOT SET");
99edd1c3 757 debug(33, 5) ("clientInterpretRequestHeaders: REQ_CACHABLE = %s\n",
92695e5e 758 request->flags.cachable ? "SET" : "NOT SET");
99edd1c3 759 debug(33, 5) ("clientInterpretRequestHeaders: REQ_HIERARCHICAL = %s\n",
92695e5e 760 request->flags.hierarchical ? "SET" : "NOT SET");
7a2f978b 761}
762
31be8b80 763static int
efb9218c 764clientCheckContentLength(request_t * r)
31be8b80 765{
205080e2 766 /* We only require a content-length for "upload" methods */
767 if (!pumpMethod(r->method))
0cdcddb9 768 return 1;
205080e2 769 if (httpHeaderGetInt(&r->header, HDR_CONTENT_LENGTH) < 0)
31be8b80 770 return 0;
771 return 1;
772}
773
7a2f978b 774static int
50ddd7a4 775clientCachable(clientHttpRequest * http)
7a2f978b 776{
23d92c64 777 const char *url = http->uri;
7a2f978b 778 request_t *req = http->request;
779 method_t method = req->method;
bd05e3e3 780 aclCheck_t ch;
781 memset(&ch, '\0', sizeof(ch));
782 /*
783 * Hopefully, nobody really wants 'no_cache' by client's IP
784 * address, but if they do, this should work if they use IP
785 * addresses in their ACLs, or if the client's address is in
786 * the FQDN cache.
787 *
788 * This may not work yet for 'dst' and 'dst_domain' ACLs.
789 */
790 ch.src_addr = http->conn->peer.sin_addr;
791 ch.request = http->request;
79a51871 792 /*
793 * aclCheckFast returns 1 for ALLOW and 0 for DENY. The default
794 * is ALLOW, so we require 'no_cache DENY foo' in squid.conf
795 * to indicate uncachable objects.
796 */
95291419 797 if (!aclCheckFast(Config.accessList.noCache, &ch))
4b4cd312 798 return 0;
7a2f978b 799 if (req->protocol == PROTO_HTTP)
800 return httpCachable(method);
801 /* FTP is always cachable */
802 if (req->protocol == PROTO_GOPHER)
803 return gopherCachable(url);
804 if (req->protocol == PROTO_WAIS)
805 return 0;
806 if (method == METHOD_CONNECT)
807 return 0;
808 if (method == METHOD_TRACE)
809 return 0;
810 if (req->protocol == PROTO_CACHEOBJ)
811 return 0;
812 return 1;
813}
814
815/* Return true if we can query our neighbors for this object */
816static int
50ddd7a4 817clientHierarchical(clientHttpRequest * http)
7a2f978b 818{
23d92c64 819 const char *url = http->uri;
7a2f978b 820 request_t *request = http->request;
821 method_t method = request->method;
822 const wordlist *p = NULL;
823
824 /* IMS needs a private key, so we can use the hierarchy for IMS only
825 * if our neighbors support private keys */
92695e5e 826 if (request->flags.ims && !neighbors_do_private_keys)
7a2f978b 827 return 0;
92695e5e 828 if (request->flags.auth)
7a2f978b 829 return 0;
830 if (method == METHOD_TRACE)
831 return 1;
832 if (method != METHOD_GET)
833 return 0;
834 /* scan hierarchy_stoplist */
835 for (p = Config.hierarchy_stoplist; p; p = p->next)
836 if (strstr(url, p->key))
837 return 0;
92695e5e 838 if (request->flags.loopdetect)
7a2f978b 839 return 0;
840 if (request->protocol == PROTO_HTTP)
841 return httpCachable(method);
842 if (request->protocol == PROTO_GOPHER)
843 return gopherCachable(url);
844 if (request->protocol == PROTO_WAIS)
845 return 0;
846 if (request->protocol == PROTO_CACHEOBJ)
847 return 0;
848 return 1;
849}
850
cf50a0af 851int
7a2f978b 852isTcpHit(log_type code)
853{
854 /* this should be a bitmap for better optimization */
855 if (code == LOG_TCP_HIT)
856 return 1;
857 if (code == LOG_TCP_IMS_HIT)
858 return 1;
859 if (code == LOG_TCP_REFRESH_FAIL_HIT)
860 return 1;
861 if (code == LOG_TCP_REFRESH_HIT)
862 return 1;
863 if (code == LOG_TCP_NEGATIVE_HIT)
864 return 1;
865 if (code == LOG_TCP_MEM_HIT)
866 return 1;
867 return 0;
868}
869
1c3e77cd 870/*
871 * returns true if If-Range specs match reply, false otherwise
872 */
a9771e51 873static int
874clientIfRangeMatch(clientHttpRequest * http, HttpReply * rep)
875{
876 const TimeOrTag spec = httpHeaderGetTimeOrTag(&http->request->header, HDR_IF_RANGE);
877 /* check for parsing falure */
878 if (!spec.valid)
879 return 0;
880 /* got an ETag? */
881 if (spec.tag.str) {
882 ETag rep_tag = httpHeaderGetETag(&rep->header, HDR_ETAG);
ebb6e9a0 883 debug(33, 3) ("clientIfRangeMatch: ETags: %s and %s\n",
a9771e51 884 spec.tag.str, rep_tag.str ? rep_tag.str : "<none>");
885 if (!rep_tag.str)
ebb6e9a0 886 return 0; /* entity has no etag to compare with! */
a9771e51 887 if (spec.tag.weak || rep_tag.weak) {
9834a631 888 debug(33, 1) ("clientIfRangeMatch: Weak ETags are not allowed in If-Range: %s ? %s\n",
a9771e51 889 spec.tag.str, rep_tag.str);
ebb6e9a0 890 return 0; /* must use strong validator for sub-range requests */
a9771e51 891 }
892 return etagIsEqual(&rep_tag, &spec.tag);
893 }
894 /* got modification time? */
895 if (spec.time >= 0) {
896 return http->entry->lastmod <= spec.time;
897 }
ebb6e9a0 898 assert(0); /* should not happen */
a9771e51 899 return 0;
900}
901
e17d81d3 902/* adds appropriate Range headers if needed */
903static void
904clientBuildRangeHeader(clientHttpRequest * http, HttpReply * rep)
905{
5e2dba16 906 HttpHeader *hdr = rep ? &rep->header : 0;
e17d81d3 907 const char *range_err = NULL;
908 assert(http->request->range);
909 /* check if we still want to do ranges */
9834a631 910 if (!rep)
911 range_err = "no [parse-able] reply";
912 else if (rep->sline.status != HTTP_OK)
e17d81d3 913 range_err = "wrong status code";
ebb6e9a0 914 else if (httpHeaderHas(hdr, HDR_CONTENT_RANGE))
e17d81d3 915 range_err = "origin server does ranges";
ebb6e9a0 916 else if (rep->content_length < 0)
e17d81d3 917 range_err = "unknown length";
ebb6e9a0 918 else if (rep->content_length != http->entry->mem_obj->reply->content_length)
919 range_err = "INCONSISTENT length"; /* a bug? */
920 else if (httpHeaderHas(&http->request->header, HDR_IF_RANGE) && !clientIfRangeMatch(http, rep))
a9771e51 921 range_err = "If-Range match failed";
ebb6e9a0 922 else if (!httpHdrRangeCanonize(http->request->range, rep->content_length))
e17d81d3 923 range_err = "canonization failed";
ebb6e9a0 924 else if (httpHdrRangeIsComplex(http->request->range))
e17d81d3 925 range_err = "too complex range header";
926 /* get rid of our range specs on error */
927 if (range_err) {
cdedf7db 928 debug(33, 2) ("clientBuildRangeHeader: will not do ranges: %s.\n", range_err);
e17d81d3 929 httpHdrRangeDestroy(http->request->range);
930 http->request->range = NULL;
931 } else {
932 const int spec_count = http->request->range->specs.count;
cdedf7db 933 debug(33, 2) ("clientBuildRangeHeader: range spec count: %d clen: %d\n",
e17d81d3 934 spec_count, rep->content_length);
935 assert(spec_count > 0);
a9771e51 936 /* ETags should not be returned with Partial Content replies? */
937 httpHeaderDelById(hdr, HDR_ETAG);
ebb6e9a0 938 /* append appropriate header(s) */
e17d81d3 939 if (spec_count == 1) {
940 HttpHdrRangePos pos = HttpHdrRangeInitPos;
889b534a 941 const HttpHdrRangeSpec *spec = httpHdrRangeGetSpec(http->request->range, &pos);
942 assert(spec);
e17d81d3 943 /* append Content-Range */
889b534a 944 httpHeaderAddContRange(hdr, *spec, rep->content_length);
e17d81d3 945 /* set new Content-Length to the actual number of OCTETs
946 * transmitted in the message-body */
947 httpHeaderDelById(hdr, HDR_CONTENT_LENGTH);
889b534a 948 httpHeaderPutInt(hdr, HDR_CONTENT_LENGTH, spec->length);
949 debug(33, 2) ("clientBuildRangeHeader: actual content length: %d\n", spec->length);
e17d81d3 950 } else {
951 /* multipart! */
952 /* generate boundary string */
953 http->range_iter.boundary = httpHdrRangeBoundaryStr(http);
954 /* delete old Content-Type, add ours */
955 httpHeaderDelById(hdr, HDR_CONTENT_TYPE);
956 httpHeaderPutStrf(hdr, HDR_CONTENT_TYPE,
957 "multipart/byteranges; boundary=\"%s\"",
958 strBuf(http->range_iter.boundary));
959 /* no need for Content-Length in multipart responses */
cded937d 960 /* but we must delete the original one if we cannot (yet)
961 * calculate the actual length */
962 httpHeaderDelById(hdr, HDR_CONTENT_LENGTH);
e17d81d3 963 }
964 }
965}
966
d192d11f 967/* filters out unwanted entries from original reply header
968 * adds extra entries if we have more info than origin server
969 * adds Squid specific entries */
2246b732 970static void
eeb423fb 971clientBuildReplyHeader(clientHttpRequest * http, HttpReply * rep)
2246b732 972{
973 HttpHeader *hdr = &rep->header;
974 int is_hit = isTcpHit(http->log_type);
7673173d 975 request_t *request = http->request;
2246b732 976#if DONT_FILTER_THESE
977 /* but you might want to if you run Squid as an HTTP accelerator */
d192d11f 978 /* httpHeaderDelById(hdr, HDR_ACCEPT_RANGES); */
2246b732 979 httpHeaderDelById(hdr, HDR_ETAG);
980#endif
981 httpHeaderDelById(hdr, HDR_PROXY_CONNECTION);
982 /* here: Keep-Alive is a field-name, not a connection directive! */
983 httpHeaderDelByName(hdr, "Keep-Alive");
984 /* remove Set-Cookie if a hit */
985 if (is_hit)
986 httpHeaderDelById(hdr, HDR_SET_COOKIE);
987 /* handle Connection header */
988 if (httpHeaderHas(hdr, HDR_CONNECTION)) {
989 /* anything that matches Connection list member will be deleted */
990 String strConnection = httpHeaderGetList(hdr, HDR_CONNECTION);
991 const HttpHeaderEntry *e;
992 HttpHeaderPos pos = HttpHeaderInitPos;
7673173d 993 /*
994 * think: on-average-best nesting of the two loops (hdrEntry
995 * and strListItem) @?@
996 */
997 /*
998 * maybe we should delete standard stuff ("keep-alive","close")
999 * from strConnection first?
1000 */
2246b732 1001 while ((e = httpHeaderGetEntry(hdr, &pos))) {
1002 if (strListIsMember(&strConnection, strBuf(e->name), ','))
1003 httpHeaderDelAt(hdr, pos);
1004 }
1005 httpHeaderDelById(hdr, HDR_CONNECTION);
1006 stringClean(&strConnection);
1007 }
d192d11f 1008 /* Handle Ranges */
7673173d 1009 if (request->range)
e17d81d3 1010 clientBuildRangeHeader(http, rep);
7673173d 1011 /*
1012 * Add Age header, not that our header must replace Age headers
1013 * from other caches if any
1014 */
cc66f616 1015 if (http->entry->timestamp > 0) {
1016 httpHeaderDelById(hdr, HDR_AGE);
7673173d 1017 /*
1018 * we do not follow HTTP/1.1 precisely here becuase we rely
1019 * on Date header when computing entry->timestamp; we should
1020 * be using _request_ time if Date header is not available
1021 * or if it is out of sync
1022 */
cc66f616 1023 httpHeaderPutInt(hdr, HDR_AGE,
7673173d 1024 http->entry->timestamp <= squid_curtime ?
1025 squid_curtime - http->entry->timestamp : 0);
cc66f616 1026 }
2246b732 1027 /* Append X-Cache */
1028 httpHeaderPutStrf(hdr, HDR_X_CACHE, "%s from %s",
1029 is_hit ? "HIT" : "MISS", getMyHostname());
1030#if USE_CACHE_DIGESTS
1031 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1032 httpHeaderPutStrf(hdr, HDR_X_CACHE_LOOKUP, "%s from %s:%d",
1033 http->lookup_type ? http->lookup_type : "NONE",
1034 getMyHostname(), Config.Port.http->i);
1035#endif
1036 /* Only replies with valid Content-Length can be sent with keep-alive */
7673173d 1037 if (request->method != METHOD_HEAD &&
2246b732 1038 http->entry->mem_obj->reply->content_length < 0)
92695e5e 1039 request->flags.proxy_keepalive = 0;
2246b732 1040 /* Signal keep-alive if needed */
7673173d 1041 httpHeaderPutStr(hdr,
1042 http->flags.accel ? HDR_CONNECTION : HDR_PROXY_CONNECTION,
92695e5e 1043 request->flags.proxy_keepalive ? "keep-alive" : "close");
2246b732 1044#if ADD_X_REQUEST_URI
1045 /*
1046 * Knowing the URI of the request is useful when debugging persistent
1047 * connections in a client; we cannot guarantee the order of http headers,
1048 * but X-Request-URI is likely to be the very last header to ease use from a
1049 * debugger [hdr->entries.count-1].
1050 */
eeb423fb 1051 httpHeaderPutStr(hdr, HDR_X_REQUEST_URI,
2246b732 1052 http->entry->mem_obj->url ? http->entry->mem_obj->url : http->uri);
1053#endif
1054}
1055
eeb423fb 1056static HttpReply *
2246b732 1057clientBuildReply(clientHttpRequest * http, const char *buf, size_t size)
1058{
1059 HttpReply *rep = httpReplyCreate();
2246b732 1060 if (httpReplyParse(rep, buf)) {
1061 /* enforce 1.0 reply version */
1062 rep->sline.version = 1.0;
1063 /* do header conversions */
1064 clientBuildReplyHeader(http, rep);
d192d11f 1065 /* if we do ranges, change status to "Partial Content" */
1066 if (http->request->range)
1067 httpStatusLineSet(&rep->sline, rep->sline.version, HTTP_PARTIAL_CONTENT, NULL);
2246b732 1068 } else {
1069 /* parsing failure, get rid of the invalid reply */
1070 httpReplyDestroy(rep);
1071 rep = NULL;
9834a631 1072 /* if we were going to do ranges, backoff */
1073 if (http->request->range)
782b5f40 1074 clientBuildRangeHeader(http, rep); /* will fail and destroy request->range */
2246b732 1075 }
1076 return rep;
1077}
7a2f978b 1078
85071fe3 1079/*
1080 * clientCacheHit should only be called until the HTTP reply headers
1081 * have been parsed. Normally this should be a single call, but
1082 * it might take more than one. As soon as we have the headers,
1083 * we hand off to clientSendMoreData, clientProcessExpired, or
1084 * clientProcessMiss.
1085 */
4c323c5f 1086static void
7a2f978b 1087clientCacheHit(void *data, char *buf, ssize_t size)
1088{
1089 clientHttpRequest *http = data;
49d3fcb0 1090 StoreEntry *e = http->entry;
1091 MemObject *mem;
1092 request_t *r = http->request;
93f9abd0 1093 debug(33, 3) ("clientCacheHit: %s, %d bytes\n", http->uri, (int) size);
49d3fcb0 1094 if (http->entry == NULL) {
cc27d775 1095 memFree(MEM_CLIENT_SOCK_BUF, buf);
93f9abd0 1096 debug(33, 3) ("clientCacheHit: request aborted\n");
49d3fcb0 1097 return;
1098 } else if (size < 0) {
7a2f978b 1099 /* swap in failure */
cc27d775 1100 memFree(MEM_CLIENT_SOCK_BUF, buf);
93f9abd0 1101 debug(33, 3) ("clientCacheHit: swapin failure for %s\n", http->uri);
7a2f978b 1102 http->log_type = LOG_TCP_SWAPFAIL_MISS;
fdfc0d63 1103 if ((e = http->entry)) {
1104 http->entry = NULL;
1105 storeUnregister(e, http);
fdfc0d63 1106 storeUnlockObject(e);
1107 }
fb63215a 1108 clientProcessMiss(http);
49d3fcb0 1109 return;
1110 }
1111 assert(size > 0);
1112 mem = e->mem_obj;
1113 assert(e->store_status != STORE_ABORTED);
1114 if (mem->reply->sline.status == 0) {
1115 /*
1116 * we don't have full reply headers yet; either wait for more or
1117 * punt to clientProcessMiss.
1118 */
25944e56 1119 if (e->mem_status == IN_MEMORY || e->store_status == STORE_OK) {
cc27d775 1120 memFree(MEM_CLIENT_SOCK_BUF, buf);
49d3fcb0 1121 clientProcessMiss(http);
cc27d775 1122 } else if (size == CLIENT_SOCK_SZ && http->out.offset == 0) {
1123 memFree(MEM_CLIENT_SOCK_BUF, buf);
49d3fcb0 1124 clientProcessMiss(http);
1125 } else {
1126 debug(33, 3) ("clientCacheHit: waiting for HTTP reply headers\n");
1127 storeClientCopy(e,
1128 http->out.offset + size,
1129 http->out.offset,
cc27d775 1130 CLIENT_SOCK_SZ,
49d3fcb0 1131 buf,
1132 clientCacheHit,
1133 http);
1134 }
1135 return;
1136 }
1137 /*
1138 * Got the headers, now grok them
1139 */
1140 assert(http->log_type == LOG_TCP_HIT);
1141 if (checkNegativeHit(e)) {
1142 http->log_type = LOG_TCP_NEGATIVE_HIT;
1143 clientSendMoreData(data, buf, size);
d657ffad 1144 } else if (r->method == METHOD_HEAD) {
1145 /*
1146 * RFC 2068 seems to indicate there is no "conditional HEAD"
1147 * request. We cannot validate a cached object for a HEAD
1148 * request, nor can we return 304.
1149 */
1150 if (e->mem_status == IN_MEMORY)
1151 http->log_type = LOG_TCP_MEM_HIT;
1152 clientSendMoreData(data, buf, size);
e25c139f 1153 } else if (refreshCheck(e, r, 0) && !http->flags.internal) {
49d3fcb0 1154 /*
1155 * We hold a stale copy; it needs to be validated
1156 */
0cdcddb9 1157 if (e->lastmod < 0) {
1158 /*
1c3e77cd 1159 * Previous reply didn't have a Last-Modified header,
1160 * we cannot revalidate it.
1161 */
1162 http->log_type = LOG_TCP_MISS;
1163 clientProcessMiss(http);
92695e5e 1164 } else if (r->flags.nocache) {
cbe3a719 1165 /*
1166 * This did not match a refresh pattern that overrides no-cache
1167 * we should honour the client no-cache header.
1168 */
1169 http->log_type = LOG_TCP_CLIENT_REFRESH_MISS;
1170 clientProcessMiss(http);
1c3e77cd 1171 } else if (r->protocol == PROTO_HTTP) {
cbe3a719 1172 /*
1173 * Object needs to be revalidated
1174 * XXX This could apply to FTP as well, if Last-Modified is known.
1175 */
49d3fcb0 1176 http->log_type = LOG_TCP_REFRESH_MISS;
1177 clientProcessExpired(http);
1178 } else {
cbe3a719 1179 /*
1180 * We don't know how to re-validate other protocols. Handle
1181 * them as if the object has expired.
1182 */
49d3fcb0 1183 http->log_type = LOG_TCP_MISS;
1184 clientProcessMiss(http);
1185 }
cc27d775 1186 memFree(MEM_CLIENT_SOCK_BUF, buf);
92695e5e 1187 } else if (r->flags.ims) {
49d3fcb0 1188 /*
1189 * Handle If-Modified-Since requests from the client
1190 */
1191 if (mem->reply->sline.status != HTTP_OK) {
1192 debug(33, 4) ("clientCacheHit: Reply code %d != 200\n",
1193 mem->reply->sline.status);
cc27d775 1194 memFree(MEM_CLIENT_SOCK_BUF, buf);
49d3fcb0 1195 clientProcessMiss(http);
1196 } else if (modifiedSince(e, http->request)) {
815ef411 1197 http->log_type = LOG_TCP_IMS_HIT;
49d3fcb0 1198 clientSendMoreData(data, buf, size);
1199 } else {
1200 MemBuf mb = httpPacked304Reply(e->mem_obj->reply);
1201 http->log_type = LOG_TCP_IMS_HIT;
cc27d775 1202 memFree(MEM_CLIENT_SOCK_BUF, buf);
49d3fcb0 1203 storeUnregister(e, http);
1204 storeUnlockObject(e);
92695e5e 1205 e = clientCreateStoreEntry(http, http->request->method, null_request_flags);
49d3fcb0 1206 http->entry = e;
1207 httpReplyParse(e->mem_obj->reply, mb.buf);
1208 storeAppend(e, mb.buf, mb.size);
1209 memBufClean(&mb);
1210 storeComplete(e);
1211 }
1212 } else {
1213 /*
1214 * plain ol' cache hit
1215 */
1216 if (e->mem_status == IN_MEMORY)
1217 http->log_type = LOG_TCP_MEM_HIT;
1218 clientSendMoreData(data, buf, size);
7a2f978b 1219 }
1220}
1221
d192d11f 1222
1223/* extracts a "range" from *buf and appends them to mb, updating all offsets and such */
1224static void
ebb6e9a0 1225clientPackRange(clientHttpRequest * http, HttpHdrRangeIter * i, const char **buf, ssize_t * size, MemBuf * mb)
d192d11f 1226{
1227 const size_t copy_sz = i->debt_size <= *size ? i->debt_size : *size;
1228 off_t body_off = http->out.offset - i->prefix_size;
1229 assert(*size > 0);
889b534a 1230 assert(i->spec);
d192d11f 1231 /* intersection of "have" and "need" ranges must not be empty */
889b534a 1232 assert(body_off < i->spec->offset + i->spec->length);
1233 assert(body_off + *size > i->spec->offset);
d192d11f 1234 /* put boundary and headers at the beginning of range in a multi-range */
889b534a 1235 if (http->request->range->specs.count > 1 && i->debt_size == i->spec->length) {
ebb6e9a0 1236 HttpReply *rep = http->entry->mem_obj ? /* original reply */
1237 http->entry->mem_obj->reply : NULL;
d192d11f 1238 HttpHeader hdr;
1239 Packer p;
1240 assert(rep);
1241 /* put boundary */
cdedf7db 1242 debug(33, 5) ("clientPackRange: appending boundary: %s\n", strBuf(i->boundary));
d192d11f 1243 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1244 memBufPrintf(mb, "\r\n--%s\r\n", strBuf(i->boundary));
1245 httpHeaderInit(&hdr, hoReply);
1246 if (httpHeaderHas(&rep->header, HDR_CONTENT_TYPE))
1247 httpHeaderPutStr(&hdr, HDR_CONTENT_TYPE, httpHeaderGetStr(&rep->header, HDR_CONTENT_TYPE));
889b534a 1248 httpHeaderAddContRange(&hdr, *i->spec, rep->content_length);
d192d11f 1249 packerToMemInit(&p, mb);
1250 httpHeaderPackInto(&hdr, &p);
1251 packerClean(&p);
1252 httpHeaderClean(&hdr);
1253 /* append <crlf> (we packed a header, not a reply */
1254 memBufPrintf(mb, "\r\n");
1255 }
1256 /* append */
cdedf7db 1257 debug(33, 3) ("clientPackRange: appending %d bytes\n", copy_sz);
d192d11f 1258 memBufAppend(mb, *buf, copy_sz);
1259 /* update offsets */
1260 *size -= copy_sz;
1261 i->debt_size -= copy_sz;
1262 body_off += copy_sz;
1263 *buf += copy_sz;
ebb6e9a0 1264 http->out.offset = body_off + i->prefix_size; /* sync */
d192d11f 1265 /* paranoid check */
1266 assert(*size >= 0 && i->debt_size >= 0);
1267}
1268
889b534a 1269/* returns true if there is still data available to pack more ranges
1270 * increments iterator "i"
1271 * used by clientPackMoreRanges */
1272static int
ebb6e9a0 1273clientCanPackMoreRanges(const clientHttpRequest * http, HttpHdrRangeIter * i, ssize_t size)
889b534a 1274{
1275 /* first update "i" if needed */
1276 if (!i->debt_size) {
1277 if ((i->spec = httpHdrRangeGetSpec(http->request->range, &i->pos)))
1278 i->debt_size = i->spec->length;
1279 }
ebb6e9a0 1280 assert(!i->debt_size == !i->spec); /* paranoid sync condition */
889b534a 1281 /* continue condition: need_more_data && have_more_data */
1282 return i->spec && size > 0;
1283}
d192d11f 1284
1285/* extracts "ranges" from buf and appends them to mb, updating all offsets and such */
1286/* returns true if we need more data */
1287static int
ebb6e9a0 1288clientPackMoreRanges(clientHttpRequest * http, const char *buf, ssize_t size, MemBuf * mb)
d192d11f 1289{
1290 HttpHdrRangeIter *i = &http->range_iter;
d192d11f 1291 /* offset in range specs does not count the prefix of an http msg */
1292 off_t body_off = http->out.offset - i->prefix_size;
1293 assert(size >= 0);
9834a631 1294 /* check: reply was parsed and range iterator was initialized */
1295 assert(i->prefix_size > 0);
d192d11f 1296 /* filter out data according to range specs */
1297 /* note: order of loop conditions is significant! */
889b534a 1298 while (clientCanPackMoreRanges(http, i, size)) {
ebb6e9a0 1299 off_t start; /* offset of still missing data */
889b534a 1300 assert(i->spec);
1301 start = i->spec->offset + i->spec->length - i->debt_size;
cdedf7db 1302 debug(33, 2) ("clientPackMoreRanges: in: offset: %d size: %d\n",
ebb6e9a0 1303 (int) body_off, size);
cdedf7db 1304 debug(33, 2) ("clientPackMoreRanges: out: start: %d spec[%d]: [%d, %d), len: %d debt: %d\n",
ebb6e9a0 1305 (int) start, (int) i->pos, i->spec->offset, (int) (i->spec->offset + i->spec->length), i->spec->length, i->debt_size);
1306 assert(body_off <= start); /* we did not miss it */
d192d11f 1307 /* skip up to start */
1308 if (body_off + size > start) {
1309 const size_t skip_size = start - body_off;
1310 body_off = start;
1311 size -= skip_size;
1312 buf += skip_size;
1313 } else {
1314 /* has not reached start yet */
1315 body_off += size;
1316 size = 0;
1317 buf = NULL;
1318 }
1319 /* put next chunk if any */
1320 if (size) {
ebb6e9a0 1321 http->out.offset = body_off + i->prefix_size; /* sync */
d192d11f 1322 clientPackRange(http, i, &buf, &size, mb);
ebb6e9a0 1323 body_off = http->out.offset - i->prefix_size; /* sync */
d192d11f 1324 }
1325 }
ebb6e9a0 1326 assert(!i->debt_size == !i->spec); /* paranoid sync condition */
cdedf7db 1327 debug(33, 2) ("clientPackMoreRanges: buf exhausted: in: offset: %d size: %d need_more: %d\n",
ebb6e9a0 1328 (int) body_off, size, i->debt_size);
889b534a 1329 if (i->debt_size) {
1330 debug(33, 2) ("clientPackMoreRanges: need more: spec[%d]: [%d, %d), len: %d\n",
ebb6e9a0 1331 (int) i->pos, i->spec->offset, (int) (i->spec->offset + i->spec->length), i->spec->length);
889b534a 1332 /* skip the data we do not need if possible */
ebb6e9a0 1333 if (i->debt_size == i->spec->length) /* at the start of the cur. spec */
889b534a 1334 body_off = i->spec->offset;
d192d11f 1335 else
889b534a 1336 assert(body_off == i->spec->offset + i->spec->length - i->debt_size);
ebb6e9a0 1337 } else if (http->request->range->specs.count > 1) {
d192d11f 1338 /* put terminating boundary for multiparts */
1339 memBufPrintf(mb, "\r\n--%s--\r\n", strBuf(i->boundary));
1340 }
ebb6e9a0 1341 http->out.offset = body_off + i->prefix_size; /* sync */
889b534a 1342 return i->debt_size > 0;
d192d11f 1343}
1344
2246b732 1345/*
1346 * accepts chunk of a http message in buf, parses prefix, filters headers and
1347 * such, writes processed message to the client's socket
1348 */
4c323c5f 1349static void
7a2f978b 1350clientSendMoreData(void *data, char *buf, ssize_t size)
1351{
1352 clientHttpRequest *http = data;
1353 StoreEntry *entry = http->entry;
1354 ConnStateData *conn = http->conn;
1355 int fd = conn->fd;
2246b732 1356 HttpReply *rep = NULL;
2246b732 1357 const char *body_buf = buf;
1358 ssize_t body_size = size;
9f086470 1359 MemBuf mb;
bcd3b08a 1360 ssize_t check_size = 0;
93f9abd0 1361 debug(33, 5) ("clientSendMoreData: %s, %d bytes\n", http->uri, (int) size);
cc27d775 1362 assert(size <= CLIENT_SOCK_SZ);
40defb17 1363 assert(http->request != NULL);
93f9abd0 1364 debug(33, 5) ("clientSendMoreData: FD %d '%s', out.offset=%d \n",
5f6ac48b 1365 fd, storeUrl(entry), (int) http->out.offset);
7a2f978b 1366 if (conn->chr != http) {
1367 /* there is another object in progress, defer this one */
aebbcd07 1368 debug(33, 1) ("clientSendMoreData: Deferring %s\n", storeUrl(entry));
cc27d775 1369 memFree(MEM_CLIENT_SOCK_BUF, buf);
7a2f978b 1370 return;
fdfc0d63 1371 } else if (entry && entry->store_status == STORE_ABORTED) {
d6e928c9 1372 /* call clientWriteComplete so the client socket gets closed */
1373 clientWriteComplete(fd, NULL, 0, COMM_OK, http);
cc27d775 1374 memFree(MEM_CLIENT_SOCK_BUF, buf);
7a2f978b 1375 return;
1376 } else if (size < 0) {
d6e928c9 1377 /* call clientWriteComplete so the client socket gets closed */
1378 clientWriteComplete(fd, NULL, 0, COMM_OK, http);
cc27d775 1379 memFree(MEM_CLIENT_SOCK_BUF, buf);
7a2f978b 1380 return;
1381 } else if (size == 0) {
d6e928c9 1382 /* call clientWriteComplete so the client socket gets closed */
1383 clientWriteComplete(fd, NULL, 0, COMM_OK, http);
cc27d775 1384 memFree(MEM_CLIENT_SOCK_BUF, buf);
7a2f978b 1385 return;
1386 }
40defb17 1387 if (http->out.offset == 0) {
7a2f978b 1388 if (Config.onoff.log_mime_hdrs) {
2334c194 1389 size_t k;
1390 if ((k = headersEnd(buf, size))) {
7a2f978b 1391 safe_free(http->al.headers.reply);
1afe05c5 1392 http->al.headers.reply = xcalloc(k + 1, 1);
2334c194 1393 xstrncpy(http->al.headers.reply, buf, k);
7a2f978b 1394 }
1395 }
2246b732 1396 rep = clientBuildReply(http, buf, size);
1397 if (rep) {
1398 body_size = size - rep->hdr_sz;
1399 assert(body_size >= 0);
1f7e91a1 1400 body_buf = buf + rep->hdr_sz;
d192d11f 1401 http->range_iter.prefix_size = rep->hdr_sz;
2246b732 1402 debug(33, 3) ("clientSendMoreData: Appending %d bytes after %d bytes of headers\n",
1403 body_size, rep->hdr_sz);
cc27d775 1404 } else if (size < CLIENT_SOCK_SZ && entry->store_status == STORE_PENDING) {
9f086470 1405 /* wait for more to arrive */
1406 storeClientCopy(entry,
1407 http->out.offset + size,
1408 http->out.offset,
cc27d775 1409 CLIENT_SOCK_SZ,
9f086470 1410 buf,
1411 clientSendMoreData,
1412 http);
1413 return;
7a2f978b 1414 }
d192d11f 1415 /* reset range iterator */
1416 http->range_iter.pos = HttpHdrRangeInitPos;
7a2f978b 1417 }
7a2f978b 1418 if (http->request->method == METHOD_HEAD) {
9f086470 1419 if (rep) {
1420 /* do not forward body for HEAD replies */
1421 body_size = 0;
9f086470 1422 http->flags.done_copying = 1;
1423 } else {
782b5f40 1424 /*
1425 * If we are here, then store_status == STORE_OK and it
1426 * seems we have a HEAD repsponse which is missing the
1427 * empty end-of-headers line (home.mira.net, phttpd/0.99.72
1428 * does this). Because clientBuildReply() fails we just
1429 * call this reply a body, set the done_copying flag and
1430 * continue...
1431 */
1432 http->flags.done_copying = 1;
7a2f978b 1433 }
1434 }
d192d11f 1435 /* write headers and/or body if any */
1f7e91a1 1436 assert(rep || (body_buf && body_size));
9f086470 1437 /* init mb; put status line and headers if any */
1438 if (rep) {
1439 mb = httpReplyPack(rep);
bcd3b08a 1440 http->out.offset += rep->hdr_sz;
1441 check_size += rep->hdr_sz;
9f086470 1442 httpReplyDestroy(rep);
1443 rep = NULL;
1444 } else {
1445 /* leave space for growth incase we do ranges */
cc27d775 1446 memBufInit(&mb, CLIENT_SOCK_SZ, 2 * CLIENT_SOCK_SZ);
9f086470 1447 }
1448 /* append body if any */
1f7e91a1 1449 if (body_buf && body_size) {
9f086470 1450 if (http->request->range) {
bcd3b08a 1451 /* Only GET requests should have ranges */
1452 assert(http->request->method == METHOD_GET);
1453 /* clientPackMoreRanges() updates http->out.offset */
9f086470 1454 /* force the end of the transfer if we are done */
1455 if (!clientPackMoreRanges(http, body_buf, body_size, &mb))
1456 http->flags.done_copying = 1;
2246b732 1457 } else {
bcd3b08a 1458 http->out.offset += body_size;
1459 check_size += body_size;
9f086470 1460 memBufAppend(&mb, body_buf, body_size);
2246b732 1461 }
2246b732 1462 }
bbe3cbdc 1463 if (!http->request->range && http->request->method == METHOD_GET)
bcd3b08a 1464 assert(check_size == size);
9f086470 1465 /* write */
1466 comm_write_mbuf(fd, mb, clientWriteComplete, http);
2246b732 1467 /* if we don't do it, who will? */
cc27d775 1468 memFree(MEM_CLIENT_SOCK_BUF, buf);
7a2f978b 1469}
1470
1a92a1e2 1471static
1472void
1473clientKeepaliveNextRequest(clientHttpRequest * http)
1474{
1475 ConnStateData *conn = http->conn;
1476 StoreEntry *entry;
ebb6e9a0 1477 debug(33, 3) ("clientKeepaliveNextRequest: FD %d\n", conn->fd);
1a92a1e2 1478 conn->defer.until = 0; /* Kick it to read a new request */
1479 httpRequestFree(http);
1480 if ((http = conn->chr) != NULL) {
1481 debug(33, 1) ("clientKeepaliveNextRequest: FD %d Sending next\n",
1482 conn->fd);
1483 entry = http->entry;
1484 if (0 == storeClientCopyPending(entry, http)) {
1485 if (entry->store_status == STORE_ABORTED)
c07aed63 1486 debug(33, 0) ("clientKeepaliveNextRequest: entry->swap_status == STORE_ABORTED\n");
1a92a1e2 1487 storeClientCopy(entry,
1488 http->out.offset,
1489 http->out.offset,
cc27d775 1490 CLIENT_SOCK_SZ,
1491 memAllocate(MEM_CLIENT_SOCK_BUF),
1a92a1e2 1492 clientSendMoreData,
1493 http);
1494 }
1495 } else {
c07aed63 1496 debug(33, 5) ("clientKeepaliveNextRequest: FD %d reading next request\n",
1a92a1e2 1497 conn->fd);
1498 fd_note(conn->fd, "Reading next request");
1499 /*
1500 * Set the timeout BEFORE calling clientReadRequest().
1501 */
1502 commSetTimeout(conn->fd, 15, requestTimeout, conn);
1503 clientReadRequest(conn->fd, conn); /* Read next request */
1504 /*
1505 * Note, the FD may be closed at this point.
1506 */
1507 }
1508}
1509
fc5d6f7f 1510static void
79a15e0a 1511clientWriteComplete(int fd, char *bufnotused, size_t size, int errflag, void *data)
7a2f978b 1512{
1513 clientHttpRequest *http = data;
7a2f978b 1514 StoreEntry *entry = http->entry;
b34ed725 1515 int done;
7a2f978b 1516 http->out.size += size;
93f9abd0 1517 debug(33, 5) ("clientWriteComplete: FD %d, sz %d, err %d, off %d, len %d\n",
007b8be4 1518 fd, size, errflag, (int) http->out.offset, entry ? objectLen(entry) : 0);
d8b83480 1519 if (size > 0) {
ea285003 1520 kb_incr(&Counter.client_http.kbytes_out, size);
1521 if (isTcpHit(http->log_type))
d8b83480 1522 kb_incr(&Counter.client_http.hit_kbytes_out, size);
1523 }
7a2f978b 1524 if (errflag) {
e55650e3 1525 /*
1526 * just close the socket, httpRequestFree will abort if needed
1527 */
7a2f978b 1528 comm_close(fd);
fdfc0d63 1529 } else if (NULL == entry) {
1530 comm_close(fd); /* yuk */
7a2f978b 1531 } else if (entry->store_status == STORE_ABORTED) {
7a2f978b 1532 comm_close(fd);
a200bbd2 1533 } else if ((done = clientCheckTransferDone(http)) != 0 || size == 0) {
93f9abd0 1534 debug(33, 5) ("clientWriteComplete: FD %d transfer is DONE\n", fd);
7a2f978b 1535 /* We're finished case */
c07aed63 1536 if (http->entry->mem_obj->reply->content_length < 0) {
ebb6e9a0 1537 debug(33, 5) ("clientWriteComplete: closing, content_length < 0\n");
c07aed63 1538 comm_close(fd);
1539 } else if (!done) {
ebb6e9a0 1540 debug(33, 5) ("clientWriteComplete: closing, !done\n");
c07aed63 1541 comm_close(fd);
d46a87a8 1542 } else if (EBIT_TEST(entry->flags, ENTRY_BAD_LENGTH)) {
ebb6e9a0 1543 debug(33, 5) ("clientWriteComplete: closing, ENTRY_BAD_LENGTH\n");
7a2f978b 1544 comm_close(fd);
92695e5e 1545 } else if (http->request->flags.proxy_keepalive) {
93f9abd0 1546 debug(33, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd);
1a92a1e2 1547 clientKeepaliveNextRequest(http);
7a2f978b 1548 } else {
1549 comm_close(fd);
1550 }
1551 } else {
1552 /* More data will be coming from primary server; register with
1553 * storage manager. */
0e473d70 1554 if (entry->store_status == STORE_ABORTED)
6cf028ab 1555 debug(33, 0) ("clientWriteComplete 2: entry->swap_status == STORE_ABORTED\n");
7a2f978b 1556 storeClientCopy(entry,
1557 http->out.offset,
1558 http->out.offset,
cc27d775 1559 CLIENT_SOCK_SZ,
1560 memAllocate(MEM_CLIENT_SOCK_BUF),
7a2f978b 1561 clientSendMoreData,
1562 http);
1563 }
1564}
1565
038eb4ed 1566/*
99edd1c3 1567 * client issued a request with an only-if-cached cache-control directive;
038eb4ed 1568 * we did not find a cached object that can be returned without
99edd1c3 1569 * contacting other servers;
038eb4ed 1570 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
1571 */
1572static void
1573clientProcessOnlyIfCachedMiss(clientHttpRequest * http)
1574{
1575 char *url = http->uri;
1576 request_t *r = http->request;
1577 ErrorState *err = NULL;
1578 debug(33, 4) ("clientProcessOnlyIfCachedMiss: '%s %s'\n",
1579 RequestMethodStr[r->method], url);
038eb4ed 1580 http->al.http.code = HTTP_GATEWAY_TIMEOUT;
1581 err = errorCon(ERR_ONLY_IF_CACHED_MISS, HTTP_GATEWAY_TIMEOUT);
1582 err->request = requestLink(r);
1583 err->src_addr = http->conn->peer.sin_addr;
92695e5e 1584 http->entry = clientCreateStoreEntry(http, r->method, null_request_flags);
038eb4ed 1585 errorAppendEntry(http->entry, err);
1586}
1587
50ddd7a4 1588static log_type
1589clientProcessRequest2(clientHttpRequest * http)
1590{
1591 const request_t *r = http->request;
9f086470 1592 const cache_key *key;
50ddd7a4 1593 StoreEntry *e;
0c7ccf77 1594 key = storeKeyPublic(http->uri, r->method);
2f9aa365 1595 e = http->entry = storeGetPublic(http->uri, r->method);
0c7ccf77 1596 if (r->method == METHOD_HEAD && e == NULL) {
1597 /* We can generate a HEAD reply from a cached GET object */
1598 key = storeKeyPublic(http->uri, METHOD_GET);
2f9aa365 1599 e = http->entry = storeGetPublic(http->uri, METHOD_GET);
0c7ccf77 1600 }
6cfa8966 1601#if USE_CACHE_DIGESTS
57b1ff70 1602 http->lookup_type = e ? "HIT" : "MISS";
1ca847dd 1603#endif
49d3fcb0 1604 if (NULL == e) {
50ddd7a4 1605 /* this object isn't in the cache */
1606 return LOG_TCP_MISS;
50ddd7a4 1607 } else if (!storeEntryValidToSend(e)) {
50ddd7a4 1608 http->entry = NULL;
1609 return LOG_TCP_MISS;
d46a87a8 1610 } else if (EBIT_TEST(e->flags, ENTRY_SPECIAL)) {
abe471ef 1611 /* Special entries are always hits, no matter what the client says */
1612 http->entry = e;
1613 return LOG_TCP_HIT;
9f60cfdf 1614#if HTTP_VIOLATIONS
92695e5e 1615 } else if (r->flags.nocache_hack) {
cbe3a719 1616 http->entry = NULL;
50ddd7a4 1617 ipcacheReleaseInvalid(r->host);
cbe3a719 1618 return LOG_TCP_CLIENT_REFRESH_MISS;
9f60cfdf 1619#endif
92695e5e 1620 } else if (r->flags.nocache) {
50ddd7a4 1621 http->entry = NULL;
cbe3a719 1622 ipcacheReleaseInvalid(r->host);
ee1679df 1623 return LOG_TCP_CLIENT_REFRESH_MISS;
5d679edb 1624 } else if (r->range && httpHdrRangeWillBeComplex(r->range)) {
1625 /* some clients break if we return "200 OK" for a Range request
1626 * and we _will_ return 200 if ranges happen to bee too complex */
1627 http->entry = NULL;
1628 return LOG_TCP_MISS;
50ddd7a4 1629 } else {
49d3fcb0 1630 http->entry = e;
50ddd7a4 1631 return LOG_TCP_HIT;
1632 }
1633}
1634
4c323c5f 1635static void
fb63215a 1636clientProcessRequest(clientHttpRequest * http)
7a2f978b 1637{
23d92c64 1638 char *url = http->uri;
50ddd7a4 1639 request_t *r = http->request;
fb63215a 1640 int fd = http->conn->fd;
1bea1d83 1641 HttpReply *rep;
93f9abd0 1642 debug(33, 4) ("clientProcessRequest: %s '%s'\n",
50ddd7a4 1643 RequestMethodStr[r->method],
7a2f978b 1644 url);
fb63215a 1645 if (r->method == METHOD_CONNECT) {
7a2f978b 1646 http->log_type = LOG_TCP_MISS;
ea0efb98 1647 sslStart(fd, url, r, &http->out.size);
1648 return;
fb63215a 1649 } else if (r->method == METHOD_PURGE) {
ea0efb98 1650 clientPurgeRequest(http);
1651 return;
fb63215a 1652 } else if (r->method == METHOD_TRACE) {
50ddd7a4 1653 if (r->max_forwards == 0) {
92695e5e 1654 http->entry = clientCreateStoreEntry(http, r->method, null_request_flags);
b17b22eb 1655 storeReleaseRequest(http->entry);
1656 storeBuffer(http->entry);
1bea1d83 1657 rep = httpReplyCreate();
31be8b80 1658 httpReplySetHeaders(rep, 1.0, HTTP_OK, NULL, "text/plain",
2246b732 1659 httpRequestPrefixLen(r), 0, squid_curtime);
1bea1d83 1660 httpReplySwapOut(rep, http->entry);
1661 httpReplyDestroy(rep);
2246b732 1662 httpRequestSwapOut(r, http->entry);
b17b22eb 1663 storeComplete(http->entry);
7a2f978b 1664 return;
1665 }
1666 /* yes, continue */
6addbd81 1667 http->log_type = LOG_TCP_MISS;
efb9218c 1668 } else if (pumpMethod(r->method)) {
fb63215a 1669 http->log_type = LOG_TCP_MISS;
31be8b80 1670 /* XXX oof, POST can be cached! */
54220df8 1671 pumpInit(fd, r, http->uri);
31be8b80 1672 } else {
efb9218c 1673 http->log_type = clientProcessRequest2(http);
7a2f978b 1674 }
93f9abd0 1675 debug(33, 4) ("clientProcessRequest: %s for '%s'\n",
7a2f978b 1676 log_tags[http->log_type],
23d92c64 1677 http->uri);
7a2f978b 1678 http->out.offset = 0;
49d3fcb0 1679 if (NULL != http->entry) {
1680 storeLockObject(http->entry);
1681 storeCreateMemObject(http->entry, http->uri, http->log_uri);
1682 storeClientListAdd(http->entry, http);
447e176b 1683#if DELAY_POOLS
1684 delaySetStoreClient(http->entry, http, http->request->delay_id);
1685#endif
49d3fcb0 1686 http->entry->refcount++;
1687 storeClientCopy(http->entry,
7a2f978b 1688 http->out.offset,
1689 http->out.offset,
cc27d775 1690 CLIENT_SOCK_SZ,
1691 memAllocate(MEM_CLIENT_SOCK_BUF),
7a2f978b 1692 clientCacheHit,
1693 http);
49d3fcb0 1694 } else {
1695 /* MISS CASE */
1696 http->log_type = LOG_TCP_MISS;
fb63215a 1697 clientProcessMiss(http);
7a2f978b 1698 }
1699}
1700
1701/*
1702 * Prepare to fetch the object as it's a cache miss of some kind.
1703 */
1704static void
fb63215a 1705clientProcessMiss(clientHttpRequest * http)
7a2f978b 1706{
23d92c64 1707 char *url = http->uri;
f44af445 1708 request_t *r = http->request;
7a2f978b 1709 ErrorState *err = NULL;
93f9abd0 1710 debug(33, 4) ("clientProcessMiss: '%s %s'\n",
f44af445 1711 RequestMethodStr[r->method], url);
79e0dc20 1712 /*
1713 * We might have a left-over StoreEntry from a failed cache hit
1714 * or IMS request.
1715 */
1716 if (http->entry) {
d46a87a8 1717 if (EBIT_TEST(http->entry->flags, ENTRY_SPECIAL))
12784378 1718 debug(33, 0) ("clientProcessMiss: miss on a special object (%s).\n", url);
79e0dc20 1719 storeUnregister(http->entry, http);
1720 storeUnlockObject(http->entry);
1721 http->entry = NULL;
1722 }
7c1d4010 1723 if (clientOnlyIfCached(http)) {
1724 clientProcessOnlyIfCachedMiss(http);
1725 return;
1726 }
9330543e 1727 /*
1728 * Deny loops when running in accelerator/transproxy mode.
1729 */
92695e5e 1730 if (http->flags.accel && r->flags.loopdetect) {
9330543e 1731 http->al.http.code = HTTP_FORBIDDEN;
1732 err = errorCon(ERR_ACCESS_DENIED, HTTP_FORBIDDEN);
1733 err->request = requestLink(r);
1734 err->src_addr = http->conn->peer.sin_addr;
92695e5e 1735 http->entry = clientCreateStoreEntry(http, r->method, null_request_flags);
9330543e 1736 errorAppendEntry(http->entry, err);
1737 return;
1738 }
79e0dc20 1739 assert(http->out.offset == 0);
f44af445 1740 http->entry = clientCreateStoreEntry(http, r->method, r->flags);
79e0dc20 1741 http->entry->refcount++;
1da5651f 1742 if (http->flags.internal)
1743 r->protocol = PROTO_INTERNAL;
d1061d2b 1744 fwdStart(http->conn->fd, http->entry, r, http->conn->peer.sin_addr);
7a2f978b 1745}
1746
99edd1c3 1747static clientHttpRequest *
1748parseHttpRequestAbort(ConnStateData * conn, const char *uri)
1749{
1750 clientHttpRequest *http = xcalloc(1, sizeof(clientHttpRequest));
1751 cbdataAdd(http, MEM_NONE);
1752 http->conn = conn;
1753 http->start = current_time;
1754 http->req_sz = conn->in.offset;
1755 http->uri = xstrdup(uri);
1756 http->log_uri = xstrdup(uri);
d192d11f 1757 http->range_iter.boundary = StringNull;
99edd1c3 1758 return http;
1759}
1760
7a2f978b 1761/*
1762 * parseHttpRequest()
1763 *
1764 * Returns
1765 * NULL on error or incomplete request
1766 * a clientHttpRequest structure on success
1767 */
1768static clientHttpRequest *
1769parseHttpRequest(ConnStateData * conn, method_t * method_p, int *status,
ea285003 1770 char **prefix_p, size_t * req_line_sz_p)
7a2f978b 1771{
1772 char *inbuf = NULL;
1773 char *mstr = NULL;
1774 char *url = NULL;
1775 char *req_hdr = NULL;
7a2f978b 1776 float http_ver;
1777 char *token = NULL;
1778 char *t = NULL;
2334c194 1779 char *end;
7a2f978b 1780 int free_request = 0;
1781 size_t header_sz; /* size of headers, not including first line */
ea285003 1782 size_t prefix_sz; /* size of whole request (req-line + headers) */
7a2f978b 1783 size_t url_sz;
1784 method_t method;
1785 clientHttpRequest *http = NULL;
5cafc1d6 1786#if IPF_TRANSPARENT
1787 struct natlookup natLookup;
1788 static int natfd = -1;
1789#endif
7a2f978b 1790
1791 /* Make sure a complete line has been received */
99edd1c3 1792 if ((t = strchr(conn->in.buf, '\n')) == NULL) {
93f9abd0 1793 debug(33, 5) ("Incomplete request line, waiting for more data\n");
7a2f978b 1794 *status = 0;
08e70b8f 1795 *prefix_p = NULL;
1796 *method_p = METHOD_NONE;
7a2f978b 1797 return NULL;
1798 }
99edd1c3 1799 *req_line_sz_p = t - conn->in.buf;
7a2f978b 1800 /* Use xmalloc/xmemcpy instead of xstrdup because inbuf might
1801 * contain NULL bytes; especially for POST data */
1802 inbuf = xmalloc(conn->in.offset + 1);
1803 xmemcpy(inbuf, conn->in.buf, conn->in.offset);
1804 *(inbuf + conn->in.offset) = '\0';
1805
99edd1c3 1806 /* pre-set these values to make aborting simpler */
1807 *prefix_p = inbuf;
1808 *method_p = METHOD_NONE;
1809 *status = -1;
1810
7a2f978b 1811 /* Look for request method */
1812 if ((mstr = strtok(inbuf, "\t ")) == NULL) {
93f9abd0 1813 debug(33, 1) ("parseHttpRequest: Can't get request method\n");
99edd1c3 1814 return parseHttpRequestAbort(conn, "error:invalid-request-method");
7a2f978b 1815 }
1816 method = urlParseMethod(mstr);
1817 if (method == METHOD_NONE) {
93f9abd0 1818 debug(33, 1) ("parseHttpRequest: Unsupported method '%s'\n", mstr);
99edd1c3 1819 return parseHttpRequestAbort(conn, "error:unsupported-request-method");
7a2f978b 1820 }
93f9abd0 1821 debug(33, 5) ("parseHttpRequest: Method is '%s'\n", mstr);
3775d53c 1822 *method_p = method;
7a2f978b 1823
1824 /* look for URL */
1825 if ((url = strtok(NULL, "\r\n\t ")) == NULL) {
93f9abd0 1826 debug(33, 1) ("parseHttpRequest: Missing URL\n");
99edd1c3 1827 return parseHttpRequestAbort(conn, "error:missing-url");
7a2f978b 1828 }
93f9abd0 1829 debug(33, 5) ("parseHttpRequest: Request is '%s'\n", url);
7a2f978b 1830
1831 token = strtok(NULL, null_string);
1832 for (t = token; t && *t && *t != '\n' && *t != '\r'; t++);
97ce5179 1833 if (t == NULL || *t == '\0' || t == token || strncasecmp(token, "HTTP/", 5)) {
93f9abd0 1834 debug(33, 3) ("parseHttpRequest: Missing HTTP identifier\n");
46052490 1835#if RELAXED_HTTP_PARSER
1836 http_ver = (float) 0.9; /* wild guess */
1837#else
99edd1c3 1838 return parseHttpRequestAbort(conn, "error:missing-http-ident");
7518fce5 1839#endif
99edd1c3 1840 } else {
7518fce5 1841 http_ver = (float) atof(token + 5);
99edd1c3 1842 }
7a2f978b 1843
1844 /* Check if headers are received */
754b9ce9 1845 req_hdr = t;
8d9810cd 1846 header_sz = headersEnd(req_hdr, conn->in.offset - (req_hdr - inbuf));
2334c194 1847 if (0 == header_sz) {
1a92a1e2 1848 debug(33, 3) ("parseHttpRequest: header_sz == 0\n");
7a2f978b 1849 *status = 0;
1850 return NULL;
1851 }
754b9ce9 1852 /*
99edd1c3 1853 * Skip whitespace at the end of the first line, up to the
754b9ce9 1854 * first newline.
1855 */
1856 while (isspace(*req_hdr)) {
1857 header_sz--;
1858 if (*(req_hdr++) == '\n')
1859 break;
1860 }
1861 assert(header_sz > 0);
1862 debug(33, 3) ("parseHttpRequest: req_hdr = {%s}\n", req_hdr);
2334c194 1863 end = req_hdr + header_sz;
04990e2d 1864 debug(33, 3) ("parseHttpRequest: end = {%s}\n", end);
99edd1c3 1865
99edd1c3 1866 prefix_sz = end - inbuf;
1867 *req_line_sz_p = req_hdr - inbuf;
ea285003 1868 debug(33, 3) ("parseHttpRequest: prefix_sz = %d, req_line_sz = %d\n",
99edd1c3 1869 (int) prefix_sz, (int) *req_line_sz_p);
1870 assert(prefix_sz <= conn->in.offset);
7a2f978b 1871
1872 /* Ok, all headers are received */
1873 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1874 cbdataAdd(http, MEM_NONE);
7a2f978b 1875 http->http_ver = http_ver;
1876 http->conn = conn;
1877 http->start = current_time;
99edd1c3 1878 http->req_sz = prefix_sz;
d192d11f 1879 http->range_iter.boundary = StringNull;
99edd1c3 1880 *prefix_p = xmalloc(prefix_sz + 1);
1881 xmemcpy(*prefix_p, conn->in.buf, prefix_sz);
1882 *(*prefix_p + prefix_sz) = '\0';
7a2f978b 1883
ea285003 1884 debug(33, 5) ("parseHttpRequest: Request Header is\n%s\n", (*prefix_p) + *req_line_sz_p);
23d92c64 1885 /* Assign http->uri */
7a2f978b 1886 if ((t = strchr(url, '\n'))) /* remove NL */
1887 *t = '\0';
1888 if ((t = strchr(url, '\r'))) /* remove CR */
1889 *t = '\0';
1890 if ((t = strchr(url, '#'))) /* remove HTML anchors */
1891 *t = '\0';
1892
4162ee3b 1893 /* handle internal objects */
1da5651f 1894 if (internalCheck(url)) {
4162ee3b 1895 /* prepend our name & port */
1da5651f 1896 http->uri = xstrdup(internalLocalUri(NULL, url));
77ed547a 1897 http->flags.internal = 1;
4162ee3b 1898 }
7a2f978b 1899 /* see if we running in Config2.Accel.on, if so got to convert it to URL */
4162ee3b 1900 else if (Config2.Accel.on && *url == '/') {
7a2f978b 1901 /* prepend the accel prefix */
dbfed404 1902 if (opt_accel_uses_host && (t = mime_get_header(req_hdr, "Host"))) {
7a2f978b 1903 /* If a Host: header was specified, use it to build the URL
1904 * instead of the one in the Config file. */
1905 /*
1906 * XXX Use of the Host: header here opens a potential
1907 * security hole. There are no checks that the Host: value
1908 * corresponds to one of your servers. It might, for example,
1909 * refer to www.playboy.com. The 'dst' and/or 'dst_domain' ACL
1910 * types should be used to prevent httpd-accelerators
1911 * handling requests for non-local servers */
1912 strtok(t, " :/;@");
12fc602c 1913 url_sz = strlen(url) + 32 + Config.appendDomainLen +
1914 strlen(t);
23d92c64 1915 http->uri = xcalloc(url_sz, 1);
1916 snprintf(http->uri, url_sz, "http://%s:%d%s",
7a2f978b 1917 t, (int) Config.Accel.port, url);
dbfed404 1918 } else if (vhost_mode) {
1919 /* Put the local socket IP address as the hostname */
1920 url_sz = strlen(url) + 32 + Config.appendDomainLen;
1921 http->uri = xcalloc(url_sz, 1);
5cafc1d6 1922#if IPF_TRANSPARENT
1923 natLookup.nl_inport = http->conn->me.sin_port;
1924 natLookup.nl_outport = http->conn->peer.sin_port;
1925 natLookup.nl_inip = http->conn->me.sin_addr;
1926 natLookup.nl_outip = http->conn->peer.sin_addr;
1927 natLookup.nl_flags = IPN_TCP;
1928 if (natfd < 0)
1929 natfd = open(IPL_NAT, O_RDONLY,0 );
1930 if (natfd < 0) {
1931 debug(50,1)("parseHttpRequest: NAT open failed: %s\n",
1932 xstrerror());
1933 return NULL;
1934 }
1935 if (ioctl(natfd, SIOCGNATL, &natLookup) < 0) {
1936 debug(50,1)("parseHttpRequest: NAT lookup failed: %s\n",
1937 xstrerror());
1938 close(natfd);
1939 natfd = -1;
1940 return NULL;
1941 }
1942 snprintf(http->uri, url_sz, "http://%s:%d%s",
1943 inet_ntoa(natLookup.nl_realip),
1944 (int)Config.Accel.port,
1945 url);
1946#else
dbfed404 1947 snprintf(http->uri, url_sz, "http://%s:%d%s",
1948 inet_ntoa(http->conn->me.sin_addr),
1949 (int) Config.Accel.port,
1950 url);
5cafc1d6 1951#endif
93f9abd0 1952 debug(33, 5) ("VHOST REWRITE: '%s'\n", http->uri);
7a2f978b 1953 } else {
1954 url_sz = strlen(Config2.Accel.prefix) + strlen(url) +
1955 Config.appendDomainLen + 1;
23d92c64 1956 http->uri = xcalloc(url_sz, 1);
1957 snprintf(http->uri, url_sz, "%s%s", Config2.Accel.prefix, url);
7a2f978b 1958 }
77ed547a 1959 http->flags.accel = 1;
7a2f978b 1960 } else {
1961 /* URL may be rewritten later, so make extra room */
1962 url_sz = strlen(url) + Config.appendDomainLen + 5;
23d92c64 1963 http->uri = xcalloc(url_sz, 1);
1964 strcpy(http->uri, url);
77ed547a 1965 http->flags.accel = 0;
7a2f978b 1966 }
23d92c64 1967 http->log_uri = xstrdup(http->uri);
93f9abd0 1968 debug(33, 5) ("parseHttpRequest: Complete request received\n");
7a2f978b 1969 if (free_request)
1970 safe_free(url);
1971 xfree(inbuf);
7a2f978b 1972 *status = 1;
1973 return http;
1974}
1975
1976static int
79d39a72 1977clientReadDefer(int fdnotused, void *data)
7a2f978b 1978{
1979 ConnStateData *conn = data;
1980 return conn->defer.until > squid_curtime;
1981}
1982
1983static void
1984clientReadRequest(int fd, void *data)
1985{
1986 ConnStateData *conn = data;
1987 int parser_return_code = 0;
1988 int k;
1989 request_t *request = NULL;
7a2f978b 1990 int size;
7a2f978b 1991 method_t method;
1992 clientHttpRequest *http = NULL;
1993 clientHttpRequest **H = NULL;
08e70b8f 1994 char *prefix = NULL;
7a2f978b 1995 ErrorState *err = NULL;
1996 fde *F = &fd_table[fd];
44db45e8 1997 int len = conn->in.size - conn->in.offset - 1;
93f9abd0 1998 debug(33, 4) ("clientReadRequest: FD %d: reading request...\n", fd);
886f2785 1999 Counter.syscalls.sock.reads++;
7a2f978b 2000 size = read(fd, conn->in.buf + conn->in.offset, len);
d8b83480 2001 if (size > 0) {
ea285003 2002 fd_bytes(fd, size, FD_READ);
2003 kb_incr(&Counter.client_http.kbytes_in, size);
d8b83480 2004 }
44db45e8 2005 /*
2006 * Don't reset the timeout value here. The timeout value will be
2007 * set to Config.Timeout.request by httpAccept() and
2008 * clientWriteComplete(), and should apply to the request as a
2009 * whole, not individual read() calls. Plus, it breaks our
2010 * lame half-close detection
2011 */
2012 commSetSelect(fd, COMM_SELECT_READ, clientReadRequest, conn, 0);
7a2f978b 2013 if (size == 0) {
2014 if (conn->chr == NULL) {
2015 /* no current or pending requests */
2016 comm_close(fd);
2017 return;
ea285003 2018 } else if (!Config.onoff.half_closed_clients) {
2019 /* admin doesn't want to support half-closed client sockets */
2020 comm_close(fd);
2021 return;
7a2f978b 2022 }
2023 /* It might be half-closed, we can't tell */
93f9abd0 2024 debug(33, 5) ("clientReadRequest: FD %d closed?\n", fd);
58a6c186 2025 F->flags.socket_eof = 1;
7a2f978b 2026 conn->defer.until = squid_curtime + 1;
2027 conn->defer.n++;
44db45e8 2028 fd_note(fd, "half-closed");
7a2f978b 2029 return;
2030 } else if (size < 0) {
6d3caf23 2031 if (!ignoreErrno(errno)) {
7a2f978b 2032 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd, xstrerror());
2033 comm_close(fd);
ebf4efff 2034 return;
47130615 2035 } else if (conn->in.offset == 0) {
7c1d4010 2036 debug(50, 2) ("clientReadRequest: FD %d: no data to process (%s)\n", fd, xstrerror());
ebf4efff 2037 return;
7a2f978b 2038 }
ebf4efff 2039 /* Continue to process previously read data */
47130615 2040 size = 0;
7a2f978b 2041 }
2042 conn->in.offset += size;
5ede6c8f 2043 /* Skip leading (and trailing) whitespace */
7a2f978b 2044 while (conn->in.offset > 0) {
ebf4efff 2045 int nrequests;
cff0c749 2046 size_t req_line_sz;
9a6f98a5 2047 while (conn->in.offset > 0 && isspace(conn->in.buf[0])) {
2048 xmemmove(conn->in.buf, conn->in.buf + 1, conn->in.offset - 1);
2049 conn->in.offset--;
2050 }
2051 conn->in.buf[conn->in.offset] = '\0'; /* Terminate the string */
2052 if (conn->in.offset == 0)
2053 break;
ebf4efff 2054 /* Limit the number of concurrent requests to 2 */
2055 for (H = &conn->chr, nrequests = 0; *H; H = &(*H)->next, nrequests++);
2056 if (nrequests >= 2) {
93f9abd0 2057 debug(33, 2) ("clientReadRequest: FD %d max concurrent requests reached\n", fd);
2058 debug(33, 5) ("clientReadRequest: FD %d defering new request until one is done\n", fd);
47130615 2059 conn->defer.until = squid_curtime + 100; /* Reset when a request is complete */
ebf4efff 2060 break;
2061 }
2062 /* Process request */
7a2f978b 2063 http = parseHttpRequest(conn,
2064 &method,
2065 &parser_return_code,
99edd1c3 2066 &prefix,
2067 &req_line_sz);
13f11a4a 2068 if (!http)
2069 safe_free(prefix);
7a2f978b 2070 if (http) {
2071 assert(http->req_sz > 0);
2072 conn->in.offset -= http->req_sz;
2073 assert(conn->in.offset >= 0);
ebb6e9a0 2074 debug(33, 5) ("conn->in.offset = %d\n", (int) conn->in.offset);
6fa92aa2 2075 /*
2076 * If we read past the end of this request, move the remaining
2077 * data to the beginning
2078 */
2079 if (conn->in.offset > 0)
dbfed404 2080 xmemmove(conn->in.buf, conn->in.buf + http->req_sz, conn->in.offset);
ebf4efff 2081 /* add to the client request queue */
7a2f978b 2082 for (H = &conn->chr; *H; H = &(*H)->next);
2083 *H = http;
2084 conn->nrequests++;
2085 commSetTimeout(fd, Config.Timeout.lifetime, NULL, NULL);
3775d53c 2086 if (parser_return_code < 0) {
93f9abd0 2087 debug(33, 1) ("clientReadRequest: FD %d Invalid Request\n", fd);
3775d53c 2088 err = errorCon(ERR_INVALID_REQ, HTTP_BAD_REQUEST);
2089 err->request_hdrs = xstrdup(conn->in.buf);
92695e5e 2090 http->entry = clientCreateStoreEntry(http, method, null_request_flags);
3775d53c 2091 errorAppendEntry(http->entry, err);
13f11a4a 2092 safe_free(prefix);
3775d53c 2093 break;
2094 }
23d92c64 2095 if ((request = urlParse(method, http->uri)) == NULL) {
93f9abd0 2096 debug(33, 5) ("Invalid URL: %s\n", http->uri);
7a2f978b 2097 err = errorCon(ERR_INVALID_URL, HTTP_BAD_REQUEST);
2098 err->src_addr = conn->peer.sin_addr;
23d92c64 2099 err->url = xstrdup(http->uri);
7a2f978b 2100 http->al.http.code = err->http_status;
92695e5e 2101 http->entry = clientCreateStoreEntry(http, method, null_request_flags);
79e0dc20 2102 errorAppendEntry(http->entry, err);
99edd1c3 2103 safe_free(prefix);
7a2f978b 2104 break;
99edd1c3 2105 } else {
2106 /* compile headers */
2107 /* we should skip request line! */
ea285003 2108 if (!httpRequestParseHeader(request, prefix + req_line_sz))
99edd1c3 2109 debug(33, 1) ("Failed to parse request headers: %s\n%s\n",
2110 http->uri, prefix);
2111 /* continue anyway? */
7a2f978b 2112 }
ba26bca4 2113 if (!http->flags.internal) {
2114 if (internalCheck(strBuf(request->urlpath))) {
2115 if (0 == strcasecmp(request->host, getMyHostname())) {
4b4cd312 2116 if (request->port == Config.Port.http->i)
2117 http->flags.internal = 1;
ba26bca4 2118 } else if (internalStaticCheck(strBuf(request->urlpath))) {
5999b776 2119 xstrncpy(request->host, getMyHostname(), SQUIDHOSTNAMELEN);
2120 request->port = Config.Port.http->i;
2121 http->flags.internal = 1;
ba26bca4 2122 }
2123 }
2124 }
13f11a4a 2125 safe_free(prefix);
23d92c64 2126 safe_free(http->log_uri);
2127 http->log_uri = xstrdup(urlCanonicalClean(request));
7a2f978b 2128 request->client_addr = conn->peer.sin_addr;
2129 request->http_ver = http->http_ver;
7a2f978b 2130 if (!urlCheckRequest(request)) {
2131 err = errorCon(ERR_UNSUP_REQ, HTTP_NOT_IMPLEMENTED);
2132 err->src_addr = conn->peer.sin_addr;
7a2f978b 2133 err->request = requestLink(request);
2134 http->al.http.code = err->http_status;
92695e5e 2135 http->entry = clientCreateStoreEntry(http, request->method, null_request_flags);
79e0dc20 2136 errorAppendEntry(http->entry, err);
3775d53c 2137 break;
7a2f978b 2138 }
31be8b80 2139 if (0 == clientCheckContentLength(request)) {
2140 err = errorCon(ERR_INVALID_REQ, HTTP_LENGTH_REQUIRED);
2141 err->src_addr = conn->peer.sin_addr;
2142 err->request = requestLink(request);
2143 http->al.http.code = err->http_status;
92695e5e 2144 http->entry = clientCreateStoreEntry(http, request->method, null_request_flags);
31be8b80 2145 errorAppendEntry(http->entry, err);
2146 break;
2147 }
7a2f978b 2148 http->request = requestLink(request);
3775d53c 2149 /*
2150 * break here for NON-GET because most likely there is a
7a2f978b 2151 * reqeust body following and we don't want to parse it
3775d53c 2152 * as though it was new request
2153 */
7a2f978b 2154 if (request->method != METHOD_GET) {
ebb6e9a0 2155 int cont_len = httpHeaderGetInt(&request->header, HDR_CONTENT_LENGTH);
2156 int copy_len = XMIN(cont_len, conn->in.offset);
e34195c0 2157 if (copy_len > 0) {
ebb6e9a0 2158 assert(conn->in.offset >= copy_len);
2159 request->body_sz = copy_len;
7a2f978b 2160 request->body = xmalloc(request->body_sz);
2161 xmemcpy(request->body, conn->in.buf, request->body_sz);
ebb6e9a0 2162 conn->in.offset -= copy_len;
2163 if (conn->in.offset)
2164 xmemmove(conn->in.buf, conn->in.buf + copy_len, conn->in.offset);
7a2f978b 2165 }
f7237ed2 2166 /*
2aecf121 2167 * if we didn't get the full body now, then more will
2168 * be arriving on the client socket. Lets cancel
2169 * the read handler until this request gets forwarded.
f7237ed2 2170 */
2aecf121 2171 if (request->body_sz < cont_len)
2172 commSetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
7a2f978b 2173 }
2aecf121 2174 clientAccessCheck(http);
7a2f978b 2175 continue; /* while offset > 0 */
2176 } else if (parser_return_code == 0) {
2177 /*
2178 * Partial request received; reschedule until parseHttpRequest()
2179 * is happy with the input
2180 */
2181 k = conn->in.size - 1 - conn->in.offset;
2182 if (k == 0) {
2183 if (conn->in.offset >= Config.maxRequestSize) {
2184 /* The request is too large to handle */
93f9abd0 2185 debug(33, 0) ("Request won't fit in buffer.\n");
2186 debug(33, 0) ("Config 'request_size'= %d bytes.\n",
7a2f978b 2187 Config.maxRequestSize);
93f9abd0 2188 debug(33, 0) ("This request = %d bytes.\n",
5f6ac48b 2189 (int) conn->in.offset);
7a2f978b 2190 err = errorCon(ERR_INVALID_REQ, HTTP_REQUEST_ENTITY_TOO_LARGE);
92695e5e 2191 http->entry = clientCreateStoreEntry(http, request->method, null_request_flags);
79e0dc20 2192 errorAppendEntry(http->entry, err);
7a2f978b 2193 return;
2194 }
2195 /* Grow the request memory area to accomodate for a large request */
2196 conn->in.size += REQUEST_BUF_SIZE;
2197 conn->in.buf = xrealloc(conn->in.buf, conn->in.size);
59c4d35b 2198 /* XXX account conn->in.buf */
93f9abd0 2199 debug(33, 2) ("Handling a large request, offset=%d inbufsize=%d\n",
5f6ac48b 2200 (int) conn->in.offset, conn->in.size);
7a2f978b 2201 k = conn->in.size - 1 - conn->in.offset;
2202 }
7a2f978b 2203 break;
7a2f978b 2204 }
2205 }
2206}
2207
2208/* general lifetime handler for HTTP requests */
2209static void
2210requestTimeout(int fd, void *data)
2211{
2212 ConnStateData *conn = data;
2213 ErrorState *err;
93f9abd0 2214 debug(33, 2) ("requestTimeout: FD %d: lifetime is expired.\n", fd);
7a2f978b 2215 if (fd_table[fd].rwstate) {
79e0dc20 2216 /*
2217 * Some data has been sent to the client, just close the FD
2218 */
7a2f978b 2219 comm_close(fd);
2220 } else if (conn->nrequests) {
79e0dc20 2221 /*
2222 * assume its a persistent connection; just close it
2223 */
7a2f978b 2224 comm_close(fd);
2225 } else {
79e0dc20 2226 /*
2227 * Generate an error
2228 */
7a2f978b 2229 err = errorCon(ERR_LIFETIME_EXP, HTTP_REQUEST_TIMEOUT);
7a2f978b 2230 err->url = xstrdup("N/A");
79e0dc20 2231 /*
2232 * Normally we shouldn't call errorSend() in client_side.c, but
2233 * it should be okay in this case. Presumably if we get here
2234 * this is the first request for the connection, and no data
2235 * has been written yet
2236 */
2237 assert(conn->chr == NULL);
7a2f978b 2238 errorSend(fd, err);
79e0dc20 2239 /*
2240 * if we don't close() here, we still need a timeout handler!
2241 */
7a2f978b 2242 commSetTimeout(fd, 30, requestTimeout, conn);
2243 }
2244}
2245
ba4f8e5a 2246static int
2247httpAcceptDefer(void)
7a2f978b 2248{
3d6629c6 2249 static time_t last_warn = 0;
2250 if (fdNFree() >= RESERVED_FD)
2251 return 0;
2252 if (last_warn + 15 < squid_curtime) {
2253 debug(33, 0) ("WARNING! Your cache is running out of filedescriptors\n");
2254 last_warn = squid_curtime;
2255 }
2256 return 1;
7a2f978b 2257}
2258
bf8e5903 2259/* Handle a new connection on HTTP socket. */
7a2f978b 2260void
ba4f8e5a 2261httpAccept(int sock, void *data)
7a2f978b 2262{
ba4f8e5a 2263 int *N = data;
7a2f978b 2264 int fd = -1;
2265 ConnStateData *connState = NULL;
2266 struct sockaddr_in peer;
2267 struct sockaddr_in me;
309ad3b6 2268 int max = INCOMING_HTTP_MAX;
c411b98a 2269 commSetSelect(sock, COMM_SELECT_READ, httpAccept, NULL, 0);
ba4f8e5a 2270 while (max-- && !httpAcceptDefer()) {
e2525655 2271 memset(&peer, '\0', sizeof(struct sockaddr_in));
2272 memset(&me, '\0', sizeof(struct sockaddr_in));
e2525655 2273 if ((fd = comm_accept(sock, &peer, &me)) < 0) {
2274 if (!ignoreErrno(errno))
eeb423fb 2275 debug(50, 1) ("httpAccept: FD %d: accept failure: %s\n",
e2525655 2276 sock, xstrerror());
2277 break;
2278 }
2279 debug(33, 4) ("httpAccept: FD %d: accepted\n", fd);
2280 connState = xcalloc(1, sizeof(ConnStateData));
2281 connState->peer = peer;
2282 connState->log_addr = peer.sin_addr;
2283 connState->log_addr.s_addr &= Config.Addrs.client_netmask.s_addr;
2284 connState->me = me;
2285 connState->fd = fd;
2286 connState->ident.fd = -1;
2287 connState->in.size = REQUEST_BUF_SIZE;
2288 connState->in.buf = xcalloc(connState->in.size, 1);
2289 cbdataAdd(connState, MEM_NONE);
2290 /* XXX account connState->in.buf */
2291 comm_add_close_handler(fd, connStateFree, connState);
2292 if (Config.onoff.log_fqdn)
2293 fqdncache_gethostbyaddr(peer.sin_addr, FQDN_LOOKUP_IF_MISS);
2294 commSetTimeout(fd, Config.Timeout.request, requestTimeout, connState);
2295 commSetSelect(fd, COMM_SELECT_READ, clientReadRequest, connState, 0);
2296 commSetDefer(fd, clientReadDefer, connState);
ba4f8e5a 2297 (*N)++;
7a2f978b 2298 }
7a2f978b 2299}
2300
7a2f978b 2301/* return 1 if the request should be aborted */
2302static int
2303CheckQuickAbort2(const clientHttpRequest * http)
2304{
4efca7da 2305 int curlen;
2306 int minlen;
2307 int expectlen;
7a2f978b 2308
92695e5e 2309 if (!http->request->flags.cachable)
7a2f978b 2310 return 1;
d46a87a8 2311 if (EBIT_TEST(http->entry->flags, KEY_PRIVATE))
7a2f978b 2312 return 1;
2313 if (http->entry->mem_obj == NULL)
2314 return 1;
038eb4ed 2315 expectlen = http->entry->mem_obj->reply->content_length;
4efca7da 2316 curlen = (int) http->entry->mem_obj->inmem_hi;
59cb9808 2317 minlen = (int) Config.quickAbort.min << 10;
7a2f978b 2318 if (minlen < 0)
2319 /* disabled */
2320 return 0;
2321 if (curlen > expectlen)
2322 /* bad content length */
2323 return 1;
2324 if ((expectlen - curlen) < minlen)
2325 /* only little more left */
2326 return 0;
59cb9808 2327 if ((expectlen - curlen) > (Config.quickAbort.max << 10))
7a2f978b 2328 /* too much left to go */
2329 return 1;
37d0359b 2330 if (expectlen < 100)
4efca7da 2331 /* avoid FPE */
2332 return 0;
37d0359b 2333 if ((curlen / (expectlen / 100)) > Config.quickAbort.pct)
7a2f978b 2334 /* past point of no return */
2335 return 0;
2336 return 1;
2337}
2338
2339
2340static void
2341CheckQuickAbort(clientHttpRequest * http)
2342{
2343 StoreEntry *entry = http->entry;
2344 /* Note, set entry here because http->entry might get changed (for IMS
2345 * requests) during the storeAbort() call */
2346 if (entry == NULL)
2347 return;
36547bcf 2348 if (storePendingNClients(entry) > 0)
7a2f978b 2349 return;
2350 if (entry->store_status != STORE_PENDING)
2351 return;
2352 if (CheckQuickAbort2(http) == 0)
2353 return;
93f9abd0 2354 debug(33, 3) ("CheckQuickAbort: ABORTING %s\n", storeUrl(entry));
59cb9808 2355 Counter.aborted_requests++;
7a2f978b 2356 storeAbort(entry, 1);
2357}
2358
978e455f 2359#define SENDING_BODY 0
2360#define SENDING_HDRSONLY 1
7a2f978b 2361static int
1b02b5be 2362clientCheckTransferDone(clientHttpRequest * http)
7a2f978b 2363{
978e455f 2364 int sending = SENDING_BODY;
7a2f978b 2365 StoreEntry *entry = http->entry;
978e455f 2366 MemObject *mem;
2367 http_reply *reply;
2368 int sendlen;
7a2f978b 2369 if (entry == NULL)
2370 return 0;
9f086470 2371 /*
2372 * For now, 'done_copying' is used for special cases like
2373 * Range and HEAD requests.
2374 */
2375 if (http->flags.done_copying)
2376 return 1;
978e455f 2377 /*
2378 * Handle STORE_OK and STORE_ABORTED objects.
07304bf9 2379 * objectLen(entry) will be set proprely.
978e455f 2380 */
2381 if (entry->store_status != STORE_PENDING) {
07304bf9 2382 if (http->out.offset >= objectLen(entry))
7a2f978b 2383 return 1;
513f05a6 2384 else
2385 return 0;
2386 }
978e455f 2387 /*
2388 * Now, handle STORE_PENDING objects
2389 */
2390 mem = entry->mem_obj;
2391 assert(mem != NULL);
2392 assert(http->request != NULL);
2393 reply = mem->reply;
2394 if (reply->hdr_sz == 0)
b34ed725 2395 return 0; /* haven't found end of headers yet */
cb69b4c7 2396 else if (reply->sline.status == HTTP_OK)
b34ed725 2397 sending = SENDING_BODY;
cb69b4c7 2398 else if (reply->sline.status == HTTP_NO_CONTENT)
b34ed725 2399 sending = SENDING_HDRSONLY;
cb69b4c7 2400 else if (reply->sline.status == HTTP_NOT_MODIFIED)
b34ed725 2401 sending = SENDING_HDRSONLY;
cb69b4c7 2402 else if (reply->sline.status < HTTP_OK)
a3c60429 2403 sending = SENDING_HDRSONLY;
978e455f 2404 else if (http->request->method == METHOD_HEAD)
b34ed725 2405 sending = SENDING_HDRSONLY;
978e455f 2406 else
2407 sending = SENDING_BODY;
2408 /*
2409 * Figure out how much data we are supposed to send.
2410 * If we are sending a body and we don't have a content-length,
2411 * then we must wait for the object to become STORE_OK or
2412 * STORE_ABORTED.
2413 */
2414 if (sending == SENDING_HDRSONLY)
2415 sendlen = reply->hdr_sz;
038eb4ed 2416 else if (reply->content_length < 0)
978e455f 2417 return 0;
2418 else
038eb4ed 2419 sendlen = reply->content_length + reply->hdr_sz;
978e455f 2420 /*
2421 * Now that we have the expected length, did we send it all?
2422 */
2423 if (http->out.offset < sendlen)
2424 return 0;
2425 else
b34ed725 2426 return 1;
7a2f978b 2427}
2428
7a2f978b 2429/*
2430 * This function is designed to serve a fairly specific purpose.
2431 * Occasionally our vBNS-connected caches can talk to each other, but not
2432 * the rest of the world. Here we try to detect frequent failures which
2433 * make the cache unusable (e.g. DNS lookup and connect() failures). If
2434 * the failure:success ratio goes above 1.0 then we go into "hit only"
2435 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
2436 * will only fetch HITs from us if they are using the ICP protocol. We
2437 * stay in this mode for 5 minutes.
2438 *
2439 * Duane W., Sept 16, 1996
2440 */
2441
2442static void
88aad2e5 2443checkFailureRatio(err_type etype, hier_code hcode)
7a2f978b 2444{
88aad2e5 2445 static double magic_factor = 100.0;
7a2f978b 2446 double n_good;
2447 double n_bad;
2448 if (hcode == HIER_NONE)
2449 return;
88aad2e5 2450 n_good = magic_factor / (1.0 + request_failure_ratio);
7a2f978b 2451 n_bad = magic_factor - n_good;
88aad2e5 2452 switch (etype) {
7a2f978b 2453 case ERR_DNS_FAIL:
2454 case ERR_CONNECT_FAIL:
2455 case ERR_READ_ERROR:
2456 n_bad++;
2457 break;
2458 default:
2459 n_good++;
2460 }
88aad2e5 2461 request_failure_ratio = n_bad / n_good;
7a2f978b 2462 if (hit_only_mode_until > squid_curtime)
2463 return;
88aad2e5 2464 if (request_failure_ratio < 1.0)
7a2f978b 2465 return;
93f9abd0 2466 debug(33, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio);
2467 debug(33, 0) ("Going into hit-only-mode for %d minutes...\n",
7a2f978b 2468 FAILURE_MODE_TIME / 60);
2469 hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
88aad2e5 2470 request_failure_ratio = 0.8; /* reset to something less than 1.0 */
7a2f978b 2471}
15df8349 2472
2473void
2474clientHttpConnectionsOpen(void)
2475{
2476 ushortlist *u;
2477 int fd;
15df8349 2478 for (u = Config.Port.http; u; u = u->next) {
8daca701 2479 enter_suid();
2480 fd = comm_open(SOCK_STREAM,
2481 0,
2482 Config.Addrs.tcp_incoming,
2483 u->i,
2484 COMM_NONBLOCKING,
2485 "HTTP Socket");
2486 leave_suid();
2487 if (fd < 0)
2488 continue;
2489 comm_listen(fd);
2490 commSetSelect(fd, COMM_SELECT_READ, httpAccept, NULL, 0);
eeb423fb 2491 /*commSetDefer(fd, httpAcceptDefer, NULL); */
8daca701 2492 debug(1, 1) ("Accepting HTTP connections on port %d, FD %d.\n",
2493 (int) u->i, fd);
2494 HttpSockets[NHttpSockets++] = fd;
15df8349 2495 }
2496 if (NHttpSockets < 1)
8daca701 2497 fatal("Cannot open HTTP Port");
15df8349 2498}
c0fbae16 2499
2500void
2501clientHttpConnectionsClose(void)
2502{
2503 int i;
2504 for (i = 0; i < NHttpSockets; i++) {
2505 if (HttpSockets[i] >= 0) {
2506 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets[i]);
2507 comm_close(HttpSockets[i]);
2508 HttpSockets[i] = -1;
2509 }
2510 }
2511 NHttpSockets = 0;
2512}