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