3 * $Id: client_side.cc,v 1.444 1999/04/23 23:01:23 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";
57 #define REQUEST_BUF_SIZE 4096
58 #define FAILURE_MODE_TIME 300
62 static CWCB clientWriteComplete
;
63 static PF clientReadRequest
;
64 static PF connStateFree
;
65 static PF requestTimeout
;
66 static int clientCheckTransferDone(clientHttpRequest
*);
67 static int clientGotNotEnough(clientHttpRequest
*);
68 static void checkFailureRatio(err_type
, hier_code
);
69 static void clientProcessMiss(clientHttpRequest
*);
70 static void clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
);
71 static clientHttpRequest
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
72 static clientHttpRequest
*parseHttpRequest(ConnStateData
*, method_t
*, int *, char **, size_t *);
73 static RH clientRedirectDone
;
74 static STCB clientHandleIMSReply
;
75 static int clientGetsOldEntry(StoreEntry
* new, StoreEntry
* old
, request_t
* request
);
76 static int checkAccelOnly(clientHttpRequest
*);
78 static IDCB clientIdentDone
;
80 static int clientOnlyIfCached(clientHttpRequest
* http
);
81 static STCB clientSendMoreData
;
82 static STCB clientCacheHit
;
83 static void clientSetKeepaliveFlag(clientHttpRequest
*);
84 static void clientPackRangeHdr(const HttpReply
*rep
, const HttpHdrRangeSpec
*spec
, String boundary
, MemBuf
*mb
);
85 static void clientPackTermBound(String boundary
, MemBuf
*mb
);
86 static void clientInterpretRequestHeaders(clientHttpRequest
*);
87 static void clientProcessRequest(clientHttpRequest
*);
88 static void clientProcessExpired(void *data
);
89 static void clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
);
90 static int clientCachable(clientHttpRequest
* http
);
91 static int clientHierarchical(clientHttpRequest
* http
);
92 static int clientCheckContentLength(request_t
* r
);
93 static int httpAcceptDefer(void);
94 static log_type
clientProcessRequest2(clientHttpRequest
* http
);
97 checkAccelOnly(clientHttpRequest
* http
)
99 /* return TRUE if someone makes a proxy request to us and
100 * we are in httpd-accel only mode */
101 if (!Config2
.Accel
.on
)
103 if (Config
.onoff
.accel_with_proxy
)
105 if (http
->request
->protocol
== PROTO_CACHEOBJ
)
107 if (http
->flags
.accel
)
114 clientIdentDone(const char *ident
, void *data
)
116 ConnStateData
*conn
= data
;
118 xstrncpy(conn
->ident
, ident
, sizeof(conn
->ident
));
120 xstrncpy(conn
->ident
, "-", sizeof(conn
->ident
));
125 clientAccessCheck(void *data
)
127 clientHttpRequest
*http
= data
;
128 ConnStateData
*conn
= http
->conn
;
130 if (checkAccelOnly(http
)) {
131 clientAccessCheckDone(0, http
);
134 browser
= httpHeaderGetStr(&http
->request
->header
, HDR_USER_AGENT
);
135 http
->acl_checklist
= aclChecklistCreate(Config
.accessList
.http
,
143 * hack for ident ACL. It needs to get full addresses, and a
144 * place to store the ident result on persistent connections...
146 http
->acl_checklist
->conn
= conn
;
147 cbdataLock(http
->acl_checklist
->conn
);
149 aclNBCheck(http
->acl_checklist
, clientAccessCheckDone
, http
);
153 * returns true if client specified that the object must come from the cache
154 * witout contacting origin server
157 clientOnlyIfCached(clientHttpRequest
* http
)
159 const request_t
*r
= http
->request
;
161 return r
->cache_control
&&
162 EBIT_TEST(r
->cache_control
->mask
, CC_ONLY_IF_CACHED
);
166 clientCreateStoreEntry(clientHttpRequest
* h
, method_t m
, request_flags flags
)
170 * For erroneous requests, we might not have a h->request,
171 * so make a fake one.
173 if (h
->request
== NULL
)
174 h
->request
= requestLink(requestCreate(m
, PROTO_NONE
, NULL
));
175 e
= storeCreateEntry(h
->uri
, h
->log_uri
, flags
, m
);
176 storeClientListAdd(e
, h
);
178 delaySetStoreClient(e
, h
, delayClient(h
->request
));
180 storeClientCopy(e
, 0, 0, CLIENT_SOCK_SZ
,
181 memAllocate(MEM_CLIENT_SOCK_BUF
), clientSendMoreData
, h
);
186 clientAccessCheckDone(int answer
, void *data
)
188 clientHttpRequest
*http
= data
;
191 ErrorState
*err
= NULL
;
192 debug(33, 5) ("clientAccessCheckDone: '%s' answer=%d\n", http
->uri
, answer
);
193 http
->acl_checklist
= NULL
;
194 if (answer
== ACCESS_ALLOWED
) {
195 safe_free(http
->uri
);
196 http
->uri
= xstrdup(urlCanonical(http
->request
));
197 assert(http
->redirect_state
== REDIRECT_NONE
);
198 http
->redirect_state
= REDIRECT_PENDING
;
199 redirectStart(http
, clientRedirectDone
, http
);
201 debug(33, 5) ("Access Denied: %s\n", http
->uri
);
202 debug(33, 5) ("AclMatchedName = %s\n",
203 AclMatchedName
? AclMatchedName
: "<null>");
205 * NOTE: get page_id here, based on AclMatchedName because
206 * if USE_DELAY_POOLS is enabled, then AclMatchedName gets
207 * clobbered in the clientCreateStoreEntry() call
208 * just below. Pedro Ribeiro <pribeiro@isel.pt>
210 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
);
211 http
->log_type
= LOG_TCP_DENIED
;
212 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
214 if (answer
== ACCESS_REQ_PROXY_AUTH
|| aclIsProxyAuth(AclMatchedName
)) {
215 if (!http
->flags
.accel
) {
216 /* Proxy authorisation needed */
217 status
= HTTP_PROXY_AUTHENTICATION_REQUIRED
;
219 /* WWW authorisation needed */
220 status
= HTTP_UNAUTHORIZED
;
223 page_id
= ERR_CACHE_ACCESS_DENIED
;
225 status
= HTTP_FORBIDDEN
;
227 page_id
= ERR_ACCESS_DENIED
;
229 err
= errorCon(page_id
, status
);
230 err
->request
= requestLink(http
->request
);
231 err
->src_addr
= http
->conn
->peer
.sin_addr
;
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
->my_addr
= old_request
->my_addr
;
267 new_request
->flags
.redirected
= 1;
268 if (old_request
->body
) {
269 new_request
->body
= xmalloc(old_request
->body_sz
);
270 xmemcpy(new_request
->body
, old_request
->body
, old_request
->body_sz
);
271 new_request
->body_sz
= old_request
->body_sz
;
273 requestUnlink(old_request
);
274 http
->request
= requestLink(new_request
);
276 clientInterpretRequestHeaders(http
);
277 fd_note(http
->conn
->fd
, http
->uri
);
278 clientProcessRequest(http
);
282 clientProcessExpired(void *data
)
284 clientHttpRequest
*http
= data
;
285 char *url
= http
->uri
;
286 StoreEntry
*entry
= NULL
;
287 debug(33, 3) ("clientProcessExpired: '%s'\n", http
->uri
);
288 assert(http
->entry
->lastmod
>= 0);
290 * check if we are allowed to contact other servers
291 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
292 * a stale entry *if* it matches client requirements
294 if (clientOnlyIfCached(http
)) {
295 clientProcessOnlyIfCachedMiss(http
);
298 http
->request
->flags
.refresh
= 1;
299 http
->old_entry
= http
->entry
;
301 * Assert that 'http' is already a client of old_entry. If
302 * it is not, then the beginning of the object data might get
303 * freed from memory before we need to access it.
305 assert(storeClientListSearch(http
->old_entry
->mem_obj
, http
));
306 entry
= storeCreateEntry(url
,
308 http
->request
->flags
,
309 http
->request
->method
);
310 /* NOTE, don't call storeLockObject(), storeCreateEntry() does it */
311 storeClientListAdd(entry
, http
);
313 /* delay_id is already set on original store client */
314 delaySetStoreClient(entry
, http
, delayClient(http
->request
));
316 entry
->lastmod
= http
->old_entry
->lastmod
;
317 debug(33, 5) ("clientProcessExpired: lastmod %d\n", (int) entry
->lastmod
);
318 entry
->refcount
++; /* EXPIRED CASE */
320 http
->out
.offset
= 0;
321 fwdStart(http
->conn
->fd
, http
->entry
, http
->request
,
322 http
->conn
->peer
.sin_addr
, http
->conn
->me
.sin_addr
);
323 /* Register with storage manager to receive updates when data comes in. */
324 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
325 debug(33, 0) ("clientProcessExpired: found ENTRY_ABORTED object\n");
326 storeClientCopy(entry
,
330 memAllocate(MEM_CLIENT_SOCK_BUF
),
331 clientHandleIMSReply
,
336 clientGetsOldEntry(StoreEntry
* new_entry
, StoreEntry
* old_entry
, request_t
* request
)
338 const http_status status
= new_entry
->mem_obj
->reply
->sline
.status
;
340 debug(33, 5) ("clientGetsOldEntry: YES, broken HTTP reply\n");
343 /* If the reply is a failure then send the old object as a last
345 if (status
>= 500 && status
< 600) {
346 debug(33, 2) ("clientGetsOldEntry: YES, failure reply=%d\n", status
);
349 /* If the reply is anything but "Not Modified" then
350 * we must forward it to the client */
351 if (HTTP_NOT_MODIFIED
!= status
) {
352 debug(33, 5) ("clientGetsOldEntry: NO, reply=%d\n", status
);
355 /* If the client did not send IMS in the request, then it
356 * must get the old object, not this "Not Modified" reply */
357 if (!request
->flags
.ims
) {
358 debug(33, 5) ("clientGetsOldEntry: YES, no client IMS\n");
361 /* If the client IMS time is prior to the entry LASTMOD time we
362 * need to send the old object */
363 if (modifiedSince(old_entry
, request
)) {
364 debug(33, 5) ("clientGetsOldEntry: YES, modified since %d\n",
368 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
374 clientHandleIMSReply(void *data
, char *buf
, ssize_t size
)
376 clientHttpRequest
*http
= data
;
377 StoreEntry
*entry
= http
->entry
;
379 const char *url
= storeUrl(entry
);
380 int unlink_request
= 0;
381 StoreEntry
*oldentry
;
384 debug(33, 3) ("clientHandleIMSReply: %s, %d bytes\n", url
, (int) size
);
386 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
389 if (size
< 0 && !EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
390 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
393 mem
= entry
->mem_obj
;
394 status
= mem
->reply
->sline
.status
;
395 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
396 debug(33, 3) ("clientHandleIMSReply: ABORTED '%s'\n", url
);
397 /* We have an existing entry, but failed to validate it */
398 /* Its okay to send the old one anyway */
399 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
400 storeUnregister(entry
, http
);
401 storeUnlockObject(entry
);
402 entry
= http
->entry
= http
->old_entry
;
404 } else if (STORE_PENDING
== entry
->store_status
&& 0 == status
) {
405 debug(33, 3) ("clientHandleIMSReply: Incomplete headers for '%s'\n", url
);
406 if (size
>= CLIENT_SOCK_SZ
) {
407 /* will not get any bigger than that */
408 debug(33, 3) ("clientHandleIMSReply: Reply is too large '%s', using old entry\n", url
);
409 /* use old entry, this repeats the code abovez */
410 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
411 storeUnregister(entry
, http
);
412 storeUnlockObject(entry
);
413 entry
= http
->entry
= http
->old_entry
;
417 storeClientCopy(entry
,
418 http
->out
.offset
+ size
,
422 clientHandleIMSReply
,
426 } else if (clientGetsOldEntry(entry
, http
->old_entry
, http
->request
)) {
427 /* We initiated the IMS request, the client is not expecting
428 * 304, so put the good one back. First, make sure the old entry
429 * headers have been loaded from disk. */
430 oldentry
= http
->old_entry
;
431 http
->log_type
= LOG_TCP_REFRESH_HIT
;
432 if (oldentry
->mem_obj
->request
== NULL
) {
433 oldentry
->mem_obj
->request
= requestLink(mem
->request
);
436 /* Don't memcpy() the whole reply structure here. For example,
437 * www.thegist.com (Netscape/1.13) returns a content-length for
438 * 304's which seems to be the length of the 304 HEADERS!!! and
439 * not the body they refer to. */
440 httpReplyUpdateOnNotModified(oldentry
->mem_obj
->reply
, mem
->reply
);
441 storeTimestampsSet(oldentry
);
442 storeUnregister(entry
, http
);
443 storeUnlockObject(entry
);
444 entry
= http
->entry
= oldentry
;
445 entry
->timestamp
= squid_curtime
;
446 if (unlink_request
) {
447 requestUnlink(entry
->mem_obj
->request
);
448 entry
->mem_obj
->request
= NULL
;
451 /* the client can handle this reply, whatever it is */
452 http
->log_type
= LOG_TCP_REFRESH_MISS
;
453 if (HTTP_NOT_MODIFIED
== mem
->reply
->sline
.status
) {
454 httpReplyUpdateOnNotModified(http
->old_entry
->mem_obj
->reply
,
456 storeTimestampsSet(http
->old_entry
);
457 http
->old_entry
->refcount
++;
458 http
->log_type
= LOG_TCP_REFRESH_HIT
;
460 storeUnregister(http
->old_entry
, http
);
461 storeUnlockObject(http
->old_entry
);
464 http
->old_entry
= NULL
; /* done with old_entry */
465 assert(!EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
467 storeClientCopy(entry
,
475 clientSendMoreData(data
, buf
, size
);
480 modifiedSince(StoreEntry
* entry
, request_t
* request
)
483 MemObject
*mem
= entry
->mem_obj
;
484 time_t mod_time
= entry
->lastmod
;
485 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry
));
487 mod_time
= entry
->timestamp
;
488 debug(33, 3) ("modifiedSince: mod_time = %d\n", (int) mod_time
);
491 /* Find size of the object */
492 object_length
= mem
->reply
->content_length
;
493 if (object_length
< 0)
494 object_length
= contentLen(entry
);
495 if (mod_time
> request
->ims
) {
496 debug(33, 3) ("--> YES: entry newer than client\n");
498 } else if (mod_time
< request
->ims
) {
499 debug(33, 3) ("--> NO: entry older than client\n");
501 } else if (request
->imslen
< 0) {
502 debug(33, 3) ("--> NO: same LMT, no client length\n");
504 } else if (request
->imslen
== object_length
) {
505 debug(33, 3) ("--> NO: same LMT, same length\n");
508 debug(33, 3) ("--> YES: same LMT, different length\n");
514 clientPurgeRequest(clientHttpRequest
* http
)
517 ErrorState
*err
= NULL
;
519 debug(33, 3) ("Config.onoff.enable_purge = %d\n", Config
.onoff
.enable_purge
);
520 if (!Config
.onoff
.enable_purge
) {
521 http
->log_type
= LOG_TCP_DENIED
;
522 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
523 err
->request
= requestLink(http
->request
);
524 err
->src_addr
= http
->conn
->peer
.sin_addr
;
525 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
526 errorAppendEntry(http
->entry
, err
);
529 http
->log_type
= LOG_TCP_MISS
;
530 if ((entry
= storeGetPublic(http
->uri
, METHOD_GET
)) == NULL
) {
531 http
->http_code
= HTTP_NOT_FOUND
;
534 http
->http_code
= HTTP_OK
;
536 debug(33, 4) ("clientPurgeRequest: Not modified '%s'\n",
539 * Make a new entry to hold the reply to be written
542 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
543 httpReplyReset(r
= http
->entry
->mem_obj
->reply
);
544 httpReplySetHeaders(r
, 1.0, http
->http_code
, NULL
, NULL
, 0, 0, -1);
545 httpReplySwapOut(r
, http
->entry
);
546 storeComplete(http
->entry
);
550 checkNegativeHit(StoreEntry
* e
)
552 if (!EBIT_TEST(e
->flags
, ENTRY_NEGCACHED
))
554 if (e
->expires
<= squid_curtime
)
556 if (e
->store_status
!= STORE_OK
)
562 clientUpdateCounters(clientHttpRequest
* http
)
564 int svc_time
= tvSubMsec(http
->start
, current_time
);
566 HierarchyLogEntry
*H
;
567 Counter
.client_http
.requests
++;
568 if (isTcpHit(http
->log_type
))
569 Counter
.client_http
.hits
++;
570 if (http
->request
->err_type
!= ERR_NONE
)
571 Counter
.client_http
.errors
++;
572 statHistCount(&Counter
.client_http
.all_svc_time
, svc_time
);
574 * The idea here is not to be complete, but to get service times
575 * for only well-defined types. For example, we don't include
576 * LOG_TCP_REFRESH_FAIL_HIT because its not really a cache hit
577 * (we *tried* to validate it, but failed).
579 switch (http
->log_type
) {
580 case LOG_TCP_REFRESH_HIT
:
581 statHistCount(&Counter
.client_http
.nh_svc_time
, svc_time
);
583 case LOG_TCP_IMS_HIT
:
584 statHistCount(&Counter
.client_http
.nm_svc_time
, svc_time
);
587 case LOG_TCP_MEM_HIT
:
588 case LOG_TCP_OFFLINE_HIT
:
589 statHistCount(&Counter
.client_http
.hit_svc_time
, svc_time
);
592 case LOG_TCP_CLIENT_REFRESH_MISS
:
593 statHistCount(&Counter
.client_http
.miss_svc_time
, svc_time
);
596 /* make compiler warnings go away */
599 H
= &http
->request
->hier
;
602 Counter
.cd
.times_used
++;
605 Counter
.icp
.times_used
++;
607 if (0 != i
->stop
.tv_sec
&& 0 != i
->start
.tv_sec
)
608 statHistCount(&Counter
.icp
.query_svc_time
,
609 tvSubUsec(i
->start
, i
->stop
));
611 Counter
.icp
.query_timeouts
++;
614 Counter
.netdb
.times_used
++;
622 httpRequestFree(void *data
)
624 clientHttpRequest
*http
= data
;
625 clientHttpRequest
**H
;
626 ConnStateData
*conn
= http
->conn
;
628 request_t
*request
= http
->request
;
629 MemObject
*mem
= NULL
;
630 debug(33, 3) ("httpRequestFree: %s\n", storeUrl(http
->entry
));
631 if (!clientCheckTransferDone(http
)) {
632 if ((e
= http
->entry
)) {
634 storeUnregister(e
, http
);
635 storeUnlockObject(e
);
637 if (http
->entry
&& http
->entry
->ping_status
== PING_WAITING
)
638 storeReleaseRequest(http
->entry
);
640 assert(http
->log_type
< LOG_TYPE_MAX
);
642 mem
= http
->entry
->mem_obj
;
643 if (http
->out
.size
|| http
->log_type
) {
644 http
->al
.icp
.opcode
= ICP_INVALID
;
645 http
->al
.url
= http
->log_uri
;
646 debug(33, 9) ("httpRequestFree: al.url='%s'\n", http
->al
.url
);
648 http
->al
.http
.code
= mem
->reply
->sline
.status
;
649 http
->al
.http
.content_type
= strBuf(mem
->reply
->content_type
);
651 http
->al
.cache
.caddr
= conn
->log_addr
;
652 http
->al
.cache
.size
= http
->out
.size
;
653 http
->al
.cache
.code
= http
->log_type
;
654 http
->al
.cache
.msec
= tvSubMsec(http
->start
, current_time
);
655 if (request
->user_ident
[0])
656 http
->al
.cache
.ident
= request
->user_ident
;
658 http
->al
.cache
.ident
= conn
->ident
;
663 packerToMemInit(&p
, &mb
);
664 httpHeaderPackInto(&request
->header
, &p
);
665 http
->al
.http
.method
= request
->method
;
666 http
->al
.http
.version
= request
->http_ver
;
667 http
->al
.headers
.request
= xstrdup(mb
.buf
);
668 http
->al
.hier
= request
->hier
;
672 accessLogLog(&http
->al
);
673 clientUpdateCounters(http
);
674 clientdbUpdate(conn
->peer
.sin_addr
, http
->log_type
, PROTO_HTTP
, http
->out
.size
);
676 if (http
->acl_checklist
)
677 aclChecklistFree(http
->acl_checklist
);
679 checkFailureRatio(request
->err_type
, http
->al
.hier
.code
);
680 safe_free(http
->uri
);
681 safe_free(http
->log_uri
);
682 safe_free(http
->al
.headers
.request
);
683 safe_free(http
->al
.headers
.reply
);
684 safe_free(http
->redirect
.location
);
685 stringClean(&http
->range_iter
.boundary
);
686 if ((e
= http
->entry
)) {
688 storeUnregister(e
, http
);
689 storeUnlockObject(e
);
691 /* old_entry might still be set if we didn't yet get the reply
692 * code in clientHandleIMSReply() */
693 if ((e
= http
->old_entry
)) {
694 http
->old_entry
= NULL
;
695 storeUnregister(e
, http
);
696 storeUnlockObject(e
);
698 requestUnlink(http
->request
);
699 assert(http
!= http
->next
);
700 assert(http
->conn
->chr
!= NULL
);
701 H
= &http
->conn
->chr
;
710 dlinkDelete(&http
->active
, &ClientActiveRequests
);
714 /* This is a handler normally called by comm_close() */
716 connStateFree(int fd
, void *data
)
718 ConnStateData
*connState
= data
;
719 clientHttpRequest
*http
;
720 debug(33, 3) ("connStateFree: FD %d\n", fd
);
721 assert(connState
!= NULL
);
722 while ((http
= connState
->chr
) != NULL
) {
723 assert(http
->conn
== connState
);
724 assert(connState
->chr
!= connState
->chr
->next
);
725 httpRequestFree(http
);
727 safe_free(connState
->in
.buf
);
728 /* XXX account connState->in.buf */
729 pconnHistCount(0, connState
->nrequests
);
730 cbdataFree(connState
);
732 /* prevent those nasty RST packets */
734 char buf
[SQUID_TCP_SO_RCVBUF
];
735 while (read(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0);
741 clientInterpretRequestHeaders(clientHttpRequest
* http
)
743 request_t
*request
= http
->request
;
744 const HttpHeader
*req_hdr
= &request
->header
;
746 #if USE_USERAGENT_LOG
749 request
->imslen
= -1;
750 request
->ims
= httpHeaderGetTime(req_hdr
, HDR_IF_MODIFIED_SINCE
);
751 if (request
->ims
> 0)
752 request
->flags
.ims
= 1;
753 if (httpHeaderHas(req_hdr
, HDR_PRAGMA
)) {
754 String s
= httpHeaderGetList(req_hdr
, HDR_PRAGMA
);
755 if (strListIsMember(&s
, "no-cache", ','))
759 if (request
->cache_control
)
760 if (EBIT_TEST(request
->cache_control
->mask
, CC_NO_CACHE
))
764 if (Config
.onoff
.reload_into_ims
)
765 request
->flags
.nocache_hack
= 1;
766 else if (refresh_nocache_hack
)
767 request
->flags
.nocache_hack
= 1;
770 request
->flags
.nocache
= 1;
772 /* ignore range header in non-GETs */
773 if (request
->method
== METHOD_GET
) {
774 request
->range
= httpHeaderGetRange(req_hdr
);
776 request
->flags
.range
= 1;
778 if (httpHeaderHas(req_hdr
, HDR_AUTHORIZATION
))
779 request
->flags
.auth
= 1;
780 if (request
->login
[0] != '\0')
781 request
->flags
.auth
= 1;
782 if (httpHeaderHas(req_hdr
, HDR_VIA
)) {
783 String s
= httpHeaderGetList(req_hdr
, HDR_VIA
);
785 * ThisCache cannot be a member of Via header, "1.0 ThisCache" can.
786 * Note ThisCache2 has a space prepended to the hostname so we don't
787 * accidentally match super-domains.
789 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
790 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
791 request
, (ObjPackMethod
) & httpRequestPack
);
792 request
->flags
.loopdetect
= 1;
795 fvdbCountVia(strBuf(s
));
799 #if USE_USERAGENT_LOG
800 if ((str
= httpHeaderGetStr(req_hdr
, HDR_USER_AGENT
)))
801 logUserAgent(fqdnFromAddr(http
->conn
->peer
.sin_addr
), str
);
804 if (httpHeaderHas(req_hdr
, HDR_X_FORWARDED_FOR
)) {
805 String s
= httpHeaderGetList(req_hdr
, HDR_X_FORWARDED_FOR
);
806 fvdbCountForw(strBuf(s
));
810 request
->cache_control
= httpHeaderGetCc(req_hdr
);
811 if (request
->method
== METHOD_TRACE
) {
812 request
->max_forwards
= httpHeaderGetInt(req_hdr
, HDR_MAX_FORWARDS
);
814 if (clientCachable(http
))
815 request
->flags
.cachable
= 1;
816 if (clientHierarchical(http
))
817 request
->flags
.hierarchical
= 1;
818 debug(33, 5) ("clientInterpretRequestHeaders: REQ_NOCACHE = %s\n",
819 request
->flags
.nocache
? "SET" : "NOT SET");
820 debug(33, 5) ("clientInterpretRequestHeaders: REQ_CACHABLE = %s\n",
821 request
->flags
.cachable
? "SET" : "NOT SET");
822 debug(33, 5) ("clientInterpretRequestHeaders: REQ_HIERARCHICAL = %s\n",
823 request
->flags
.hierarchical
? "SET" : "NOT SET");
827 * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive.
828 * This is the client-side persistent connection flag. We need
829 * to set this relatively early in the request processing
830 * to handle hacks for broken servers and clients.
833 clientSetKeepaliveFlag(clientHttpRequest
* http
)
835 request_t
*request
= http
->request
;
836 const HttpHeader
*req_hdr
= &request
->header
;
837 debug(33, 3) ("clientSetKeepaliveFlag: http_ver = %3.1f\n",
839 debug(33, 3) ("clientSetKeepaliveFlag: method = %s\n",
840 RequestMethodStr
[request
->method
]);
841 if (httpMsgIsPersistent(request
->http_ver
, req_hdr
))
842 request
->flags
.proxy_keepalive
= 1;
846 clientCheckContentLength(request_t
* r
)
848 /* We only require a content-length for "upload" methods */
849 if (!pumpMethod(r
->method
))
851 if (httpHeaderGetInt(&r
->header
, HDR_CONTENT_LENGTH
) < 0)
857 clientCachable(clientHttpRequest
* http
)
859 const char *url
= http
->uri
;
860 request_t
*req
= http
->request
;
861 method_t method
= req
->method
;
863 memset(&ch
, '\0', sizeof(ch
));
865 * Hopefully, nobody really wants 'no_cache' by client's IP
866 * address, but if they do, this should work if they use IP
867 * addresses in their ACLs, or if the client's address is in
870 * This may not work yet for 'dst' and 'dst_domain' ACLs.
872 ch
.src_addr
= http
->conn
->peer
.sin_addr
;
873 ch
.my_addr
= http
->conn
->me
.sin_addr
;
874 ch
.request
= http
->request
;
876 * aclCheckFast returns 1 for ALLOW and 0 for DENY. The default
877 * is ALLOW, so we require 'no_cache DENY foo' in squid.conf
878 * to indicate uncachable objects.
880 if (!aclCheckFast(Config
.accessList
.noCache
, &ch
))
882 if (req
->protocol
== PROTO_HTTP
)
883 return httpCachable(method
);
884 /* FTP is always cachable */
885 if (req
->protocol
== PROTO_GOPHER
)
886 return gopherCachable(url
);
887 if (req
->protocol
== PROTO_WAIS
)
889 if (method
== METHOD_CONNECT
)
891 if (method
== METHOD_TRACE
)
893 if (req
->protocol
== PROTO_CACHEOBJ
)
898 /* Return true if we can query our neighbors for this object */
900 clientHierarchical(clientHttpRequest
* http
)
902 const char *url
= http
->uri
;
903 request_t
*request
= http
->request
;
904 method_t method
= request
->method
;
905 const wordlist
*p
= NULL
;
907 /* IMS needs a private key, so we can use the hierarchy for IMS only
908 * if our neighbors support private keys */
909 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
911 if (request
->flags
.auth
)
913 if (method
== METHOD_TRACE
)
915 if (method
!= METHOD_GET
)
917 /* scan hierarchy_stoplist */
918 for (p
= Config
.hierarchy_stoplist
; p
; p
= p
->next
)
919 if (strstr(url
, p
->key
))
921 if (request
->flags
.loopdetect
)
923 if (request
->protocol
== PROTO_HTTP
)
924 return httpCachable(method
);
925 if (request
->protocol
== PROTO_GOPHER
)
926 return gopherCachable(url
);
927 if (request
->protocol
== PROTO_WAIS
)
929 if (request
->protocol
== PROTO_CACHEOBJ
)
935 isTcpHit(log_type code
)
937 /* this should be a bitmap for better optimization */
938 if (code
== LOG_TCP_HIT
)
940 if (code
== LOG_TCP_IMS_HIT
)
942 if (code
== LOG_TCP_REFRESH_FAIL_HIT
)
944 if (code
== LOG_TCP_REFRESH_HIT
)
946 if (code
== LOG_TCP_NEGATIVE_HIT
)
948 if (code
== LOG_TCP_MEM_HIT
)
950 if (code
== LOG_TCP_OFFLINE_HIT
)
956 * returns true if If-Range specs match reply, false otherwise
959 clientIfRangeMatch(clientHttpRequest
* http
, HttpReply
* rep
)
961 const TimeOrTag spec
= httpHeaderGetTimeOrTag(&http
->request
->header
, HDR_IF_RANGE
);
962 /* check for parsing falure */
967 ETag rep_tag
= httpHeaderGetETag(&rep
->header
, HDR_ETAG
);
968 debug(33, 3) ("clientIfRangeMatch: ETags: %s and %s\n",
969 spec
.tag
.str
, rep_tag
.str
? rep_tag
.str
: "<none>");
971 return 0; /* entity has no etag to compare with! */
972 if (spec
.tag
.weak
|| rep_tag
.weak
) {
973 debug(33, 1) ("clientIfRangeMatch: Weak ETags are not allowed in If-Range: %s ? %s\n",
974 spec
.tag
.str
, rep_tag
.str
);
975 return 0; /* must use strong validator for sub-range requests */
977 return etagIsEqual(&rep_tag
, &spec
.tag
);
979 /* got modification time? */
980 if (spec
.time
>= 0) {
981 return http
->entry
->lastmod
<= spec
.time
;
983 assert(0); /* should not happen */
987 /* returns expected content length for multi-range replies
988 * note: assumes that httpHdrRangeCanonize has already been called
989 * warning: assumes that HTTP headers for individual ranges at the
990 * time of the actuall assembly will be exactly the same as
991 * the headers when clientMRangeCLen() is called */
993 clientMRangeCLen(clientHttpRequest
* http
) {
995 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
996 const HttpHdrRangeSpec
*spec
;
999 assert(http
->entry
->mem_obj
);
1002 while ((spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
))) {
1004 /* account for headers for this range */
1006 clientPackRangeHdr(http
->entry
->mem_obj
->reply
,
1007 spec
, http
->range_iter
.boundary
, &mb
);
1010 /* account for range content */
1011 clen
+= spec
->length
;
1013 debug(33, 6) ("clientMRangeCLen: (clen += %d + %d) == %d\n",
1014 mb
.size
, spec
->length
, clen
);
1016 /* account for the terminating boundary */
1018 clientPackTermBound(http
->range_iter
.boundary
, &mb
);
1025 /* adds appropriate Range headers if needed */
1027 clientBuildRangeHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1029 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1030 const char *range_err
= NULL
;
1031 assert(http
->request
->range
);
1032 /* check if we still want to do ranges */
1034 range_err
= "no [parse-able] reply";
1035 else if (rep
->sline
.status
!= HTTP_OK
)
1036 range_err
= "wrong status code";
1037 else if (httpHeaderHas(hdr
, HDR_CONTENT_RANGE
))
1038 range_err
= "origin server does ranges";
1039 else if (rep
->content_length
< 0)
1040 range_err
= "unknown length";
1041 else if (rep
->content_length
!= http
->entry
->mem_obj
->reply
->content_length
)
1042 range_err
= "INCONSISTENT length"; /* a bug? */
1043 else if (httpHeaderHas(&http
->request
->header
, HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1044 range_err
= "If-Range match failed";
1045 else if (!httpHdrRangeCanonize(http
->request
->range
, rep
->content_length
))
1046 range_err
= "canonization failed";
1047 else if (httpHdrRangeIsComplex(http
->request
->range
))
1048 range_err
= "too complex range header";
1049 /* get rid of our range specs on error */
1051 debug(33, 2) ("clientBuildRangeHeader: will not do ranges: %s.\n", range_err
);
1052 httpHdrRangeDestroy(http
->request
->range
);
1053 http
->request
->range
= NULL
;
1055 const int spec_count
= http
->request
->range
->specs
.count
;
1056 int actual_clen
= -1;
1058 debug(33, 2) ("clientBuildRangeHeader: range spec count: %d virgin clen: %d\n",
1059 spec_count
, rep
->content_length
);
1060 assert(spec_count
> 0);
1061 /* ETags should not be returned with Partial Content replies? */
1062 httpHeaderDelById(hdr
, HDR_ETAG
);
1063 /* append appropriate header(s) */
1064 if (spec_count
== 1) {
1065 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1066 const HttpHdrRangeSpec
*spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
);
1068 /* append Content-Range */
1069 httpHeaderAddContRange(hdr
, *spec
, rep
->content_length
);
1070 /* set new Content-Length to the actual number of bytes
1071 * transmitted in the message-body */
1072 actual_clen
= spec
->length
;
1075 /* generate boundary string */
1076 http
->range_iter
.boundary
= httpHdrRangeBoundaryStr(http
);
1077 /* delete old Content-Type, add ours */
1078 httpHeaderDelById(hdr
, HDR_CONTENT_TYPE
);
1079 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1080 "multipart/byteranges; boundary=\"%s\"",
1081 strBuf(http
->range_iter
.boundary
));
1082 /* Content-Length is not required in multipart responses
1083 * but it is always nice to have one */
1084 actual_clen
= clientMRangeCLen(http
);
1087 /* replace Content-Length header */
1088 assert(actual_clen
>= 0);
1089 httpHeaderDelById(hdr
, HDR_CONTENT_LENGTH
);
1090 httpHeaderPutInt(hdr
, HDR_CONTENT_LENGTH
, actual_clen
);
1091 debug(33, 2) ("clientBuildRangeHeader: actual content length: %d\n", actual_clen
);
1095 /* filters out unwanted entries from original reply header
1096 * adds extra entries if we have more info than origin server
1097 * adds Squid specific entries */
1099 clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1101 HttpHeader
*hdr
= &rep
->header
;
1102 int is_hit
= isTcpHit(http
->log_type
);
1103 request_t
*request
= http
->request
;
1104 #if DONT_FILTER_THESE
1105 /* but you might want to if you run Squid as an HTTP accelerator */
1106 /* httpHeaderDelById(hdr, HDR_ACCEPT_RANGES); */
1107 httpHeaderDelById(hdr
, HDR_ETAG
);
1109 httpHeaderDelById(hdr
, HDR_PROXY_CONNECTION
);
1110 /* here: Keep-Alive is a field-name, not a connection directive! */
1111 httpHeaderDelByName(hdr
, "Keep-Alive");
1112 /* remove Set-Cookie if a hit */
1114 httpHeaderDelById(hdr
, HDR_SET_COOKIE
);
1115 /* handle Connection header */
1116 if (httpHeaderHas(hdr
, HDR_CONNECTION
)) {
1117 /* anything that matches Connection list member will be deleted */
1118 String strConnection
= httpHeaderGetList(hdr
, HDR_CONNECTION
);
1119 const HttpHeaderEntry
*e
;
1120 HttpHeaderPos pos
= HttpHeaderInitPos
;
1122 * think: on-average-best nesting of the two loops (hdrEntry
1123 * and strListItem) @?@
1126 * maybe we should delete standard stuff ("keep-alive","close")
1127 * from strConnection first?
1129 while ((e
= httpHeaderGetEntry(hdr
, &pos
))) {
1130 if (strListIsMember(&strConnection
, strBuf(e
->name
), ','))
1131 httpHeaderDelAt(hdr
, pos
);
1133 httpHeaderDelById(hdr
, HDR_CONNECTION
);
1134 stringClean(&strConnection
);
1138 clientBuildRangeHeader(http
, rep
);
1140 * Add Age header, not that our header must replace Age headers
1141 * from other caches if any
1143 if (http
->entry
->timestamp
> 0) {
1144 httpHeaderDelById(hdr
, HDR_AGE
);
1146 * we do not follow HTTP/1.1 precisely here becuase we rely
1147 * on Date header when computing entry->timestamp; we should
1148 * be using _request_ time if Date header is not available
1149 * or if it is out of sync
1151 httpHeaderPutInt(hdr
, HDR_AGE
,
1152 http
->entry
->timestamp
<= squid_curtime
?
1153 squid_curtime
- http
->entry
->timestamp
: 0);
1155 /* Append X-Cache */
1156 httpHeaderPutStrf(hdr
, HDR_X_CACHE
, "%s from %s",
1157 is_hit
? "HIT" : "MISS", getMyHostname());
1158 #if USE_CACHE_DIGESTS
1159 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1160 httpHeaderPutStrf(hdr
, HDR_X_CACHE_LOOKUP
, "%s from %s:%d",
1161 http
->lookup_type
? http
->lookup_type
: "NONE",
1162 getMyHostname(), Config
.Port
.http
->i
);
1165 * Clear keepalive for NON-HEAD requests with invalid content length
1167 if (request
->method
!= METHOD_HEAD
)
1168 if (http
->entry
->mem_obj
->reply
->content_length
< 0)
1169 request
->flags
.proxy_keepalive
= 0;
1170 /* Signal keep-alive if needed */
1171 httpHeaderPutStr(hdr
,
1172 http
->flags
.accel
? HDR_CONNECTION
: HDR_PROXY_CONNECTION
,
1173 request
->flags
.proxy_keepalive
? "keep-alive" : "close");
1174 #if ADD_X_REQUEST_URI
1176 * Knowing the URI of the request is useful when debugging persistent
1177 * connections in a client; we cannot guarantee the order of http headers,
1178 * but X-Request-URI is likely to be the very last header to ease use from a
1179 * debugger [hdr->entries.count-1].
1181 httpHeaderPutStr(hdr
, HDR_X_REQUEST_URI
,
1182 http
->entry
->mem_obj
->url
? http
->entry
->mem_obj
->url
: http
->uri
);
1187 clientBuildReply(clientHttpRequest
* http
, const char *buf
, size_t size
)
1189 HttpReply
*rep
= httpReplyCreate();
1190 if (httpReplyParse(rep
, buf
)) {
1191 /* enforce 1.0 reply version */
1192 rep
->sline
.version
= 1.0;
1193 /* do header conversions */
1194 clientBuildReplyHeader(http
, rep
);
1195 /* if we do ranges, change status to "Partial Content" */
1196 if (http
->request
->range
)
1197 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
, HTTP_PARTIAL_CONTENT
, NULL
);
1199 /* parsing failure, get rid of the invalid reply */
1200 httpReplyDestroy(rep
);
1202 /* if we were going to do ranges, backoff */
1203 if (http
->request
->range
)
1204 clientBuildRangeHeader(http
, rep
); /* will fail and destroy request->range */
1210 * clientCacheHit should only be called until the HTTP reply headers
1211 * have been parsed. Normally this should be a single call, but
1212 * it might take more than one. As soon as we have the headers,
1213 * we hand off to clientSendMoreData, clientProcessExpired, or
1214 * clientProcessMiss.
1217 clientCacheHit(void *data
, char *buf
, ssize_t size
)
1219 clientHttpRequest
*http
= data
;
1220 StoreEntry
*e
= http
->entry
;
1222 request_t
*r
= http
->request
;
1223 debug(33, 3) ("clientCacheHit: %s, %d bytes\n", http
->uri
, (int) size
);
1224 if (http
->entry
== NULL
) {
1225 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1226 debug(33, 3) ("clientCacheHit: request aborted\n");
1228 } else if (size
< 0) {
1229 /* swap in failure */
1230 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1231 debug(33, 3) ("clientCacheHit: swapin failure for %s\n", http
->uri
);
1232 http
->log_type
= LOG_TCP_SWAPFAIL_MISS
;
1233 if ((e
= http
->entry
)) {
1235 storeUnregister(e
, http
);
1236 storeUnlockObject(e
);
1238 clientProcessMiss(http
);
1243 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
1244 if (mem
->reply
->sline
.status
== 0) {
1246 * we don't have full reply headers yet; either wait for more or
1247 * punt to clientProcessMiss.
1249 if (e
->mem_status
== IN_MEMORY
|| e
->store_status
== STORE_OK
) {
1250 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1251 clientProcessMiss(http
);
1252 } else if (size
== CLIENT_SOCK_SZ
&& http
->out
.offset
== 0) {
1253 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1254 clientProcessMiss(http
);
1256 debug(33, 3) ("clientCacheHit: waiting for HTTP reply headers\n");
1258 http
->out
.offset
+ size
,
1268 * Got the headers, now grok them
1270 assert(http
->log_type
== LOG_TCP_HIT
);
1271 if (checkNegativeHit(e
)) {
1272 http
->log_type
= LOG_TCP_NEGATIVE_HIT
;
1273 clientSendMoreData(data
, buf
, size
);
1274 } else if (r
->method
== METHOD_HEAD
) {
1276 * RFC 2068 seems to indicate there is no "conditional HEAD"
1277 * request. We cannot validate a cached object for a HEAD
1278 * request, nor can we return 304.
1280 if (e
->mem_status
== IN_MEMORY
)
1281 http
->log_type
= LOG_TCP_MEM_HIT
;
1282 clientSendMoreData(data
, buf
, size
);
1283 } else if (refreshCheckHTTP(e
, r
) && !http
->flags
.internal
) {
1284 debug(33, 5) ("clientCacheHit: in refreshCheck() block\n");
1286 * We hold a stale copy; it needs to be validated
1289 * The 'need_validation' flag is used to prevent forwarding
1290 * loops between siblings. If our copy of the object is stale,
1291 * then we should probably only use parents for the validation
1292 * request. Otherwise two siblings could generate a loop if
1293 * both have a stale version of the object.
1295 r
->flags
.need_validation
= 1;
1296 if (e
->lastmod
< 0) {
1298 * Previous reply didn't have a Last-Modified header,
1299 * we cannot revalidate it.
1301 http
->log_type
= LOG_TCP_MISS
;
1302 clientProcessMiss(http
);
1303 } else if (r
->flags
.nocache
) {
1305 * This did not match a refresh pattern that overrides no-cache
1306 * we should honour the client no-cache header.
1308 http
->log_type
= LOG_TCP_CLIENT_REFRESH_MISS
;
1309 clientProcessMiss(http
);
1310 } else if (r
->protocol
== PROTO_HTTP
) {
1312 * Object needs to be revalidated
1313 * XXX This could apply to FTP as well, if Last-Modified is known.
1315 http
->log_type
= LOG_TCP_REFRESH_MISS
;
1316 clientProcessExpired(http
);
1319 * We don't know how to re-validate other protocols. Handle
1320 * them as if the object has expired.
1322 http
->log_type
= LOG_TCP_MISS
;
1323 clientProcessMiss(http
);
1325 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1326 } else if (r
->flags
.ims
) {
1328 * Handle If-Modified-Since requests from the client
1330 if (mem
->reply
->sline
.status
!= HTTP_OK
) {
1331 debug(33, 4) ("clientCacheHit: Reply code %d != 200\n",
1332 mem
->reply
->sline
.status
);
1333 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1334 clientProcessMiss(http
);
1335 } else if (modifiedSince(e
, http
->request
)) {
1336 http
->log_type
= LOG_TCP_IMS_HIT
;
1337 clientSendMoreData(data
, buf
, size
);
1339 MemBuf mb
= httpPacked304Reply(e
->mem_obj
->reply
);
1340 http
->log_type
= LOG_TCP_IMS_HIT
;
1341 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1342 storeUnregister(e
, http
);
1343 storeUnlockObject(e
);
1344 e
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
1346 httpReplyParse(e
->mem_obj
->reply
, mb
.buf
);
1347 storeAppend(e
, mb
.buf
, mb
.size
);
1353 * plain ol' cache hit
1355 if (e
->mem_status
== IN_MEMORY
)
1356 http
->log_type
= LOG_TCP_MEM_HIT
;
1357 else if (Config
.onoff
.offline
)
1358 http
->log_type
= LOG_TCP_OFFLINE_HIT
;
1359 clientSendMoreData(data
, buf
, size
);
1363 /* put terminating boundary for multiparts */
1365 clientPackTermBound(String boundary
, MemBuf
*mb
)
1367 memBufPrintf(mb
, "\r\n--%s--\r\n", strBuf(boundary
));
1368 debug(33, 6) ("clientPackTermBound: buf offset: %d\n", mb
->size
);
1371 /* appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1373 clientPackRangeHdr(const HttpReply
*rep
, const HttpHdrRangeSpec
*spec
, String boundary
, MemBuf
*mb
)
1381 debug(33, 5) ("clientPackRangeHdr: appending boundary: %s\n", strBuf(boundary
));
1382 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1383 memBufPrintf(mb
, "\r\n--%s\r\n", strBuf(boundary
));
1385 /* stuff the header with required entries and pack it */
1386 httpHeaderInit(&hdr
, hoReply
);
1387 if (httpHeaderHas(&rep
->header
, HDR_CONTENT_TYPE
))
1388 httpHeaderPutStr(&hdr
, HDR_CONTENT_TYPE
, httpHeaderGetStr(&rep
->header
, HDR_CONTENT_TYPE
));
1389 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1390 packerToMemInit(&p
, mb
);
1391 httpHeaderPackInto(&hdr
, &p
);
1393 httpHeaderClean(&hdr
);
1395 /* append <crlf> (we packed a header, not a reply) */
1396 memBufPrintf(mb
, crlf
);
1399 /* extracts a "range" from *buf and appends them to mb, updating all offsets and such */
1401 clientPackRange(clientHttpRequest
* http
, HttpHdrRangeIter
* i
, const char **buf
, ssize_t
* size
, MemBuf
* mb
)
1403 const size_t copy_sz
= i
->debt_size
<= *size
? i
->debt_size
: *size
;
1404 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1408 /* intersection of "have" and "need" ranges must not be empty */
1409 assert(body_off
< i
->spec
->offset
+ i
->spec
->length
);
1410 assert(body_off
+ *size
> i
->spec
->offset
);
1412 /* put boundary and headers at the beginning of a range in a multi-range */
1413 if (http
->request
->range
->specs
.count
> 1 && i
->debt_size
== i
->spec
->length
) {
1414 assert(http
->entry
->mem_obj
);
1416 http
->entry
->mem_obj
->reply
, /* original reply */
1417 i
->spec
, /* current range */
1418 i
->boundary
, /* boundary, the same for all */
1423 /* append content */
1424 debug(33, 3) ("clientPackRange: appending %d bytes\n", copy_sz
);
1425 memBufAppend(mb
, *buf
, copy_sz
);
1427 /* update offsets */
1429 i
->debt_size
-= copy_sz
;
1430 body_off
+= copy_sz
;
1432 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1434 /* paranoid check */
1435 assert(*size
>= 0 && i
->debt_size
>= 0);
1438 /* returns true if there is still data available to pack more ranges
1439 * increments iterator "i"
1440 * used by clientPackMoreRanges */
1442 clientCanPackMoreRanges(const clientHttpRequest
* http
, HttpHdrRangeIter
* i
, ssize_t size
)
1444 /* first update "i" if needed */
1445 if (!i
->debt_size
) {
1446 if ((i
->spec
= httpHdrRangeGetSpec(http
->request
->range
, &i
->pos
)))
1447 i
->debt_size
= i
->spec
->length
;
1449 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1450 /* continue condition: need_more_data && have_more_data */
1451 return i
->spec
&& size
> 0;
1454 /* extracts "ranges" from buf and appends them to mb, updating all offsets and such */
1455 /* returns true if we need more data */
1457 clientPackMoreRanges(clientHttpRequest
* http
, const char *buf
, ssize_t size
, MemBuf
* mb
)
1459 HttpHdrRangeIter
*i
= &http
->range_iter
;
1460 /* offset in range specs does not count the prefix of an http msg */
1461 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1463 /* check: reply was parsed and range iterator was initialized */
1464 assert(i
->prefix_size
> 0);
1465 /* filter out data according to range specs */
1466 while (clientCanPackMoreRanges(http
, i
, size
)) {
1467 off_t start
; /* offset of still missing data */
1469 start
= i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
;
1470 debug(33, 2) ("clientPackMoreRanges: in: offset: %d size: %d\n",
1471 (int) body_off
, size
);
1472 debug(33, 2) ("clientPackMoreRanges: out: start: %d spec[%d]: [%d, %d), len: %d debt: %d\n",
1473 (int) start
, (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
, i
->debt_size
);
1474 assert(body_off
<= start
); /* we did not miss it */
1475 /* skip up to start */
1476 if (body_off
+ size
> start
) {
1477 const size_t skip_size
= start
- body_off
;
1482 /* has not reached start yet */
1487 /* put next chunk if any */
1489 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1490 clientPackRange(http
, i
, &buf
, &size
, mb
);
1491 body_off
= http
->out
.offset
- i
->prefix_size
; /* sync */
1494 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1495 debug(33, 2) ("clientPackMoreRanges: buf exhausted: in: offset: %d size: %d need_more: %d\n",
1496 (int) body_off
, size
, i
->debt_size
);
1498 debug(33, 2) ("clientPackMoreRanges: need more: spec[%d]: [%d, %d), len: %d\n",
1499 (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
);
1500 /* skip the data we do not need if possible */
1501 if (i
->debt_size
== i
->spec
->length
) /* at the start of the cur. spec */
1502 body_off
= i
->spec
->offset
;
1504 assert(body_off
== i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
);
1505 } else if (http
->request
->range
->specs
.count
> 1) {
1506 /* put terminating boundary for multiparts */
1507 clientPackTermBound(i
->boundary
, mb
);
1509 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1510 return i
->debt_size
> 0;
1514 * accepts chunk of a http message in buf, parses prefix, filters headers and
1515 * such, writes processed message to the client's socket
1518 clientSendMoreData(void *data
, char *buf
, ssize_t size
)
1520 clientHttpRequest
*http
= data
;
1521 StoreEntry
*entry
= http
->entry
;
1522 ConnStateData
*conn
= http
->conn
;
1524 HttpReply
*rep
= NULL
;
1525 const char *body_buf
= buf
;
1526 ssize_t body_size
= size
;
1528 ssize_t check_size
= 0;
1529 debug(33, 5) ("clientSendMoreData: %s, %d bytes\n", http
->uri
, (int) size
);
1530 assert(size
<= CLIENT_SOCK_SZ
);
1531 assert(http
->request
!= NULL
);
1532 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1533 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1534 debug(33, 5) ("clientSendMoreData: FD %d '%s', out.offset=%d \n",
1535 fd
, storeUrl(entry
), (int) http
->out
.offset
);
1536 if (conn
->chr
!= http
) {
1537 /* there is another object in progress, defer this one */
1538 debug(33, 1) ("clientSendMoreData: Deferring %s\n", storeUrl(entry
));
1539 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1541 } else if (entry
&& EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1542 /* call clientWriteComplete so the client socket gets closed */
1543 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1544 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1546 } else if (size
< 0) {
1547 /* call clientWriteComplete so the client socket gets closed */
1548 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1549 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1551 } else if (size
== 0) {
1552 /* call clientWriteComplete so the client socket gets closed */
1553 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1554 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1557 if (http
->out
.offset
== 0) {
1558 if (Config
.onoff
.log_mime_hdrs
) {
1560 if ((k
= headersEnd(buf
, size
))) {
1561 safe_free(http
->al
.headers
.reply
);
1562 http
->al
.headers
.reply
= xcalloc(k
+ 1, 1);
1563 xstrncpy(http
->al
.headers
.reply
, buf
, k
);
1566 rep
= clientBuildReply(http
, buf
, size
);
1568 body_size
= size
- rep
->hdr_sz
;
1569 assert(body_size
>= 0);
1570 body_buf
= buf
+ rep
->hdr_sz
;
1571 http
->range_iter
.prefix_size
= rep
->hdr_sz
;
1572 debug(33, 3) ("clientSendMoreData: Appending %d bytes after %d bytes of headers\n",
1573 body_size
, rep
->hdr_sz
);
1574 } else if (size
< CLIENT_SOCK_SZ
&& entry
->store_status
== STORE_PENDING
) {
1575 /* wait for more to arrive */
1576 storeClientCopy(entry
,
1577 http
->out
.offset
+ size
,
1585 /* reset range iterator */
1586 http
->range_iter
.pos
= HttpHdrRangeInitPos
;
1588 if (http
->request
->method
== METHOD_HEAD
) {
1590 /* do not forward body for HEAD replies */
1592 http
->flags
.done_copying
= 1;
1595 * If we are here, then store_status == STORE_OK and it
1596 * seems we have a HEAD repsponse which is missing the
1597 * empty end-of-headers line (home.mira.net, phttpd/0.99.72
1598 * does this). Because clientBuildReply() fails we just
1599 * call this reply a body, set the done_copying flag and
1602 http
->flags
.done_copying
= 1;
1605 /* write headers and/or body if any */
1606 assert(rep
|| (body_buf
&& body_size
));
1607 /* init mb; put status line and headers if any */
1609 mb
= httpReplyPack(rep
);
1610 http
->out
.offset
+= rep
->hdr_sz
;
1611 check_size
+= rep
->hdr_sz
;
1612 httpReplyDestroy(rep
);
1617 /* append body if any */
1618 if (http
->request
->range
) {
1619 /* Only GET requests should have ranges */
1620 assert(http
->request
->method
== METHOD_GET
);
1621 /* clientPackMoreRanges() updates http->out.offset */
1622 /* force the end of the transfer if we are done */
1623 if (!clientPackMoreRanges(http
, body_buf
, body_size
, &mb
))
1624 http
->flags
.done_copying
= 1;
1625 } else if (body_buf
&& body_size
) {
1626 http
->out
.offset
+= body_size
;
1627 check_size
+= body_size
;
1628 memBufAppend(&mb
, body_buf
, body_size
);
1630 if (!http
->request
->range
&& http
->request
->method
== METHOD_GET
)
1631 assert(check_size
== size
);
1633 comm_write_mbuf(fd
, mb
, clientWriteComplete
, http
);
1634 /* if we don't do it, who will? */
1635 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1639 clientKeepaliveNextRequest(clientHttpRequest
* http
)
1641 ConnStateData
*conn
= http
->conn
;
1643 debug(33, 3) ("clientKeepaliveNextRequest: FD %d\n", conn
->fd
);
1644 conn
->defer
.until
= 0; /* Kick it to read a new request */
1645 httpRequestFree(http
);
1646 if ((http
= conn
->chr
) == NULL
) {
1647 debug(33, 5) ("clientKeepaliveNextRequest: FD %d reading next req\n",
1649 fd_note(conn
->fd
, "Reading next request");
1651 * Set the timeout BEFORE calling clientReadRequest().
1653 commSetTimeout(conn
->fd
, 15, requestTimeout
, conn
);
1654 clientReadRequest(conn
->fd
, conn
); /* Read next request */
1656 * Note, the FD may be closed at this point.
1658 } else if ((entry
= http
->entry
) == NULL
) {
1660 * this request is in progress, maybe doing an ACL or a redirect,
1661 * execution will resume after the operation completes.
1664 debug(33, 1) ("clientKeepaliveNextRequest: FD %d Sending next\n",
1667 if (0 == storeClientCopyPending(entry
, http
)) {
1668 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1669 debug(33, 0) ("clientKeepaliveNextRequest: ENTRY_ABORTED\n");
1670 storeClientCopy(entry
,
1674 memAllocate(MEM_CLIENT_SOCK_BUF
),
1682 clientWriteComplete(int fd
, char *bufnotused
, size_t size
, int errflag
, void *data
)
1684 clientHttpRequest
*http
= data
;
1685 StoreEntry
*entry
= http
->entry
;
1687 http
->out
.size
+= size
;
1688 debug(33, 5) ("clientWriteComplete: FD %d, sz %d, err %d, off %d, len %d\n",
1689 fd
, size
, errflag
, (int) http
->out
.offset
, entry
? objectLen(entry
) : 0);
1691 kb_incr(&Counter
.client_http
.kbytes_out
, size
);
1692 if (isTcpHit(http
->log_type
))
1693 kb_incr(&Counter
.client_http
.hit_kbytes_out
, size
);
1697 * just close the socket, httpRequestFree will abort if needed
1700 } else if (NULL
== entry
) {
1701 comm_close(fd
); /* yuk */
1702 } else if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1704 } else if ((done
= clientCheckTransferDone(http
)) != 0 || size
== 0) {
1705 debug(33, 5) ("clientWriteComplete: FD %d transfer is DONE\n", fd
);
1706 /* We're finished case */
1707 if (http
->entry
->mem_obj
->reply
->content_length
< 0) {
1708 debug(33, 5) ("clientWriteComplete: closing, content_length < 0\n");
1711 debug(33, 5) ("clientWriteComplete: closing, !done\n");
1713 } else if (clientGotNotEnough(http
)) {
1714 debug(33, 5) ("clientWriteComplete: client didn't get all it expected\n");
1716 } else if (http
->request
->flags
.proxy_keepalive
) {
1717 debug(33, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd
);
1718 clientKeepaliveNextRequest(http
);
1723 /* More data will be coming from primary server; register with
1724 * storage manager. */
1725 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1726 debug(33, 0) ("clientWriteComplete 2: ENTRY_ABORTED\n");
1727 storeClientCopy(entry
,
1731 memAllocate(MEM_CLIENT_SOCK_BUF
),
1738 * client issued a request with an only-if-cached cache-control directive;
1739 * we did not find a cached object that can be returned without
1740 * contacting other servers;
1741 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
1744 clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
)
1746 char *url
= http
->uri
;
1747 request_t
*r
= http
->request
;
1748 ErrorState
*err
= NULL
;
1749 debug(33, 4) ("clientProcessOnlyIfCachedMiss: '%s %s'\n",
1750 RequestMethodStr
[r
->method
], url
);
1751 http
->al
.http
.code
= HTTP_GATEWAY_TIMEOUT
;
1752 err
= errorCon(ERR_ONLY_IF_CACHED_MISS
, HTTP_GATEWAY_TIMEOUT
);
1753 err
->request
= requestLink(r
);
1754 err
->src_addr
= http
->conn
->peer
.sin_addr
;
1756 storeUnregister(http
->entry
, http
);
1757 storeUnlockObject(http
->entry
);
1759 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1760 errorAppendEntry(http
->entry
, err
);
1764 clientProcessRequest2(clientHttpRequest
* http
)
1766 request_t
*r
= http
->request
;
1768 e
= http
->entry
= storeGetPublic(http
->uri
, r
->method
);
1769 if (r
->method
== METHOD_HEAD
&& e
== NULL
) {
1770 /* We can generate a HEAD reply from a cached GET object */
1771 e
= http
->entry
= storeGetPublic(http
->uri
, METHOD_GET
);
1773 #if USE_CACHE_DIGESTS
1774 http
->lookup_type
= e
? "HIT" : "MISS";
1777 /* this object isn't in the cache */
1778 debug(33, 3) ("clientProcessRequest2: storeGet() MISS\n");
1779 return LOG_TCP_MISS
;
1781 if (Config
.onoff
.offline
) {
1782 debug(33, 3) ("clientProcessRequest2: offline HIT\n");
1786 if (!storeEntryValidToSend(e
)) {
1787 debug(33, 3) ("clientProcessRequest2: !storeEntryValidToSend MISS\n");
1789 return LOG_TCP_MISS
;
1791 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1792 /* Special entries are always hits, no matter what the client says */
1793 debug(33, 3) ("clientProcessRequest2: ENTRY_SPECIAL HIT\n");
1798 if (r
->flags
.nocache_hack
) {
1799 /* if nocache_hack is set, nocache should always be clear, right? */
1800 assert(!r
->flags
.nocache
);
1801 ipcacheReleaseInvalid(r
->host
);
1804 if (e
->store_status
== STORE_PENDING
) {
1805 if (r
->flags
.nocache
|| r
->flags
.nocache_hack
) {
1806 debug(33, 3) ("Clearing no-cache for STORE_PENDING request\n\t%s\n",
1808 r
->flags
.nocache
= 0;
1809 r
->flags
.nocache_hack
= 0;
1813 if (r
->flags
.nocache
) {
1814 debug(33, 3) ("clientProcessRequest2: no-cache REFRESH MISS\n");
1816 ipcacheReleaseInvalid(r
->host
);
1817 return LOG_TCP_CLIENT_REFRESH_MISS
;
1819 if (r
->range
&& httpHdrRangeWillBeComplex(r
->range
)) {
1821 * Some clients break if we return "200 OK" for a Range
1822 * request. We would have to return "200 OK" for a _complex_
1823 * Range request that is also a HIT. Thus, let's prevent HITs
1824 * on complex Range requests
1826 debug(33, 3) ("clientProcessRequest2: complex range MISS\n");
1828 return LOG_TCP_MISS
;
1830 debug(33, 3) ("clientProcessRequest2: default HIT\n");
1836 clientProcessRequest(clientHttpRequest
* http
)
1838 char *url
= http
->uri
;
1839 request_t
*r
= http
->request
;
1840 int fd
= http
->conn
->fd
;
1842 debug(33, 4) ("clientProcessRequest: %s '%s'\n",
1843 RequestMethodStr
[r
->method
],
1845 if (r
->method
== METHOD_CONNECT
) {
1846 http
->log_type
= LOG_TCP_MISS
;
1847 sslStart(fd
, url
, r
, &http
->out
.size
);
1849 } else if (r
->method
== METHOD_PURGE
) {
1850 clientPurgeRequest(http
);
1852 } else if (r
->method
== METHOD_TRACE
) {
1853 if (r
->max_forwards
== 0) {
1854 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1855 storeReleaseRequest(http
->entry
);
1856 storeBuffer(http
->entry
);
1857 rep
= httpReplyCreate();
1858 httpReplySetHeaders(rep
, 1.0, HTTP_OK
, NULL
, "text/plain",
1859 httpRequestPrefixLen(r
), 0, squid_curtime
);
1860 httpReplySwapOut(rep
, http
->entry
);
1861 httpReplyDestroy(rep
);
1862 httpRequestSwapOut(r
, http
->entry
);
1863 storeComplete(http
->entry
);
1867 http
->log_type
= LOG_TCP_MISS
;
1868 } else if (pumpMethod(r
->method
)) {
1869 http
->log_type
= LOG_TCP_MISS
;
1870 /* XXX oof, POST can be cached! */
1871 pumpInit(fd
, r
, http
->uri
);
1873 http
->log_type
= clientProcessRequest2(http
);
1875 debug(33, 4) ("clientProcessRequest: %s for '%s'\n",
1876 log_tags
[http
->log_type
],
1878 http
->out
.offset
= 0;
1879 if (NULL
!= http
->entry
) {
1880 storeLockObject(http
->entry
);
1881 storeCreateMemObject(http
->entry
, http
->uri
, http
->log_uri
);
1882 storeClientListAdd(http
->entry
, http
);
1884 delaySetStoreClient(http
->entry
, http
, delayClient(r
));
1886 http
->entry
->refcount
++;
1887 storeClientCopy(http
->entry
,
1891 memAllocate(MEM_CLIENT_SOCK_BUF
),
1896 http
->log_type
= LOG_TCP_MISS
;
1897 clientProcessMiss(http
);
1902 * Prepare to fetch the object as it's a cache miss of some kind.
1905 clientProcessMiss(clientHttpRequest
* http
)
1907 char *url
= http
->uri
;
1908 request_t
*r
= http
->request
;
1909 ErrorState
*err
= NULL
;
1910 debug(33, 4) ("clientProcessMiss: '%s %s'\n",
1911 RequestMethodStr
[r
->method
], url
);
1913 * We might have a left-over StoreEntry from a failed cache hit
1917 if (EBIT_TEST(http
->entry
->flags
, ENTRY_SPECIAL
))
1918 debug(33, 0) ("clientProcessMiss: miss on a special object (%s).\n", url
);
1919 storeUnregister(http
->entry
, http
);
1920 storeUnlockObject(http
->entry
);
1923 if (clientOnlyIfCached(http
)) {
1924 clientProcessOnlyIfCachedMiss(http
);
1928 * Deny loops when running in accelerator/transproxy mode.
1930 if (http
->flags
.accel
&& r
->flags
.loopdetect
) {
1931 http
->al
.http
.code
= HTTP_FORBIDDEN
;
1932 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
1933 err
->request
= requestLink(r
);
1934 err
->src_addr
= http
->conn
->peer
.sin_addr
;
1935 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1936 errorAppendEntry(http
->entry
, err
);
1939 assert(http
->out
.offset
== 0);
1940 http
->entry
= clientCreateStoreEntry(http
, r
->method
, r
->flags
);
1941 http
->entry
->refcount
++;
1942 if (http
->redirect
.status
) {
1943 HttpReply
*rep
= httpReplyCreate();
1944 storeReleaseRequest(http
->entry
);
1945 httpRedirectReply(rep
, http
->redirect
.status
, http
->redirect
.location
);
1946 httpReplySwapOut(rep
, http
->entry
);
1947 httpReplyDestroy(rep
);
1948 storeComplete(http
->entry
);
1951 if (http
->flags
.internal
)
1952 r
->protocol
= PROTO_INTERNAL
;
1953 fwdStart(http
->conn
->fd
, http
->entry
, r
,
1954 http
->conn
->peer
.sin_addr
, http
->conn
->me
.sin_addr
);
1957 static clientHttpRequest
*
1958 parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
)
1960 clientHttpRequest
*http
= xcalloc(1, sizeof(clientHttpRequest
));
1961 cbdataAdd(http
, cbdataXfree
, 0);
1963 http
->start
= current_time
;
1964 http
->req_sz
= conn
->in
.offset
;
1965 http
->uri
= xstrdup(uri
);
1966 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1967 http
->range_iter
.boundary
= StringNull
;
1968 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1973 * parseHttpRequest()
1976 * NULL on error or incomplete request
1977 * a clientHttpRequest structure on success
1979 static clientHttpRequest
*
1980 parseHttpRequest(ConnStateData
* conn
, method_t
* method_p
, int *status
,
1981 char **prefix_p
, size_t * req_line_sz_p
)
1986 char *req_hdr
= NULL
;
1991 int free_request
= 0;
1992 size_t header_sz
; /* size of headers, not including first line */
1993 size_t prefix_sz
; /* size of whole request (req-line + headers) */
1997 clientHttpRequest
*http
= NULL
;
1999 struct natlookup natLookup
;
2000 static int natfd
= -1;
2003 if ((req_sz
= headersEnd(conn
->in
.buf
, conn
->in
.offset
)) == 0) {
2004 debug(33, 5) ("Incomplete request, waiting for end of headers\n");
2007 *method_p
= METHOD_NONE
;
2010 assert(req_sz
<= conn
->in
.offset
);
2011 /* Use memcpy, not strdup! */
2012 inbuf
= xmalloc(req_sz
+ 1);
2013 xmemcpy(inbuf
, conn
->in
.buf
, req_sz
);
2014 *(inbuf
+ req_sz
) = '\0';
2016 /* pre-set these values to make aborting simpler */
2018 *method_p
= METHOD_NONE
;
2021 /* Barf on NULL characters in the headers */
2022 if (strlen(inbuf
) != req_sz
) {
2023 debug(33, 1) ("parseHttpRequest: Requestheader contains NULL characters\n");
2024 return parseHttpRequestAbort(conn
, "error:invalid-request");
2026 /* Look for request method */
2027 if ((mstr
= strtok(inbuf
, "\t ")) == NULL
) {
2028 debug(33, 1) ("parseHttpRequest: Can't get request method\n");
2029 return parseHttpRequestAbort(conn
, "error:invalid-request-method");
2031 method
= urlParseMethod(mstr
);
2032 if (method
== METHOD_NONE
) {
2033 debug(33, 1) ("parseHttpRequest: Unsupported method '%s'\n", mstr
);
2034 return parseHttpRequestAbort(conn
, "error:unsupported-request-method");
2036 debug(33, 5) ("parseHttpRequest: Method is '%s'\n", mstr
);
2039 /* look for URL+HTTP/x.x */
2040 if ((url
= strtok(NULL
, "\n")) == NULL
) {
2041 debug(33, 1) ("parseHttpRequest: Missing URL\n");
2042 return parseHttpRequestAbort(conn
, "error:missing-url");
2044 while (xisspace(*url
))
2046 t
= url
+ strlen(url
);
2051 if (xisspace(*t
) && !strncmp(t
+ 1, "HTTP/", 5)) {
2056 while (t
> url
&& xisspace(*t
))
2058 debug(33, 5) ("parseHttpRequest: URI is '%s'\n", url
);
2059 if (token
== NULL
) {
2060 debug(33, 3) ("parseHttpRequest: Missing HTTP identifier\n");
2061 #if RELAXED_HTTP_PARSER
2062 http_ver
= (float) 0.9; /* wild guess */
2064 return parseHttpRequestAbort(conn
, "error:missing-http-ident");
2067 http_ver
= (float) atof(token
+ 5);
2071 * Process headers after request line
2073 req_hdr
= strtok(NULL
, null_string
);
2074 header_sz
= req_sz
- (req_hdr
- inbuf
);
2075 if (0 == header_sz
) {
2076 debug(33, 3) ("parseHttpRequest: header_sz == 0\n");
2080 assert(header_sz
> 0);
2081 debug(33, 3) ("parseHttpRequest: req_hdr = {%s}\n", req_hdr
);
2082 end
= req_hdr
+ header_sz
;
2083 debug(33, 3) ("parseHttpRequest: end = {%s}\n", end
);
2085 prefix_sz
= end
- inbuf
;
2086 *req_line_sz_p
= req_hdr
- inbuf
;
2087 debug(33, 3) ("parseHttpRequest: prefix_sz = %d, req_line_sz = %d\n",
2088 (int) prefix_sz
, (int) *req_line_sz_p
);
2089 assert(prefix_sz
<= conn
->in
.offset
);
2091 /* Ok, all headers are received */
2092 http
= xcalloc(1, sizeof(clientHttpRequest
));
2093 cbdataAdd(http
, cbdataXfree
, 0);
2094 http
->http_ver
= http_ver
;
2096 http
->start
= current_time
;
2097 http
->req_sz
= prefix_sz
;
2098 http
->range_iter
.boundary
= StringNull
;
2099 *prefix_p
= xmalloc(prefix_sz
+ 1);
2100 xmemcpy(*prefix_p
, conn
->in
.buf
, prefix_sz
);
2101 *(*prefix_p
+ prefix_sz
) = '\0';
2102 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2104 debug(33, 5) ("parseHttpRequest: Request Header is\n%s\n", (*prefix_p
) + *req_line_sz_p
);
2105 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2108 /* handle internal objects */
2109 if (internalCheck(url
)) {
2110 /* prepend our name & port */
2111 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2112 http
->flags
.internal
= 1;
2113 http
->flags
.accel
= 1;
2115 /* see if we running in Config2.Accel.on, if so got to convert it to URL */
2116 else if (Config2
.Accel
.on
&& *url
== '/') {
2117 /* prepend the accel prefix */
2118 if (opt_accel_uses_host
&& (t
= mime_get_header(req_hdr
, "Host"))) {
2119 /* If a Host: header was specified, use it to build the URL
2120 * instead of the one in the Config file. */
2122 * XXX Use of the Host: header here opens a potential
2123 * security hole. There are no checks that the Host: value
2124 * corresponds to one of your servers. It might, for example,
2125 * refer to www.playboy.com. The 'dst' and/or 'dst_domain' ACL
2126 * types should be used to prevent httpd-accelerators
2127 * handling requests for non-local servers */
2129 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2131 http
->uri
= xcalloc(url_sz
, 1);
2132 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2133 t
, (int) Config
.Accel
.port
, url
);
2134 } else if (vhost_mode
) {
2135 /* Put the local socket IP address as the hostname */
2136 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2137 http
->uri
= xcalloc(url_sz
, 1);
2139 natLookup
.nl_inport
= http
->conn
->me
.sin_port
;
2140 natLookup
.nl_outport
= http
->conn
->peer
.sin_port
;
2141 natLookup
.nl_inip
= http
->conn
->me
.sin_addr
;
2142 natLookup
.nl_outip
= http
->conn
->peer
.sin_addr
;
2143 natLookup
.nl_flags
= IPN_TCP
;
2145 natfd
= open(IPL_NAT
, O_RDONLY
, 0);
2147 debug(50, 1) ("parseHttpRequest: NAT open failed: %s\n",
2149 return parseHttpRequestAbort(conn
, "error:nat-open-failed");
2151 if (ioctl(natfd
, SIOCGNATL
, &natLookup
) < 0) {
2152 if (errno
!= ESRCH
) {
2153 debug(50, 1) ("parseHttpRequest: NAT lookup failed: ioctl(SIOCGNATL)\n");
2156 return parseHttpRequestAbort(conn
, "error:nat-lookup-failed");
2158 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2159 inet_ntoa(http
->conn
->me
.sin_addr
),
2160 (int) Config
.Accel
.port
,
2163 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2164 inet_ntoa(natLookup
.nl_realip
),
2165 (int) Config
.Accel
.port
,
2168 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2169 inet_ntoa(http
->conn
->me
.sin_addr
),
2170 (int) Config
.Accel
.port
,
2173 debug(33, 5) ("VHOST REWRITE: '%s'\n", http
->uri
);
2175 url_sz
= strlen(Config2
.Accel
.prefix
) + strlen(url
) +
2176 Config
.appendDomainLen
+ 1;
2177 http
->uri
= xcalloc(url_sz
, 1);
2178 snprintf(http
->uri
, url_sz
, "%s%s", Config2
.Accel
.prefix
, url
);
2180 http
->flags
.accel
= 1;
2182 /* URL may be rewritten later, so make extra room */
2183 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2184 http
->uri
= xcalloc(url_sz
, 1);
2185 strcpy(http
->uri
, url
);
2186 http
->flags
.accel
= 0;
2188 if (!stringHasWhitespace(http
->uri
))
2189 http
->log_uri
= xstrndup(http
->uri
, MAX_URL
);
2191 http
->log_uri
= xstrndup(rfc1738_escape(http
->uri
), MAX_URL
);
2192 debug(33, 5) ("parseHttpRequest: Complete request received\n");
2201 clientReadDefer(int fdnotused
, void *data
)
2203 ConnStateData
*conn
= data
;
2204 return conn
->defer
.until
> squid_curtime
;
2208 clientReadRequest(int fd
, void *data
)
2210 ConnStateData
*conn
= data
;
2211 int parser_return_code
= 0;
2213 request_t
*request
= NULL
;
2216 clientHttpRequest
*http
= NULL
;
2217 clientHttpRequest
**H
= NULL
;
2218 char *prefix
= NULL
;
2219 ErrorState
*err
= NULL
;
2220 fde
*F
= &fd_table
[fd
];
2221 int len
= conn
->in
.size
- conn
->in
.offset
- 1;
2222 debug(33, 4) ("clientReadRequest: FD %d: reading request...\n", fd
);
2223 Counter
.syscalls
.sock
.reads
++;
2224 size
= read(fd
, conn
->in
.buf
+ conn
->in
.offset
, len
);
2226 fd_bytes(fd
, size
, FD_READ
);
2227 kb_incr(&Counter
.client_http
.kbytes_in
, size
);
2230 * Don't reset the timeout value here. The timeout value will be
2231 * set to Config.Timeout.request by httpAccept() and
2232 * clientWriteComplete(), and should apply to the request as a
2233 * whole, not individual read() calls. Plus, it breaks our
2234 * lame half-close detection
2236 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, conn
, 0);
2238 if (conn
->chr
== NULL
) {
2239 /* no current or pending requests */
2242 } else if (!Config
.onoff
.half_closed_clients
) {
2243 /* admin doesn't want to support half-closed client sockets */
2247 /* It might be half-closed, we can't tell */
2248 debug(33, 5) ("clientReadRequest: FD %d closed?\n", fd
);
2249 F
->flags
.socket_eof
= 1;
2250 conn
->defer
.until
= squid_curtime
+ 1;
2252 fd_note(fd
, "half-closed");
2254 } else if (size
< 0) {
2255 if (!ignoreErrno(errno
)) {
2256 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd
, xstrerror());
2259 } else if (conn
->in
.offset
== 0) {
2260 debug(50, 2) ("clientReadRequest: FD %d: no data to process (%s)\n", fd
, xstrerror());
2263 /* Continue to process previously read data */
2266 conn
->in
.offset
+= size
;
2267 /* Skip leading (and trailing) whitespace */
2268 while (conn
->in
.offset
> 0) {
2271 while (conn
->in
.offset
> 0 && xisspace(conn
->in
.buf
[0])) {
2272 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.offset
- 1);
2275 conn
->in
.buf
[conn
->in
.offset
] = '\0'; /* Terminate the string */
2276 if (conn
->in
.offset
== 0)
2278 /* Limit the number of concurrent requests to 2 */
2279 for (H
= &conn
->chr
, nrequests
= 0; *H
; H
= &(*H
)->next
, nrequests
++);
2280 if (nrequests
>= 2) {
2281 debug(33, 2) ("clientReadRequest: FD %d max concurrent requests reached\n", fd
);
2282 debug(33, 5) ("clientReadRequest: FD %d defering new request until one is done\n", fd
);
2283 conn
->defer
.until
= squid_curtime
+ 100; /* Reset when a request is complete */
2286 /* Process request */
2287 http
= parseHttpRequest(conn
,
2289 &parser_return_code
,
2295 assert(http
->req_sz
> 0);
2296 conn
->in
.offset
-= http
->req_sz
;
2297 assert(conn
->in
.offset
>= 0);
2298 debug(33, 5) ("conn->in.offset = %d\n", (int) conn
->in
.offset
);
2300 * If we read past the end of this request, move the remaining
2301 * data to the beginning
2303 if (conn
->in
.offset
> 0)
2304 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ http
->req_sz
, conn
->in
.offset
);
2305 /* add to the client request queue */
2306 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2309 commSetTimeout(fd
, Config
.Timeout
.lifetime
, NULL
, NULL
);
2310 if (parser_return_code
< 0) {
2311 debug(33, 1) ("clientReadRequest: FD %d Invalid Request\n", fd
);
2312 err
= errorCon(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
);
2313 err
->request_hdrs
= xstrdup(conn
->in
.buf
);
2314 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2315 errorAppendEntry(http
->entry
, err
);
2319 if ((request
= urlParse(method
, http
->uri
)) == NULL
) {
2320 debug(33, 5) ("Invalid URL: %s\n", http
->uri
);
2321 err
= errorCon(ERR_INVALID_URL
, HTTP_BAD_REQUEST
);
2322 err
->src_addr
= conn
->peer
.sin_addr
;
2323 err
->url
= xstrdup(http
->uri
);
2324 http
->al
.http
.code
= err
->http_status
;
2325 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2326 errorAppendEntry(http
->entry
, err
);
2330 /* compile headers */
2331 /* we should skip request line! */
2332 if (!httpRequestParseHeader(request
, prefix
+ req_line_sz
))
2333 debug(33, 1) ("Failed to parse request headers: %s\n%s\n",
2335 /* continue anyway? */
2337 request
->flags
.accelerated
= http
->flags
.accel
;
2338 if (!http
->flags
.internal
) {
2339 if (internalCheck(strBuf(request
->urlpath
))) {
2340 if (0 == strcasecmp(request
->host
, internalHostname()) &&
2341 request
->port
== Config
.Port
.http
->i
) {
2342 http
->flags
.internal
= 1;
2343 } else if (internalStaticCheck(strBuf(request
->urlpath
))) {
2344 xstrncpy(request
->host
, internalHostname(), SQUIDHOSTNAMELEN
);
2345 request
->port
= Config
.Port
.http
->i
;
2346 http
->flags
.internal
= 1;
2350 request
->flags
.internal
= http
->flags
.internal
;
2352 safe_free(http
->log_uri
);
2353 http
->log_uri
= xstrdup(urlCanonicalClean(request
));
2354 request
->client_addr
= conn
->peer
.sin_addr
;
2355 request
->my_addr
= conn
->me
.sin_addr
;
2356 request
->http_ver
= http
->http_ver
;
2357 if (!urlCheckRequest(request
)) {
2358 err
= errorCon(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
);
2359 err
->src_addr
= conn
->peer
.sin_addr
;
2360 err
->request
= requestLink(request
);
2361 http
->al
.http
.code
= err
->http_status
;
2362 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2363 errorAppendEntry(http
->entry
, err
);
2366 if (0 == clientCheckContentLength(request
)) {
2367 err
= errorCon(ERR_INVALID_REQ
, HTTP_LENGTH_REQUIRED
);
2368 err
->src_addr
= conn
->peer
.sin_addr
;
2369 err
->request
= requestLink(request
);
2370 http
->al
.http
.code
= err
->http_status
;
2371 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2372 errorAppendEntry(http
->entry
, err
);
2375 http
->request
= requestLink(request
);
2377 * We need to set the keepalive flag before doing some
2378 * hacks for POST/PUT requests below. Maybe we could
2379 * set keepalive flag even earlier.
2381 clientSetKeepaliveFlag(http
);
2383 * break here for NON-GET because most likely there is a
2384 * reqeust body following and we don't want to parse it
2385 * as though it was new request
2387 if (request
->method
!= METHOD_GET
) {
2388 int cont_len
= httpHeaderGetInt(&request
->header
, HDR_CONTENT_LENGTH
);
2389 int copy_len
= XMIN(conn
->in
.offset
, cont_len
);
2391 assert(conn
->in
.offset
>= copy_len
);
2392 request
->body_sz
= copy_len
;
2393 request
->body
= xmalloc(request
->body_sz
);
2394 xmemcpy(request
->body
, conn
->in
.buf
, request
->body_sz
);
2395 conn
->in
.offset
-= copy_len
;
2396 if (conn
->in
.offset
)
2397 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ copy_len
, conn
->in
.offset
);
2400 * if we didn't get the full body now, then more will
2401 * be arriving on the client socket. Lets cancel
2402 * the read handler until this request gets forwarded.
2404 if (request
->body_sz
< cont_len
)
2405 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2407 clientAccessCheck(http
);
2408 continue; /* while offset > 0 */
2409 } else if (parser_return_code
== 0) {
2411 * Partial request received; reschedule until parseHttpRequest()
2412 * is happy with the input
2414 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2416 if (conn
->in
.offset
>= Config
.maxRequestSize
) {
2417 /* The request is too large to handle */
2418 debug(33, 0) ("Request won't fit in buffer.\n");
2419 debug(33, 0) ("Config 'request_size'= %d bytes.\n",
2420 Config
.maxRequestSize
);
2421 debug(33, 0) ("This request = %d bytes.\n",
2422 (int) conn
->in
.offset
);
2423 err
= errorCon(ERR_INVALID_REQ
, HTTP_REQUEST_ENTITY_TOO_LARGE
);
2424 http
= parseHttpRequestAbort(conn
, "error:request-too-large");
2425 /* add to the client request queue */
2426 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2428 http
->entry
= clientCreateStoreEntry(http
, METHOD_NONE
, null_request_flags
);
2429 errorAppendEntry(http
->entry
, err
);
2432 /* Grow the request memory area to accomodate for a large request */
2433 conn
->in
.size
+= REQUEST_BUF_SIZE
;
2434 conn
->in
.buf
= xrealloc(conn
->in
.buf
, conn
->in
.size
);
2435 /* XXX account conn->in.buf */
2436 debug(33, 2) ("Handling a large request, offset=%d inbufsize=%d\n",
2437 (int) conn
->in
.offset
, conn
->in
.size
);
2438 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2445 /* general lifetime handler for HTTP requests */
2447 requestTimeout(int fd
, void *data
)
2449 ConnStateData
*conn
= data
;
2451 debug(33, 2) ("requestTimeout: FD %d: lifetime is expired.\n", fd
);
2452 if (fd_table
[fd
].rwstate
) {
2454 * Some data has been sent to the client, just close the FD
2457 } else if (conn
->nrequests
) {
2459 * assume its a persistent connection; just close it
2466 err
= errorCon(ERR_LIFETIME_EXP
, HTTP_REQUEST_TIMEOUT
);
2467 err
->url
= xstrdup("N/A");
2469 * Normally we shouldn't call errorSend() in client_side.c, but
2470 * it should be okay in this case. Presumably if we get here
2471 * this is the first request for the connection, and no data
2472 * has been written yet
2474 assert(conn
->chr
== NULL
);
2477 * if we don't close() here, we still need a timeout handler!
2479 commSetTimeout(fd
, 30, requestTimeout
, conn
);
2484 httpAcceptDefer(void)
2486 static time_t last_warn
= 0;
2487 if (fdNFree() >= RESERVED_FD
)
2489 if (last_warn
+ 15 < squid_curtime
) {
2490 debug(33, 0) ("WARNING! Your cache is running out of filedescriptors\n");
2491 last_warn
= squid_curtime
;
2496 /* Handle a new connection on HTTP socket. */
2498 httpAccept(int sock
, void *data
)
2502 ConnStateData
*connState
= NULL
;
2503 struct sockaddr_in peer
;
2504 struct sockaddr_in me
;
2505 int max
= INCOMING_HTTP_MAX
;
2507 static aclCheck_t identChecklist
;
2509 commSetSelect(sock
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2510 while (max
-- && !httpAcceptDefer()) {
2511 memset(&peer
, '\0', sizeof(struct sockaddr_in
));
2512 memset(&me
, '\0', sizeof(struct sockaddr_in
));
2513 if ((fd
= comm_accept(sock
, &peer
, &me
)) < 0) {
2514 if (!ignoreErrno(errno
))
2515 debug(50, 1) ("httpAccept: FD %d: accept failure: %s\n",
2519 debug(33, 4) ("httpAccept: FD %d: accepted\n", fd
);
2520 connState
= xcalloc(1, sizeof(ConnStateData
));
2521 connState
->peer
= peer
;
2522 connState
->log_addr
= peer
.sin_addr
;
2523 connState
->log_addr
.s_addr
&= Config
.Addrs
.client_netmask
.s_addr
;
2526 connState
->in
.size
= REQUEST_BUF_SIZE
;
2527 connState
->in
.buf
= xcalloc(connState
->in
.size
, 1);
2528 cbdataAdd(connState
, cbdataXfree
, 0);
2529 /* XXX account connState->in.buf */
2530 comm_add_close_handler(fd
, connStateFree
, connState
);
2531 if (Config
.onoff
.log_fqdn
)
2532 fqdncache_gethostbyaddr(peer
.sin_addr
, FQDN_LOOKUP_IF_MISS
);
2533 commSetTimeout(fd
, Config
.Timeout
.request
, requestTimeout
, connState
);
2535 identChecklist
.src_addr
= peer
.sin_addr
;
2536 identChecklist
.my_addr
= me
.sin_addr
;
2537 if (aclCheckFast(Config
.accessList
.identLookup
, &identChecklist
))
2538 identStart(&me
, &peer
, clientIdentDone
, connState
);
2540 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, connState
, 0);
2541 commSetDefer(fd
, clientReadDefer
, connState
);
2546 #define SENDING_BODY 0
2547 #define SENDING_HDRSONLY 1
2549 clientCheckTransferDone(clientHttpRequest
* http
)
2551 int sending
= SENDING_BODY
;
2552 StoreEntry
*entry
= http
->entry
;
2559 * For now, 'done_copying' is used for special cases like
2560 * Range and HEAD requests.
2562 if (http
->flags
.done_copying
)
2565 * Handle STORE_OK objects.
2566 * objectLen(entry) will be set proprely.
2568 if (entry
->store_status
== STORE_OK
) {
2569 if (http
->out
.offset
>= objectLen(entry
))
2575 * Now, handle STORE_PENDING objects
2577 mem
= entry
->mem_obj
;
2578 assert(mem
!= NULL
);
2579 assert(http
->request
!= NULL
);
2581 if (reply
->hdr_sz
== 0)
2582 return 0; /* haven't found end of headers yet */
2583 else if (reply
->sline
.status
== HTTP_OK
)
2584 sending
= SENDING_BODY
;
2585 else if (reply
->sline
.status
== HTTP_NO_CONTENT
)
2586 sending
= SENDING_HDRSONLY
;
2587 else if (reply
->sline
.status
== HTTP_NOT_MODIFIED
)
2588 sending
= SENDING_HDRSONLY
;
2589 else if (reply
->sline
.status
< HTTP_OK
)
2590 sending
= SENDING_HDRSONLY
;
2591 else if (http
->request
->method
== METHOD_HEAD
)
2592 sending
= SENDING_HDRSONLY
;
2594 sending
= SENDING_BODY
;
2596 * Figure out how much data we are supposed to send.
2597 * If we are sending a body and we don't have a content-length,
2598 * then we must wait for the object to become STORE_OK.
2600 if (sending
== SENDING_HDRSONLY
)
2601 sendlen
= reply
->hdr_sz
;
2602 else if (reply
->content_length
< 0)
2605 sendlen
= reply
->content_length
+ reply
->hdr_sz
;
2607 * Now that we have the expected length, did we send it all?
2609 if (http
->out
.offset
< sendlen
)
2616 clientGotNotEnough(clientHttpRequest
* http
)
2618 int cl
= http
->entry
->mem_obj
->reply
->content_length
;
2619 int hs
= http
->entry
->mem_obj
->reply
->hdr_sz
;
2621 if (http
->out
.offset
< cl
+ hs
)
2627 * This function is designed to serve a fairly specific purpose.
2628 * Occasionally our vBNS-connected caches can talk to each other, but not
2629 * the rest of the world. Here we try to detect frequent failures which
2630 * make the cache unusable (e.g. DNS lookup and connect() failures). If
2631 * the failure:success ratio goes above 1.0 then we go into "hit only"
2632 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
2633 * will only fetch HITs from us if they are using the ICP protocol. We
2634 * stay in this mode for 5 minutes.
2636 * Duane W., Sept 16, 1996
2640 checkFailureRatio(err_type etype
, hier_code hcode
)
2642 static double magic_factor
= 100.0;
2645 if (hcode
== HIER_NONE
)
2647 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
2648 n_bad
= magic_factor
- n_good
;
2651 case ERR_CONNECT_FAIL
:
2652 case ERR_READ_ERROR
:
2658 request_failure_ratio
= n_bad
/ n_good
;
2659 if (hit_only_mode_until
> squid_curtime
)
2661 if (request_failure_ratio
< 1.0)
2663 debug(33, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio
);
2664 debug(33, 0) ("Going into hit-only-mode for %d minutes...\n",
2665 FAILURE_MODE_TIME
/ 60);
2666 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
2667 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
2671 clientHttpConnectionsOpen(void)
2675 for (u
= Config
.Port
.http
; u
; u
= u
->next
) {
2677 fd
= comm_open(SOCK_STREAM
,
2679 Config
.Addrs
.tcp_incoming
,
2687 commSetSelect(fd
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2688 /*commSetDefer(fd, httpAcceptDefer, NULL); */
2689 debug(1, 1) ("Accepting HTTP connections on port %d, FD %d.\n",
2691 HttpSockets
[NHttpSockets
++] = fd
;
2693 if (NHttpSockets
< 1)
2694 fatal("Cannot open HTTP Port");
2698 clientHttpConnectionsClose(void)
2701 for (i
= 0; i
< NHttpSockets
; i
++) {
2702 if (HttpSockets
[i
] >= 0) {
2703 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets
[i
]);
2704 comm_close(HttpSockets
[i
]);
2705 HttpSockets
[i
] = -1;