]> git.ipfire.org Git - thirdparty/squid.git/blame - src/client_side.cc
remove src/options.h
[thirdparty/squid.git] / src / client_side.cc
CommitLineData
3c66d057 1
dd11e0b7 2/*
3f6c0fb2 3 * $Id: client_side.cc,v 1.198 1998/01/12 04:29:58 wessels 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/
dd11e0b7 9 * --------------------------------------------------------
10 *
11 * Squid is the result of efforts by numerous individuals from the
12 * Internet community. Development is led by Duane Wessels of the
13 * National Laboratory for Applied Network Research and funded by
14 * the National Science Foundation.
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 *
30 */
f88bb09c 31
32#include "squid.h"
33
7a2f978b 34static const char *const crlf = "\r\n";
fc5d6f7f 35static const char *const proxy_auth_line =
36"Proxy-Authenticate: Basic realm=\"Squid proxy-caching web server\"\r\n";
7a2f978b 37
38#define REQUEST_BUF_SIZE 4096
39#define FAILURE_MODE_TIME 300
40
41/* Local functions */
42
1b02b5be 43static CWCB clientHandleIMSComplete;
fc5d6f7f 44static CWCB clientWriteComplete;
7a2f978b 45static PF clientReadRequest;
46static PF connStateFree;
47static PF requestTimeout;
1b02b5be 48static STCB clientGetHeadersForIMS;
49static char *clientConstruct304reply(struct _http_reply *);
7a2f978b 50static int CheckQuickAbort2(const clientHttpRequest *);
1b02b5be 51static int clientCheckTransferDone(clientHttpRequest *);
7a2f978b 52static void CheckQuickAbort(clientHttpRequest *);
88aad2e5 53static void checkFailureRatio(err_type, hier_code);
fb63215a 54static void clientProcessMiss(clientHttpRequest *);
7a2f978b 55static void clientAppendReplyHeader(char *, const char *, size_t *, size_t);
56size_t clientBuildReplyHeader(clientHttpRequest *, char *, size_t *, char *, size_t);
57static clientHttpRequest *parseHttpRequest(ConnStateData *, method_t *, int *, char **, size_t *);
582b6456 58static RH clientRedirectDone;
1b02b5be 59static STCB clientHandleIMSReply;
f5b8bbc4 60static int clientGetsOldEntry(StoreEntry * new, StoreEntry * old, request_t * request);
61static int checkAccelOnly(clientHttpRequest *);
7a2f978b 62static STCB clientSendMoreData;
63static STCB clientCacheHit;
50ddd7a4 64static void clientParseRequestHeaders(clientHttpRequest *);
fb63215a 65static void clientProcessRequest(clientHttpRequest *);
66static void clientProcessExpired(void *data);
fc5d6f7f 67static char *clientConstructProxyAuthReply(clientHttpRequest * http);
50ddd7a4 68static int clientCachable(clientHttpRequest * http);
69static int clientHierarchical(clientHttpRequest * http);
ea6f43cd 70
38d7734b 71static int
382d851a 72checkAccelOnly(clientHttpRequest * http)
38d7734b 73{
74 /* return TRUE if someone makes a proxy request to us and
75 * we are in httpd-accel only mode */
f1dc9b30 76 if (!Config2.Accel.on)
38d7734b 77 return 0;
17a0a4ee 78 if (Config.onoff.accel_with_proxy)
38d7734b 79 return 0;
382d851a 80 if (http->request->protocol == PROTO_CACHEOBJ)
38d7734b 81 return 0;
382d851a 82 if (http->accel)
38d7734b 83 return 0;
84 return 1;
85}
86
b8d8561b 87void
382d851a 88clientAccessCheck(void *data)
f88bb09c 89{
382d851a 90 clientHttpRequest *http = data;
91 ConnStateData *conn = http->conn;
75e88d56 92 char *browser;
17a0a4ee 93 if (Config.onoff.ident_lookup && conn->ident.state == IDENT_NONE) {
382d851a 94 identStart(-1, conn, clientAccessCheck);
ba1d2afa 95 return;
96 }
382d851a 97 if (checkAccelOnly(http)) {
98 clientAccessCheckDone(0, http);
75e88d56 99 return;
f88bb09c 100 }
f182d1c5 101 browser = mime_get_header(http->request->headers, "User-Agent");
f1dc9b30 102 http->acl_checklist = aclChecklistCreate(Config.accessList.http,
382d851a 103 http->request,
104 conn->peer.sin_addr,
75e88d56 105 browser,
382d851a 106 conn->ident.ident);
107 aclNBCheck(http->acl_checklist, clientAccessCheckDone, http);
f88bb09c 108}
109
fc5d6f7f 110static char *
111clientConstructProxyAuthReply(clientHttpRequest * http)
112{
113 LOCAL_ARRAY(char, buf, 8192);
114 LOCAL_ARRAY(char, content, 4096);
115 char *hdr;
116 memset(buf, '\0', 8192);
117 memset(content, '\0', 4096);
118 snprintf(content, 4096,
119 "<TITLE>Cache Access Denied</TITLE>\n"
120 "<H2>Cache Access Denied</H2>\n"
121 "<P>\n"
122 "Sorry, you are not currently allowed to request:\n"
123 "<PRE> %s</PRE>\n"
124 "from this cache until you have authenticated yourself.\n"
125 "\n<p>"
126 "You need to use Netscape version 2.0 or greater, or Microsoft\n"
127 "Internet Explorer 3.0 or an HTTP/1.1 compliant browser for this\n"
128 "to work. Please contact the <a href=\"mailto:%s\">cache\n"
129 "administrator</a> if you have difficulties authenticating\n"
130 "yourself, or\n"
131 "<a href=\"http://%s/cgi-bin/chpasswd.cgi\">change</a> your\n"
132 "default password.\n"
133 "<P>\n"
134 "%s\n"
135 "<HR>\n"
136 "<ADDRESS>\n"
137 "Generated by %s/%s@%s\n"
138 "</ADDRESS>\n",
23d92c64 139 http->uri,
fc5d6f7f 140 Config.adminEmail,
141 getMyHostname(),
142 Config.errHtmlText,
143 appname,
144 version_string,
145 getMyHostname());
146 hdr = httpReplyHeader(1.0,
147 HTTP_PROXY_AUTHENTICATION_REQUIRED,
148 "text/html",
149 strlen(content),
9daad6f0 150 0,
fc5d6f7f 151 squid_curtime);
152 snprintf(buf, 8192, "%s%s\r\n%s",
153 hdr,
154 proxy_auth_line,
155 content);
156 return buf;
157}
158
23d92c64 159StoreEntry *
f44af445 160clientCreateStoreEntry(clientHttpRequest * h, method_t m, int flags)
79e0dc20 161{
162 StoreEntry *e;
40defb17 163 request_t *r;
164 /*
165 * For erroneous requests, we might not have a h->request,
166 * so make a fake one.
167 */
168 if (h->request == NULL) {
3f6c0fb2 169 r = memAllocate(MEM_REQUEST_T, 1);
40defb17 170 r->method = m;
171 r->protocol = PROTO_NONE;
172 h->request = requestLink(r);
173 }
23d92c64 174 e = storeCreateEntry(h->uri, h->log_uri, flags, m);
79e0dc20 175 storeClientListAdd(e, h);
3f6c0fb2 176 storeClientCopy(e, 0, 0, 4096, memAllocate(MEM_4K_BUF, 1), clientSendMoreData, h);
79e0dc20 177 return e;
178}
179
180
b8d8561b 181void
75e88d56 182clientAccessCheckDone(int answer, void *data)
f88bb09c 183{
382d851a 184 clientHttpRequest *http = data;
e92d33a5 185 char *redirectUrl = NULL;
fc5d6f7f 186 char *buf;
9b312a19 187 ErrorState *err = NULL;
23d92c64 188 debug(33, 5) ("clientAccessCheckDone: '%s' answer=%d\n", http->uri, answer);
382d851a 189 http->acl_checklist = NULL;
fc5d6f7f 190 if (answer == ACCESS_ALLOWED) {
23d92c64 191 urlCanonical(http->request, http->uri);
ce66013b 192 assert(http->redirect_state == REDIRECT_NONE);
382d851a 193 http->redirect_state = REDIRECT_PENDING;
194 redirectStart(http, clientRedirectDone, http);
fc5d6f7f 195 } else if (answer == ACCESS_REQ_PROXY_AUTH) {
196 http->al.http.code = HTTP_PROXY_AUTHENTICATION_REQUIRED;
197 http->log_type = LOG_TCP_DENIED;
198 buf = clientConstructProxyAuthReply(http);
f44af445 199 http->entry = clientCreateStoreEntry(http, http->request->method, 0);
79e0dc20 200 storeAppend(http->entry, buf, strlen(buf));
f88bb09c 201 } else {
23d92c64 202 debug(33, 5) ("Access Denied: %s\n", http->uri);
79a15e0a 203 http->log_type = LOG_TCP_DENIED;
f44af445 204 http->entry = clientCreateStoreEntry(http, http->request->method, 0);
85034133 205 redirectUrl = aclGetDenyInfoUrl(&Config.denyInfoList, AclMatchedName);
e92d33a5 206 if (redirectUrl) {
fe40a877 207 err = errorCon(ERR_ACCESS_DENIED, HTTP_MOVED_TEMPORARILY);
208 err->request = requestLink(http->request);
209 err->src_addr = http->conn->peer.sin_addr;
9b312a19 210 err->redirect_url = xstrdup(redirectUrl);
79e0dc20 211 errorAppendEntry(http->entry, err);
e92d33a5 212 } else {
d2989683 213 /* NOTE: don't use HTTP_UNAUTHORIZED because then the
437e2060 214 * stupid browser wants us to authenticate */
fe40a877 215 err = errorCon(ERR_ACCESS_DENIED, HTTP_FORBIDDEN);
216 err->request = requestLink(http->request);
217 err->src_addr = http->conn->peer.sin_addr;
79e0dc20 218 errorAppendEntry(http->entry, err);
e92d33a5 219 }
f88bb09c 220 }
221}
222
b8d8561b 223static void
224clientRedirectDone(void *data, char *result)
f88bb09c 225{
382d851a 226 clientHttpRequest *http = data;
88738790 227 size_t l;
c0cdaf99 228 request_t *new_request = NULL;
382d851a 229 request_t *old_request = http->request;
23d92c64 230 debug(33, 5) ("clientRedirectDone: '%s' result=%s\n", http->uri,
f88bb09c 231 result ? result : "NULL");
ce66013b 232 assert(http->redirect_state == REDIRECT_PENDING);
382d851a 233 http->redirect_state = REDIRECT_DONE;
c0cdaf99 234 if (result)
20cc1450 235 new_request = urlParse(old_request->method, result);
c0cdaf99 236 if (new_request) {
23d92c64 237 safe_free(http->uri);
88738790 238 /* need to malloc because the URL returned by the redirector might
239 * not be big enough to append the local domain
240 * -- David Lamkin drl@net-tel.co.uk */
241 l = strlen(result) + Config.appendDomainLen + 5;
23d92c64 242 http->uri = xcalloc(l, 1);
243 xstrncpy(http->uri, result, l);
20cc1450 244 new_request->http_ver = old_request->http_ver;
16b9d3df 245 new_request->headers = xstrdup(old_request->headers);
2357f74a 246 new_request->headers_sz = old_request->headers_sz;
20cc1450 247 requestUnlink(old_request);
382d851a 248 http->request = requestLink(new_request);
23d92c64 249 urlCanonical(http->request, http->uri);
f88bb09c 250 }
50ddd7a4 251 clientParseRequestHeaders(http);
23d92c64 252 fd_note(http->conn->fd, http->uri);
fb63215a 253 clientProcessRequest(http);
e81957b7 254}
255
fb63215a 256static void
257clientProcessExpired(void *data)
620da955 258{
382d851a 259 clientHttpRequest *http = data;
23d92c64 260 char *url = http->uri;
620da955 261 StoreEntry *entry = NULL;
23d92c64 262 debug(33, 3) ("clientProcessExpired: '%s'\n", http->uri);
79a15e0a 263 EBIT_SET(http->request->flags, REQ_REFRESH);
382d851a 264 http->old_entry = http->entry;
620da955 265 entry = storeCreateEntry(url,
23d92c64 266 http->log_uri,
382d851a 267 http->request->flags,
268 http->request->method);
620da955 269 /* NOTE, don't call storeLockObject(), storeCreateEntry() does it */
fe96bbe6 270 storeClientListAdd(entry, http);
271 storeClientListAdd(http->old_entry, http);
382d851a 272 entry->lastmod = http->old_entry->lastmod;
50ddd7a4 273 debug(33, 5) ("clientProcessExpired: setting lmt = %d\n",
620da955 274 entry->lastmod);
d1a43e28 275 entry->refcount++; /* EXPIRED CASE */
382d851a 276 http->entry = entry;
277 http->out.offset = 0;
fb63215a 278 protoDispatch(http->conn->fd, http->entry, http->request);
f990cccc 279 /* Register with storage manager to receive updates when data comes in. */
d89d1fb6 280 storeClientCopy(entry,
fe96bbe6 281 http->out.offset,
d89d1fb6 282 http->out.offset,
283 4096,
3f6c0fb2 284 memAllocate(MEM_4K_BUF, 1),
1b02b5be 285 clientHandleIMSReply,
d89d1fb6 286 http);
620da955 287}
288
91f4d519 289static int
290clientGetsOldEntry(StoreEntry * new_entry, StoreEntry * old_entry, request_t * request)
291{
292 /* If the reply is anything but "Not Modified" then
293 * we must forward it to the client */
294 if (new_entry->mem_obj->reply->code != 304) {
a3d5953d 295 debug(33, 5) ("clientGetsOldEntry: NO, reply=%d\n", new_entry->mem_obj->reply->code);
91f4d519 296 return 0;
297 }
298 /* If the client did not send IMS in the request, then it
299 * must get the old object, not this "Not Modified" reply */
79a15e0a 300 if (!EBIT_TEST(request->flags, REQ_IMS)) {
a3d5953d 301 debug(33, 5) ("clientGetsOldEntry: YES, no client IMS\n");
91f4d519 302 return 1;
303 }
304 /* If the client IMS time is prior to the entry LASTMOD time we
305 * need to send the old object */
306 if (modifiedSince(old_entry, request)) {
a3d5953d 307 debug(33, 5) ("clientGetsOldEntry: YES, modified since %d\n", request->ims);
91f4d519 308 return 1;
309 }
a3d5953d 310 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
91f4d519 311 return 0;
312}
313
314
52d4522b 315static void
1b02b5be 316clientHandleIMSReply(void *data, char *buf, ssize_t size)
620da955 317{
382d851a 318 clientHttpRequest *http = data;
382d851a 319 StoreEntry *entry = http->entry;
620da955 320 MemObject *mem = entry->mem_obj;
9fb13bb6 321 const char *url = storeUrl(entry);
e92d33a5 322 int unlink_request = 0;
76cff1d4 323 StoreEntry *oldentry;
1b02b5be 324 debug(33, 3) ("clientHandleIMSReply: %s\n", url);
3f6c0fb2 325 memFree(MEM_4K_BUF, buf);
76a5501f 326 buf = NULL;
620da955 327 /* unregister this handler */
070d29eb 328 if (size < 0 || entry->store_status == STORE_ABORTED) {
1b02b5be 329 debug(33, 3) ("clientHandleIMSReply: ABORTED '%s'\n", url);
c54e9052 330 /* We have an existing entry, but failed to validate it */
accc6d47 331 /* Its okay to send the old one anyway */
332 http->log_type = LOG_TCP_REFRESH_FAIL_HIT;
333 storeUnregister(entry, http);
334 storeUnlockObject(entry);
335 entry = http->entry = http->old_entry;
336 entry->refcount++;
a18b8172 337 } else if (mem->reply->code == 0) {
1b02b5be 338 debug(33, 3) ("clientHandleIMSReply: Incomplete headers for '%s'\n", url);
d89d1fb6 339 storeClientCopy(entry,
fe96bbe6 340 http->out.offset + size,
d89d1fb6 341 http->out.offset,
342 4096,
3f6c0fb2 343 memAllocate(MEM_4K_BUF, 1),
1b02b5be 344 clientHandleIMSReply,
d89d1fb6 345 http);
52d4522b 346 return;
382d851a 347 } else if (clientGetsOldEntry(entry, http->old_entry, http->request)) {
620da955 348 /* We initiated the IMS request, the client is not expecting
76cff1d4 349 * 304, so put the good one back. First, make sure the old entry
350 * headers have been loaded from disk. */
382d851a 351 oldentry = http->old_entry;
382d851a 352 http->log_type = LOG_TCP_REFRESH_HIT;
d89d1fb6 353 if (oldentry->mem_obj->request == NULL) {
354 oldentry->mem_obj->request = requestLink(mem->request);
355 unlink_request = 1;
e92d33a5 356 }
64763c37 357 /* Don't memcpy() the whole reply structure here. For example,
358 * www.thegist.com (Netscape/1.13) returns a content-length for
359 * 304's which seems to be the length of the 304 HEADERS!!! and
360 * not the body they refer to. */
361 storeCopyNotModifiedReplyHeaders(entry->mem_obj, oldentry->mem_obj);
d89d1fb6 362 storeTimestampsSet(oldentry);
382d851a 363 storeUnregister(entry, http);
6d54aea8 364 storeUnlockObject(entry);
382d851a 365 entry = http->entry = oldentry;
41fad779 366 entry->timestamp = squid_curtime;
657266fe 367 if (unlink_request) {
e92d33a5 368 requestUnlink(entry->mem_obj->request);
657266fe 369 entry->mem_obj->request = NULL;
370 }
620da955 371 } else {
372 /* the client can handle this reply, whatever it is */
382d851a 373 http->log_type = LOG_TCP_REFRESH_MISS;
d1a43e28 374 if (mem->reply->code == 304) {
382d851a 375 http->old_entry->timestamp = squid_curtime;
376 http->old_entry->refcount++;
377 http->log_type = LOG_TCP_REFRESH_HIT;
d1a43e28 378 }
382d851a 379 storeUnregister(http->old_entry, http);
380 storeUnlockObject(http->old_entry);
620da955 381 }
382d851a 382 http->old_entry = NULL; /* done with old_entry */
e8479da9 383 /* use clientCacheHit() here as the callback because we might
6a54c60e 384 * be swapping in from disk, and the file might not really be
385 * there */
d89d1fb6 386 storeClientCopy(entry,
fe96bbe6 387 http->out.offset,
d89d1fb6 388 http->out.offset,
389 4096,
3f6c0fb2 390 memAllocate(MEM_4K_BUF, 1),
e8479da9 391 clientCacheHit,
d89d1fb6 392 http);
620da955 393}
91f4d519 394
395int
304d07cb 396modifiedSince(StoreEntry * entry, request_t * request)
91f4d519 397{
398 int object_length;
399 MemObject *mem = entry->mem_obj;
9fb13bb6 400 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry));
91f4d519 401 if (entry->lastmod < 0)
402 return 1;
403 /* Find size of the object */
1790d392 404 if (mem->reply->content_length >= 0)
91f4d519 405 object_length = mem->reply->content_length;
406 else
407 object_length = entry->object_len - mem->reply->hdr_sz;
408 if (entry->lastmod > request->ims) {
a3d5953d 409 debug(33, 3) ("--> YES: entry newer than client\n");
91f4d519 410 return 1;
411 } else if (entry->lastmod < request->ims) {
a3d5953d 412 debug(33, 3) ("--> NO: entry older than client\n");
91f4d519 413 return 0;
414 } else if (request->imslen < 0) {
a3d5953d 415 debug(33, 3) ("--> NO: same LMT, no client length\n");
91f4d519 416 return 0;
417 } else if (request->imslen == object_length) {
a3d5953d 418 debug(33, 3) ("--> NO: same LMT, same length\n");
91f4d519 419 return 0;
420 } else {
a3d5953d 421 debug(33, 3) ("--> YES: same LMT, different length\n");
91f4d519 422 return 1;
423 }
424}
b3b64e58 425
426char *
382d851a 427clientConstructTraceEcho(clientHttpRequest * http)
b3b64e58 428{
429 LOCAL_ARRAY(char, line, 256);
430 LOCAL_ARRAY(char, buf, 8192);
431 size_t len;
432 memset(buf, '\0', 8192);
042461c3 433 snprintf(buf, 8192, "HTTP/1.0 200 OK\r\n");
56878878 434 snprintf(line, 256, "Date: %s\r\n", mkrfc1123(squid_curtime));
b3b64e58 435 strcat(buf, line);
042461c3 436 snprintf(line, 256, "Server: Squid/%s\r\n", SQUID_VERSION);
b3b64e58 437 strcat(buf, line);
042461c3 438 snprintf(line, 256, "Content-Type: message/http\r\n");
b3b64e58 439 strcat(buf, line);
440 strcat(buf, "\r\n");
441 len = strlen(buf);
382d851a 442 httpBuildRequestHeader(http->request,
443 http->request,
b3b64e58 444 NULL, /* entry */
b3b64e58 445 NULL, /* in_len */
446 buf + len,
447 8192 - len,
603a02fd 448 http->conn->fd,
449 0); /* flags */
382d851a 450 http->log_type = LOG_TCP_MISS;
4869e8a1 451 http->http_code = HTTP_OK;
b3b64e58 452 return buf;
453}
a90eae18 454
455void
382d851a 456clientPurgeRequest(clientHttpRequest * http)
a90eae18 457{
382d851a 458 int fd = http->conn->fd;
9b312a19 459 char *msg;
a90eae18 460 StoreEntry *entry;
9b312a19 461 ErrorState *err = NULL;
9fb13bb6 462 const cache_key *k;
9b312a19 463 debug(33, 3) ("Config.onoff.enable_purge = %d\n", Config.onoff.enable_purge);
17a0a4ee 464 if (!Config.onoff.enable_purge) {
79a15e0a 465 http->log_type = LOG_TCP_DENIED;
fe40a877 466 err = errorCon(ERR_ACCESS_DENIED, HTTP_FORBIDDEN);
9b312a19 467 err->request = requestLink(http->request);
468 err->src_addr = http->conn->peer.sin_addr;
f44af445 469 http->entry = clientCreateStoreEntry(http, http->request->method, 0);
79e0dc20 470 errorAppendEntry(http->entry, err);
a90eae18 471 return;
472 }
382d851a 473 http->log_type = LOG_TCP_MISS;
23d92c64 474 k = storeKeyPublic(http->uri, METHOD_GET);
9fb13bb6 475 if ((entry = storeGet(k)) == NULL) {
9b312a19 476 http->http_code = HTTP_NOT_FOUND;
a90eae18 477 } else {
478 storeRelease(entry);
9b312a19 479 http->http_code = HTTP_OK;
a90eae18 480 }
9b312a19 481 msg = httpReplyHeader(1.0, http->http_code, NULL, 0, 0, -1);
482 if (strlen(msg) < 8190)
483 strcat(msg, "\r\n");
484 comm_write(fd, xstrdup(msg), strlen(msg), clientWriteComplete, http, xfree);
a90eae18 485}
e33ba616 486
487int
ea3a2a69 488checkNegativeHit(StoreEntry * e)
e33ba616 489{
79a15e0a 490 if (!EBIT_TEST(e->flag, ENTRY_NEGCACHED))
ea3a2a69 491 return 0;
492 if (e->expires <= squid_curtime)
493 return 0;
494 if (e->store_status != STORE_OK)
495 return 0;
496 return 1;
e33ba616 497}
7a2f978b 498
499static void
500httpRequestFree(void *data)
501{
502 clientHttpRequest *http = data;
503 clientHttpRequest **H;
504 ConnStateData *conn = http->conn;
505 StoreEntry *entry = http->entry;
506 request_t *request = http->request;
507 MemObject *mem = NULL;
508 debug(12, 3) ("httpRequestFree: %s\n", storeUrl(entry));
1b02b5be 509 if (!clientCheckTransferDone(http)) {
7a2f978b 510 if (entry)
511 storeUnregister(entry, http); /* unregister BEFORE abort */
512 CheckQuickAbort(http);
513 entry = http->entry; /* reset, IMS might have changed it */
514 if (entry && entry->ping_status == PING_WAITING)
515 storeReleaseRequest(entry);
79d39a72 516 protoUnregister(entry, request);
7a2f978b 517 }
518 assert(http->log_type < LOG_TYPE_MAX);
519 if (entry)
520 mem = entry->mem_obj;
521 if (http->out.size || http->log_type) {
522 http->al.icp.opcode = 0;
23d92c64 523 http->al.url = http->uri;
7a2f978b 524 if (mem) {
525 http->al.http.code = mem->reply->code;
526 http->al.http.content_type = mem->reply->content_type;
527 }
528 http->al.cache.caddr = conn->log_addr;
529 http->al.cache.size = http->out.size;
530 http->al.cache.code = http->log_type;
531 http->al.cache.msec = tvSubMsec(http->start, current_time);
532 http->al.cache.ident = conn->ident.ident;
533 if (request) {
534 http->al.http.method = request->method;
535 http->al.headers.request = request->headers;
536 http->al.hier = request->hier;
537 }
538 accessLogLog(&http->al);
539 HTTPCacheInfo->proto_count(HTTPCacheInfo,
540 request ? request->protocol : PROTO_NONE,
541 http->log_type);
542 clientdbUpdate(conn->peer.sin_addr, http->log_type, PROTO_HTTP);
543 }
544 if (http->redirect_state == REDIRECT_PENDING)
23d92c64 545 redirectUnregister(http->uri, http);
7a2f978b 546 if (http->acl_checklist)
547 aclChecklistFree(http->acl_checklist);
88aad2e5 548 if (request)
c24fca87 549 checkFailureRatio(request->err_type, http->al.hier.code);
23d92c64 550 safe_free(http->uri);
551 safe_free(http->log_uri);
7a2f978b 552 safe_free(http->al.headers.reply);
553 if (entry) {
554 http->entry = NULL;
555 storeUnregister(entry, http);
556 storeUnlockObject(entry);
557 }
558 /* old_entry might still be set if we didn't yet get the reply
1b02b5be 559 * code in clientHandleIMSReply() */
7a2f978b 560 if (http->old_entry) {
561 storeUnregister(http->old_entry, http);
562 storeUnlockObject(http->old_entry);
563 http->old_entry = NULL;
564 }
565 requestUnlink(http->request);
566 assert(http != http->next);
567 assert(http->conn->chr != NULL);
568 H = &http->conn->chr;
569 while (*H) {
570 if (*H == http)
571 break;
572 H = &(*H)->next;
573 }
574 assert(*H != NULL);
575 *H = http->next;
576 http->next = NULL;
577 cbdataFree(http);
578}
579
580/* This is a handler normally called by comm_close() */
581static void
582connStateFree(int fd, void *data)
583{
584 ConnStateData *connState = data;
585 clientHttpRequest *http;
586 debug(12, 3) ("connStateFree: FD %d\n", fd);
587 assert(connState != NULL);
79d39a72 588 while ((http = connState->chr) != NULL) {
7a2f978b 589 assert(http->conn == connState);
590 assert(connState->chr != connState->chr->next);
591 httpRequestFree(http);
592 }
593 if (connState->ident.fd > -1)
594 comm_close(connState->ident.fd);
595 safe_free(connState->in.buf);
596 meta_data.misc -= connState->in.size;
597 pconnHistCount(0, connState->nrequests);
598 cbdataFree(connState);
599}
600
601static void
50ddd7a4 602clientParseRequestHeaders(clientHttpRequest * http)
7a2f978b 603{
604 request_t *request = http->request;
605 char *request_hdr = request->headers;
606 char *t = NULL;
607 request->ims = -2;
608 request->imslen = -1;
609 if ((t = mime_get_header(request_hdr, "If-Modified-Since"))) {
79a15e0a 610 EBIT_SET(request->flags, REQ_IMS);
7a2f978b 611 request->ims = parse_rfc1123(t);
612 while ((t = strchr(t, ';'))) {
613 for (t++; isspace(*t); t++);
614 if (strncasecmp(t, "length=", 7) == 0)
615 request->imslen = atoi(t + 7);
616 }
617 }
618 if ((t = mime_get_header(request_hdr, "Pragma"))) {
619 if (!strcasecmp(t, "no-cache"))
79a15e0a 620 EBIT_SET(request->flags, REQ_NOCACHE);
7a2f978b 621 }
622 if (mime_get_header(request_hdr, "Range")) {
79a15e0a 623 EBIT_SET(request->flags, REQ_NOCACHE);
624 EBIT_SET(request->flags, REQ_RANGE);
7a2f978b 625 } else if (mime_get_header(request_hdr, "Request-Range")) {
79a15e0a 626 EBIT_SET(request->flags, REQ_NOCACHE);
627 EBIT_SET(request->flags, REQ_RANGE);
7a2f978b 628 }
629 if (mime_get_header(request_hdr, "Authorization"))
79a15e0a 630 EBIT_SET(request->flags, REQ_AUTH);
7a2f978b 631 if (request->login[0] != '\0')
79a15e0a 632 EBIT_SET(request->flags, REQ_AUTH);
7a2f978b 633 if ((t = mime_get_header(request_hdr, "Proxy-Connection"))) {
634 if (!strcasecmp(t, "Keep-Alive"))
79a15e0a 635 EBIT_SET(request->flags, REQ_PROXY_KEEPALIVE);
7a2f978b 636 }
637 if ((t = mime_get_header(request_hdr, "Via")))
638 if (strstr(t, ThisCache)) {
639 if (!http->accel) {
640 debug(12, 1) ("WARNING: Forwarding loop detected for '%s'\n",
23d92c64 641 http->uri);
7a2f978b 642 debug(12, 1) ("--> %s\n", t);
643 }
79a15e0a 644 EBIT_SET(request->flags, REQ_LOOPDETECT);
7a2f978b 645 }
646#if USE_USERAGENT_LOG
647 if ((t = mime_get_header(request_hdr, "User-Agent")))
648 logUserAgent(fqdnFromAddr(http->conn->peer.sin_addr), t);
649#endif
650 request->max_age = -1;
651 if ((t = mime_get_header(request_hdr, "Cache-control"))) {
652 if (!strncasecmp(t, "Max-age=", 8))
653 request->max_age = atoi(t + 8);
654 }
655 if (request->method == METHOD_TRACE) {
656 if ((t = mime_get_header(request_hdr, "Max-Forwards")))
657 request->max_forwards = atoi(t);
658 }
50ddd7a4 659 if (clientCachable(http))
660 EBIT_SET(request->flags, REQ_CACHABLE);
661 if (clientHierarchical(http))
662 EBIT_SET(request->flags, REQ_HIERARCHICAL);
663 debug(12, 5) ("clientParseRequestHeaders: REQ_NOCACHE = %s\n",
664 EBIT_TEST(request->flags, REQ_NOCACHE) ? "SET" : "NOT SET");
665 debug(12, 5) ("clientParseRequestHeaders: REQ_CACHABLE = %s\n",
666 EBIT_TEST(request->flags, REQ_CACHABLE) ? "SET" : "NOT SET");
667 debug(12, 5) ("clientParseRequestHeaders: REQ_HIERARCHICAL = %s\n",
668 EBIT_TEST(request->flags, REQ_HIERARCHICAL) ? "SET" : "NOT SET");
7a2f978b 669}
670
671static int
50ddd7a4 672clientCachable(clientHttpRequest * http)
7a2f978b 673{
23d92c64 674 const char *url = http->uri;
7a2f978b 675 request_t *req = http->request;
676 method_t method = req->method;
677 const wordlist *p;
678 for (p = Config.cache_stoplist; p; p = p->next) {
679 if (strstr(url, p->key))
680 return 0;
681 }
682 if (Config.cache_stop_relist)
683 if (aclMatchRegex(Config.cache_stop_relist, url))
684 return 0;
685 if (req->protocol == PROTO_HTTP)
686 return httpCachable(method);
687 /* FTP is always cachable */
688 if (req->protocol == PROTO_GOPHER)
689 return gopherCachable(url);
690 if (req->protocol == PROTO_WAIS)
691 return 0;
692 if (method == METHOD_CONNECT)
693 return 0;
694 if (method == METHOD_TRACE)
695 return 0;
696 if (req->protocol == PROTO_CACHEOBJ)
697 return 0;
698 return 1;
699}
700
701/* Return true if we can query our neighbors for this object */
702static int
50ddd7a4 703clientHierarchical(clientHttpRequest * http)
7a2f978b 704{
23d92c64 705 const char *url = http->uri;
7a2f978b 706 request_t *request = http->request;
707 method_t method = request->method;
708 const wordlist *p = NULL;
709
710 /* IMS needs a private key, so we can use the hierarchy for IMS only
711 * if our neighbors support private keys */
79a15e0a 712 if (EBIT_TEST(request->flags, REQ_IMS) && !neighbors_do_private_keys)
7a2f978b 713 return 0;
79a15e0a 714 if (EBIT_TEST(request->flags, REQ_AUTH))
7a2f978b 715 return 0;
716 if (method == METHOD_TRACE)
717 return 1;
718 if (method != METHOD_GET)
719 return 0;
720 /* scan hierarchy_stoplist */
721 for (p = Config.hierarchy_stoplist; p; p = p->next)
722 if (strstr(url, p->key))
723 return 0;
79a15e0a 724 if (EBIT_TEST(request->flags, REQ_LOOPDETECT))
7a2f978b 725 return 0;
726 if (request->protocol == PROTO_HTTP)
727 return httpCachable(method);
728 if (request->protocol == PROTO_GOPHER)
729 return gopherCachable(url);
730 if (request->protocol == PROTO_WAIS)
731 return 0;
732 if (request->protocol == PROTO_CACHEOBJ)
733 return 0;
734 return 1;
735}
736
7a2f978b 737int
738isTcpHit(log_type code)
739{
740 /* this should be a bitmap for better optimization */
741 if (code == LOG_TCP_HIT)
742 return 1;
743 if (code == LOG_TCP_IMS_HIT)
744 return 1;
745 if (code == LOG_TCP_REFRESH_FAIL_HIT)
746 return 1;
747 if (code == LOG_TCP_REFRESH_HIT)
748 return 1;
749 if (code == LOG_TCP_NEGATIVE_HIT)
750 return 1;
751 if (code == LOG_TCP_MEM_HIT)
752 return 1;
753 return 0;
754}
755
756static void
757clientAppendReplyHeader(char *hdr, const char *line, size_t * sz, size_t max)
758{
759 size_t n = *sz + strlen(line) + 2;
760 if (n >= max)
761 return;
762 strcpy(hdr + (*sz), line);
763 strcat(hdr + (*sz), crlf);
764 *sz = n;
765}
766
767size_t
768clientBuildReplyHeader(clientHttpRequest * http,
769 char *hdr_in,
770 size_t * in_len,
771 char *hdr_out,
772 size_t out_sz)
773{
ab013258 774 LOCAL_ARRAY(char, no_forward, 1024);
7a2f978b 775 char *xbuf;
776 char *ybuf;
777 char *t = NULL;
778 char *end = NULL;
779 size_t len = 0;
780 size_t hdr_len = 0;
781 size_t l;
782 end = mime_headers_end(hdr_in);
783 if (end == NULL) {
784 debug(12, 3) ("clientBuildReplyHeader: DIDN'T FIND END-OF-HEADERS\n");
7a2f978b 785 return 0;
786 }
3f6c0fb2 787 xbuf = memAllocate(MEM_4K_BUF, 1);
788 ybuf = memAllocate(MEM_4K_BUF, 1);
7a2f978b 789 for (t = hdr_in; t < end; t += strcspn(t, crlf), t += strspn(t, crlf)) {
790 hdr_len = t - hdr_in;
791 l = strcspn(t, crlf) + 1;
792 xstrncpy(xbuf, t, l > 4096 ? 4096 : l);
7a2f978b 793#if 0
794 if (strncasecmp(xbuf, "Accept-Ranges:", 14) == 0)
795 continue;
796 if (strncasecmp(xbuf, "Etag:", 5) == 0)
797 continue;
798#endif
799 if (strncasecmp(xbuf, "Proxy-Connection:", 17) == 0)
800 continue;
ab013258 801 if (strncasecmp(xbuf, "Connection:", 11) == 0) {
802 handleConnectionHeader(0, no_forward, &xbuf[11]);
7a2f978b 803 continue;
ab013258 804 }
7a2f978b 805 if (strncasecmp(xbuf, "Keep-Alive:", 11) == 0)
806 continue;
807 if (strncasecmp(xbuf, "Set-Cookie:", 11) == 0)
808 if (isTcpHit(http->log_type))
809 continue;
ab013258 810 if (!handleConnectionHeader(1, no_forward, xbuf))
811 clientAppendReplyHeader(hdr_out, xbuf, &len, out_sz - 512);
7a2f978b 812 }
813 hdr_len = end - hdr_in;
814 /* Append X-Cache: */
815 snprintf(ybuf, 4096, "X-Cache: %s", isTcpHit(http->log_type) ? "HIT" : "MISS");
816 clientAppendReplyHeader(hdr_out, ybuf, &len, out_sz);
817 /* Append Proxy-Connection: */
79a15e0a 818 if (EBIT_TEST(http->request->flags, REQ_PROXY_KEEPALIVE)) {
7a2f978b 819 snprintf(ybuf, 4096, "Proxy-Connection: Keep-Alive");
820 clientAppendReplyHeader(hdr_out, ybuf, &len, out_sz);
821 }
822 clientAppendReplyHeader(hdr_out, null_string, &len, out_sz);
823 if (in_len)
824 *in_len = hdr_len;
825 if ((l = strlen(hdr_out)) != len) {
826 debug_trap("clientBuildReplyHeader: size mismatch");
827 len = l;
828 }
829 debug(12, 3) ("clientBuildReplyHeader: OUTPUT:\n%s\n", hdr_out);
3f6c0fb2 830 memFree(MEM_4K_BUF, xbuf);
831 memFree(MEM_4K_BUF, ybuf);
7a2f978b 832 return len;
833}
834
4c323c5f 835static void
7a2f978b 836clientCacheHit(void *data, char *buf, ssize_t size)
837{
838 clientHttpRequest *http = data;
839 if (size >= 0) {
840 clientSendMoreData(data, buf, size);
841 } else if (http->entry == NULL) {
842 debug(12, 3) ("clientCacheHit: request aborted\n");
843 } else {
844 /* swap in failure */
845 http->log_type = LOG_TCP_SWAPFAIL_MISS;
fb63215a 846 clientProcessMiss(http);
7a2f978b 847 }
848}
849
4c323c5f 850static void
7a2f978b 851clientSendMoreData(void *data, char *buf, ssize_t size)
852{
853 clientHttpRequest *http = data;
854 StoreEntry *entry = http->entry;
855 ConnStateData *conn = http->conn;
856 int fd = conn->fd;
857 char *p = NULL;
858 size_t hdrlen;
859 size_t l = 0;
860 size_t writelen;
861 char *newbuf;
3f6c0fb2 862 FREE *freefunc = memFree4K;
7a2f978b 863 int hack = 0;
864 char C = '\0';
865 assert(size <= SM_PAGE_SIZE);
40defb17 866 assert(http->request != NULL);
ab013258 867 debug(12, 5) ("clientSendMoreData: FD %d '%s', out.offset=%d \n",
7a2f978b 868 fd, storeUrl(entry), http->out.offset);
869 if (conn->chr != http) {
870 /* there is another object in progress, defer this one */
a43b3862 871 debug(0, 0) ("clientSendMoreData: Deferring %s\n", storeUrl(entry));
7a2f978b 872 freefunc(buf);
873 return;
874 } else if (entry->store_status == STORE_ABORTED) {
875 freefunc(buf);
876 return;
877 } else if (size < 0) {
878 freefunc(buf);
879 return;
880 } else if (size == 0) {
881 clientWriteComplete(fd, NULL, 0, DISK_OK, http);
882 freefunc(buf);
883 return;
884 }
885 writelen = size;
40defb17 886 if (http->out.offset == 0) {
7a2f978b 887 if (Config.onoff.log_mime_hdrs) {
888 if ((p = mime_headers_end(buf))) {
889 safe_free(http->al.headers.reply);
890 http->al.headers.reply = xcalloc(1 + p - buf, 1);
891 xstrncpy(http->al.headers.reply, buf, p - buf);
892 }
893 }
894 /* make sure 'buf' is null terminated somewhere */
895 if (size == SM_PAGE_SIZE) {
896 hack = 1;
897 size--;
898 C = *(buf + size);
899 }
900 *(buf + size) = '\0';
3f6c0fb2 901 newbuf = memAllocate(MEM_8K_BUF, 1);
7a2f978b 902 hdrlen = 0;
ab013258 903
7a2f978b 904 l = clientBuildReplyHeader(http, buf, &hdrlen, newbuf, 8192);
905 if (hack)
906 *(buf + size++) = C;
907 if (l != 0) {
908 writelen = l + size - hdrlen;
909 assert(writelen <= 8192);
910 /*
911 * l is the length of the new headers in newbuf
912 * hdrlen is the length of the old headers in buf
913 * size - hdrlen is the amount of body in buf
914 */
915 debug(12, 3) ("clientSendMoreData: Appending %d bytes after headers\n",
916 (int) (size - hdrlen));
917 xmemcpy(newbuf + l, buf + hdrlen, size - hdrlen);
918 /* replace buf with newbuf */
919 freefunc(buf);
920 buf = newbuf;
3f6c0fb2 921 freefunc = memFree8K;
7a2f978b 922 newbuf = NULL;
923 } else {
3f6c0fb2 924 memFree(MEM_8K_BUF, newbuf);
7a2f978b 925 newbuf = NULL;
926 if (size < SM_PAGE_SIZE && entry->store_status == STORE_PENDING) {
927 /* wait for more to arrive */
928 storeClientCopy(entry,
929 http->out.offset + size,
930 http->out.offset,
931 SM_PAGE_SIZE,
932 buf,
933 clientSendMoreData,
934 http);
935 return;
936 }
937 }
938 }
939 http->out.offset += size;
40defb17 940 /*
941 * ick, this is gross
942 */
7a2f978b 943 if (http->request->method == METHOD_HEAD) {
944 if ((p = mime_headers_end(buf))) {
945 *p = '\0';
946 writelen = p - buf;
947 /* force end */
f68b5d81 948 if (entry->store_status == STORE_PENDING)
c24fca87 949 http->out.offset = entry->mem_obj->inmem_hi;
f68b5d81 950 else
c24fca87 951 http->out.offset = entry->object_len;
7a2f978b 952 }
953 }
954 comm_write(fd, buf, writelen, clientWriteComplete, http, freefunc);
955}
956
fc5d6f7f 957static void
79a15e0a 958clientWriteComplete(int fd, char *bufnotused, size_t size, int errflag, void *data)
7a2f978b 959{
960 clientHttpRequest *http = data;
961 ConnStateData *conn;
962 StoreEntry *entry = http->entry;
b34ed725 963 int done;
7a2f978b 964 http->out.size += size;
965 debug(12, 5) ("clientWriteComplete: FD %d, sz %d, err %d, off %d, len %d\n",
966 fd, size, errflag, http->out.offset, entry->object_len);
967 if (errflag) {
968 CheckQuickAbort(http);
969 /* Log the number of bytes that we managed to read */
970 HTTPCacheInfo->proto_touchobject(HTTPCacheInfo,
971 urlParseProtocol(storeUrl(entry)),
972 http->out.size);
973 comm_close(fd);
974 } else if (entry->store_status == STORE_ABORTED) {
975 HTTPCacheInfo->proto_touchobject(HTTPCacheInfo,
976 urlParseProtocol(storeUrl(entry)),
977 http->out.size);
978 comm_close(fd);
1b02b5be 979 } else if ((done = clientCheckTransferDone(http)) || size == 0) {
7a2f978b 980 debug(12, 5) ("clientWriteComplete: FD %d transfer is DONE\n", fd);
981 /* We're finished case */
982 HTTPCacheInfo->proto_touchobject(HTTPCacheInfo,
983 http->request->protocol,
984 http->out.size);
b34ed725 985 if (http->entry->mem_obj->reply->content_length < 0 || !done ||
986 EBIT_TEST(entry->flag, ENTRY_BAD_LENGTH)) {
987 /*
988 * Client connection closed due to unknown or invalid
989 * content length. Persistent connection is not possible.
990 * This catches most cases, but probably not all.
991 */
7a2f978b 992 comm_close(fd);
79a15e0a 993 } else if (EBIT_TEST(http->request->flags, REQ_PROXY_KEEPALIVE)) {
7a2f978b 994 debug(12, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd);
995 conn = http->conn;
b34ed725 996 conn->defer.until = 0; /* Kick it to read a new request */
7a2f978b 997 httpRequestFree(http);
79d39a72 998 if ((http = conn->chr) != NULL) {
7a2f978b 999 debug(12, 1) ("clientWriteComplete: FD %d Sending next request\n", fd);
8daca701 1000 if (!storeClientCopyPending(http->entry, http))
1001 storeClientCopy(http->entry,
1002 http->out.offset,
1003 http->out.offset,
1004 SM_PAGE_SIZE,
3f6c0fb2 1005 memAllocate(MEM_4K_BUF, 1),
8daca701 1006 clientSendMoreData,
1007 http);
7a2f978b 1008 } else {
0ca54a51 1009 debug(12, 5) ("clientWriteComplete: FD %d reading next request\n", fd);
7a2f978b 1010 fd_note(fd, "Reading next request");
0ca54a51 1011 /*
1012 * Set the timeout BEFORE calling clientReadRequest().
1013 */
7a2f978b 1014 commSetTimeout(fd, 15, requestTimeout, conn);
47130615 1015 clientReadRequest(fd, conn); /* Read next request */
0ca54a51 1016 /*
1017 * Note, the FD may be closed at this point.
1018 */
7a2f978b 1019 }
1020 } else {
1021 comm_close(fd);
1022 }
1023 } else {
1024 /* More data will be coming from primary server; register with
1025 * storage manager. */
1026 storeClientCopy(entry,
1027 http->out.offset,
1028 http->out.offset,
1029 SM_PAGE_SIZE,
3f6c0fb2 1030 memAllocate(MEM_4K_BUF, 1),
7a2f978b 1031 clientSendMoreData,
1032 http);
1033 }
1034}
1035
1036static void
1b02b5be 1037clientGetHeadersForIMS(void *data, char *buf, ssize_t size)
7a2f978b 1038{
1039 clientHttpRequest *http = data;
7a2f978b 1040 StoreEntry *entry = http->entry;
1041 MemObject *mem = entry->mem_obj;
1042 char *reply = NULL;
1043 assert(size <= SM_PAGE_SIZE);
3f6c0fb2 1044 memFree(MEM_4K_BUF, buf);
1b02b5be 1045 buf = NULL;
7a2f978b 1046 if (size < 0) {
1b02b5be 1047 debug(12, 1) ("clientGetHeadersForIMS: storeClientCopy failed for '%s'\n",
7a2f978b 1048 storeKeyText(entry->key));
fb63215a 1049 clientProcessMiss(http);
7a2f978b 1050 return;
1051 }
1052 if (mem->reply->code == 0) {
1053 if (entry->mem_status == IN_MEMORY) {
fb63215a 1054 clientProcessMiss(http);
7a2f978b 1055 return;
1056 }
1057 /* All headers are not yet available, wait for more data */
1058 storeClientCopy(entry,
1059 http->out.offset + size,
1060 http->out.offset,
1061 SM_PAGE_SIZE,
3f6c0fb2 1062 memAllocate(MEM_4K_BUF, 1),
1b02b5be 1063 clientGetHeadersForIMS,
7a2f978b 1064 http);
1065 return;
1066 }
1067 /* All headers are available, check if object is modified or not */
1068 /* ---------------------------------------------------------------
1069 * Removed check for reply->code != 200 because of a potential
1070 * problem with ICP. We will return a HIT for any public, cached
1071 * object. This includes other responses like 301, 410, as coded in
1072 * http.c. It is Bad(tm) to return UDP_HIT and then, if the reply
50ddd7a4 1073 * code is not 200, hand off to clientProcessMiss(), which may disallow
7a2f978b 1074 * the request based on 'miss_access' rules. Alternatively, we might
1075 * consider requiring returning UDP_HIT only for 200's. This
1076 * problably means an entry->flag bit, which would be lost during
1077 * restart because the flags aren't preserved across restarts.
1078 * --DW 3/11/96.
1079 * ---------------------------------------------------------------- */
1080#ifdef CHECK_REPLY_CODE_NOTEQUAL_200
1081 /* Only objects with statuscode==200 can be "Not modified" */
1082 if (mem->reply->code != 200) {
1b02b5be 1083 debug(12, 4) ("clientGetHeadersForIMS: Reply code %d!=200\n",
7a2f978b 1084 mem->reply->code);
fb63215a 1085 clientProcessMiss(http);
7a2f978b 1086 return;
1087 }
7a2f978b 1088#endif
1b02b5be 1089 http->log_type = LOG_TCP_IMS_HIT;
7a2f978b 1090 entry->refcount++;
1091 if (modifiedSince(entry, http->request)) {
1092 storeClientCopy(entry,
1093 http->out.offset,
1094 http->out.offset,
1095 SM_PAGE_SIZE,
3f6c0fb2 1096 memAllocate(MEM_4K_BUF, 1),
7a2f978b 1097 clientSendMoreData,
1098 http);
1099 return;
1100 }
1b02b5be 1101 debug(12, 4) ("clientGetHeadersForIMS: Not modified '%s'\n", storeUrl(entry));
1102 reply = clientConstruct304reply(mem->reply);
fb63215a 1103 comm_write(http->conn->fd,
7a2f978b 1104 xstrdup(reply),
1105 strlen(reply),
1b02b5be 1106 clientHandleIMSComplete,
7a2f978b 1107 http,
1108 xfree);
1109}
1110
1111static void
1b02b5be 1112clientHandleIMSComplete(int fd, char *bufnotused, size_t size, int flag, void *data)
7a2f978b 1113{
1114 clientHttpRequest *http = data;
1115 StoreEntry *entry = http->entry;
1b02b5be 1116 debug(12, 5) ("clientHandleIMSComplete: Not Modified sent '%s'\n", storeUrl(entry));
7a2f978b 1117 HTTPCacheInfo->proto_touchobject(HTTPCacheInfo,
1118 http->request->protocol,
1119 size);
1120 /* Set up everything for the logging */
1121 storeUnregister(entry, http);
1122 storeUnlockObject(entry);
1123 http->entry = NULL;
1124 http->out.size += size;
1125 http->al.http.code = 304;
79a15e0a 1126 if (flag != COMM_ERR_CLOSING)
7a2f978b 1127 comm_close(fd);
1128}
1129
50ddd7a4 1130static log_type
1131clientProcessRequest2(clientHttpRequest * http)
1132{
1133 const request_t *r = http->request;
23d92c64 1134 const cache_key *key = storeKeyPublic(http->uri, r->method);
50ddd7a4 1135 StoreEntry *e;
1136 if ((e = http->entry = storeGet(key)) == NULL) {
1137 /* this object isn't in the cache */
1138 return LOG_TCP_MISS;
1139 } else if (EBIT_TEST(e->flag, ENTRY_SPECIAL)) {
1140 if (e->mem_status == IN_MEMORY)
1141 return LOG_TCP_MEM_HIT;
1142 else
1143 return LOG_TCP_HIT;
1144 } else if (!storeEntryValidToSend(e)) {
1145 storeRelease(e);
1146 http->entry = NULL;
1147 return LOG_TCP_MISS;
1148 } else if (EBIT_TEST(r->flags, REQ_NOCACHE)) {
1149 /* NOCACHE should always eject a negative cached object */
1150 if (EBIT_TEST(e->flag, ENTRY_NEGCACHED))
1151 storeRelease(e);
1152 /* NOCACHE+IMS should not eject a valid object */
1153 else if (EBIT_TEST(r->flags, REQ_IMS))
1154 (void) 0;
1155 /* Request-Range should not eject a valid object */
1156 else if (EBIT_TEST(r->flags, REQ_RANGE))
1157 (void) 0;
1158 else
1159 storeRelease(e);
1160 ipcacheReleaseInvalid(r->host);
1161 http->entry = NULL;
1162 return LOG_TCP_CLIENT_REFRESH;
1163 } else if (checkNegativeHit(e)) {
1164 return LOG_TCP_NEGATIVE_HIT;
1165 } else if (refreshCheck(e, r, 0)) {
1166 /* The object is in the cache, but it needs to be validated. Use
1167 * LOG_TCP_REFRESH_MISS for the time being, maybe change it to
1b02b5be 1168 * _HIT later in clientHandleIMSReply() */
50ddd7a4 1169 if (r->protocol == PROTO_HTTP)
1170 return LOG_TCP_REFRESH_MISS;
1171 else
1172 return LOG_TCP_MISS; /* XXX zoinks */
1173 } else if (EBIT_TEST(r->flags, REQ_IMS)) {
1174 /* User-initiated IMS request for something we think is valid */
1175 return LOG_TCP_IMS_MISS;
1176 } else if (e->mem_status == IN_MEMORY) {
1177 return LOG_TCP_MEM_HIT;
1178 } else {
1179 return LOG_TCP_HIT;
1180 }
1181}
1182
4c323c5f 1183static void
fb63215a 1184clientProcessRequest(clientHttpRequest * http)
7a2f978b 1185{
23d92c64 1186 char *url = http->uri;
7a2f978b 1187 StoreEntry *entry = NULL;
50ddd7a4 1188 request_t *r = http->request;
fb63215a 1189 int fd = http->conn->fd;
b17b22eb 1190 char *hdr;
50ddd7a4 1191 debug(12, 4) ("clientProcessRequest: %s '%s'\n",
1192 RequestMethodStr[r->method],
7a2f978b 1193 url);
fb63215a 1194 if (r->method == METHOD_CONNECT) {
7a2f978b 1195 http->log_type = LOG_TCP_MISS;
ea0efb98 1196 sslStart(fd, url, r, &http->out.size);
1197 return;
fb63215a 1198 } else if (r->method == METHOD_PURGE) {
ea0efb98 1199 clientPurgeRequest(http);
1200 return;
fb63215a 1201 } else if (r->method == METHOD_TRACE) {
50ddd7a4 1202 if (r->max_forwards == 0) {
b17b22eb 1203 http->entry = clientCreateStoreEntry(http, r->method, 0);
1204 storeReleaseRequest(http->entry);
1205 storeBuffer(http->entry);
1206 hdr = httpReplyHeader(1.0,
164f7660 1207 HTTP_OK,
1208 "text/plain",
1209 r->headers_sz,
1210 0,
1211 squid_curtime);
b17b22eb 1212 storeAppend(http->entry, hdr, strlen(hdr));
1213 storeAppend(http->entry, "\r\n", 2);
1214 storeAppend(http->entry, r->headers, r->headers_sz);
1215 storeComplete(http->entry);
7a2f978b 1216 return;
1217 }
1218 /* yes, continue */
fb63215a 1219 } else if (r->protocol != PROTO_HTTP) {
1220 (void) 0; /* fallthrough */
1221 } else if (r->method == METHOD_POST) {
7a2f978b 1222 http->log_type = LOG_TCP_MISS;
ea0efb98 1223 passStart(fd, url, r, &http->out.size);
1224 return;
fb63215a 1225 } else if (r->method == METHOD_PUT) {
1226 http->log_type = LOG_TCP_MISS;
ea0efb98 1227 passStart(fd, url, r, &http->out.size);
1228 return;
7a2f978b 1229 }
fb63215a 1230 http->log_type = clientProcessRequest2(http);
50ddd7a4 1231 debug(12, 4) ("clientProcessRequest: %s for '%s'\n",
7a2f978b 1232 log_tags[http->log_type],
23d92c64 1233 http->uri);
50ddd7a4 1234 if ((entry = http->entry) != NULL) {
7a2f978b 1235 storeLockObject(entry);
23d92c64 1236 storeCreateMemObject(entry, http->uri, http->log_uri);
7a2f978b 1237 storeClientListAdd(entry, http);
1238 }
7a2f978b 1239 http->out.offset = 0;
1240 switch (http->log_type) {
1241 case LOG_TCP_HIT:
1242 case LOG_TCP_NEGATIVE_HIT:
1243 case LOG_TCP_MEM_HIT:
1244 entry->refcount++; /* HIT CASE */
1245 storeClientCopy(entry,
1246 http->out.offset,
1247 http->out.offset,
1248 SM_PAGE_SIZE,
3f6c0fb2 1249 memAllocate(MEM_4K_BUF, 1),
7a2f978b 1250 clientCacheHit,
1251 http);
1252 break;
1253 case LOG_TCP_IMS_MISS:
1254 storeClientCopy(entry,
1255 http->out.offset,
1256 http->out.offset,
1257 SM_PAGE_SIZE,
3f6c0fb2 1258 memAllocate(MEM_4K_BUF, 1),
1b02b5be 1259 clientGetHeadersForIMS,
7a2f978b 1260 http);
1261 break;
1262 case LOG_TCP_REFRESH_MISS:
fb63215a 1263 clientProcessExpired(http);
7a2f978b 1264 break;
1265 default:
fb63215a 1266 clientProcessMiss(http);
7a2f978b 1267 break;
1268 }
1269}
1270
1271/*
1272 * Prepare to fetch the object as it's a cache miss of some kind.
1273 */
1274static void
fb63215a 1275clientProcessMiss(clientHttpRequest * http)
7a2f978b 1276{
23d92c64 1277 char *url = http->uri;
f44af445 1278 request_t *r = http->request;
1279 char *request_hdr = r->headers;
7a2f978b 1280 aclCheck_t ch;
1281 int answer;
1282 ErrorState *err = NULL;
50ddd7a4 1283 debug(12, 4) ("clientProcessMiss: '%s %s'\n",
f44af445 1284 RequestMethodStr[r->method], url);
50ddd7a4 1285 debug(12, 10) ("clientProcessMiss: request_hdr:\n%s\n", request_hdr);
79e0dc20 1286 /*
1287 * We might have a left-over StoreEntry from a failed cache hit
1288 * or IMS request.
1289 */
1290 if (http->entry) {
1291 storeUnregister(http->entry, http);
1292 storeUnlockObject(http->entry);
1293 http->entry = NULL;
1294 }
1295 /*
1296 * Check if this host is allowed to fetch MISSES from us (miss_access)
1297 */
7a2f978b 1298 memset(&ch, '\0', sizeof(aclCheck_t));
1299 ch.src_addr = http->conn->peer.sin_addr;
f44af445 1300 ch.request = r;
7a2f978b 1301 answer = aclCheckFast(Config.accessList.miss, &ch);
1302 if (answer == 0) {
1303 http->al.http.code = HTTP_FORBIDDEN;
bdb3c273 1304 err = errorCon(ERR_FORWARDING_DENIED, HTTP_FORBIDDEN);
f44af445 1305 err->request = requestLink(r);
7a2f978b 1306 err->src_addr = http->conn->peer.sin_addr;
f44af445 1307 http->entry = clientCreateStoreEntry(http, r->method, 0);
79e0dc20 1308 errorAppendEntry(http->entry, err);
7a2f978b 1309 return;
1310 }
79e0dc20 1311 assert(http->out.offset == 0);
f44af445 1312 http->entry = clientCreateStoreEntry(http, r->method, r->flags);
79e0dc20 1313 http->entry->mem_obj->fd = http->conn->fd;
1314 http->entry->refcount++;
f44af445 1315 protoDispatch(http->conn->fd, http->entry, r);
7a2f978b 1316}
1317
1318/*
1319 * parseHttpRequest()
1320 *
1321 * Returns
1322 * NULL on error or incomplete request
1323 * a clientHttpRequest structure on success
1324 */
1325static clientHttpRequest *
1326parseHttpRequest(ConnStateData * conn, method_t * method_p, int *status,
1327 char **headers_p, size_t * headers_sz_p)
1328{
1329 char *inbuf = NULL;
1330 char *mstr = NULL;
1331 char *url = NULL;
1332 char *req_hdr = NULL;
7a2f978b 1333 float http_ver;
1334 char *token = NULL;
1335 char *t = NULL;
1336 char *end = NULL;
1337 int free_request = 0;
1338 size_t header_sz; /* size of headers, not including first line */
1339 size_t req_sz; /* size of whole request */
1340 size_t url_sz;
1341 method_t method;
1342 clientHttpRequest *http = NULL;
1343
1344 /* Make sure a complete line has been received */
1345 if (strchr(conn->in.buf, '\n') == NULL) {
1346 debug(12, 5) ("Incomplete request line, waiting for more data\n");
1347 *status = 0;
1348 return NULL;
1349 }
1350 /* Use xmalloc/xmemcpy instead of xstrdup because inbuf might
1351 * contain NULL bytes; especially for POST data */
1352 inbuf = xmalloc(conn->in.offset + 1);
1353 xmemcpy(inbuf, conn->in.buf, conn->in.offset);
1354 *(inbuf + conn->in.offset) = '\0';
1355
1356 /* Look for request method */
1357 if ((mstr = strtok(inbuf, "\t ")) == NULL) {
1358 debug(12, 1) ("parseHttpRequest: Can't get request method\n");
3775d53c 1359 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1360 cbdataAdd(http, MEM_NONE);
3775d53c 1361 http->conn = conn;
1362 http->start = current_time;
1363 http->req_sz = conn->in.offset;
23d92c64 1364 http->uri = xstrdup("error:invalid-request-method");
1365 http->log_uri = xstrdup("error:invalid-request-method");
3775d53c 1366 *headers_sz_p = conn->in.offset;
1367 *headers_p = inbuf;
1368 *method_p = METHOD_NONE;
7a2f978b 1369 *status = -1;
3775d53c 1370 return http;
7a2f978b 1371 }
1372 method = urlParseMethod(mstr);
1373 if (method == METHOD_NONE) {
1374 debug(12, 1) ("parseHttpRequest: Unsupported method '%s'\n", mstr);
3775d53c 1375 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1376 cbdataAdd(http, MEM_NONE);
3775d53c 1377 http->conn = conn;
1378 http->start = current_time;
1379 http->req_sz = conn->in.offset;
23d92c64 1380 http->uri = xstrdup("error:unsupported-request-method");
1381 http->log_uri = xstrdup("error:unsupported-request-method");
3775d53c 1382 *headers_sz_p = conn->in.offset;
1383 *headers_p = inbuf;
1384 *method_p = METHOD_NONE;
7a2f978b 1385 *status = -1;
3775d53c 1386 return http;
7a2f978b 1387 }
1388 debug(12, 5) ("parseHttpRequest: Method is '%s'\n", mstr);
3775d53c 1389 *method_p = method;
7a2f978b 1390
1391 /* look for URL */
1392 if ((url = strtok(NULL, "\r\n\t ")) == NULL) {
1393 debug(12, 1) ("parseHttpRequest: Missing URL\n");
3775d53c 1394 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1395 cbdataAdd(http, MEM_NONE);
3775d53c 1396 http->conn = conn;
1397 http->start = current_time;
1398 http->req_sz = conn->in.offset;
23d92c64 1399 http->uri = xstrdup("error:missing-url");
1400 http->log_uri = xstrdup("error:missing-url");
3775d53c 1401 *headers_sz_p = conn->in.offset;
1402 *headers_p = inbuf;
7a2f978b 1403 *status = -1;
3775d53c 1404 return http;
7a2f978b 1405 }
1406 debug(12, 5) ("parseHttpRequest: Request is '%s'\n", url);
1407
1408 token = strtok(NULL, null_string);
1409 for (t = token; t && *t && *t != '\n' && *t != '\r'; t++);
46c7dbf0 1410 if (t == NULL || *t == '\0' || t == token || strncmp(token, "HTTP/", 5)) {
7a2f978b 1411 debug(12, 3) ("parseHttpRequest: Missing HTTP identifier\n");
3775d53c 1412 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1413 cbdataAdd(http, MEM_NONE);
3775d53c 1414 http->conn = conn;
1415 http->start = current_time;
1416 http->req_sz = conn->in.offset;
23d92c64 1417 http->uri = xstrdup("error:missing-http-ident");
1418 http->log_uri = xstrdup("error:missing-http-ident");
3775d53c 1419 *headers_sz_p = conn->in.offset;
1420 *headers_p = inbuf;
7a2f978b 1421 *status = -1;
3775d53c 1422 return http;
7a2f978b 1423 }
84116757 1424 http_ver = (float) atof(token + 5);
7a2f978b 1425
1426 /* Check if headers are received */
1427 if ((end = mime_headers_end(t)) == NULL) {
1428 xfree(inbuf);
1429 *status = 0;
1430 return NULL;
1431 }
7a2f978b 1432 req_hdr = t;
c24fca87 1433 /*
1434 * Skip whitespace at the end of the frist line, up to the
1435 * first newline.
1436 */
1437 while (isspace(*req_hdr))
1438 if (*(req_hdr++) == '\n')
1439 break;
1440 if (end <= req_hdr) {
1441 /* Invalid request */
1442 debug(12, 3) ("parseHttpRequest: No request headers?\n");
1443 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1444 cbdataAdd(http, MEM_NONE);
c24fca87 1445 http->conn = conn;
1446 http->start = current_time;
1447 http->req_sz = conn->in.offset;
1448 http->uri = xstrdup("error:no-request-headers");
1449 http->log_uri = xstrdup("error:no-request-headers");
1450 *headers_sz_p = conn->in.offset;
1451 *headers_p = inbuf;
1452 *status = -1;
1453 return http;
1454 }
7a2f978b 1455 header_sz = end - req_hdr;
1456 req_sz = end - inbuf;
1457
1458 /* Ok, all headers are received */
1459 http = xcalloc(1, sizeof(clientHttpRequest));
3f6c0fb2 1460 cbdataAdd(http, MEM_NONE);
7a2f978b 1461 http->http_ver = http_ver;
1462 http->conn = conn;
1463 http->start = current_time;
1464 http->req_sz = req_sz;
1465 *headers_sz_p = header_sz;
1466 *headers_p = xmalloc(header_sz + 1);
1467 xmemcpy(*headers_p, req_hdr, header_sz);
1468 *(*headers_p + header_sz) = '\0';
1469
1470 debug(12, 5) ("parseHttpRequest: Request Header is\n%s\n", *headers_p);
1471
23d92c64 1472 /* Assign http->uri */
7a2f978b 1473 if ((t = strchr(url, '\n'))) /* remove NL */
1474 *t = '\0';
1475 if ((t = strchr(url, '\r'))) /* remove CR */
1476 *t = '\0';
1477 if ((t = strchr(url, '#'))) /* remove HTML anchors */
1478 *t = '\0';
1479
1480 /* see if we running in Config2.Accel.on, if so got to convert it to URL */
1481 if (Config2.Accel.on && *url == '/') {
1482 /* prepend the accel prefix */
1483 if (vhost_mode) {
1484 /* Put the local socket IP address as the hostname */
1485 url_sz = strlen(url) + 32 + Config.appendDomainLen;
23d92c64 1486 http->uri = xcalloc(url_sz, 1);
1487 snprintf(http->uri, url_sz, "http://%s:%d%s",
7a2f978b 1488 inet_ntoa(http->conn->me.sin_addr),
1489 (int) Config.Accel.port,
1490 url);
23d92c64 1491 debug(12, 5) ("VHOST REWRITE: '%s'\n", http->uri);
7a2f978b 1492 } else if (opt_accel_uses_host && (t = mime_get_header(req_hdr, "Host"))) {
1493 /* If a Host: header was specified, use it to build the URL
1494 * instead of the one in the Config file. */
1495 /*
1496 * XXX Use of the Host: header here opens a potential
1497 * security hole. There are no checks that the Host: value
1498 * corresponds to one of your servers. It might, for example,
1499 * refer to www.playboy.com. The 'dst' and/or 'dst_domain' ACL
1500 * types should be used to prevent httpd-accelerators
1501 * handling requests for non-local servers */
1502 strtok(t, " :/;@");
12fc602c 1503 url_sz = strlen(url) + 32 + Config.appendDomainLen +
1504 strlen(t);
23d92c64 1505 http->uri = xcalloc(url_sz, 1);
1506 snprintf(http->uri, url_sz, "http://%s:%d%s",
7a2f978b 1507 t, (int) Config.Accel.port, url);
1508 } else {
1509 url_sz = strlen(Config2.Accel.prefix) + strlen(url) +
1510 Config.appendDomainLen + 1;
23d92c64 1511 http->uri = xcalloc(url_sz, 1);
1512 snprintf(http->uri, url_sz, "%s%s", Config2.Accel.prefix, url);
7a2f978b 1513 }
1514 http->accel = 1;
1515 } else {
1516 /* URL may be rewritten later, so make extra room */
1517 url_sz = strlen(url) + Config.appendDomainLen + 5;
23d92c64 1518 http->uri = xcalloc(url_sz, 1);
1519 strcpy(http->uri, url);
7a2f978b 1520 http->accel = 0;
1521 }
23d92c64 1522 http->log_uri = xstrdup(http->uri);
7a2f978b 1523 debug(12, 5) ("parseHttpRequest: Complete request received\n");
1524 if (free_request)
1525 safe_free(url);
1526 xfree(inbuf);
7a2f978b 1527 *status = 1;
1528 return http;
1529}
1530
1531static int
79d39a72 1532clientReadDefer(int fdnotused, void *data)
7a2f978b 1533{
1534 ConnStateData *conn = data;
1535 return conn->defer.until > squid_curtime;
1536}
1537
1538static void
1539clientReadRequest(int fd, void *data)
1540{
1541 ConnStateData *conn = data;
1542 int parser_return_code = 0;
1543 int k;
1544 request_t *request = NULL;
7a2f978b 1545 int size;
7a2f978b 1546 method_t method;
1547 clientHttpRequest *http = NULL;
1548 clientHttpRequest **H = NULL;
1549 char *headers;
1550 size_t headers_sz;
1551 ErrorState *err = NULL;
1552 fde *F = &fd_table[fd];
44db45e8 1553 int len = conn->in.size - conn->in.offset - 1;
7a2f978b 1554 debug(12, 4) ("clientReadRequest: FD %d: reading request...\n", fd);
1555 size = read(fd, conn->in.buf + conn->in.offset, len);
1556 fd_bytes(fd, size, FD_READ);
44db45e8 1557 /*
1558 * Don't reset the timeout value here. The timeout value will be
1559 * set to Config.Timeout.request by httpAccept() and
1560 * clientWriteComplete(), and should apply to the request as a
1561 * whole, not individual read() calls. Plus, it breaks our
1562 * lame half-close detection
1563 */
1564 commSetSelect(fd, COMM_SELECT_READ, clientReadRequest, conn, 0);
7a2f978b 1565 if (size == 0) {
1566 if (conn->chr == NULL) {
1567 /* no current or pending requests */
1568 comm_close(fd);
1569 return;
1570 }
1571 /* It might be half-closed, we can't tell */
1572 debug(12, 5) ("clientReadRequest: FD %d closed?\n", fd);
79a15e0a 1573 EBIT_SET(F->flags, FD_SOCKET_EOF);
7a2f978b 1574 conn->defer.until = squid_curtime + 1;
1575 conn->defer.n++;
44db45e8 1576 fd_note(fd, "half-closed");
7a2f978b 1577 return;
1578 } else if (size < 0) {
6d3caf23 1579 if (!ignoreErrno(errno)) {
7a2f978b 1580 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd, xstrerror());
1581 comm_close(fd);
ebf4efff 1582 return;
47130615 1583 } else if (conn->in.offset == 0) {
ebf4efff 1584 debug(50, 2) ("clientReadRequest: FD %d: no data to process\n");
1585 return;
7a2f978b 1586 }
ebf4efff 1587 /* Continue to process previously read data */
47130615 1588 size = 0;
7a2f978b 1589 }
1590 conn->in.offset += size;
1591 conn->in.buf[conn->in.offset] = '\0'; /* Terminate the string */
7a2f978b 1592 while (conn->in.offset > 0) {
ebf4efff 1593 int nrequests;
1594 /* Limit the number of concurrent requests to 2 */
1595 for (H = &conn->chr, nrequests = 0; *H; H = &(*H)->next, nrequests++);
1596 if (nrequests >= 2) {
1597 debug(12, 2) ("clientReadRequest: FD %d max concurrent requests reached\n", fd);
1598 debug(12, 5) ("clientReadRequest: FD %d defering new request until one is done\n", fd);
47130615 1599 conn->defer.until = squid_curtime + 100; /* Reset when a request is complete */
ebf4efff 1600 break;
1601 }
1602 /* Process request */
7a2f978b 1603 http = parseHttpRequest(conn,
1604 &method,
1605 &parser_return_code,
1606 &headers,
1607 &headers_sz);
1608 if (http) {
1609 assert(http->req_sz > 0);
1610 conn->in.offset -= http->req_sz;
1611 assert(conn->in.offset >= 0);
6fa92aa2 1612 /*
1613 * If we read past the end of this request, move the remaining
1614 * data to the beginning
1615 */
1616 if (conn->in.offset > 0)
a21f5057 1617 memmove(conn->in.buf, conn->in.buf + http->req_sz, conn->in.offset);
ebf4efff 1618 /* add to the client request queue */
7a2f978b 1619 for (H = &conn->chr; *H; H = &(*H)->next);
1620 *H = http;
1621 conn->nrequests++;
f2908497 1622 Counter.client_http.requests++;
7a2f978b 1623 commSetTimeout(fd, Config.Timeout.lifetime, NULL, NULL);
3775d53c 1624 if (parser_return_code < 0) {
1625 debug(12, 1) ("clientReadRequest: FD %d Invalid Request\n", fd);
1626 err = errorCon(ERR_INVALID_REQ, HTTP_BAD_REQUEST);
1627 err->request_hdrs = xstrdup(conn->in.buf);
1628 http->entry = clientCreateStoreEntry(http, method, 0);
1629 errorAppendEntry(http->entry, err);
1630 break;
1631 }
23d92c64 1632 if ((request = urlParse(method, http->uri)) == NULL) {
1633 debug(12, 5) ("Invalid URL: %s\n", http->uri);
7a2f978b 1634 err = errorCon(ERR_INVALID_URL, HTTP_BAD_REQUEST);
1635 err->src_addr = conn->peer.sin_addr;
23d92c64 1636 err->url = xstrdup(http->uri);
7a2f978b 1637 http->al.http.code = err->http_status;
f44af445 1638 http->entry = clientCreateStoreEntry(http, method, 0);
79e0dc20 1639 errorAppendEntry(http->entry, err);
7a2f978b 1640 safe_free(headers);
1641 break;
1642 }
23d92c64 1643 safe_free(http->log_uri);
1644 http->log_uri = xstrdup(urlCanonicalClean(request));
7a2f978b 1645 request->client_addr = conn->peer.sin_addr;
1646 request->http_ver = http->http_ver;
1647 request->headers = headers;
1648 request->headers_sz = headers_sz;
1649 if (!urlCheckRequest(request)) {
1650 err = errorCon(ERR_UNSUP_REQ, HTTP_NOT_IMPLEMENTED);
1651 err->src_addr = conn->peer.sin_addr;
7a2f978b 1652 err->request = requestLink(request);
1653 http->al.http.code = err->http_status;
f44af445 1654 http->entry = clientCreateStoreEntry(http, request->method, 0);
79e0dc20 1655 errorAppendEntry(http->entry, err);
3775d53c 1656 break;
7a2f978b 1657 }
1658 http->request = requestLink(request);
cf26e54c 1659 clientAccessCheck(http);
3775d53c 1660 /*
1661 * break here for NON-GET because most likely there is a
7a2f978b 1662 * reqeust body following and we don't want to parse it
3775d53c 1663 * as though it was new request
1664 */
7a2f978b 1665 if (request->method != METHOD_GET) {
1666 if (conn->in.offset) {
1667 request->body_sz = conn->in.offset;
1668 request->body = xmalloc(request->body_sz);
1669 xmemcpy(request->body, conn->in.buf, request->body_sz);
1670 conn->in.offset = 0;
1671 }
1672 break;
1673 }
7a2f978b 1674 continue; /* while offset > 0 */
1675 } else if (parser_return_code == 0) {
1676 /*
1677 * Partial request received; reschedule until parseHttpRequest()
1678 * is happy with the input
1679 */
1680 k = conn->in.size - 1 - conn->in.offset;
1681 if (k == 0) {
1682 if (conn->in.offset >= Config.maxRequestSize) {
1683 /* The request is too large to handle */
1684 debug(12, 0) ("Request won't fit in buffer.\n");
1685 debug(12, 0) ("Config 'request_size'= %d bytes.\n",
1686 Config.maxRequestSize);
1687 debug(12, 0) ("This request = %d bytes.\n",
1688 conn->in.offset);
1689 err = errorCon(ERR_INVALID_REQ, HTTP_REQUEST_ENTITY_TOO_LARGE);
f44af445 1690 http->entry = clientCreateStoreEntry(http, request->method, 0);
79e0dc20 1691 errorAppendEntry(http->entry, err);
7a2f978b 1692 return;
1693 }
1694 /* Grow the request memory area to accomodate for a large request */
1695 conn->in.size += REQUEST_BUF_SIZE;
1696 conn->in.buf = xrealloc(conn->in.buf, conn->in.size);
1697 meta_data.misc += REQUEST_BUF_SIZE;
1698 debug(12, 2) ("Handling a large request, offset=%d inbufsize=%d\n",
1699 conn->in.offset, conn->in.size);
1700 k = conn->in.size - 1 - conn->in.offset;
1701 }
7a2f978b 1702 break;
7a2f978b 1703 }
1704 }
1705}
1706
1707/* general lifetime handler for HTTP requests */
1708static void
1709requestTimeout(int fd, void *data)
1710{
1711 ConnStateData *conn = data;
1712 ErrorState *err;
1713 debug(12, 2) ("requestTimeout: FD %d: lifetime is expired.\n", fd);
1714 if (fd_table[fd].rwstate) {
79e0dc20 1715 /*
1716 * Some data has been sent to the client, just close the FD
1717 */
7a2f978b 1718 comm_close(fd);
1719 } else if (conn->nrequests) {
79e0dc20 1720 /*
1721 * assume its a persistent connection; just close it
1722 */
7a2f978b 1723 comm_close(fd);
1724 } else {
79e0dc20 1725 /*
1726 * Generate an error
1727 */
7a2f978b 1728 err = errorCon(ERR_LIFETIME_EXP, HTTP_REQUEST_TIMEOUT);
7a2f978b 1729 err->url = xstrdup("N/A");
79e0dc20 1730 /*
1731 * Normally we shouldn't call errorSend() in client_side.c, but
1732 * it should be okay in this case. Presumably if we get here
1733 * this is the first request for the connection, and no data
1734 * has been written yet
1735 */
1736 assert(conn->chr == NULL);
7a2f978b 1737 errorSend(fd, err);
79e0dc20 1738 /*
1739 * if we don't close() here, we still need a timeout handler!
1740 */
7a2f978b 1741 commSetTimeout(fd, 30, requestTimeout, conn);
1742 }
1743}
1744
1745int
79d39a72 1746httpAcceptDefer(int fdnotused, void *notused)
7a2f978b 1747{
1748 return !fdstat_are_n_free_fd(RESERVED_FD);
1749}
1750
bf8e5903 1751/* Handle a new connection on HTTP socket. */
7a2f978b 1752void
1753httpAccept(int sock, void *notused)
1754{
1755 int fd = -1;
1756 ConnStateData *connState = NULL;
1757 struct sockaddr_in peer;
1758 struct sockaddr_in me;
1759 memset(&peer, '\0', sizeof(struct sockaddr_in));
1760 memset(&me, '\0', sizeof(struct sockaddr_in));
1761 commSetSelect(sock, COMM_SELECT_READ, httpAccept, NULL, 0);
1762 if ((fd = comm_accept(sock, &peer, &me)) < 0) {
1763 debug(50, 1) ("httpAccept: FD %d: accept failure: %s\n",
1764 sock, xstrerror());
1765 return;
1766 }
7a2f978b 1767 debug(12, 4) ("httpAccept: FD %d: accepted\n", fd);
1768 connState = xcalloc(1, sizeof(ConnStateData));
1769 connState->peer = peer;
1770 connState->log_addr = peer.sin_addr;
1771 connState->log_addr.s_addr &= Config.Addrs.client_netmask.s_addr;
1772 connState->me = me;
1773 connState->fd = fd;
1774 connState->ident.fd = -1;
1775 connState->in.size = REQUEST_BUF_SIZE;
1776 connState->in.buf = xcalloc(connState->in.size, 1);
3f6c0fb2 1777 cbdataAdd(connState, MEM_NONE);
7a2f978b 1778 meta_data.misc += connState->in.size;
1779 comm_add_close_handler(fd, connStateFree, connState);
1780 if (Config.onoff.log_fqdn)
1781 fqdncache_gethostbyaddr(peer.sin_addr, FQDN_LOOKUP_IF_MISS);
1782 commSetTimeout(fd, Config.Timeout.request, requestTimeout, connState);
1783 commSetSelect(fd, COMM_SELECT_READ, clientReadRequest, connState, 0);
1784 commSetDefer(fd, clientReadDefer, connState);
1785}
1786
1787void
1788AppendUdp(icpUdpData * item)
1789{
1790 item->next = NULL;
1791 if (UdpQueueHead == NULL) {
1792 UdpQueueHead = item;
1793 UdpQueueTail = item;
1794 } else if (UdpQueueTail == UdpQueueHead) {
1795 UdpQueueTail = item;
1796 UdpQueueHead->next = item;
1797 } else {
1798 UdpQueueTail->next = item;
1799 UdpQueueTail = item;
1800 }
1801}
1802
1803/* return 1 if the request should be aborted */
1804static int
1805CheckQuickAbort2(const clientHttpRequest * http)
1806{
1807 long curlen;
1808 long minlen;
1809 long expectlen;
1810
79a15e0a 1811 if (!EBIT_TEST(http->request->flags, REQ_CACHABLE))
7a2f978b 1812 return 1;
79a15e0a 1813 if (EBIT_TEST(http->entry->flag, KEY_PRIVATE))
7a2f978b 1814 return 1;
1815 if (http->entry->mem_obj == NULL)
1816 return 1;
1817 expectlen = http->entry->mem_obj->reply->content_length;
1818 curlen = http->entry->mem_obj->inmem_hi;
1819 minlen = Config.quickAbort.min;
1820 if (minlen < 0)
1821 /* disabled */
1822 return 0;
1823 if (curlen > expectlen)
1824 /* bad content length */
1825 return 1;
1826 if ((expectlen - curlen) < minlen)
1827 /* only little more left */
1828 return 0;
1829 if ((expectlen - curlen) > Config.quickAbort.max)
1830 /* too much left to go */
1831 return 1;
1832 if ((curlen / (expectlen / 128U)) > Config.quickAbort.pct)
1833 /* past point of no return */
1834 return 0;
1835 return 1;
1836}
1837
1838
1839static void
1840CheckQuickAbort(clientHttpRequest * http)
1841{
1842 StoreEntry *entry = http->entry;
1843 /* Note, set entry here because http->entry might get changed (for IMS
1844 * requests) during the storeAbort() call */
1845 if (entry == NULL)
1846 return;
1847 if (storePendingNClients(entry) > 1)
1848 return;
1849 if (entry->store_status != STORE_PENDING)
1850 return;
1851 if (CheckQuickAbort2(http) == 0)
1852 return;
1853 debug(12, 3) ("CheckQuickAbort: ABORTING %s\n", storeUrl(entry));
1854 storeAbort(entry, 1);
1855}
1856
978e455f 1857#define SENDING_BODY 0
1858#define SENDING_HDRSONLY 1
7a2f978b 1859static int
1b02b5be 1860clientCheckTransferDone(clientHttpRequest * http)
7a2f978b 1861{
978e455f 1862 int sending = SENDING_BODY;
7a2f978b 1863 StoreEntry *entry = http->entry;
978e455f 1864 MemObject *mem;
1865 http_reply *reply;
1866 int sendlen;
7a2f978b 1867 if (entry == NULL)
1868 return 0;
978e455f 1869 /*
1870 * Handle STORE_OK and STORE_ABORTED objects.
1871 * entry->object_len will be set proprely.
1872 */
1873 if (entry->store_status != STORE_PENDING) {
7a2f978b 1874 if (http->out.offset >= entry->object_len)
1875 return 1;
513f05a6 1876 else
1877 return 0;
1878 }
978e455f 1879 /*
1880 * Now, handle STORE_PENDING objects
1881 */
1882 mem = entry->mem_obj;
1883 assert(mem != NULL);
1884 assert(http->request != NULL);
1885 reply = mem->reply;
1886 if (reply->hdr_sz == 0)
b34ed725 1887 return 0; /* haven't found end of headers yet */
978e455f 1888 else if (reply->code == HTTP_OK)
b34ed725 1889 sending = SENDING_BODY;
978e455f 1890 else if (reply->code == HTTP_NO_CONTENT)
b34ed725 1891 sending = SENDING_HDRSONLY;
978e455f 1892 else if (reply->code == HTTP_NOT_MODIFIED)
b34ed725 1893 sending = SENDING_HDRSONLY;
a3c60429 1894 else if (reply->code < HTTP_OK)
1895 sending = SENDING_HDRSONLY;
978e455f 1896 else if (http->request->method == METHOD_HEAD)
b34ed725 1897 sending = SENDING_HDRSONLY;
978e455f 1898 else
1899 sending = SENDING_BODY;
1900 /*
1901 * Figure out how much data we are supposed to send.
1902 * If we are sending a body and we don't have a content-length,
1903 * then we must wait for the object to become STORE_OK or
1904 * STORE_ABORTED.
1905 */
1906 if (sending == SENDING_HDRSONLY)
1907 sendlen = reply->hdr_sz;
1908 else if (reply->content_length < 0)
1909 return 0;
1910 else
1911 sendlen = reply->content_length + reply->hdr_sz;
1912 /*
1913 * Now that we have the expected length, did we send it all?
1914 */
1915 if (http->out.offset < sendlen)
1916 return 0;
1917 else
b34ed725 1918 return 1;
7a2f978b 1919}
1920
1921static char *
1b02b5be 1922clientConstruct304reply(struct _http_reply *source)
7a2f978b 1923{
1924 LOCAL_ARRAY(char, line, 256);
1925 LOCAL_ARRAY(char, reply, 8192);
7a2f978b 1926 memset(reply, '\0', 8192);
1927 strcpy(reply, "HTTP/1.0 304 Not Modified\r\n");
1928 if (source->date > -1) {
1929 snprintf(line, 256, "Date: %s\r\n", mkrfc1123(source->date));
1930 strcat(reply, line);
1931 }
1932 if ((int) strlen(source->content_type) > 0) {
1933 snprintf(line, 256, "Content-type: %s\r\n", source->content_type);
1934 strcat(reply, line);
1935 }
1936 if (source->content_length) {
1937 snprintf(line, 256, "Content-length: %d\r\n", source->content_length);
1938 strcat(reply, line);
1939 }
1940 if (source->expires > -1) {
1941 snprintf(line, 256, "Expires: %s\r\n", mkrfc1123(source->expires));
1942 strcat(reply, line);
1943 }
1944 if (source->last_modified > -1) {
1945 snprintf(line, 256, "Last-modified: %s\r\n",
1946 mkrfc1123(source->last_modified));
1947 strcat(reply, line);
1948 }
1949 strcat(reply, "\r\n");
1950 return reply;
1951}
1952
1953/*
1954 * This function is designed to serve a fairly specific purpose.
1955 * Occasionally our vBNS-connected caches can talk to each other, but not
1956 * the rest of the world. Here we try to detect frequent failures which
1957 * make the cache unusable (e.g. DNS lookup and connect() failures). If
1958 * the failure:success ratio goes above 1.0 then we go into "hit only"
1959 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
1960 * will only fetch HITs from us if they are using the ICP protocol. We
1961 * stay in this mode for 5 minutes.
1962 *
1963 * Duane W., Sept 16, 1996
1964 */
1965
1966static void
88aad2e5 1967checkFailureRatio(err_type etype, hier_code hcode)
7a2f978b 1968{
88aad2e5 1969 static double magic_factor = 100.0;
7a2f978b 1970 double n_good;
1971 double n_bad;
1972 if (hcode == HIER_NONE)
1973 return;
88aad2e5 1974 n_good = magic_factor / (1.0 + request_failure_ratio);
7a2f978b 1975 n_bad = magic_factor - n_good;
88aad2e5 1976 switch (etype) {
7a2f978b 1977 case ERR_DNS_FAIL:
1978 case ERR_CONNECT_FAIL:
1979 case ERR_READ_ERROR:
1980 n_bad++;
1981 break;
1982 default:
1983 n_good++;
1984 }
88aad2e5 1985 request_failure_ratio = n_bad / n_good;
7a2f978b 1986 if (hit_only_mode_until > squid_curtime)
1987 return;
88aad2e5 1988 if (request_failure_ratio < 1.0)
7a2f978b 1989 return;
88aad2e5 1990 debug(12, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio);
7a2f978b 1991 debug(12, 0) ("Going into hit-only-mode for %d minutes...\n",
1992 FAILURE_MODE_TIME / 60);
1993 hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
88aad2e5 1994 request_failure_ratio = 0.8; /* reset to something less than 1.0 */
7a2f978b 1995}
15df8349 1996
1997void
1998clientHttpConnectionsOpen(void)
1999{
2000 ushortlist *u;
2001 int fd;
15df8349 2002 for (u = Config.Port.http; u; u = u->next) {
8daca701 2003 enter_suid();
2004 fd = comm_open(SOCK_STREAM,
2005 0,
2006 Config.Addrs.tcp_incoming,
2007 u->i,
2008 COMM_NONBLOCKING,
2009 "HTTP Socket");
2010 leave_suid();
2011 if (fd < 0)
2012 continue;
2013 comm_listen(fd);
2014 commSetSelect(fd, COMM_SELECT_READ, httpAccept, NULL, 0);
2015 commSetDefer(fd, httpAcceptDefer, NULL);
2016 debug(1, 1) ("Accepting HTTP connections on port %d, FD %d.\n",
2017 (int) u->i, fd);
2018 HttpSockets[NHttpSockets++] = fd;
15df8349 2019 }
2020 if (NHttpSockets < 1)
8daca701 2021 fatal("Cannot open HTTP Port");
15df8349 2022}
c0fbae16 2023
ab013258 2024int
2025handleConnectionHeader(int flag, char *where, char *what)
2026{
2027 char *t, *p, *wh;
2028 int i;
2029 LOCAL_ARRAY(char, mbuf, 256);
2030
2031 if (flag) { /* lookup mode */
2032 if (where[0] == '\0' || what[0] == '\0')
2033 return 0;
2034 p = xstrdup(what);
2035 t = strtok(p, ":");
2036 if (t == NULL)
2037 return 0;
2038 debug(20, 3) ("handleConnectionHeader: %s\n AND %s (%p)\n", where, t, p);
2039 i = strstr(where, t) ? 1 : 0;
2040 xfree(p);
2041 return (i);
2042 }
2043 where[0] = '\0';
2044 wh = xstrdup(what);
2045 t = strtok(wh, ",");
2046 while (t != NULL) {
2047
2048#ifdef BE_PARANOID
2049 static char no_conn[] = "Expires:Host:Content-length:Content-type:";
2050
2051 if (handleConnectionHeader(1, no_conn, t)) {
2052 debug(1, 1) ("handleConnectionHeader: problematic header %s\n", t);
2053 t = strtok(NULL, ",\n");
2054 continue;
2055 }
2056#endif
2057 if ((p = strchr(t, ':')))
2058 xstrncpy(mbuf, t, p - t + 1);
2059 else
2060 snprintf(mbuf, 256, "%s:", t);
2061 strcat(where, mbuf);
2062 t = strtok(NULL, ",\n");
2063 }
2064 debug(20, 3) ("handleConnectionHeader: we have %s\n", where);
2065 xfree(wh);
2066 return 1;
2067}
2068
c0fbae16 2069void
2070clientHttpConnectionsClose(void)
2071{
2072 int i;
2073 for (i = 0; i < NHttpSockets; i++) {
2074 if (HttpSockets[i] >= 0) {
2075 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets[i]);
2076 comm_close(HttpSockets[i]);
2077 HttpSockets[i] = -1;
2078 }
2079 }
2080 NHttpSockets = 0;
2081}