3 * $Id: client_side.cc,v 1.453 1999/05/10 19:43:36 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
);
95 static int clientReplyBodyTooLarge(int clen
);
98 checkAccelOnly(clientHttpRequest
* http
)
100 /* return TRUE if someone makes a proxy request to us and
101 * we are in httpd-accel only mode */
102 if (!Config2
.Accel
.on
)
104 if (Config
.onoff
.accel_with_proxy
)
106 if (http
->request
->protocol
== PROTO_CACHEOBJ
)
108 if (http
->flags
.accel
)
115 clientIdentDone(const char *ident
, void *data
)
117 ConnStateData
*conn
= data
;
119 xstrncpy(conn
->ident
, ident
, sizeof(conn
->ident
));
121 xstrncpy(conn
->ident
, "-", sizeof(conn
->ident
));
126 clientAccessCheck(void *data
)
128 clientHttpRequest
*http
= data
;
129 ConnStateData
*conn
= http
->conn
;
131 if (checkAccelOnly(http
)) {
132 clientAccessCheckDone(0, http
);
135 browser
= httpHeaderGetStr(&http
->request
->header
, HDR_USER_AGENT
);
136 http
->acl_checklist
= aclChecklistCreate(Config
.accessList
.http
,
144 * hack for ident ACL. It needs to get full addresses, and a
145 * place to store the ident result on persistent connections...
147 http
->acl_checklist
->conn
= conn
;
148 cbdataLock(http
->acl_checklist
->conn
);
150 aclNBCheck(http
->acl_checklist
, clientAccessCheckDone
, http
);
154 * returns true if client specified that the object must come from the cache
155 * witout contacting origin server
158 clientOnlyIfCached(clientHttpRequest
* http
)
160 const request_t
*r
= http
->request
;
162 return r
->cache_control
&&
163 EBIT_TEST(r
->cache_control
->mask
, CC_ONLY_IF_CACHED
);
167 clientCreateStoreEntry(clientHttpRequest
* h
, method_t m
, request_flags flags
)
171 * For erroneous requests, we might not have a h->request,
172 * so make a fake one.
174 if (h
->request
== NULL
)
175 h
->request
= requestLink(requestCreate(m
, PROTO_NONE
, NULL
));
176 e
= storeCreateEntry(h
->uri
, h
->log_uri
, flags
, m
);
177 storeClientListAdd(e
, h
);
179 delaySetStoreClient(e
, h
, delayClient(h
->request
));
181 storeClientCopy(e
, 0, 0, CLIENT_SOCK_SZ
,
182 memAllocate(MEM_CLIENT_SOCK_BUF
), clientSendMoreData
, h
);
187 clientAccessCheckDone(int answer
, void *data
)
189 clientHttpRequest
*http
= data
;
192 ErrorState
*err
= NULL
;
193 debug(33, 2) ("The request %s %s is %s, because it matched '%s'\n",
194 RequestMethodStr
[http
->request
->method
], http
->uri
,
195 answer
? "ALLOWED" : "DENIED",
196 AclMatchedName
? AclMatchedName
: "NO ACL's");
197 http
->acl_checklist
= NULL
;
198 if (answer
== ACCESS_ALLOWED
) {
199 safe_free(http
->uri
);
200 http
->uri
= xstrdup(urlCanonical(http
->request
));
201 assert(http
->redirect_state
== REDIRECT_NONE
);
202 http
->redirect_state
= REDIRECT_PENDING
;
203 redirectStart(http
, clientRedirectDone
, http
);
205 debug(33, 5) ("Access Denied: %s\n", http
->uri
);
206 debug(33, 5) ("AclMatchedName = %s\n",
207 AclMatchedName
? AclMatchedName
: "<null>");
209 * NOTE: get page_id here, based on AclMatchedName because
210 * if USE_DELAY_POOLS is enabled, then AclMatchedName gets
211 * clobbered in the clientCreateStoreEntry() call
212 * just below. Pedro Ribeiro <pribeiro@isel.pt>
214 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
);
215 http
->log_type
= LOG_TCP_DENIED
;
216 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
218 if (answer
== ACCESS_REQ_PROXY_AUTH
|| aclIsProxyAuth(AclMatchedName
)) {
219 if (!http
->flags
.accel
) {
220 /* Proxy authorisation needed */
221 status
= HTTP_PROXY_AUTHENTICATION_REQUIRED
;
223 /* WWW authorisation needed */
224 status
= HTTP_UNAUTHORIZED
;
227 page_id
= ERR_CACHE_ACCESS_DENIED
;
229 status
= HTTP_FORBIDDEN
;
231 page_id
= ERR_ACCESS_DENIED
;
233 err
= errorCon(page_id
, status
);
234 err
->request
= requestLink(http
->request
);
235 err
->src_addr
= http
->conn
->peer
.sin_addr
;
236 errorAppendEntry(http
->entry
, err
);
241 clientRedirectDone(void *data
, char *result
)
243 clientHttpRequest
*http
= data
;
244 request_t
*new_request
= NULL
;
245 request_t
*old_request
= http
->request
;
246 debug(33, 5) ("clientRedirectDone: '%s' result=%s\n", http
->uri
,
247 result
? result
: "NULL");
248 assert(http
->redirect_state
== REDIRECT_PENDING
);
249 http
->redirect_state
= REDIRECT_DONE
;
251 http_status status
= atoi(result
);
252 if (status
== 301 || status
== 302) {
254 if ((t
= strchr(result
, ':')) != NULL
) {
255 http
->redirect
.status
= status
;
256 http
->redirect
.location
= xstrdup(t
+ 1);
258 debug(33, 1) ("clientRedirectDone: bad input: %s\n", result
);
261 if (strcmp(result
, http
->uri
))
262 new_request
= urlParse(old_request
->method
, result
);
265 safe_free(http
->uri
);
266 http
->uri
= xstrdup(urlCanonical(new_request
));
267 new_request
->http_ver
= old_request
->http_ver
;
268 httpHeaderAppend(&new_request
->header
, &old_request
->header
);
269 new_request
->client_addr
= old_request
->client_addr
;
270 new_request
->my_addr
= old_request
->my_addr
;
271 new_request
->flags
.redirected
= 1;
272 if (old_request
->body
) {
273 new_request
->body
= xmalloc(old_request
->body_sz
);
274 xmemcpy(new_request
->body
, old_request
->body
, old_request
->body_sz
);
275 new_request
->body_sz
= old_request
->body_sz
;
277 requestUnlink(old_request
);
278 http
->request
= requestLink(new_request
);
280 clientInterpretRequestHeaders(http
);
281 fd_note(http
->conn
->fd
, http
->uri
);
282 clientProcessRequest(http
);
286 clientProcessExpired(void *data
)
288 clientHttpRequest
*http
= data
;
289 char *url
= http
->uri
;
290 StoreEntry
*entry
= NULL
;
291 debug(33, 3) ("clientProcessExpired: '%s'\n", http
->uri
);
292 assert(http
->entry
->lastmod
>= 0);
294 * check if we are allowed to contact other servers
295 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
296 * a stale entry *if* it matches client requirements
298 if (clientOnlyIfCached(http
)) {
299 clientProcessOnlyIfCachedMiss(http
);
302 http
->request
->flags
.refresh
= 1;
303 http
->old_entry
= http
->entry
;
305 * Assert that 'http' is already a client of old_entry. If
306 * it is not, then the beginning of the object data might get
307 * freed from memory before we need to access it.
309 assert(storeClientListSearch(http
->old_entry
->mem_obj
, http
));
310 entry
= storeCreateEntry(url
,
312 http
->request
->flags
,
313 http
->request
->method
);
314 /* NOTE, don't call storeLockObject(), storeCreateEntry() does it */
315 storeClientListAdd(entry
, http
);
317 /* delay_id is already set on original store client */
318 delaySetStoreClient(entry
, http
, delayClient(http
->request
));
320 entry
->lastmod
= http
->old_entry
->lastmod
;
321 debug(33, 5) ("clientProcessExpired: lastmod %d\n", (int) entry
->lastmod
);
322 entry
->refcount
++; /* EXPIRED CASE */
324 http
->out
.offset
= 0;
325 fwdStart(http
->conn
->fd
, http
->entry
, http
->request
,
326 http
->conn
->peer
.sin_addr
, http
->conn
->me
.sin_addr
);
327 /* Register with storage manager to receive updates when data comes in. */
328 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
329 debug(33, 0) ("clientProcessExpired: found ENTRY_ABORTED object\n");
330 storeClientCopy(entry
,
334 memAllocate(MEM_CLIENT_SOCK_BUF
),
335 clientHandleIMSReply
,
340 clientGetsOldEntry(StoreEntry
* new_entry
, StoreEntry
* old_entry
, request_t
* request
)
342 const http_status status
= new_entry
->mem_obj
->reply
->sline
.status
;
344 debug(33, 5) ("clientGetsOldEntry: YES, broken HTTP reply\n");
347 /* If the reply is a failure then send the old object as a last
349 if (status
>= 500 && status
< 600) {
350 debug(33, 3) ("clientGetsOldEntry: YES, failure reply=%d\n", status
);
353 /* If the reply is anything but "Not Modified" then
354 * we must forward it to the client */
355 if (HTTP_NOT_MODIFIED
!= status
) {
356 debug(33, 5) ("clientGetsOldEntry: NO, reply=%d\n", status
);
359 /* If the client did not send IMS in the request, then it
360 * must get the old object, not this "Not Modified" reply */
361 if (!request
->flags
.ims
) {
362 debug(33, 5) ("clientGetsOldEntry: YES, no client IMS\n");
365 /* If the client IMS time is prior to the entry LASTMOD time we
366 * need to send the old object */
367 if (modifiedSince(old_entry
, request
)) {
368 debug(33, 5) ("clientGetsOldEntry: YES, modified since %d\n",
372 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
378 clientHandleIMSReply(void *data
, char *buf
, ssize_t size
)
380 clientHttpRequest
*http
= data
;
381 StoreEntry
*entry
= http
->entry
;
383 const char *url
= storeUrl(entry
);
384 int unlink_request
= 0;
385 StoreEntry
*oldentry
;
388 debug(33, 3) ("clientHandleIMSReply: %s, %d bytes\n", url
, (int) size
);
390 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
393 if (size
< 0 && !EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
394 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
397 mem
= entry
->mem_obj
;
398 status
= mem
->reply
->sline
.status
;
399 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
400 debug(33, 3) ("clientHandleIMSReply: ABORTED '%s'\n", url
);
401 /* We have an existing entry, but failed to validate it */
402 /* Its okay to send the old one anyway */
403 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
404 storeUnregister(entry
, http
);
405 storeUnlockObject(entry
);
406 entry
= http
->entry
= http
->old_entry
;
408 } else if (STORE_PENDING
== entry
->store_status
&& 0 == status
) {
409 debug(33, 3) ("clientHandleIMSReply: Incomplete headers for '%s'\n", url
);
410 if (size
>= CLIENT_SOCK_SZ
) {
411 /* will not get any bigger than that */
412 debug(33, 3) ("clientHandleIMSReply: Reply is too large '%s', using old entry\n", url
);
413 /* use old entry, this repeats the code abovez */
414 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
415 storeUnregister(entry
, http
);
416 storeUnlockObject(entry
);
417 entry
= http
->entry
= http
->old_entry
;
421 storeClientCopy(entry
,
422 http
->out
.offset
+ size
,
426 clientHandleIMSReply
,
430 } else if (clientGetsOldEntry(entry
, http
->old_entry
, http
->request
)) {
431 /* We initiated the IMS request, the client is not expecting
432 * 304, so put the good one back. First, make sure the old entry
433 * headers have been loaded from disk. */
434 oldentry
= http
->old_entry
;
435 http
->log_type
= LOG_TCP_REFRESH_HIT
;
436 if (oldentry
->mem_obj
->request
== NULL
) {
437 oldentry
->mem_obj
->request
= requestLink(mem
->request
);
440 /* Don't memcpy() the whole reply structure here. For example,
441 * www.thegist.com (Netscape/1.13) returns a content-length for
442 * 304's which seems to be the length of the 304 HEADERS!!! and
443 * not the body they refer to. */
444 httpReplyUpdateOnNotModified(oldentry
->mem_obj
->reply
, mem
->reply
);
445 storeTimestampsSet(oldentry
);
446 storeUnregister(entry
, http
);
447 storeUnlockObject(entry
);
448 entry
= http
->entry
= oldentry
;
449 entry
->timestamp
= squid_curtime
;
450 if (unlink_request
) {
451 requestUnlink(entry
->mem_obj
->request
);
452 entry
->mem_obj
->request
= NULL
;
455 /* the client can handle this reply, whatever it is */
456 http
->log_type
= LOG_TCP_REFRESH_MISS
;
457 if (HTTP_NOT_MODIFIED
== mem
->reply
->sline
.status
) {
458 httpReplyUpdateOnNotModified(http
->old_entry
->mem_obj
->reply
,
460 storeTimestampsSet(http
->old_entry
);
461 http
->old_entry
->refcount
++;
462 http
->log_type
= LOG_TCP_REFRESH_HIT
;
464 storeUnregister(http
->old_entry
, http
);
465 storeUnlockObject(http
->old_entry
);
468 http
->old_entry
= NULL
; /* done with old_entry */
469 assert(!EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
471 storeClientCopy(entry
,
479 clientSendMoreData(data
, buf
, size
);
484 modifiedSince(StoreEntry
* entry
, request_t
* request
)
487 MemObject
*mem
= entry
->mem_obj
;
488 time_t mod_time
= entry
->lastmod
;
489 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry
));
491 mod_time
= entry
->timestamp
;
492 debug(33, 3) ("modifiedSince: mod_time = %d\n", (int) mod_time
);
495 /* Find size of the object */
496 object_length
= mem
->reply
->content_length
;
497 if (object_length
< 0)
498 object_length
= contentLen(entry
);
499 if (mod_time
> request
->ims
) {
500 debug(33, 3) ("--> YES: entry newer than client\n");
502 } else if (mod_time
< request
->ims
) {
503 debug(33, 3) ("--> NO: entry older than client\n");
505 } else if (request
->imslen
< 0) {
506 debug(33, 3) ("--> NO: same LMT, no client length\n");
508 } else if (request
->imslen
== object_length
) {
509 debug(33, 3) ("--> NO: same LMT, same length\n");
512 debug(33, 3) ("--> YES: same LMT, different length\n");
518 clientPurgeRequest(clientHttpRequest
* http
)
521 ErrorState
*err
= NULL
;
523 debug(33, 3) ("Config.onoff.enable_purge = %d\n", Config
.onoff
.enable_purge
);
524 if (!Config
.onoff
.enable_purge
) {
525 http
->log_type
= LOG_TCP_DENIED
;
526 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
527 err
->request
= requestLink(http
->request
);
528 err
->src_addr
= http
->conn
->peer
.sin_addr
;
529 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
530 errorAppendEntry(http
->entry
, err
);
533 http
->log_type
= LOG_TCP_MISS
;
534 if ((entry
= storeGetPublic(http
->uri
, METHOD_GET
)) == NULL
) {
535 http
->http_code
= HTTP_NOT_FOUND
;
538 http
->http_code
= HTTP_OK
;
540 debug(33, 4) ("clientPurgeRequest: Not modified '%s'\n",
543 * Make a new entry to hold the reply to be written
546 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
547 httpReplyReset(r
= http
->entry
->mem_obj
->reply
);
548 httpReplySetHeaders(r
, 1.0, http
->http_code
, NULL
, NULL
, 0, 0, -1);
549 httpReplySwapOut(r
, http
->entry
);
550 storeComplete(http
->entry
);
554 checkNegativeHit(StoreEntry
* e
)
556 if (!EBIT_TEST(e
->flags
, ENTRY_NEGCACHED
))
558 if (e
->expires
<= squid_curtime
)
560 if (e
->store_status
!= STORE_OK
)
566 clientUpdateCounters(clientHttpRequest
* http
)
568 int svc_time
= tvSubMsec(http
->start
, current_time
);
570 HierarchyLogEntry
*H
;
571 Counter
.client_http
.requests
++;
572 if (isTcpHit(http
->log_type
))
573 Counter
.client_http
.hits
++;
574 if (http
->request
->err_type
!= ERR_NONE
)
575 Counter
.client_http
.errors
++;
576 statHistCount(&Counter
.client_http
.all_svc_time
, svc_time
);
578 * The idea here is not to be complete, but to get service times
579 * for only well-defined types. For example, we don't include
580 * LOG_TCP_REFRESH_FAIL_HIT because its not really a cache hit
581 * (we *tried* to validate it, but failed).
583 switch (http
->log_type
) {
584 case LOG_TCP_REFRESH_HIT
:
585 statHistCount(&Counter
.client_http
.nh_svc_time
, svc_time
);
587 case LOG_TCP_IMS_HIT
:
588 statHistCount(&Counter
.client_http
.nm_svc_time
, svc_time
);
591 case LOG_TCP_MEM_HIT
:
592 case LOG_TCP_OFFLINE_HIT
:
593 statHistCount(&Counter
.client_http
.hit_svc_time
, svc_time
);
596 case LOG_TCP_CLIENT_REFRESH_MISS
:
597 statHistCount(&Counter
.client_http
.miss_svc_time
, svc_time
);
600 /* make compiler warnings go away */
603 H
= &http
->request
->hier
;
606 Counter
.cd
.times_used
++;
609 Counter
.icp
.times_used
++;
611 if (0 != i
->stop
.tv_sec
&& 0 != i
->start
.tv_sec
)
612 statHistCount(&Counter
.icp
.query_svc_time
,
613 tvSubUsec(i
->start
, i
->stop
));
615 Counter
.icp
.query_timeouts
++;
618 Counter
.netdb
.times_used
++;
626 httpRequestFree(void *data
)
628 clientHttpRequest
*http
= data
;
629 clientHttpRequest
**H
;
630 ConnStateData
*conn
= http
->conn
;
632 request_t
*request
= http
->request
;
633 MemObject
*mem
= NULL
;
634 debug(33, 3) ("httpRequestFree: %s\n", storeUrl(http
->entry
));
635 if (!clientCheckTransferDone(http
)) {
636 if ((e
= http
->entry
)) {
638 storeUnregister(e
, http
);
639 storeUnlockObject(e
);
641 if (http
->entry
&& http
->entry
->ping_status
== PING_WAITING
)
642 storeReleaseRequest(http
->entry
);
644 assert(http
->log_type
< LOG_TYPE_MAX
);
646 mem
= http
->entry
->mem_obj
;
647 if (http
->out
.size
|| http
->log_type
) {
648 http
->al
.icp
.opcode
= ICP_INVALID
;
649 http
->al
.url
= http
->log_uri
;
650 debug(33, 9) ("httpRequestFree: al.url='%s'\n", http
->al
.url
);
652 http
->al
.http
.code
= mem
->reply
->sline
.status
;
653 http
->al
.http
.content_type
= strBuf(mem
->reply
->content_type
);
655 http
->al
.cache
.caddr
= conn
->log_addr
;
656 http
->al
.cache
.size
= http
->out
.size
;
657 http
->al
.cache
.code
= http
->log_type
;
658 http
->al
.cache
.msec
= tvSubMsec(http
->start
, current_time
);
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
;
669 if (request
->user_ident
[0])
670 http
->al
.cache
.ident
= request
->user_ident
;
672 http
->al
.cache
.ident
= conn
->ident
;
676 accessLogLog(&http
->al
);
677 clientUpdateCounters(http
);
678 clientdbUpdate(conn
->peer
.sin_addr
, http
->log_type
, PROTO_HTTP
, http
->out
.size
);
680 if (http
->acl_checklist
)
681 aclChecklistFree(http
->acl_checklist
);
683 checkFailureRatio(request
->err_type
, http
->al
.hier
.code
);
684 safe_free(http
->uri
);
685 safe_free(http
->log_uri
);
686 safe_free(http
->al
.headers
.request
);
687 safe_free(http
->al
.headers
.reply
);
688 safe_free(http
->redirect
.location
);
689 stringClean(&http
->range_iter
.boundary
);
690 if ((e
= http
->entry
)) {
692 storeUnregister(e
, http
);
693 storeUnlockObject(e
);
695 /* old_entry might still be set if we didn't yet get the reply
696 * code in clientHandleIMSReply() */
697 if ((e
= http
->old_entry
)) {
698 http
->old_entry
= NULL
;
699 storeUnregister(e
, http
);
700 storeUnlockObject(e
);
702 requestUnlink(http
->request
);
703 assert(http
!= http
->next
);
704 assert(http
->conn
->chr
!= NULL
);
705 H
= &http
->conn
->chr
;
714 dlinkDelete(&http
->active
, &ClientActiveRequests
);
718 /* This is a handler normally called by comm_close() */
720 connStateFree(int fd
, void *data
)
722 ConnStateData
*connState
= data
;
723 clientHttpRequest
*http
;
724 debug(33, 3) ("connStateFree: FD %d\n", fd
);
725 assert(connState
!= NULL
);
726 while ((http
= connState
->chr
) != NULL
) {
727 assert(http
->conn
== connState
);
728 assert(connState
->chr
!= connState
->chr
->next
);
729 httpRequestFree(http
);
731 safe_free(connState
->in
.buf
);
732 /* XXX account connState->in.buf */
733 pconnHistCount(0, connState
->nrequests
);
734 cbdataFree(connState
);
736 /* prevent those nasty RST packets */
738 char buf
[SQUID_TCP_SO_RCVBUF
];
739 while (read(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0);
745 clientInterpretRequestHeaders(clientHttpRequest
* http
)
747 request_t
*request
= http
->request
;
748 const HttpHeader
*req_hdr
= &request
->header
;
750 #if USE_USERAGENT_LOG
753 request
->imslen
= -1;
754 request
->ims
= httpHeaderGetTime(req_hdr
, HDR_IF_MODIFIED_SINCE
);
755 if (request
->ims
> 0)
756 request
->flags
.ims
= 1;
757 if (httpHeaderHas(req_hdr
, HDR_PRAGMA
)) {
758 String s
= httpHeaderGetList(req_hdr
, HDR_PRAGMA
);
759 if (strListIsMember(&s
, "no-cache", ','))
763 if (request
->cache_control
)
764 if (EBIT_TEST(request
->cache_control
->mask
, CC_NO_CACHE
))
768 if (Config
.onoff
.reload_into_ims
)
769 request
->flags
.nocache_hack
= 1;
770 else if (refresh_nocache_hack
)
771 request
->flags
.nocache_hack
= 1;
774 request
->flags
.nocache
= 1;
776 /* ignore range header in non-GETs */
777 if (request
->method
== METHOD_GET
) {
778 request
->range
= httpHeaderGetRange(req_hdr
);
780 request
->flags
.range
= 1;
782 if (httpHeaderHas(req_hdr
, HDR_AUTHORIZATION
))
783 request
->flags
.auth
= 1;
784 if (request
->login
[0] != '\0')
785 request
->flags
.auth
= 1;
786 if (httpHeaderHas(req_hdr
, HDR_VIA
)) {
787 String s
= httpHeaderGetList(req_hdr
, HDR_VIA
);
789 * ThisCache cannot be a member of Via header, "1.0 ThisCache" can.
790 * Note ThisCache2 has a space prepended to the hostname so we don't
791 * accidentally match super-domains.
793 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
794 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
795 request
, (ObjPackMethod
) & httpRequestPack
);
796 request
->flags
.loopdetect
= 1;
799 fvdbCountVia(strBuf(s
));
803 #if USE_USERAGENT_LOG
804 if ((str
= httpHeaderGetStr(req_hdr
, HDR_USER_AGENT
)))
805 logUserAgent(fqdnFromAddr(http
->conn
->peer
.sin_addr
), str
);
808 if (httpHeaderHas(req_hdr
, HDR_X_FORWARDED_FOR
)) {
809 String s
= httpHeaderGetList(req_hdr
, HDR_X_FORWARDED_FOR
);
810 fvdbCountForw(strBuf(s
));
814 request
->cache_control
= httpHeaderGetCc(req_hdr
);
815 if (request
->method
== METHOD_TRACE
) {
816 request
->max_forwards
= httpHeaderGetInt(req_hdr
, HDR_MAX_FORWARDS
);
818 if (clientCachable(http
))
819 request
->flags
.cachable
= 1;
820 if (clientHierarchical(http
))
821 request
->flags
.hierarchical
= 1;
822 debug(33, 5) ("clientInterpretRequestHeaders: REQ_NOCACHE = %s\n",
823 request
->flags
.nocache
? "SET" : "NOT SET");
824 debug(33, 5) ("clientInterpretRequestHeaders: REQ_CACHABLE = %s\n",
825 request
->flags
.cachable
? "SET" : "NOT SET");
826 debug(33, 5) ("clientInterpretRequestHeaders: REQ_HIERARCHICAL = %s\n",
827 request
->flags
.hierarchical
? "SET" : "NOT SET");
831 * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive.
832 * This is the client-side persistent connection flag. We need
833 * to set this relatively early in the request processing
834 * to handle hacks for broken servers and clients.
837 clientSetKeepaliveFlag(clientHttpRequest
* http
)
839 request_t
*request
= http
->request
;
840 const HttpHeader
*req_hdr
= &request
->header
;
841 debug(33, 3) ("clientSetKeepaliveFlag: http_ver = %3.1f\n",
843 debug(33, 3) ("clientSetKeepaliveFlag: method = %s\n",
844 RequestMethodStr
[request
->method
]);
845 if (httpMsgIsPersistent(request
->http_ver
, req_hdr
))
846 request
->flags
.proxy_keepalive
= 1;
850 clientCheckContentLength(request_t
* r
)
852 /* We only require a content-length for "upload" methods */
853 if (!pumpMethod(r
->method
))
855 if (httpHeaderGetInt(&r
->header
, HDR_CONTENT_LENGTH
) < 0)
861 clientCachable(clientHttpRequest
* http
)
863 const char *url
= http
->uri
;
864 request_t
*req
= http
->request
;
865 method_t method
= req
->method
;
867 memset(&ch
, '\0', sizeof(ch
));
869 * Hopefully, nobody really wants 'no_cache' by client's IP
870 * address, but if they do, this should work if they use IP
871 * addresses in their ACLs, or if the client's address is in
874 * This may not work yet for 'dst' and 'dst_domain' ACLs.
876 ch
.src_addr
= http
->conn
->peer
.sin_addr
;
877 ch
.my_addr
= http
->conn
->me
.sin_addr
;
878 ch
.request
= http
->request
;
880 * aclCheckFast returns 1 for ALLOW and 0 for DENY. The default
881 * is ALLOW, so we require 'no_cache DENY foo' in squid.conf
882 * to indicate uncachable objects.
884 if (!aclCheckFast(Config
.accessList
.noCache
, &ch
))
886 if (req
->protocol
== PROTO_HTTP
)
887 return httpCachable(method
);
888 /* FTP is always cachable */
889 if (req
->protocol
== PROTO_GOPHER
)
890 return gopherCachable(url
);
891 if (req
->protocol
== PROTO_WAIS
)
893 if (method
== METHOD_CONNECT
)
895 if (method
== METHOD_TRACE
)
897 if (req
->protocol
== PROTO_CACHEOBJ
)
902 /* Return true if we can query our neighbors for this object */
904 clientHierarchical(clientHttpRequest
* http
)
906 const char *url
= http
->uri
;
907 request_t
*request
= http
->request
;
908 method_t method
= request
->method
;
909 const wordlist
*p
= NULL
;
911 /* IMS needs a private key, so we can use the hierarchy for IMS only
912 * if our neighbors support private keys */
913 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
915 if (request
->flags
.auth
)
917 if (method
== METHOD_TRACE
)
919 if (method
!= METHOD_GET
)
921 /* scan hierarchy_stoplist */
922 for (p
= Config
.hierarchy_stoplist
; p
; p
= p
->next
)
923 if (strstr(url
, p
->key
))
925 if (request
->flags
.loopdetect
)
927 if (request
->protocol
== PROTO_HTTP
)
928 return httpCachable(method
);
929 if (request
->protocol
== PROTO_GOPHER
)
930 return gopherCachable(url
);
931 if (request
->protocol
== PROTO_WAIS
)
933 if (request
->protocol
== PROTO_CACHEOBJ
)
939 isTcpHit(log_type code
)
941 /* this should be a bitmap for better optimization */
942 if (code
== LOG_TCP_HIT
)
944 if (code
== LOG_TCP_IMS_HIT
)
946 if (code
== LOG_TCP_REFRESH_FAIL_HIT
)
948 if (code
== LOG_TCP_REFRESH_HIT
)
950 if (code
== LOG_TCP_NEGATIVE_HIT
)
952 if (code
== LOG_TCP_MEM_HIT
)
954 if (code
== LOG_TCP_OFFLINE_HIT
)
960 * returns true if If-Range specs match reply, false otherwise
963 clientIfRangeMatch(clientHttpRequest
* http
, HttpReply
* rep
)
965 const TimeOrTag spec
= httpHeaderGetTimeOrTag(&http
->request
->header
, HDR_IF_RANGE
);
966 /* check for parsing falure */
971 ETag rep_tag
= httpHeaderGetETag(&rep
->header
, HDR_ETAG
);
972 debug(33, 3) ("clientIfRangeMatch: ETags: %s and %s\n",
973 spec
.tag
.str
, rep_tag
.str
? rep_tag
.str
: "<none>");
975 return 0; /* entity has no etag to compare with! */
976 if (spec
.tag
.weak
|| rep_tag
.weak
) {
977 debug(33, 1) ("clientIfRangeMatch: Weak ETags are not allowed in If-Range: %s ? %s\n",
978 spec
.tag
.str
, rep_tag
.str
);
979 return 0; /* must use strong validator for sub-range requests */
981 return etagIsEqual(&rep_tag
, &spec
.tag
);
983 /* got modification time? */
984 if (spec
.time
>= 0) {
985 return http
->entry
->lastmod
<= spec
.time
;
987 assert(0); /* should not happen */
991 /* returns expected content length for multi-range replies
992 * note: assumes that httpHdrRangeCanonize has already been called
993 * warning: assumes that HTTP headers for individual ranges at the
994 * time of the actuall assembly will be exactly the same as
995 * the headers when clientMRangeCLen() is called */
997 clientMRangeCLen(clientHttpRequest
* http
)
1000 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1001 const HttpHdrRangeSpec
*spec
;
1004 assert(http
->entry
->mem_obj
);
1007 while ((spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
))) {
1009 /* account for headers for this range */
1011 clientPackRangeHdr(http
->entry
->mem_obj
->reply
,
1012 spec
, http
->range_iter
.boundary
, &mb
);
1015 /* account for range content */
1016 clen
+= spec
->length
;
1018 debug(33, 6) ("clientMRangeCLen: (clen += %d + %d) == %d\n",
1019 mb
.size
, spec
->length
, clen
);
1021 /* account for the terminating boundary */
1023 clientPackTermBound(http
->range_iter
.boundary
, &mb
);
1030 /* adds appropriate Range headers if needed */
1032 clientBuildRangeHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1034 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1035 const char *range_err
= NULL
;
1036 assert(http
->request
->range
);
1037 /* check if we still want to do ranges */
1039 range_err
= "no [parse-able] reply";
1040 else if (rep
->sline
.status
!= HTTP_OK
)
1041 range_err
= "wrong status code";
1042 else if (httpHeaderHas(hdr
, HDR_CONTENT_RANGE
))
1043 range_err
= "origin server does ranges";
1044 else if (rep
->content_length
< 0)
1045 range_err
= "unknown length";
1046 else if (rep
->content_length
!= http
->entry
->mem_obj
->reply
->content_length
)
1047 range_err
= "INCONSISTENT length"; /* a bug? */
1048 else if (httpHeaderHas(&http
->request
->header
, HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1049 range_err
= "If-Range match failed";
1050 else if (!httpHdrRangeCanonize(http
->request
->range
, rep
->content_length
))
1051 range_err
= "canonization failed";
1052 else if (httpHdrRangeIsComplex(http
->request
->range
))
1053 range_err
= "too complex range header";
1054 /* get rid of our range specs on error */
1056 debug(33, 3) ("clientBuildRangeHeader: will not do ranges: %s.\n", range_err
);
1057 httpHdrRangeDestroy(http
->request
->range
);
1058 http
->request
->range
= NULL
;
1060 const int spec_count
= http
->request
->range
->specs
.count
;
1061 int actual_clen
= -1;
1063 debug(33, 3) ("clientBuildRangeHeader: range spec count: %d virgin clen: %d\n",
1064 spec_count
, rep
->content_length
);
1065 assert(spec_count
> 0);
1066 /* ETags should not be returned with Partial Content replies? */
1067 httpHeaderDelById(hdr
, HDR_ETAG
);
1068 /* append appropriate header(s) */
1069 if (spec_count
== 1) {
1070 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1071 const HttpHdrRangeSpec
*spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
);
1073 /* append Content-Range */
1074 httpHeaderAddContRange(hdr
, *spec
, rep
->content_length
);
1075 /* set new Content-Length to the actual number of bytes
1076 * transmitted in the message-body */
1077 actual_clen
= spec
->length
;
1080 /* generate boundary string */
1081 http
->range_iter
.boundary
= httpHdrRangeBoundaryStr(http
);
1082 /* delete old Content-Type, add ours */
1083 httpHeaderDelById(hdr
, HDR_CONTENT_TYPE
);
1084 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1085 "multipart/byteranges; boundary=\"%s\"",
1086 strBuf(http
->range_iter
.boundary
));
1087 /* Content-Length is not required in multipart responses
1088 * but it is always nice to have one */
1089 actual_clen
= clientMRangeCLen(http
);
1092 /* replace Content-Length header */
1093 assert(actual_clen
>= 0);
1094 httpHeaderDelById(hdr
, HDR_CONTENT_LENGTH
);
1095 httpHeaderPutInt(hdr
, HDR_CONTENT_LENGTH
, actual_clen
);
1096 debug(33, 3) ("clientBuildRangeHeader: actual content length: %d\n", actual_clen
);
1101 * filters out unwanted entries from original reply header
1102 * adds extra entries if we have more info than origin server
1103 * adds Squid specific entries
1106 clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1108 HttpHeader
*hdr
= &rep
->header
;
1109 int is_hit
= isTcpHit(http
->log_type
);
1110 request_t
*request
= http
->request
;
1111 #if DONT_FILTER_THESE
1112 /* but you might want to if you run Squid as an HTTP accelerator */
1113 /* httpHeaderDelById(hdr, HDR_ACCEPT_RANGES); */
1114 httpHeaderDelById(hdr
, HDR_ETAG
);
1116 httpHeaderDelById(hdr
, HDR_PROXY_CONNECTION
);
1117 /* here: Keep-Alive is a field-name, not a connection directive! */
1118 httpHeaderDelByName(hdr
, "Keep-Alive");
1119 /* remove Set-Cookie if a hit */
1121 httpHeaderDelById(hdr
, HDR_SET_COOKIE
);
1122 /* handle Connection header */
1123 if (httpHeaderHas(hdr
, HDR_CONNECTION
)) {
1124 /* anything that matches Connection list member will be deleted */
1125 String strConnection
= httpHeaderGetList(hdr
, HDR_CONNECTION
);
1126 const HttpHeaderEntry
*e
;
1127 HttpHeaderPos pos
= HttpHeaderInitPos
;
1129 * think: on-average-best nesting of the two loops (hdrEntry
1130 * and strListItem) @?@
1133 * maybe we should delete standard stuff ("keep-alive","close")
1134 * from strConnection first?
1136 while ((e
= httpHeaderGetEntry(hdr
, &pos
))) {
1137 if (strListIsMember(&strConnection
, strBuf(e
->name
), ','))
1138 httpHeaderDelAt(hdr
, pos
);
1140 httpHeaderDelById(hdr
, HDR_CONNECTION
);
1141 stringClean(&strConnection
);
1145 clientBuildRangeHeader(http
, rep
);
1147 * Add Age header, not that our header must replace Age headers
1148 * from other caches if any
1150 if (http
->entry
->timestamp
> 0) {
1151 httpHeaderDelById(hdr
, HDR_AGE
);
1153 * we do not follow HTTP/1.1 precisely here becuase we rely
1154 * on Date header when computing entry->timestamp; we should
1155 * be using _request_ time if Date header is not available
1156 * or if it is out of sync
1158 httpHeaderPutInt(hdr
, HDR_AGE
,
1159 http
->entry
->timestamp
<= squid_curtime
?
1160 squid_curtime
- http
->entry
->timestamp
: 0);
1162 /* Append X-Cache */
1163 httpHeaderPutStrf(hdr
, HDR_X_CACHE
, "%s from %s",
1164 is_hit
? "HIT" : "MISS", getMyHostname());
1165 #if USE_CACHE_DIGESTS
1166 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1167 httpHeaderPutStrf(hdr
, HDR_X_CACHE_LOOKUP
, "%s from %s:%d",
1168 http
->lookup_type
? http
->lookup_type
: "NONE",
1169 getMyHostname(), Config
.Port
.http
->i
);
1171 if (httpReplyBodySize(request
->method
, http
->entry
->mem_obj
->reply
) < 0) {
1172 debug(33, 3) ("clientBuildReplyHeader: can't keep-alive, unknown body size\n");
1173 request
->flags
.proxy_keepalive
= 0;
1175 /* Signal keep-alive if needed */
1176 httpHeaderPutStr(hdr
,
1177 http
->flags
.accel
? HDR_CONNECTION
: HDR_PROXY_CONNECTION
,
1178 request
->flags
.proxy_keepalive
? "keep-alive" : "close");
1179 #if ADD_X_REQUEST_URI
1181 * Knowing the URI of the request is useful when debugging persistent
1182 * connections in a client; we cannot guarantee the order of http headers,
1183 * but X-Request-URI is likely to be the very last header to ease use from a
1184 * debugger [hdr->entries.count-1].
1186 httpHeaderPutStr(hdr
, HDR_X_REQUEST_URI
,
1187 http
->entry
->mem_obj
->url
? http
->entry
->mem_obj
->url
: http
->uri
);
1192 clientBuildReply(clientHttpRequest
* http
, const char *buf
, size_t size
)
1194 HttpReply
*rep
= httpReplyCreate();
1195 if (httpReplyParse(rep
, buf
)) {
1196 /* enforce 1.0 reply version */
1197 rep
->sline
.version
= 1.0;
1198 /* do header conversions */
1199 clientBuildReplyHeader(http
, rep
);
1200 /* if we do ranges, change status to "Partial Content" */
1201 if (http
->request
->range
)
1202 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
, HTTP_PARTIAL_CONTENT
, NULL
);
1204 /* parsing failure, get rid of the invalid reply */
1205 httpReplyDestroy(rep
);
1207 /* if we were going to do ranges, backoff */
1208 if (http
->request
->range
)
1209 clientBuildRangeHeader(http
, rep
); /* will fail and destroy request->range */
1215 * clientCacheHit should only be called until the HTTP reply headers
1216 * have been parsed. Normally this should be a single call, but
1217 * it might take more than one. As soon as we have the headers,
1218 * we hand off to clientSendMoreData, clientProcessExpired, or
1219 * clientProcessMiss.
1222 clientCacheHit(void *data
, char *buf
, ssize_t size
)
1224 clientHttpRequest
*http
= data
;
1225 StoreEntry
*e
= http
->entry
;
1227 request_t
*r
= http
->request
;
1228 debug(33, 3) ("clientCacheHit: %s, %d bytes\n", http
->uri
, (int) size
);
1229 if (http
->entry
== NULL
) {
1230 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1231 debug(33, 3) ("clientCacheHit: request aborted\n");
1233 } else if (size
< 0) {
1234 /* swap in failure */
1235 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1236 debug(33, 3) ("clientCacheHit: swapin failure for %s\n", http
->uri
);
1237 http
->log_type
= LOG_TCP_SWAPFAIL_MISS
;
1238 if ((e
= http
->entry
)) {
1240 storeUnregister(e
, http
);
1241 storeUnlockObject(e
);
1243 clientProcessMiss(http
);
1248 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
1249 if (mem
->reply
->sline
.status
== 0) {
1251 * we don't have full reply headers yet; either wait for more or
1252 * punt to clientProcessMiss.
1254 if (e
->mem_status
== IN_MEMORY
|| e
->store_status
== STORE_OK
) {
1255 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1256 clientProcessMiss(http
);
1257 } else if (size
== CLIENT_SOCK_SZ
&& http
->out
.offset
== 0) {
1258 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1259 clientProcessMiss(http
);
1261 debug(33, 3) ("clientCacheHit: waiting for HTTP reply headers\n");
1263 http
->out
.offset
+ size
,
1273 * Got the headers, now grok them
1275 assert(http
->log_type
== LOG_TCP_HIT
);
1276 if (checkNegativeHit(e
)) {
1277 http
->log_type
= LOG_TCP_NEGATIVE_HIT
;
1278 clientSendMoreData(data
, buf
, size
);
1279 } else if (r
->method
== METHOD_HEAD
) {
1281 * RFC 2068 seems to indicate there is no "conditional HEAD"
1282 * request. We cannot validate a cached object for a HEAD
1283 * request, nor can we return 304.
1285 if (e
->mem_status
== IN_MEMORY
)
1286 http
->log_type
= LOG_TCP_MEM_HIT
;
1287 clientSendMoreData(data
, buf
, size
);
1288 } else if (refreshCheckHTTP(e
, r
) && !http
->flags
.internal
) {
1289 debug(33, 5) ("clientCacheHit: in refreshCheck() block\n");
1291 * We hold a stale copy; it needs to be validated
1294 * The 'need_validation' flag is used to prevent forwarding
1295 * loops between siblings. If our copy of the object is stale,
1296 * then we should probably only use parents for the validation
1297 * request. Otherwise two siblings could generate a loop if
1298 * both have a stale version of the object.
1300 r
->flags
.need_validation
= 1;
1301 if (e
->lastmod
< 0) {
1303 * Previous reply didn't have a Last-Modified header,
1304 * we cannot revalidate it.
1306 http
->log_type
= LOG_TCP_MISS
;
1307 clientProcessMiss(http
);
1308 } else if (r
->flags
.nocache
) {
1310 * This did not match a refresh pattern that overrides no-cache
1311 * we should honour the client no-cache header.
1313 http
->log_type
= LOG_TCP_CLIENT_REFRESH_MISS
;
1314 clientProcessMiss(http
);
1315 } else if (r
->protocol
== PROTO_HTTP
) {
1317 * Object needs to be revalidated
1318 * XXX This could apply to FTP as well, if Last-Modified is known.
1320 http
->log_type
= LOG_TCP_REFRESH_MISS
;
1321 clientProcessExpired(http
);
1324 * We don't know how to re-validate other protocols. Handle
1325 * them as if the object has expired.
1327 http
->log_type
= LOG_TCP_MISS
;
1328 clientProcessMiss(http
);
1330 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1331 } else if (r
->flags
.ims
) {
1333 * Handle If-Modified-Since requests from the client
1335 if (mem
->reply
->sline
.status
!= HTTP_OK
) {
1336 debug(33, 4) ("clientCacheHit: Reply code %d != 200\n",
1337 mem
->reply
->sline
.status
);
1338 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1339 clientProcessMiss(http
);
1340 } else if (modifiedSince(e
, http
->request
)) {
1341 http
->log_type
= LOG_TCP_IMS_HIT
;
1342 clientSendMoreData(data
, buf
, size
);
1344 MemBuf mb
= httpPacked304Reply(e
->mem_obj
->reply
);
1345 http
->log_type
= LOG_TCP_IMS_HIT
;
1346 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1347 storeUnregister(e
, http
);
1348 storeUnlockObject(e
);
1349 e
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
1351 httpReplyParse(e
->mem_obj
->reply
, mb
.buf
);
1352 storeAppend(e
, mb
.buf
, mb
.size
);
1358 * plain ol' cache hit
1360 if (e
->mem_status
== IN_MEMORY
)
1361 http
->log_type
= LOG_TCP_MEM_HIT
;
1362 else if (Config
.onoff
.offline
)
1363 http
->log_type
= LOG_TCP_OFFLINE_HIT
;
1364 clientSendMoreData(data
, buf
, size
);
1368 /* put terminating boundary for multiparts */
1370 clientPackTermBound(String boundary
, MemBuf
* mb
)
1372 memBufPrintf(mb
, "\r\n--%s--\r\n", strBuf(boundary
));
1373 debug(33, 6) ("clientPackTermBound: buf offset: %d\n", mb
->size
);
1376 /* appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1378 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1386 debug(33, 5) ("clientPackRangeHdr: appending boundary: %s\n", strBuf(boundary
));
1387 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1388 memBufPrintf(mb
, "\r\n--%s\r\n", strBuf(boundary
));
1390 /* stuff the header with required entries and pack it */
1391 httpHeaderInit(&hdr
, hoReply
);
1392 if (httpHeaderHas(&rep
->header
, HDR_CONTENT_TYPE
))
1393 httpHeaderPutStr(&hdr
, HDR_CONTENT_TYPE
, httpHeaderGetStr(&rep
->header
, HDR_CONTENT_TYPE
));
1394 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1395 packerToMemInit(&p
, mb
);
1396 httpHeaderPackInto(&hdr
, &p
);
1398 httpHeaderClean(&hdr
);
1400 /* append <crlf> (we packed a header, not a reply) */
1401 memBufPrintf(mb
, crlf
);
1404 /* extracts a "range" from *buf and appends them to mb, updating all offsets and such */
1406 clientPackRange(clientHttpRequest
* http
, HttpHdrRangeIter
* i
, const char **buf
, ssize_t
* size
, MemBuf
* mb
)
1408 const size_t copy_sz
= i
->debt_size
<= *size
? i
->debt_size
: *size
;
1409 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1413 /* intersection of "have" and "need" ranges must not be empty */
1414 assert(body_off
< i
->spec
->offset
+ i
->spec
->length
);
1415 assert(body_off
+ *size
> i
->spec
->offset
);
1417 /* put boundary and headers at the beginning of a range in a multi-range */
1418 if (http
->request
->range
->specs
.count
> 1 && i
->debt_size
== i
->spec
->length
) {
1419 assert(http
->entry
->mem_obj
);
1421 http
->entry
->mem_obj
->reply
, /* original reply */
1422 i
->spec
, /* current range */
1423 i
->boundary
, /* boundary, the same for all */
1427 /* append content */
1428 debug(33, 3) ("clientPackRange: appending %d bytes\n", copy_sz
);
1429 memBufAppend(mb
, *buf
, copy_sz
);
1431 /* update offsets */
1433 i
->debt_size
-= copy_sz
;
1434 body_off
+= copy_sz
;
1436 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1438 /* paranoid check */
1439 assert(*size
>= 0 && i
->debt_size
>= 0);
1442 /* returns true if there is still data available to pack more ranges
1443 * increments iterator "i"
1444 * used by clientPackMoreRanges */
1446 clientCanPackMoreRanges(const clientHttpRequest
* http
, HttpHdrRangeIter
* i
, ssize_t size
)
1448 /* first update "i" if needed */
1449 if (!i
->debt_size
) {
1450 if ((i
->spec
= httpHdrRangeGetSpec(http
->request
->range
, &i
->pos
)))
1451 i
->debt_size
= i
->spec
->length
;
1453 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1454 /* continue condition: need_more_data && have_more_data */
1455 return i
->spec
&& size
> 0;
1458 /* extracts "ranges" from buf and appends them to mb, updating all offsets and such */
1459 /* returns true if we need more data */
1461 clientPackMoreRanges(clientHttpRequest
* http
, const char *buf
, ssize_t size
, MemBuf
* mb
)
1463 HttpHdrRangeIter
*i
= &http
->range_iter
;
1464 /* offset in range specs does not count the prefix of an http msg */
1465 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1467 /* check: reply was parsed and range iterator was initialized */
1468 assert(i
->prefix_size
> 0);
1469 /* filter out data according to range specs */
1470 while (clientCanPackMoreRanges(http
, i
, size
)) {
1471 off_t start
; /* offset of still missing data */
1473 start
= i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
;
1474 debug(33, 3) ("clientPackMoreRanges: in: offset: %d size: %d\n",
1475 (int) body_off
, size
);
1476 debug(33, 3) ("clientPackMoreRanges: out: start: %d spec[%d]: [%d, %d), len: %d debt: %d\n",
1477 (int) start
, (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
, i
->debt_size
);
1478 assert(body_off
<= start
); /* we did not miss it */
1479 /* skip up to start */
1480 if (body_off
+ size
> start
) {
1481 const size_t skip_size
= start
- body_off
;
1486 /* has not reached start yet */
1491 /* put next chunk if any */
1493 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1494 clientPackRange(http
, i
, &buf
, &size
, mb
);
1495 body_off
= http
->out
.offset
- i
->prefix_size
; /* sync */
1498 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1499 debug(33, 3) ("clientPackMoreRanges: buf exhausted: in: offset: %d size: %d need_more: %d\n",
1500 (int) body_off
, size
, i
->debt_size
);
1502 debug(33, 3) ("clientPackMoreRanges: need more: spec[%d]: [%d, %d), len: %d\n",
1503 (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
);
1504 /* skip the data we do not need if possible */
1505 if (i
->debt_size
== i
->spec
->length
) /* at the start of the cur. spec */
1506 body_off
= i
->spec
->offset
;
1508 assert(body_off
== i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
);
1509 } else if (http
->request
->range
->specs
.count
> 1) {
1510 /* put terminating boundary for multiparts */
1511 clientPackTermBound(i
->boundary
, mb
);
1513 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1514 return i
->debt_size
> 0;
1518 clientReplyBodyTooLarge(int clen
)
1520 if (0 == Config
.maxReplyBodySize
)
1521 return 0; /* disabled */
1523 return 0; /* unknown */
1524 if (clen
> Config
.maxReplyBodySize
)
1525 return 1; /* too large */
1530 * accepts chunk of a http message in buf, parses prefix, filters headers and
1531 * such, writes processed message to the client's socket
1534 clientSendMoreData(void *data
, char *buf
, ssize_t size
)
1536 clientHttpRequest
*http
= data
;
1537 StoreEntry
*entry
= http
->entry
;
1538 ConnStateData
*conn
= http
->conn
;
1540 HttpReply
*rep
= NULL
;
1541 const char *body_buf
= buf
;
1542 ssize_t body_size
= size
;
1544 ssize_t check_size
= 0;
1545 debug(33, 5) ("clientSendMoreData: %s, %d bytes\n", http
->uri
, (int) size
);
1546 assert(size
<= CLIENT_SOCK_SZ
);
1547 assert(http
->request
!= NULL
);
1548 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1549 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1550 debug(33, 5) ("clientSendMoreData: FD %d '%s', out.offset=%d \n",
1551 fd
, storeUrl(entry
), (int) http
->out
.offset
);
1552 if (conn
->chr
!= http
) {
1553 /* there is another object in progress, defer this one */
1554 debug(33, 1) ("clientSendMoreData: Deferring %s\n", storeUrl(entry
));
1555 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1557 } else if (entry
&& EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1558 /* call clientWriteComplete so the client socket gets closed */
1559 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1560 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1562 } else if (size
< 0) {
1563 /* call clientWriteComplete so the client socket gets closed */
1564 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1565 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1567 } else if (size
== 0) {
1568 /* call clientWriteComplete so the client socket gets closed */
1569 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1570 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1573 if (http
->out
.offset
== 0) {
1574 if (Config
.onoff
.log_mime_hdrs
) {
1576 if ((k
= headersEnd(buf
, size
))) {
1577 safe_free(http
->al
.headers
.reply
);
1578 http
->al
.headers
.reply
= xcalloc(k
+ 1, 1);
1579 xstrncpy(http
->al
.headers
.reply
, buf
, k
);
1582 rep
= clientBuildReply(http
, buf
, size
);
1583 if (clientReplyBodyTooLarge(rep
->content_length
)) {
1584 ErrorState
*err
= errorCon(ERR_TOO_BIG
, HTTP_FORBIDDEN
);
1585 err
->request
= requestLink(http
->request
);
1586 storeUnregister(http
->entry
, http
);
1587 storeUnlockObject(http
->entry
);
1588 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
1589 null_request_flags
);
1590 errorAppendEntry(http
->entry
, err
);
1593 body_size
= size
- rep
->hdr_sz
;
1594 assert(body_size
>= 0);
1595 body_buf
= buf
+ rep
->hdr_sz
;
1596 http
->range_iter
.prefix_size
= rep
->hdr_sz
;
1597 debug(33, 3) ("clientSendMoreData: Appending %d bytes after %d bytes of headers\n",
1598 body_size
, rep
->hdr_sz
);
1599 } else if (size
< CLIENT_SOCK_SZ
&& entry
->store_status
== STORE_PENDING
) {
1600 /* wait for more to arrive */
1601 storeClientCopy(entry
,
1602 http
->out
.offset
+ size
,
1610 /* reset range iterator */
1611 http
->range_iter
.pos
= HttpHdrRangeInitPos
;
1613 if (http
->request
->method
== METHOD_HEAD
) {
1615 /* do not forward body for HEAD replies */
1617 http
->flags
.done_copying
= 1;
1620 * If we are here, then store_status == STORE_OK and it
1621 * seems we have a HEAD repsponse which is missing the
1622 * empty end-of-headers line (home.mira.net, phttpd/0.99.72
1623 * does this). Because clientBuildReply() fails we just
1624 * call this reply a body, set the done_copying flag and
1627 http
->flags
.done_copying
= 1;
1630 /* write headers and/or body if any */
1631 assert(rep
|| (body_buf
&& body_size
));
1632 /* init mb; put status line and headers if any */
1634 mb
= httpReplyPack(rep
);
1635 http
->out
.offset
+= rep
->hdr_sz
;
1636 check_size
+= rep
->hdr_sz
;
1637 httpReplyDestroy(rep
);
1642 /* append body if any */
1643 if (http
->request
->range
) {
1644 /* Only GET requests should have ranges */
1645 assert(http
->request
->method
== METHOD_GET
);
1646 /* clientPackMoreRanges() updates http->out.offset */
1647 /* force the end of the transfer if we are done */
1648 if (!clientPackMoreRanges(http
, body_buf
, body_size
, &mb
))
1649 http
->flags
.done_copying
= 1;
1650 } else if (body_buf
&& body_size
) {
1651 http
->out
.offset
+= body_size
;
1652 check_size
+= body_size
;
1653 memBufAppend(&mb
, body_buf
, body_size
);
1655 if (!http
->request
->range
&& http
->request
->method
== METHOD_GET
)
1656 assert(check_size
== size
);
1658 comm_write_mbuf(fd
, mb
, clientWriteComplete
, http
);
1659 /* if we don't do it, who will? */
1660 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1664 clientKeepaliveNextRequest(clientHttpRequest
* http
)
1666 ConnStateData
*conn
= http
->conn
;
1668 debug(33, 3) ("clientKeepaliveNextRequest: FD %d\n", conn
->fd
);
1669 conn
->defer
.until
= 0; /* Kick it to read a new request */
1670 httpRequestFree(http
);
1671 if ((http
= conn
->chr
) == NULL
) {
1672 debug(33, 5) ("clientKeepaliveNextRequest: FD %d reading next req\n",
1674 fd_note(conn
->fd
, "Reading next request");
1676 * Set the timeout BEFORE calling clientReadRequest().
1678 commSetTimeout(conn
->fd
, 15, requestTimeout
, conn
);
1679 clientReadRequest(conn
->fd
, conn
); /* Read next request */
1681 * Note, the FD may be closed at this point.
1683 } else if ((entry
= http
->entry
) == NULL
) {
1685 * this request is in progress, maybe doing an ACL or a redirect,
1686 * execution will resume after the operation completes.
1689 debug(33, 1) ("clientKeepaliveNextRequest: FD %d Sending next\n",
1692 if (0 == storeClientCopyPending(entry
, http
)) {
1693 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1694 debug(33, 0) ("clientKeepaliveNextRequest: ENTRY_ABORTED\n");
1695 storeClientCopy(entry
,
1699 memAllocate(MEM_CLIENT_SOCK_BUF
),
1707 clientWriteComplete(int fd
, char *bufnotused
, size_t size
, int errflag
, void *data
)
1709 clientHttpRequest
*http
= data
;
1710 StoreEntry
*entry
= http
->entry
;
1712 http
->out
.size
+= size
;
1713 debug(33, 5) ("clientWriteComplete: FD %d, sz %d, err %d, off %d, len %d\n",
1714 fd
, size
, errflag
, (int) http
->out
.offset
, entry
? objectLen(entry
) : 0);
1716 kb_incr(&Counter
.client_http
.kbytes_out
, size
);
1717 if (isTcpHit(http
->log_type
))
1718 kb_incr(&Counter
.client_http
.hit_kbytes_out
, size
);
1722 * just close the socket, httpRequestFree will abort if needed
1725 } else if (NULL
== entry
) {
1726 comm_close(fd
); /* yuk */
1727 } else if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1729 } else if ((done
= clientCheckTransferDone(http
)) != 0 || size
== 0) {
1730 debug(33, 5) ("clientWriteComplete: FD %d transfer is DONE\n", fd
);
1731 /* We're finished case */
1732 if (http
->entry
->mem_obj
->reply
->content_length
< 0) {
1733 debug(33, 5) ("clientWriteComplete: closing, content_length < 0\n");
1736 debug(33, 5) ("clientWriteComplete: closing, !done\n");
1738 } else if (clientGotNotEnough(http
)) {
1739 debug(33, 5) ("clientWriteComplete: client didn't get all it expected\n");
1741 } else if (http
->request
->flags
.proxy_keepalive
) {
1742 debug(33, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd
);
1743 clientKeepaliveNextRequest(http
);
1747 } else if (clientReplyBodyTooLarge((int) http
->out
.offset
)) {
1750 /* More data will be coming from primary server; register with
1751 * storage manager. */
1752 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1753 debug(33, 0) ("clientWriteComplete 2: ENTRY_ABORTED\n");
1754 storeClientCopy(entry
,
1758 memAllocate(MEM_CLIENT_SOCK_BUF
),
1765 * client issued a request with an only-if-cached cache-control directive;
1766 * we did not find a cached object that can be returned without
1767 * contacting other servers;
1768 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
1771 clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
)
1773 char *url
= http
->uri
;
1774 request_t
*r
= http
->request
;
1775 ErrorState
*err
= NULL
;
1776 debug(33, 4) ("clientProcessOnlyIfCachedMiss: '%s %s'\n",
1777 RequestMethodStr
[r
->method
], url
);
1778 http
->al
.http
.code
= HTTP_GATEWAY_TIMEOUT
;
1779 err
= errorCon(ERR_ONLY_IF_CACHED_MISS
, HTTP_GATEWAY_TIMEOUT
);
1780 err
->request
= requestLink(r
);
1781 err
->src_addr
= http
->conn
->peer
.sin_addr
;
1783 storeUnregister(http
->entry
, http
);
1784 storeUnlockObject(http
->entry
);
1786 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1787 errorAppendEntry(http
->entry
, err
);
1791 clientProcessRequest2(clientHttpRequest
* http
)
1793 request_t
*r
= http
->request
;
1795 e
= http
->entry
= storeGetPublic(http
->uri
, r
->method
);
1796 if (r
->method
== METHOD_HEAD
&& e
== NULL
) {
1797 /* We can generate a HEAD reply from a cached GET object */
1798 e
= http
->entry
= storeGetPublic(http
->uri
, METHOD_GET
);
1800 #if USE_CACHE_DIGESTS
1801 http
->lookup_type
= e
? "HIT" : "MISS";
1804 /* this object isn't in the cache */
1805 debug(33, 3) ("clientProcessRequest2: storeGet() MISS\n");
1806 return LOG_TCP_MISS
;
1808 if (Config
.onoff
.offline
) {
1809 debug(33, 3) ("clientProcessRequest2: offline HIT\n");
1813 if (!storeEntryValidToSend(e
)) {
1814 debug(33, 3) ("clientProcessRequest2: !storeEntryValidToSend MISS\n");
1816 return LOG_TCP_MISS
;
1818 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1819 /* Special entries are always hits, no matter what the client says */
1820 debug(33, 3) ("clientProcessRequest2: ENTRY_SPECIAL HIT\n");
1825 if (r
->flags
.nocache_hack
) {
1826 /* if nocache_hack is set, nocache should always be clear, right? */
1827 assert(!r
->flags
.nocache
);
1828 ipcacheReleaseInvalid(r
->host
);
1831 if (e
->store_status
== STORE_PENDING
) {
1832 if (r
->flags
.nocache
|| r
->flags
.nocache_hack
) {
1833 debug(33, 3) ("Clearing no-cache for STORE_PENDING request\n\t%s\n",
1835 r
->flags
.nocache
= 0;
1836 r
->flags
.nocache_hack
= 0;
1840 if (r
->flags
.nocache
) {
1841 debug(33, 3) ("clientProcessRequest2: no-cache REFRESH MISS\n");
1843 ipcacheReleaseInvalid(r
->host
);
1844 return LOG_TCP_CLIENT_REFRESH_MISS
;
1846 if (r
->range
&& httpHdrRangeWillBeComplex(r
->range
)) {
1848 * Some clients break if we return "200 OK" for a Range
1849 * request. We would have to return "200 OK" for a _complex_
1850 * Range request that is also a HIT. Thus, let's prevent HITs
1851 * on complex Range requests
1853 debug(33, 3) ("clientProcessRequest2: complex range MISS\n");
1855 return LOG_TCP_MISS
;
1857 debug(33, 3) ("clientProcessRequest2: default HIT\n");
1863 clientProcessRequest(clientHttpRequest
* http
)
1865 char *url
= http
->uri
;
1866 request_t
*r
= http
->request
;
1867 int fd
= http
->conn
->fd
;
1869 debug(33, 4) ("clientProcessRequest: %s '%s'\n",
1870 RequestMethodStr
[r
->method
],
1872 if (r
->method
== METHOD_CONNECT
) {
1873 http
->log_type
= LOG_TCP_MISS
;
1874 sslStart(fd
, url
, r
, &http
->out
.size
);
1876 } else if (r
->method
== METHOD_PURGE
) {
1877 clientPurgeRequest(http
);
1879 } else if (r
->method
== METHOD_TRACE
) {
1880 if (r
->max_forwards
== 0) {
1881 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1882 storeReleaseRequest(http
->entry
);
1883 storeBuffer(http
->entry
);
1884 rep
= httpReplyCreate();
1885 httpReplySetHeaders(rep
, 1.0, HTTP_OK
, NULL
, "text/plain",
1886 httpRequestPrefixLen(r
), 0, squid_curtime
);
1887 httpReplySwapOut(rep
, http
->entry
);
1888 httpReplyDestroy(rep
);
1889 httpRequestSwapOut(r
, http
->entry
);
1890 storeComplete(http
->entry
);
1894 http
->log_type
= LOG_TCP_MISS
;
1895 } else if (pumpMethod(r
->method
)) {
1896 http
->log_type
= LOG_TCP_MISS
;
1897 /* XXX oof, POST can be cached! */
1898 pumpInit(fd
, r
, http
->uri
);
1900 http
->log_type
= clientProcessRequest2(http
);
1902 debug(33, 4) ("clientProcessRequest: %s for '%s'\n",
1903 log_tags
[http
->log_type
],
1905 http
->out
.offset
= 0;
1906 if (NULL
!= http
->entry
) {
1907 storeLockObject(http
->entry
);
1908 storeCreateMemObject(http
->entry
, http
->uri
, http
->log_uri
);
1909 http
->entry
->mem_obj
->method
= r
->method
;
1910 storeClientListAdd(http
->entry
, http
);
1912 delaySetStoreClient(http
->entry
, http
, delayClient(r
));
1914 http
->entry
->refcount
++;
1915 storeClientCopy(http
->entry
,
1919 memAllocate(MEM_CLIENT_SOCK_BUF
),
1924 http
->log_type
= LOG_TCP_MISS
;
1925 clientProcessMiss(http
);
1930 * Prepare to fetch the object as it's a cache miss of some kind.
1933 clientProcessMiss(clientHttpRequest
* http
)
1935 char *url
= http
->uri
;
1936 request_t
*r
= http
->request
;
1937 ErrorState
*err
= NULL
;
1938 debug(33, 4) ("clientProcessMiss: '%s %s'\n",
1939 RequestMethodStr
[r
->method
], url
);
1941 * We might have a left-over StoreEntry from a failed cache hit
1945 if (EBIT_TEST(http
->entry
->flags
, ENTRY_SPECIAL
))
1946 debug(33, 0) ("clientProcessMiss: miss on a special object (%s).\n", url
);
1947 storeUnregister(http
->entry
, http
);
1948 storeUnlockObject(http
->entry
);
1951 if (clientOnlyIfCached(http
)) {
1952 clientProcessOnlyIfCachedMiss(http
);
1956 * Deny loops when running in accelerator/transproxy mode.
1958 if (http
->flags
.accel
&& r
->flags
.loopdetect
) {
1959 http
->al
.http
.code
= HTTP_FORBIDDEN
;
1960 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
1961 err
->request
= requestLink(r
);
1962 err
->src_addr
= http
->conn
->peer
.sin_addr
;
1963 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1964 errorAppendEntry(http
->entry
, err
);
1967 assert(http
->out
.offset
== 0);
1968 http
->entry
= clientCreateStoreEntry(http
, r
->method
, r
->flags
);
1969 http
->entry
->refcount
++;
1970 if (http
->redirect
.status
) {
1971 HttpReply
*rep
= httpReplyCreate();
1972 storeReleaseRequest(http
->entry
);
1973 httpRedirectReply(rep
, http
->redirect
.status
, http
->redirect
.location
);
1974 httpReplySwapOut(rep
, http
->entry
);
1975 httpReplyDestroy(rep
);
1976 storeComplete(http
->entry
);
1979 if (http
->flags
.internal
)
1980 r
->protocol
= PROTO_INTERNAL
;
1981 fwdStart(http
->conn
->fd
, http
->entry
, r
,
1982 http
->conn
->peer
.sin_addr
, http
->conn
->me
.sin_addr
);
1985 static clientHttpRequest
*
1986 parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
)
1988 clientHttpRequest
*http
= xcalloc(1, sizeof(clientHttpRequest
));
1989 cbdataAdd(http
, cbdataXfree
, 0);
1991 http
->start
= current_time
;
1992 http
->req_sz
= conn
->in
.offset
;
1993 http
->uri
= xstrdup(uri
);
1994 http
->log_uri
= xstrndup(uri
, MAX_URL
);
1995 http
->range_iter
.boundary
= StringNull
;
1996 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2001 * parseHttpRequest()
2004 * NULL on error or incomplete request
2005 * a clientHttpRequest structure on success
2007 static clientHttpRequest
*
2008 parseHttpRequest(ConnStateData
* conn
, method_t
* method_p
, int *status
,
2009 char **prefix_p
, size_t * req_line_sz_p
)
2014 char *req_hdr
= NULL
;
2019 int free_request
= 0;
2020 size_t header_sz
; /* size of headers, not including first line */
2021 size_t prefix_sz
; /* size of whole request (req-line + headers) */
2025 clientHttpRequest
*http
= NULL
;
2027 struct natlookup natLookup
;
2028 static int natfd
= -1;
2031 if ((req_sz
= headersEnd(conn
->in
.buf
, conn
->in
.offset
)) == 0) {
2032 debug(33, 5) ("Incomplete request, waiting for end of headers\n");
2035 *method_p
= METHOD_NONE
;
2038 assert(req_sz
<= conn
->in
.offset
);
2039 /* Use memcpy, not strdup! */
2040 inbuf
= xmalloc(req_sz
+ 1);
2041 xmemcpy(inbuf
, conn
->in
.buf
, req_sz
);
2042 *(inbuf
+ req_sz
) = '\0';
2044 /* pre-set these values to make aborting simpler */
2046 *method_p
= METHOD_NONE
;
2049 /* Barf on NULL characters in the headers */
2050 if (strlen(inbuf
) != req_sz
) {
2051 debug(33, 1) ("parseHttpRequest: Requestheader contains NULL characters\n");
2052 return parseHttpRequestAbort(conn
, "error:invalid-request");
2054 /* Look for request method */
2055 if ((mstr
= strtok(inbuf
, "\t ")) == NULL
) {
2056 debug(33, 1) ("parseHttpRequest: Can't get request method\n");
2057 return parseHttpRequestAbort(conn
, "error:invalid-request-method");
2059 method
= urlParseMethod(mstr
);
2060 if (method
== METHOD_NONE
) {
2061 debug(33, 1) ("parseHttpRequest: Unsupported method '%s'\n", mstr
);
2062 return parseHttpRequestAbort(conn
, "error:unsupported-request-method");
2064 debug(33, 5) ("parseHttpRequest: Method is '%s'\n", mstr
);
2067 /* look for URL+HTTP/x.x */
2068 if ((url
= strtok(NULL
, "\n")) == NULL
) {
2069 debug(33, 1) ("parseHttpRequest: Missing URL\n");
2070 return parseHttpRequestAbort(conn
, "error:missing-url");
2072 while (xisspace(*url
))
2074 t
= url
+ strlen(url
);
2079 if (xisspace(*t
) && !strncmp(t
+ 1, "HTTP/", 5)) {
2084 while (t
> url
&& xisspace(*t
))
2086 debug(33, 5) ("parseHttpRequest: URI is '%s'\n", url
);
2087 if (token
== NULL
) {
2088 debug(33, 3) ("parseHttpRequest: Missing HTTP identifier\n");
2089 #if RELAXED_HTTP_PARSER
2090 http_ver
= (float) 0.9; /* wild guess */
2092 return parseHttpRequestAbort(conn
, "error:missing-http-ident");
2095 http_ver
= (float) atof(token
+ 5);
2099 * Process headers after request line
2101 req_hdr
= strtok(NULL
, null_string
);
2102 header_sz
= req_sz
- (req_hdr
- inbuf
);
2103 if (0 == header_sz
) {
2104 debug(33, 3) ("parseHttpRequest: header_sz == 0\n");
2108 assert(header_sz
> 0);
2109 debug(33, 3) ("parseHttpRequest: req_hdr = {%s}\n", req_hdr
);
2110 end
= req_hdr
+ header_sz
;
2111 debug(33, 3) ("parseHttpRequest: end = {%s}\n", end
);
2113 prefix_sz
= end
- inbuf
;
2114 *req_line_sz_p
= req_hdr
- inbuf
;
2115 debug(33, 3) ("parseHttpRequest: prefix_sz = %d, req_line_sz = %d\n",
2116 (int) prefix_sz
, (int) *req_line_sz_p
);
2117 assert(prefix_sz
<= conn
->in
.offset
);
2119 /* Ok, all headers are received */
2120 http
= xcalloc(1, sizeof(clientHttpRequest
));
2121 cbdataAdd(http
, cbdataXfree
, 0);
2122 http
->http_ver
= http_ver
;
2124 http
->start
= current_time
;
2125 http
->req_sz
= prefix_sz
;
2126 http
->range_iter
.boundary
= StringNull
;
2127 *prefix_p
= xmalloc(prefix_sz
+ 1);
2128 xmemcpy(*prefix_p
, conn
->in
.buf
, prefix_sz
);
2129 *(*prefix_p
+ prefix_sz
) = '\0';
2130 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2132 debug(33, 5) ("parseHttpRequest: Request Header is\n%s\n", (*prefix_p
) + *req_line_sz_p
);
2133 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2136 /* handle internal objects */
2137 if (internalCheck(url
)) {
2138 /* prepend our name & port */
2139 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2140 http
->flags
.internal
= 1;
2141 http
->flags
.accel
= 1;
2143 /* see if we running in Config2.Accel.on, if so got to convert it to URL */
2144 else if (Config2
.Accel
.on
&& *url
== '/') {
2145 /* prepend the accel prefix */
2146 if (opt_accel_uses_host
&& (t
= mime_get_header(req_hdr
, "Host"))) {
2147 /* If a Host: header was specified, use it to build the URL
2148 * instead of the one in the Config file. */
2150 * XXX Use of the Host: header here opens a potential
2151 * security hole. There are no checks that the Host: value
2152 * corresponds to one of your servers. It might, for example,
2153 * refer to www.playboy.com. The 'dst' and/or 'dst_domain' ACL
2154 * types should be used to prevent httpd-accelerators
2155 * handling requests for non-local servers */
2157 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2159 http
->uri
= xcalloc(url_sz
, 1);
2160 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2161 t
, (int) Config
.Accel
.port
, url
);
2162 } else if (vhost_mode
) {
2163 /* Put the local socket IP address as the hostname */
2164 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2165 http
->uri
= xcalloc(url_sz
, 1);
2167 natLookup
.nl_inport
= http
->conn
->me
.sin_port
;
2168 natLookup
.nl_outport
= http
->conn
->peer
.sin_port
;
2169 natLookup
.nl_inip
= http
->conn
->me
.sin_addr
;
2170 natLookup
.nl_outip
= http
->conn
->peer
.sin_addr
;
2171 natLookup
.nl_flags
= IPN_TCP
;
2173 natfd
= open(IPL_NAT
, O_RDONLY
, 0);
2175 debug(50, 1) ("parseHttpRequest: NAT open failed: %s\n",
2177 return parseHttpRequestAbort(conn
, "error:nat-open-failed");
2179 if (ioctl(natfd
, SIOCGNATL
, &natLookup
) < 0) {
2180 if (errno
!= ESRCH
) {
2181 debug(50, 1) ("parseHttpRequest: NAT lookup failed: ioctl(SIOCGNATL)\n");
2184 return parseHttpRequestAbort(conn
, "error:nat-lookup-failed");
2186 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2187 inet_ntoa(http
->conn
->me
.sin_addr
),
2188 (int) Config
.Accel
.port
,
2191 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2192 inet_ntoa(natLookup
.nl_realip
),
2193 (int) Config
.Accel
.port
,
2196 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2197 inet_ntoa(http
->conn
->me
.sin_addr
),
2198 (int) Config
.Accel
.port
,
2201 debug(33, 5) ("VHOST REWRITE: '%s'\n", http
->uri
);
2203 url_sz
= strlen(Config2
.Accel
.prefix
) + strlen(url
) +
2204 Config
.appendDomainLen
+ 1;
2205 http
->uri
= xcalloc(url_sz
, 1);
2206 snprintf(http
->uri
, url_sz
, "%s%s", Config2
.Accel
.prefix
, url
);
2208 http
->flags
.accel
= 1;
2210 /* URL may be rewritten later, so make extra room */
2211 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2212 http
->uri
= xcalloc(url_sz
, 1);
2213 strcpy(http
->uri
, url
);
2214 http
->flags
.accel
= 0;
2216 if (!stringHasWhitespace(http
->uri
))
2217 http
->log_uri
= xstrndup(http
->uri
, MAX_URL
);
2219 http
->log_uri
= xstrndup(rfc1738_escape(http
->uri
), MAX_URL
);
2220 debug(33, 5) ("parseHttpRequest: Complete request received\n");
2229 clientReadDefer(int fdnotused
, void *data
)
2231 ConnStateData
*conn
= data
;
2232 return conn
->defer
.until
> squid_curtime
;
2236 clientReadRequest(int fd
, void *data
)
2238 ConnStateData
*conn
= data
;
2239 int parser_return_code
= 0;
2241 request_t
*request
= NULL
;
2244 clientHttpRequest
*http
= NULL
;
2245 clientHttpRequest
**H
= NULL
;
2246 char *prefix
= NULL
;
2247 ErrorState
*err
= NULL
;
2248 fde
*F
= &fd_table
[fd
];
2249 int len
= conn
->in
.size
- conn
->in
.offset
- 1;
2250 debug(33, 4) ("clientReadRequest: FD %d: reading request...\n", fd
);
2251 Counter
.syscalls
.sock
.reads
++;
2252 size
= read(fd
, conn
->in
.buf
+ conn
->in
.offset
, len
);
2254 fd_bytes(fd
, size
, FD_READ
);
2255 kb_incr(&Counter
.client_http
.kbytes_in
, size
);
2258 * Don't reset the timeout value here. The timeout value will be
2259 * set to Config.Timeout.request by httpAccept() and
2260 * clientWriteComplete(), and should apply to the request as a
2261 * whole, not individual read() calls. Plus, it breaks our
2262 * lame half-close detection
2264 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, conn
, 0);
2266 if (conn
->chr
== NULL
) {
2267 /* no current or pending requests */
2270 } else if (!Config
.onoff
.half_closed_clients
) {
2271 /* admin doesn't want to support half-closed client sockets */
2275 /* It might be half-closed, we can't tell */
2276 debug(33, 5) ("clientReadRequest: FD %d closed?\n", fd
);
2277 F
->flags
.socket_eof
= 1;
2278 conn
->defer
.until
= squid_curtime
+ 1;
2280 fd_note(fd
, "half-closed");
2282 } else if (size
< 0) {
2283 if (!ignoreErrno(errno
)) {
2284 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd
, xstrerror());
2287 } else if (conn
->in
.offset
== 0) {
2288 debug(50, 2) ("clientReadRequest: FD %d: no data to process (%s)\n", fd
, xstrerror());
2291 /* Continue to process previously read data */
2294 conn
->in
.offset
+= size
;
2295 /* Skip leading (and trailing) whitespace */
2296 while (conn
->in
.offset
> 0) {
2299 while (conn
->in
.offset
> 0 && xisspace(conn
->in
.buf
[0])) {
2300 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.offset
- 1);
2303 conn
->in
.buf
[conn
->in
.offset
] = '\0'; /* Terminate the string */
2304 if (conn
->in
.offset
== 0)
2306 /* Limit the number of concurrent requests to 2 */
2307 for (H
= &conn
->chr
, nrequests
= 0; *H
; H
= &(*H
)->next
, nrequests
++);
2308 if (nrequests
>= 2) {
2309 debug(33, 3) ("clientReadRequest: FD %d max concurrent requests reached\n", fd
);
2310 debug(33, 5) ("clientReadRequest: FD %d defering new request until one is done\n", fd
);
2311 conn
->defer
.until
= squid_curtime
+ 100; /* Reset when a request is complete */
2314 /* Process request */
2315 http
= parseHttpRequest(conn
,
2317 &parser_return_code
,
2323 assert(http
->req_sz
> 0);
2324 conn
->in
.offset
-= http
->req_sz
;
2325 assert(conn
->in
.offset
>= 0);
2326 debug(33, 5) ("conn->in.offset = %d\n", (int) conn
->in
.offset
);
2328 * If we read past the end of this request, move the remaining
2329 * data to the beginning
2331 if (conn
->in
.offset
> 0)
2332 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ http
->req_sz
, conn
->in
.offset
);
2333 /* add to the client request queue */
2334 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2337 commSetTimeout(fd
, Config
.Timeout
.lifetime
, NULL
, NULL
);
2338 if (parser_return_code
< 0) {
2339 debug(33, 1) ("clientReadRequest: FD %d Invalid Request\n", fd
);
2340 err
= errorCon(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
);
2341 err
->request_hdrs
= xstrdup(conn
->in
.buf
);
2342 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2343 errorAppendEntry(http
->entry
, err
);
2347 if ((request
= urlParse(method
, http
->uri
)) == NULL
) {
2348 debug(33, 5) ("Invalid URL: %s\n", http
->uri
);
2349 err
= errorCon(ERR_INVALID_URL
, HTTP_BAD_REQUEST
);
2350 err
->src_addr
= conn
->peer
.sin_addr
;
2351 err
->url
= xstrdup(http
->uri
);
2352 http
->al
.http
.code
= err
->http_status
;
2353 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2354 errorAppendEntry(http
->entry
, err
);
2358 /* compile headers */
2359 /* we should skip request line! */
2360 if (!httpRequestParseHeader(request
, prefix
+ req_line_sz
))
2361 debug(33, 1) ("Failed to parse request headers: %s\n%s\n",
2363 /* continue anyway? */
2365 request
->flags
.accelerated
= http
->flags
.accel
;
2366 if (!http
->flags
.internal
) {
2367 if (internalCheck(strBuf(request
->urlpath
))) {
2368 if (0 == strcasecmp(request
->host
, internalHostname()) &&
2369 request
->port
== Config
.Port
.http
->i
) {
2370 http
->flags
.internal
= 1;
2371 } else if (internalStaticCheck(strBuf(request
->urlpath
))) {
2372 xstrncpy(request
->host
, internalHostname(), SQUIDHOSTNAMELEN
);
2373 request
->port
= Config
.Port
.http
->i
;
2374 http
->flags
.internal
= 1;
2378 request
->flags
.internal
= http
->flags
.internal
;
2380 safe_free(http
->log_uri
);
2381 http
->log_uri
= xstrdup(urlCanonicalClean(request
));
2382 request
->client_addr
= conn
->peer
.sin_addr
;
2383 request
->my_addr
= conn
->me
.sin_addr
;
2384 request
->http_ver
= http
->http_ver
;
2385 if (!urlCheckRequest(request
)) {
2386 err
= errorCon(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
);
2387 err
->src_addr
= conn
->peer
.sin_addr
;
2388 err
->request
= requestLink(request
);
2389 http
->al
.http
.code
= err
->http_status
;
2390 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2391 errorAppendEntry(http
->entry
, err
);
2394 if (0 == clientCheckContentLength(request
)) {
2395 err
= errorCon(ERR_INVALID_REQ
, HTTP_LENGTH_REQUIRED
);
2396 err
->src_addr
= conn
->peer
.sin_addr
;
2397 err
->request
= requestLink(request
);
2398 http
->al
.http
.code
= err
->http_status
;
2399 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2400 errorAppendEntry(http
->entry
, err
);
2403 http
->request
= requestLink(request
);
2405 * We need to set the keepalive flag before doing some
2406 * hacks for POST/PUT requests below. Maybe we could
2407 * set keepalive flag even earlier.
2409 clientSetKeepaliveFlag(http
);
2411 * break here for NON-GET because most likely there is a
2412 * reqeust body following and we don't want to parse it
2413 * as though it was new request
2415 if (request
->method
!= METHOD_GET
) {
2416 int cont_len
= httpHeaderGetInt(&request
->header
, HDR_CONTENT_LENGTH
);
2417 int copy_len
= XMIN(conn
->in
.offset
, cont_len
);
2419 assert(conn
->in
.offset
>= copy_len
);
2420 request
->body_sz
= copy_len
;
2421 request
->body
= xmalloc(request
->body_sz
);
2422 xmemcpy(request
->body
, conn
->in
.buf
, request
->body_sz
);
2423 conn
->in
.offset
-= copy_len
;
2424 if (conn
->in
.offset
)
2425 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ copy_len
, conn
->in
.offset
);
2428 * if we didn't get the full body now, then more will
2429 * be arriving on the client socket. Lets cancel
2430 * the read handler until this request gets forwarded.
2432 if (request
->body_sz
< cont_len
)
2433 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2434 if (cont_len
> Config
.maxRequestBodySize
) {
2435 err
= errorCon(ERR_INVALID_REQ
,
2436 HTTP_REQUEST_ENTITY_TOO_LARGE
);
2437 err
->request
= requestLink(request
);
2438 http
->entry
= clientCreateStoreEntry(http
,
2439 METHOD_NONE
, null_request_flags
);
2440 errorAppendEntry(http
->entry
, err
);
2444 clientAccessCheck(http
);
2445 continue; /* while offset > 0 */
2446 } else if (parser_return_code
== 0) {
2448 * Partial request received; reschedule until parseHttpRequest()
2449 * is happy with the input
2451 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2453 if (conn
->in
.offset
>= Config
.maxRequestHeaderSize
) {
2454 /* The request is too large to handle */
2455 debug(33, 0) ("Request won't fit in buffer.\n");
2456 debug(33, 0) ("Config 'request_header_max_size'= %d bytes.\n",
2457 Config
.maxRequestHeaderSize
);
2458 debug(33, 0) ("This request = %d bytes.\n",
2459 (int) conn
->in
.offset
);
2460 err
= errorCon(ERR_TOO_BIG
, HTTP_REQUEST_ENTITY_TOO_LARGE
);
2461 http
= parseHttpRequestAbort(conn
, "error:request-too-large");
2462 /* add to the client request queue */
2463 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2465 http
->entry
= clientCreateStoreEntry(http
, METHOD_NONE
, null_request_flags
);
2466 errorAppendEntry(http
->entry
, err
);
2469 /* Grow the request memory area to accomodate for a large request */
2470 conn
->in
.size
+= REQUEST_BUF_SIZE
;
2471 conn
->in
.buf
= xrealloc(conn
->in
.buf
, conn
->in
.size
);
2472 /* XXX account conn->in.buf */
2473 debug(33, 3) ("Handling a large request, offset=%d inbufsize=%d\n",
2474 (int) conn
->in
.offset
, conn
->in
.size
);
2475 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2482 /* general lifetime handler for HTTP requests */
2484 requestTimeout(int fd
, void *data
)
2486 ConnStateData
*conn
= data
;
2488 debug(33, 3) ("requestTimeout: FD %d: lifetime is expired.\n", fd
);
2489 if (fd_table
[fd
].rwstate
) {
2491 * Some data has been sent to the client, just close the FD
2494 } else if (conn
->nrequests
) {
2496 * assume its a persistent connection; just close it
2503 err
= errorCon(ERR_LIFETIME_EXP
, HTTP_REQUEST_TIMEOUT
);
2504 err
->url
= xstrdup("N/A");
2506 * Normally we shouldn't call errorSend() in client_side.c, but
2507 * it should be okay in this case. Presumably if we get here
2508 * this is the first request for the connection, and no data
2509 * has been written yet
2511 assert(conn
->chr
== NULL
);
2514 * if we don't close() here, we still need a timeout handler!
2516 commSetTimeout(fd
, 30, requestTimeout
, conn
);
2521 httpAcceptDefer(void)
2523 static time_t last_warn
= 0;
2524 if (fdNFree() >= RESERVED_FD
)
2526 if (last_warn
+ 15 < squid_curtime
) {
2527 debug(33, 0) ("WARNING! Your cache is running out of filedescriptors\n");
2528 last_warn
= squid_curtime
;
2533 /* Handle a new connection on HTTP socket. */
2535 httpAccept(int sock
, void *data
)
2539 ConnStateData
*connState
= NULL
;
2540 struct sockaddr_in peer
;
2541 struct sockaddr_in me
;
2542 int max
= INCOMING_HTTP_MAX
;
2544 static aclCheck_t identChecklist
;
2546 commSetSelect(sock
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2547 while (max
-- && !httpAcceptDefer()) {
2548 memset(&peer
, '\0', sizeof(struct sockaddr_in
));
2549 memset(&me
, '\0', sizeof(struct sockaddr_in
));
2550 if ((fd
= comm_accept(sock
, &peer
, &me
)) < 0) {
2551 if (!ignoreErrno(errno
))
2552 debug(50, 1) ("httpAccept: FD %d: accept failure: %s\n",
2556 debug(33, 4) ("httpAccept: FD %d: accepted\n", fd
);
2557 connState
= xcalloc(1, sizeof(ConnStateData
));
2558 connState
->peer
= peer
;
2559 connState
->log_addr
= peer
.sin_addr
;
2560 connState
->log_addr
.s_addr
&= Config
.Addrs
.client_netmask
.s_addr
;
2563 connState
->in
.size
= REQUEST_BUF_SIZE
;
2564 connState
->in
.buf
= xcalloc(connState
->in
.size
, 1);
2565 cbdataAdd(connState
, cbdataXfree
, 0);
2566 /* XXX account connState->in.buf */
2567 comm_add_close_handler(fd
, connStateFree
, connState
);
2568 if (Config
.onoff
.log_fqdn
)
2569 fqdncache_gethostbyaddr(peer
.sin_addr
, FQDN_LOOKUP_IF_MISS
);
2570 commSetTimeout(fd
, Config
.Timeout
.request
, requestTimeout
, connState
);
2572 identChecklist
.src_addr
= peer
.sin_addr
;
2573 identChecklist
.my_addr
= me
.sin_addr
;
2574 if (aclCheckFast(Config
.accessList
.identLookup
, &identChecklist
))
2575 identStart(&me
, &peer
, clientIdentDone
, connState
);
2577 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, connState
, 0);
2578 commSetDefer(fd
, clientReadDefer
, connState
);
2583 #define SENDING_BODY 0
2584 #define SENDING_HDRSONLY 1
2586 clientCheckTransferDone(clientHttpRequest
* http
)
2588 int sending
= SENDING_BODY
;
2589 StoreEntry
*entry
= http
->entry
;
2596 * For now, 'done_copying' is used for special cases like
2597 * Range and HEAD requests.
2599 if (http
->flags
.done_copying
)
2602 * Handle STORE_OK objects.
2603 * objectLen(entry) will be set proprely.
2605 if (entry
->store_status
== STORE_OK
) {
2606 if (http
->out
.offset
>= objectLen(entry
))
2612 * Now, handle STORE_PENDING objects
2614 mem
= entry
->mem_obj
;
2615 assert(mem
!= NULL
);
2616 assert(http
->request
!= NULL
);
2618 if (reply
->hdr_sz
== 0)
2619 return 0; /* haven't found end of headers yet */
2620 else if (reply
->sline
.status
== HTTP_OK
)
2621 sending
= SENDING_BODY
;
2622 else if (reply
->sline
.status
== HTTP_NO_CONTENT
)
2623 sending
= SENDING_HDRSONLY
;
2624 else if (reply
->sline
.status
== HTTP_NOT_MODIFIED
)
2625 sending
= SENDING_HDRSONLY
;
2626 else if (reply
->sline
.status
< HTTP_OK
)
2627 sending
= SENDING_HDRSONLY
;
2628 else if (http
->request
->method
== METHOD_HEAD
)
2629 sending
= SENDING_HDRSONLY
;
2631 sending
= SENDING_BODY
;
2633 * Figure out how much data we are supposed to send.
2634 * If we are sending a body and we don't have a content-length,
2635 * then we must wait for the object to become STORE_OK.
2637 if (sending
== SENDING_HDRSONLY
)
2638 sendlen
= reply
->hdr_sz
;
2639 else if (reply
->content_length
< 0)
2642 sendlen
= reply
->content_length
+ reply
->hdr_sz
;
2644 * Now that we have the expected length, did we send it all?
2646 if (http
->out
.offset
< sendlen
)
2653 clientGotNotEnough(clientHttpRequest
* http
)
2655 int cl
= http
->entry
->mem_obj
->reply
->content_length
;
2656 int hs
= http
->entry
->mem_obj
->reply
->hdr_sz
;
2658 if (http
->out
.offset
< cl
+ hs
)
2664 * This function is designed to serve a fairly specific purpose.
2665 * Occasionally our vBNS-connected caches can talk to each other, but not
2666 * the rest of the world. Here we try to detect frequent failures which
2667 * make the cache unusable (e.g. DNS lookup and connect() failures). If
2668 * the failure:success ratio goes above 1.0 then we go into "hit only"
2669 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
2670 * will only fetch HITs from us if they are using the ICP protocol. We
2671 * stay in this mode for 5 minutes.
2673 * Duane W., Sept 16, 1996
2677 checkFailureRatio(err_type etype
, hier_code hcode
)
2679 static double magic_factor
= 100.0;
2682 if (hcode
== HIER_NONE
)
2684 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
2685 n_bad
= magic_factor
- n_good
;
2688 case ERR_CONNECT_FAIL
:
2689 case ERR_READ_ERROR
:
2695 request_failure_ratio
= n_bad
/ n_good
;
2696 if (hit_only_mode_until
> squid_curtime
)
2698 if (request_failure_ratio
< 1.0)
2700 debug(33, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio
);
2701 debug(33, 0) ("Going into hit-only-mode for %d minutes...\n",
2702 FAILURE_MODE_TIME
/ 60);
2703 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
2704 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
2708 clientHttpConnectionsOpen(void)
2712 for (u
= Config
.Port
.http
; u
; u
= u
->next
) {
2714 fd
= comm_open(SOCK_STREAM
,
2716 Config
.Addrs
.tcp_incoming
,
2724 commSetSelect(fd
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2725 /*commSetDefer(fd, httpAcceptDefer, NULL); */
2726 debug(1, 1) ("Accepting HTTP connections on port %d, FD %d.\n",
2728 HttpSockets
[NHttpSockets
++] = fd
;
2730 if (NHttpSockets
< 1)
2731 fatal("Cannot open HTTP Port");
2735 clientHttpConnectionsClose(void)
2738 for (i
= 0; i
< NHttpSockets
; i
++) {
2739 if (HttpSockets
[i
] >= 0) {
2740 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets
[i
]);
2741 comm_close(HttpSockets
[i
]);
2742 HttpSockets
[i
] = -1;