3 * $Id: client_side.cc,v 1.427 1999/01/11 16:50:29 wessels Exp $
5 * DEBUG: section 33 Client-side Routines
6 * AUTHOR: Duane Wessels
8 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
9 * ----------------------------------------------------------
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.
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.
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.
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.
40 #include <sys/ioctl.h>
42 #include <netinet/tcp.h>
44 #include <ip_compat.h>
52 #define comm_close comm_lingering_close
55 static const char *const crlf
= "\r\n";
56 static const char *const proxy_auth_challenge_fmt
= "Basic realm=\"%s\"";
58 #define REQUEST_BUF_SIZE 4096
59 #define FAILURE_MODE_TIME 300
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
);
94 checkAccelOnly(clientHttpRequest
* http
)
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
)
100 if (Config
.onoff
.accel_with_proxy
)
102 if (http
->request
->protocol
== PROTO_CACHEOBJ
)
104 if (http
->flags
.accel
)
110 clientAccessCheck(void *data
)
112 clientHttpRequest
*http
= data
;
113 ConnStateData
*conn
= http
->conn
;
115 if (Config
.onoff
.ident_lookup
&& conn
->ident
.state
== IDENT_NONE
) {
116 identStart(-1, conn
, clientAccessCheck
, http
);
119 if (checkAccelOnly(http
)) {
120 clientAccessCheckDone(0, http
);
123 browser
= httpHeaderGetStr(&http
->request
->header
, HDR_USER_AGENT
);
124 http
->acl_checklist
= aclChecklistCreate(Config
.accessList
.http
,
129 aclNBCheck(http
->acl_checklist
, clientAccessCheckDone
, http
);
133 * returns true if client specified that the object must come from the cache
134 * witout contacting origin server
137 clientOnlyIfCached(clientHttpRequest
* http
)
139 const request_t
*r
= http
->request
;
141 return r
->cache_control
&&
142 EBIT_TEST(r
->cache_control
->mask
, CC_ONLY_IF_CACHED
);
146 clientConstructProxyAuthReply(clientHttpRequest
* http
)
150 if (!http
->flags
.accel
) {
151 /* Proxy authorisation needed */
152 err
= errorCon(ERR_CACHE_ACCESS_DENIED
,
153 HTTP_PROXY_AUTHENTICATION_REQUIRED
);
155 /* WWW authorisation needed */
156 err
= errorCon(ERR_CACHE_ACCESS_DENIED
, HTTP_UNAUTHORIZED
);
158 err
->request
= requestLink(http
->request
);
159 rep
= errorBuildReply(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
);
167 /* WWW Authorisation needed */
168 httpHeaderPutStrf(&rep
->header
, HDR_WWW_AUTHENTICATE
,
169 proxy_auth_challenge_fmt
, Config
.proxyAuthRealm
);
175 clientCreateStoreEntry(clientHttpRequest
* h
, method_t m
, request_flags flags
)
179 * For erroneous requests, we might not have a h->request,
180 * so make a fake one.
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
);
187 delaySetStoreClient(e
, h
, h
->request
->delay_id
);
189 storeClientCopy(e
, 0, 0, CLIENT_SOCK_SZ
,
190 memAllocate(MEM_CLIENT_SOCK_BUF
), clientSendMoreData
, h
);
196 clientAccessCheckDone(int answer
, void *data
)
198 clientHttpRequest
*http
= data
;
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
,
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
);
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
,
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
;
231 err
->page_id
= page_id
;
232 errorAppendEntry(http
->entry
, err
);
237 clientRedirectDone(void *data
, char *result
)
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
;
247 http_status status
= atoi(result
);
248 if (status
== 301 || status
== 302) {
250 if ((t
= strchr(result
, ':')) != NULL
) {
251 http
->redirect
.status
= status
;
252 http
->redirect
.location
= xstrdup(t
+ 1);
254 debug(33, 1) ("clientRedirectDone: bad input: %s\n", result
);
257 if (strcmp(result
, http
->uri
))
258 new_request
= urlParse(old_request
->method
, result
);
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
;
272 requestUnlink(old_request
);
273 http
->request
= requestLink(new_request
);
275 clientInterpretRequestHeaders(http
);
276 fd_note(http
->conn
->fd
, http
->uri
);
277 clientProcessRequest(http
);
281 clientProcessExpired(void *data
)
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);
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
293 if (clientOnlyIfCached(http
)) {
294 clientProcessOnlyIfCachedMiss(http
);
297 http
->request
->flags
.refresh
= 1;
298 http
->old_entry
= http
->entry
;
299 entry
= storeCreateEntry(url
,
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
);
307 delaySetStoreClient(entry
, http
, http
->request
->delay_id
);
308 delaySetStoreClient(http
->old_entry
, http
, http
->request
->delay_id
);
310 entry
->lastmod
= http
->old_entry
->lastmod
;
311 debug(33, 5) ("clientProcessExpired: lastmod %d\n", (int) entry
->lastmod
);
312 entry
->refcount
++; /* EXPIRED CASE */
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 (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
319 debug(33, 0) ("clientProcessExpired: found ENTRY_ABORTED object\n");
320 storeClientCopy(entry
,
324 memAllocate(MEM_CLIENT_SOCK_BUF
),
325 clientHandleIMSReply
,
330 clientGetsOldEntry(StoreEntry
* new_entry
, StoreEntry
* old_entry
, request_t
* request
)
332 const http_status status
= new_entry
->mem_obj
->reply
->sline
.status
;
334 debug(33, 5) ("clientGetsOldEntry: YES, broken HTTP reply\n");
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
);
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");
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",
356 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
362 clientHandleIMSReply(void *data
, char *buf
, ssize_t size
)
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
;
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 && !EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
375 if (EBIT_TEST(entry
->flags
, ENTRY_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
;
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
;
397 storeClientCopy(entry
,
398 http
->out
.offset
+ size
,
402 clientHandleIMSReply
,
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
);
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
;
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
;
438 storeUnregister(http
->old_entry
, http
);
439 storeUnlockObject(http
->old_entry
);
442 http
->old_entry
= NULL
; /* done with old_entry */
443 assert(!EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
445 storeClientCopy(entry
,
453 clientSendMoreData(data
, buf
, size
);
458 modifiedSince(StoreEntry
* entry
, request_t
* request
)
461 MemObject
*mem
= entry
->mem_obj
;
462 time_t mod_time
= entry
->lastmod
;
463 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry
));
465 mod_time
= entry
->timestamp
;
466 debug(33, 3) ("modifiedSince: mod_time = %d\n", (int) mod_time
);
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");
476 } else if (mod_time
< request
->ims
) {
477 debug(33, 3) ("--> NO: entry older than client\n");
479 } else if (request
->imslen
< 0) {
480 debug(33, 3) ("--> NO: same LMT, no client length\n");
482 } else if (request
->imslen
== object_length
) {
483 debug(33, 3) ("--> NO: same LMT, same length\n");
486 debug(33, 3) ("--> YES: same LMT, different length\n");
492 clientPurgeRequest(clientHttpRequest
* http
)
495 ErrorState
*err
= NULL
;
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
);
507 http
->log_type
= LOG_TCP_MISS
;
508 if ((entry
= storeGetPublic(http
->uri
, METHOD_GET
)) == NULL
) {
509 http
->http_code
= HTTP_NOT_FOUND
;
512 http
->http_code
= HTTP_OK
;
514 debug(33, 4) ("clientPurgeRequest: Not modified '%s'\n",
517 * Make a new entry to hold the reply to be written
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
);
528 checkNegativeHit(StoreEntry
* e
)
530 if (!EBIT_TEST(e
->flags
, ENTRY_NEGCACHED
))
532 if (e
->expires
<= squid_curtime
)
534 if (e
->store_status
!= STORE_OK
)
540 clientUpdateCounters(clientHttpRequest
* http
)
542 int svc_time
= tvSubMsec(http
->start
, current_time
);
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
);
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).
557 switch (http
->log_type
) {
558 case LOG_TCP_REFRESH_HIT
:
559 statHistCount(&Counter
.client_http
.nh_svc_time
, svc_time
);
561 case LOG_TCP_IMS_HIT
:
562 statHistCount(&Counter
.client_http
.nm_svc_time
, svc_time
);
565 case LOG_TCP_MEM_HIT
:
566 case LOG_TCP_OFFLINE_HIT
:
567 statHistCount(&Counter
.client_http
.hit_svc_time
, svc_time
);
570 case LOG_TCP_CLIENT_REFRESH_MISS
:
571 statHistCount(&Counter
.client_http
.miss_svc_time
, svc_time
);
574 /* make compiler warnings go away */
577 H
= &http
->request
->hier
;
580 Counter
.cd
.times_used
++;
583 Counter
.icp
.times_used
++;
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
));
589 Counter
.icp
.query_timeouts
++;
592 Counter
.netdb
.times_used
++;
600 httpRequestFree(void *data
)
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
)) {
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
);
616 assert(http
->log_type
< LOG_TYPE_MAX
);
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
);
624 http
->al
.http
.code
= mem
->reply
->sline
.status
;
625 http
->al
.http
.content_type
= strBuf(mem
->reply
->content_type
);
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
;
634 http
->al
.cache
.ident
= conn
->ident
.ident
;
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
;
648 accessLogLog(&http
->al
);
649 clientUpdateCounters(http
);
650 clientdbUpdate(conn
->peer
.sin_addr
, http
->log_type
, PROTO_HTTP
, http
->out
.size
);
652 if (http
->acl_checklist
)
653 aclChecklistFree(http
->acl_checklist
);
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
);
664 storeUnregister(entry
, http
);
665 storeUnlockObject(entry
);
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
;
674 requestUnlink(http
->request
);
675 assert(http
!= http
->next
);
676 assert(http
->conn
->chr
!= NULL
);
677 H
= &http
->conn
->chr
;
686 dlinkDelete(&http
->active
, &ClientActiveRequests
);
690 /* This is a handler normally called by comm_close() */
692 connStateFree(int fd
, void *data
)
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
);
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
);
710 /* prevent those nasty RST packets */
712 char buf
[SQUID_TCP_SO_RCVBUF
];
713 while (read(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0);
719 clientInterpretRequestHeaders(clientHttpRequest
* http
)
721 request_t
*request
= http
->request
;
722 const HttpHeader
*req_hdr
= &request
->header
;
723 #if USE_USERAGENT_LOG
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", ',')) {
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;
740 request
->flags
.nocache
= 1;
744 /* ignore range header in non-GETs */
745 if (request
->method
== METHOD_GET
) {
746 request
->range
= httpHeaderGetRange(req_hdr
);
748 request
->flags
.range
= 1;
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;
763 fvdbCountVia(strBuf(s
));
767 #if USE_USERAGENT_LOG
768 if ((str
= httpHeaderGetStr(req_hdr
, HDR_USER_AGENT
)))
769 logUserAgent(fqdnFromAddr(http
->conn
->peer
.sin_addr
), str
);
772 if (httpHeaderHas(req_hdr
, HDR_X_FORWARDED_FOR
)) {
773 String s
= httpHeaderGetList(req_hdr
, HDR_X_FORWARDED_FOR
);
774 fvdbCountForw(strBuf(s
));
778 request
->cache_control
= httpHeaderGetCc(req_hdr
);
779 if (request
->method
== METHOD_TRACE
) {
780 request
->max_forwards
= httpHeaderGetInt(req_hdr
, HDR_MAX_FORWARDS
);
782 if (clientCachable(http
))
783 request
->flags
.cachable
= 1;
784 if (clientHierarchical(http
))
785 request
->flags
.hierarchical
= 1;
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);
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");
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.
808 clientSetKeepaliveFlag(clientHttpRequest
* http
)
810 request_t
*request
= http
->request
;
811 const HttpHeader
*req_hdr
= &request
->header
;
812 debug(33, 3) ("clientSetKeepaliveFlag: http_ver = %3.1f\n",
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;
824 clientCheckContentLength(request_t
* r
)
826 /* We only require a content-length for "upload" methods */
827 if (!pumpMethod(r
->method
))
829 if (httpHeaderGetInt(&r
->header
, HDR_CONTENT_LENGTH
) < 0)
835 clientCachable(clientHttpRequest
* http
)
837 const char *url
= http
->uri
;
838 request_t
*req
= http
->request
;
839 method_t method
= req
->method
;
841 memset(&ch
, '\0', sizeof(ch
));
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
848 * This may not work yet for 'dst' and 'dst_domain' ACLs.
850 ch
.src_addr
= http
->conn
->peer
.sin_addr
;
851 ch
.request
= http
->request
;
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.
857 if (!aclCheckFast(Config
.accessList
.noCache
, &ch
))
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
)
866 if (method
== METHOD_CONNECT
)
868 if (method
== METHOD_TRACE
)
870 if (req
->protocol
== PROTO_CACHEOBJ
)
875 /* Return true if we can query our neighbors for this object */
877 clientHierarchical(clientHttpRequest
* http
)
879 const char *url
= http
->uri
;
880 request_t
*request
= http
->request
;
881 method_t method
= request
->method
;
882 const wordlist
*p
= NULL
;
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
)
888 if (request
->flags
.auth
)
890 if (method
== METHOD_TRACE
)
892 if (method
!= METHOD_GET
)
894 /* scan hierarchy_stoplist */
895 for (p
= Config
.hierarchy_stoplist
; p
; p
= p
->next
)
896 if (strstr(url
, p
->key
))
898 if (request
->flags
.loopdetect
)
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
)
906 if (request
->protocol
== PROTO_CACHEOBJ
)
912 isTcpHit(log_type code
)
914 /* this should be a bitmap for better optimization */
915 if (code
== LOG_TCP_HIT
)
917 if (code
== LOG_TCP_IMS_HIT
)
919 if (code
== LOG_TCP_REFRESH_FAIL_HIT
)
921 if (code
== LOG_TCP_REFRESH_HIT
)
923 if (code
== LOG_TCP_NEGATIVE_HIT
)
925 if (code
== LOG_TCP_MEM_HIT
)
927 if (code
== LOG_TCP_OFFLINE_HIT
)
933 * returns true if If-Range specs match reply, false otherwise
936 clientIfRangeMatch(clientHttpRequest
* http
, HttpReply
* rep
)
938 const TimeOrTag spec
= httpHeaderGetTimeOrTag(&http
->request
->header
, HDR_IF_RANGE
);
939 /* check for parsing falure */
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>");
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 */
954 return etagIsEqual(&rep_tag
, &spec
.tag
);
956 /* got modification time? */
957 if (spec
.time
>= 0) {
958 return http
->entry
->lastmod
<= spec
.time
;
960 assert(0); /* should not happen */
964 /* adds appropriate Range headers if needed */
966 clientBuildRangeHeader(clientHttpRequest
* http
, HttpReply
* rep
)
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 */
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 */
990 debug(33, 2) ("clientBuildRangeHeader: will not do ranges: %s.\n", range_err
);
991 httpHdrRangeDestroy(http
->request
->range
);
992 http
->request
->range
= NULL
;
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
);
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
);
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
);
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 */
1033 clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
)
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
);
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 */
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
;
1056 * think: on-average-best nesting of the two loops (hdrEntry
1057 * and strListItem) @?@
1060 * maybe we should delete standard stuff ("keep-alive","close")
1061 * from strConnection first?
1063 while ((e
= httpHeaderGetEntry(hdr
, &pos
))) {
1064 if (strListIsMember(&strConnection
, strBuf(e
->name
), ','))
1065 httpHeaderDelAt(hdr
, pos
);
1067 httpHeaderDelById(hdr
, HDR_CONNECTION
);
1068 stringClean(&strConnection
);
1072 clientBuildRangeHeader(http
, rep
);
1074 * Add Age header, not that our header must replace Age headers
1075 * from other caches if any
1077 if (http
->entry
->timestamp
> 0) {
1078 httpHeaderDelById(hdr
, HDR_AGE
);
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
1085 httpHeaderPutInt(hdr
, HDR_AGE
,
1086 http
->entry
->timestamp
<= squid_curtime
?
1087 squid_curtime
- http
->entry
->timestamp
: 0);
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
);
1099 * Clear keepalive for NON-HEAD requests with invalid content length
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
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].
1115 httpHeaderPutStr(hdr
, HDR_X_REQUEST_URI
,
1116 http
->entry
->mem_obj
->url
? http
->entry
->mem_obj
->url
: http
->uri
);
1121 clientBuildReply(clientHttpRequest
* http
, const char *buf
, size_t size
)
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
);
1133 /* parsing failure, get rid of the invalid reply */
1134 httpReplyDestroy(rep
);
1136 /* if we were going to do ranges, backoff */
1137 if (http
->request
->range
)
1138 clientBuildRangeHeader(http
, rep
); /* will fail and destroy request->range */
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.
1151 clientCacheHit(void *data
, char *buf
, ssize_t size
)
1153 clientHttpRequest
*http
= data
;
1154 StoreEntry
*e
= http
->entry
;
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");
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
)) {
1169 storeUnregister(e
, http
);
1170 storeUnlockObject(e
);
1172 clientProcessMiss(http
);
1177 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
1178 if (mem
->reply
->sline
.status
== 0) {
1180 * we don't have full reply headers yet; either wait for more or
1181 * punt to clientProcessMiss.
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
);
1190 debug(33, 3) ("clientCacheHit: waiting for HTTP reply headers\n");
1192 http
->out
.offset
+ size
,
1202 * Got the headers, now grok them
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
) {
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.
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");
1220 * We hold a stale copy; it needs to be validated
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.
1229 r
->flags
.need_validation
= 1;
1230 if (e
->lastmod
< 0) {
1232 * Previous reply didn't have a Last-Modified header,
1233 * we cannot revalidate it.
1235 http
->log_type
= LOG_TCP_MISS
;
1236 clientProcessMiss(http
);
1237 } else if (r
->flags
.nocache
) {
1239 * This did not match a refresh pattern that overrides no-cache
1240 * we should honour the client no-cache header.
1242 http
->log_type
= LOG_TCP_CLIENT_REFRESH_MISS
;
1243 clientProcessMiss(http
);
1244 } else if (r
->protocol
== PROTO_HTTP
) {
1246 * Object needs to be revalidated
1247 * XXX This could apply to FTP as well, if Last-Modified is known.
1249 http
->log_type
= LOG_TCP_REFRESH_MISS
;
1250 clientProcessExpired(http
);
1253 * We don't know how to re-validate other protocols. Handle
1254 * them as if the object has expired.
1256 http
->log_type
= LOG_TCP_MISS
;
1257 clientProcessMiss(http
);
1259 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1260 } else if (r
->flags
.ims
) {
1262 * Handle If-Modified-Since requests from the client
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
);
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
);
1280 httpReplyParse(e
->mem_obj
->reply
, mb
.buf
);
1281 storeAppend(e
, mb
.buf
, mb
.size
);
1287 * plain ol' cache hit
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
);
1298 /* extracts a "range" from *buf and appends them to mb, updating all offsets and such */
1300 clientPackRange(clientHttpRequest
* http
, HttpHdrRangeIter
* i
, const char **buf
, ssize_t
* size
, MemBuf
* mb
)
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
;
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
;
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
);
1327 httpHeaderClean(&hdr
);
1328 /* append <crlf> (we packed a header, not a reply */
1329 memBufPrintf(mb
, "\r\n");
1332 debug(33, 3) ("clientPackRange: appending %d bytes\n", copy_sz
);
1333 memBufAppend(mb
, *buf
, copy_sz
);
1334 /* update offsets */
1336 i
->debt_size
-= copy_sz
;
1337 body_off
+= copy_sz
;
1339 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1340 /* paranoid check */
1341 assert(*size
>= 0 && i
->debt_size
>= 0);
1344 /* returns true if there is still data available to pack more ranges
1345 * increments iterator "i"
1346 * used by clientPackMoreRanges */
1348 clientCanPackMoreRanges(const clientHttpRequest
* http
, HttpHdrRangeIter
* i
, ssize_t size
)
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
;
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;
1360 /* extracts "ranges" from buf and appends them to mb, updating all offsets and such */
1361 /* returns true if we need more data */
1363 clientPackMoreRanges(clientHttpRequest
* http
, const char *buf
, ssize_t size
, MemBuf
* mb
)
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
;
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 */
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
;
1388 /* has not reached start yet */
1393 /* put next chunk if any */
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 */
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
);
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
;
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
));
1415 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1416 return i
->debt_size
> 0;
1420 * accepts chunk of a http message in buf, parses prefix, filters headers and
1421 * such, writes processed message to the client's socket
1424 clientSendMoreData(void *data
, char *buf
, ssize_t size
)
1426 clientHttpRequest
*http
= data
;
1427 StoreEntry
*entry
= http
->entry
;
1428 ConnStateData
*conn
= http
->conn
;
1430 HttpReply
*rep
= NULL
;
1431 const char *body_buf
= buf
;
1432 ssize_t body_size
= size
;
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
);
1447 } else if (entry
&& EBIT_TEST(entry
->flags
, ENTRY_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
);
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
);
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
);
1463 if (http
->out
.offset
== 0) {
1464 if (Config
.onoff
.log_mime_hdrs
) {
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
);
1472 rep
= clientBuildReply(http
, buf
, size
);
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
,
1491 /* reset range iterator */
1492 http
->range_iter
.pos
= HttpHdrRangeInitPos
;
1494 if (http
->request
->method
== METHOD_HEAD
) {
1496 /* do not forward body for HEAD replies */
1498 http
->flags
.done_copying
= 1;
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
1508 http
->flags
.done_copying
= 1;
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 */
1515 mb
= httpReplyPack(rep
);
1516 http
->out
.offset
+= rep
->hdr_sz
;
1517 check_size
+= rep
->hdr_sz
;
1518 httpReplyDestroy(rep
);
1521 /* leave space for growth in case we do ranges */
1522 memBufInit(&mb
, CLIENT_SOCK_SZ
, 2 * CLIENT_SOCK_SZ
);
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
);
1537 if (!http
->request
->range
&& http
->request
->method
== METHOD_GET
)
1538 assert(check_size
== size
);
1540 comm_write_mbuf(fd
, mb
, clientWriteComplete
, http
);
1541 /* if we don't do it, who will? */
1542 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1546 clientKeepaliveNextRequest(clientHttpRequest
* http
)
1548 ConnStateData
*conn
= http
->conn
;
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",
1556 fd_note(conn
->fd
, "Reading next request");
1558 * Set the timeout BEFORE calling clientReadRequest().
1560 commSetTimeout(conn
->fd
, 15, requestTimeout
, conn
);
1561 clientReadRequest(conn
->fd
, conn
); /* Read next request */
1563 * Note, the FD may be closed at this point.
1565 } else if ((entry
= http
->entry
) == NULL
) {
1567 * this request is in progress, maybe doing an ACL or a redirect,
1568 * execution will resume after the operation completes.
1571 debug(33, 1) ("clientKeepaliveNextRequest: FD %d Sending next\n",
1574 if (0 == storeClientCopyPending(entry
, http
)) {
1575 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1576 debug(33, 0) ("clientKeepaliveNextRequest: ENTRY_ABORTED\n");
1577 storeClientCopy(entry
,
1581 memAllocate(MEM_CLIENT_SOCK_BUF
),
1589 clientWriteComplete(int fd
, char *bufnotused
, size_t size
, int errflag
, void *data
)
1591 clientHttpRequest
*http
= data
;
1592 StoreEntry
*entry
= http
->entry
;
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);
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
);
1604 * just close the socket, httpRequestFree will abort if needed
1607 } else if (NULL
== entry
) {
1608 comm_close(fd
); /* yuk */
1609 } else if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
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");
1618 debug(33, 5) ("clientWriteComplete: closing, !done\n");
1620 } else if (clientGotNotEnough(http
)) {
1621 debug(33, 5) ("clientWriteComplete: client didn't get all it expected\n");
1623 } else if (http
->request
->flags
.proxy_keepalive
) {
1624 debug(33, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd
);
1625 clientKeepaliveNextRequest(http
);
1630 /* More data will be coming from primary server; register with
1631 * storage manager. */
1632 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1633 debug(33, 0) ("clientWriteComplete 2: ENTRY_ABORTED\n");
1634 storeClientCopy(entry
,
1638 memAllocate(MEM_CLIENT_SOCK_BUF
),
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]
1651 clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
)
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
);
1667 clientProcessRequest2(clientHttpRequest
* http
)
1669 request_t
*r
= http
->request
;
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
);
1676 #if USE_CACHE_DIGESTS
1677 http
->lookup_type
= e
? "HIT" : "MISS";
1680 /* this object isn't in the cache */
1681 debug(33, 3) ("clientProcessRequest2: storeGet() MISS\n");
1682 return LOG_TCP_MISS
;
1684 if (Config
.onoff
.offline
) {
1685 debug(33, 3) ("clientProcessRequest2: offline HIT\n");
1689 if (!storeEntryValidToSend(e
)) {
1690 debug(33, 3) ("clientProcessRequest2: !storeEntryValidToSend MISS\n");
1692 return LOG_TCP_MISS
;
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");
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
);
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",
1711 r
->flags
.nocache
= 0;
1712 r
->flags
.nocache_hack
= 0;
1716 if (r
->flags
.nocache
) {
1717 debug(33, 3) ("clientProcessRequest2: no-cache REFRESH MISS\n");
1719 ipcacheReleaseInvalid(r
->host
);
1720 return LOG_TCP_CLIENT_REFRESH_MISS
;
1722 if (r
->range
&& httpHdrRangeWillBeComplex(r
->range
)) {
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
1729 debug(33, 3) ("clientProcessRequest2: complex range MISS\n");
1731 return LOG_TCP_MISS
;
1733 debug(33, 3) ("clientProcessRequest2: default HIT\n");
1739 clientProcessRequest(clientHttpRequest
* http
)
1741 char *url
= http
->uri
;
1742 request_t
*r
= http
->request
;
1743 int fd
= http
->conn
->fd
;
1745 debug(33, 4) ("clientProcessRequest: %s '%s'\n",
1746 RequestMethodStr
[r
->method
],
1748 if (r
->method
== METHOD_CONNECT
) {
1749 http
->log_type
= LOG_TCP_MISS
;
1750 sslStart(fd
, url
, r
, &http
->out
.size
);
1752 } else if (r
->method
== METHOD_PURGE
) {
1753 clientPurgeRequest(http
);
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
);
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
);
1776 http
->log_type
= clientProcessRequest2(http
);
1778 debug(33, 4) ("clientProcessRequest: %s for '%s'\n",
1779 log_tags
[http
->log_type
],
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
);
1787 delaySetStoreClient(http
->entry
, http
, http
->request
->delay_id
);
1789 http
->entry
->refcount
++;
1790 storeClientCopy(http
->entry
,
1794 memAllocate(MEM_CLIENT_SOCK_BUF
),
1799 http
->log_type
= LOG_TCP_MISS
;
1800 clientProcessMiss(http
);
1805 * Prepare to fetch the object as it's a cache miss of some kind.
1808 clientProcessMiss(clientHttpRequest
* http
)
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
);
1816 * We might have a left-over StoreEntry from a failed cache hit
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
);
1826 if (clientOnlyIfCached(http
)) {
1827 clientProcessOnlyIfCachedMiss(http
);
1831 * Deny loops when running in accelerator/transproxy mode.
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
);
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
);
1854 if (http
->flags
.internal
)
1855 r
->protocol
= PROTO_INTERNAL
;
1856 fwdStart(http
->conn
->fd
, http
->entry
, r
, http
->conn
->peer
.sin_addr
);
1859 static clientHttpRequest
*
1860 parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
)
1862 clientHttpRequest
*http
= xcalloc(1, sizeof(clientHttpRequest
));
1863 cbdataAdd(http
, cbdataXfree
, 0);
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
);
1875 * parseHttpRequest()
1878 * NULL on error or incomplete request
1879 * a clientHttpRequest structure on success
1881 static clientHttpRequest
*
1882 parseHttpRequest(ConnStateData
* conn
, method_t
* method_p
, int *status
,
1883 char **prefix_p
, size_t * req_line_sz_p
)
1888 char *req_hdr
= NULL
;
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) */
1899 clientHttpRequest
*http
= NULL
;
1901 struct natlookup natLookup
;
1902 static int natfd
= -1;
1905 if ((req_sz
= headersEnd(conn
->in
.buf
, conn
->in
.offset
)) == 0) {
1906 debug(33, 5) ("Incomplete request, waiting for end of headers\n");
1909 *method_p
= METHOD_NONE
;
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';
1918 /* pre-set these values to make aborting simpler */
1920 *method_p
= METHOD_NONE
;
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");
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");
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");
1938 debug(33, 5) ("parseHttpRequest: Method is '%s'\n", mstr
);
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");
1946 while (isspace(*url
))
1948 t
= url
+ strlen(url
);
1953 if (isspace(*t
) && !strncmp(t
+ 1, "HTTP/", 5)) {
1958 while (t
> url
&& isspace(*t
))
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 */
1966 return parseHttpRequestAbort(conn
, "error:missing-http-ident");
1969 http_ver
= (float) atof(token
+ 5);
1973 * Process headers after request line
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");
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
);
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
);
1993 /* Ok, all headers are received */
1994 http
= xcalloc(1, sizeof(clientHttpRequest
));
1995 cbdataAdd(http
, cbdataXfree
, 0);
1996 http
->http_ver
= http_ver
;
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
);
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 */
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;
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. */
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 */
2031 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
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);
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
;
2047 natfd
= open(IPL_NAT
, O_RDONLY
, 0);
2049 debug(50, 1) ("parseHttpRequest: NAT open failed: %s\n",
2051 return parseHttpRequestAbort(conn
, "error:nat-open-failed");
2053 if (ioctl(natfd
, SIOCGNATL
, &natLookup
) < 0) {
2054 if (errno
!= ESRCH
) {
2055 debug(50, 1) ("parseHttpRequest: NAT lookup failed: ioctl(SIOCGNATL)\n");
2058 return parseHttpRequestAbort(conn
, "error:nat-lookup-failed");
2060 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2061 inet_ntoa(http
->conn
->me
.sin_addr
),
2062 (int) Config
.Accel
.port
,
2065 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2066 inet_ntoa(natLookup
.nl_realip
),
2067 (int) Config
.Accel
.port
,
2070 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2071 inet_ntoa(http
->conn
->me
.sin_addr
),
2072 (int) Config
.Accel
.port
,
2075 debug(33, 5) ("VHOST REWRITE: '%s'\n", http
->uri
);
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
);
2082 http
->flags
.accel
= 1;
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;
2090 if (!stringHasWhitespace(http
->uri
))
2091 http
->log_uri
= xstrndup(http
->uri
, MAX_URL
);
2093 http
->log_uri
= xstrndup(rfc1738_escape(http
->uri
), MAX_URL
);
2094 debug(33, 5) ("parseHttpRequest: Complete request received\n");
2103 clientReadDefer(int fdnotused
, void *data
)
2105 ConnStateData
*conn
= data
;
2106 return conn
->defer
.until
> squid_curtime
;
2110 clientReadRequest(int fd
, void *data
)
2112 ConnStateData
*conn
= data
;
2113 int parser_return_code
= 0;
2115 request_t
*request
= NULL
;
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
);
2128 fd_bytes(fd
, size
, FD_READ
);
2129 kb_incr(&Counter
.client_http
.kbytes_in
, size
);
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
2138 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, conn
, 0);
2140 if (conn
->chr
== NULL
) {
2141 /* no current or pending requests */
2144 } else if (!Config
.onoff
.half_closed_clients
) {
2145 /* admin doesn't want to support half-closed client sockets */
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;
2154 fd_note(fd
, "half-closed");
2156 } else if (size
< 0) {
2157 if (!ignoreErrno(errno
)) {
2158 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd
, xstrerror());
2161 } else if (conn
->in
.offset
== 0) {
2162 debug(50, 2) ("clientReadRequest: FD %d: no data to process (%s)\n", fd
, xstrerror());
2165 /* Continue to process previously read data */
2168 conn
->in
.offset
+= size
;
2169 /* Skip leading (and trailing) whitespace */
2170 while (conn
->in
.offset
> 0) {
2173 while (conn
->in
.offset
> 0 && isspace(conn
->in
.buf
[0])) {
2174 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.offset
- 1);
2177 conn
->in
.buf
[conn
->in
.offset
] = '\0'; /* Terminate the string */
2178 if (conn
->in
.offset
== 0)
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 */
2188 /* Process request */
2189 http
= parseHttpRequest(conn
,
2191 &parser_return_code
,
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
);
2202 * If we read past the end of this request, move the remaining
2203 * data to the beginning
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
);
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
);
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
);
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",
2237 /* continue anyway? */
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;
2252 request
->flags
.internal
= http
->flags
.internal
;
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
);
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
);
2276 http
->request
= requestLink(request
);
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.
2282 clientSetKeepaliveFlag(http
);
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
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
;
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
);
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.
2307 if (request
->body_sz
< cont_len
)
2308 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2310 clientAccessCheck(http
);
2311 continue; /* while offset > 0 */
2312 } else if (parser_return_code
== 0) {
2314 * Partial request received; reschedule until parseHttpRequest()
2315 * is happy with the input
2317 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
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
);
2331 http
->entry
= clientCreateStoreEntry(http
, METHOD_NONE
, null_request_flags
);
2332 errorAppendEntry(http
->entry
, err
);
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
;
2348 /* general lifetime handler for HTTP requests */
2350 requestTimeout(int fd
, void *data
)
2352 ConnStateData
*conn
= data
;
2354 debug(33, 2) ("requestTimeout: FD %d: lifetime is expired.\n", fd
);
2355 if (fd_table
[fd
].rwstate
) {
2357 * Some data has been sent to the client, just close the FD
2360 } else if (conn
->nrequests
) {
2362 * assume its a persistent connection; just close it
2369 err
= errorCon(ERR_LIFETIME_EXP
, HTTP_REQUEST_TIMEOUT
);
2370 err
->url
= xstrdup("N/A");
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
2377 assert(conn
->chr
== NULL
);
2380 * if we don't close() here, we still need a timeout handler!
2382 commSetTimeout(fd
, 30, requestTimeout
, conn
);
2387 httpAcceptDefer(void)
2389 static time_t last_warn
= 0;
2390 if (fdNFree() >= RESERVED_FD
)
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
;
2399 /* Handle a new connection on HTTP socket. */
2401 httpAccept(int sock
, void *data
)
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",
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
;
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
);
2441 #define SENDING_BODY 0
2442 #define SENDING_HDRSONLY 1
2444 clientCheckTransferDone(clientHttpRequest
* http
)
2446 int sending
= SENDING_BODY
;
2447 StoreEntry
*entry
= http
->entry
;
2454 * For now, 'done_copying' is used for special cases like
2455 * Range and HEAD requests.
2457 if (http
->flags
.done_copying
)
2460 * Handle STORE_OK objects.
2461 * objectLen(entry) will be set proprely.
2463 if (entry
->store_status
== STORE_OK
) {
2464 if (http
->out
.offset
>= objectLen(entry
))
2470 * Now, handle STORE_PENDING objects
2472 mem
= entry
->mem_obj
;
2473 assert(mem
!= NULL
);
2474 assert(http
->request
!= NULL
);
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
;
2489 sending
= SENDING_BODY
;
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.
2495 if (sending
== SENDING_HDRSONLY
)
2496 sendlen
= reply
->hdr_sz
;
2497 else if (reply
->content_length
< 0)
2500 sendlen
= reply
->content_length
+ reply
->hdr_sz
;
2502 * Now that we have the expected length, did we send it all?
2504 if (http
->out
.offset
< sendlen
)
2511 clientGotNotEnough(clientHttpRequest
* http
)
2513 int cl
= http
->entry
->mem_obj
->reply
->content_length
;
2514 int hs
= http
->entry
->mem_obj
->reply
->hdr_sz
;
2516 if (http
->out
.offset
< cl
+ hs
)
2522 * This function is designed to serve a fairly specific purpose.
2523 * Occasionally our vBNS-connected caches can talk to each other, but not
2524 * the rest of the world. Here we try to detect frequent failures which
2525 * make the cache unusable (e.g. DNS lookup and connect() failures). If
2526 * the failure:success ratio goes above 1.0 then we go into "hit only"
2527 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
2528 * will only fetch HITs from us if they are using the ICP protocol. We
2529 * stay in this mode for 5 minutes.
2531 * Duane W., Sept 16, 1996
2535 checkFailureRatio(err_type etype
, hier_code hcode
)
2537 static double magic_factor
= 100.0;
2540 if (hcode
== HIER_NONE
)
2542 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
2543 n_bad
= magic_factor
- n_good
;
2546 case ERR_CONNECT_FAIL
:
2547 case ERR_READ_ERROR
:
2553 request_failure_ratio
= n_bad
/ n_good
;
2554 if (hit_only_mode_until
> squid_curtime
)
2556 if (request_failure_ratio
< 1.0)
2558 debug(33, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio
);
2559 debug(33, 0) ("Going into hit-only-mode for %d minutes...\n",
2560 FAILURE_MODE_TIME
/ 60);
2561 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
2562 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
2566 clientHttpConnectionsOpen(void)
2570 for (u
= Config
.Port
.http
; u
; u
= u
->next
) {
2572 fd
= comm_open(SOCK_STREAM
,
2574 Config
.Addrs
.tcp_incoming
,
2582 commSetSelect(fd
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2583 /*commSetDefer(fd, httpAcceptDefer, NULL); */
2584 debug(1, 1) ("Accepting HTTP connections on port %d, FD %d.\n",
2586 HttpSockets
[NHttpSockets
++] = fd
;
2588 if (NHttpSockets
< 1)
2589 fatal("Cannot open HTTP Port");
2593 clientHttpConnectionsClose(void)
2596 for (i
= 0; i
< NHttpSockets
; i
++) {
2597 if (HttpSockets
[i
] >= 0) {
2598 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets
[i
]);
2599 comm_close(HttpSockets
[i
]);
2600 HttpSockets
[i
] = -1;