3 * $Id: client_side.cc,v 1.496 2000/08/03 21:27:54 hno 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 * the Regents of the University of California. Please see the
16 * COPYRIGHT file for full details. Squid incorporates software
17 * developed and/or copyrighted by other sources. Please see the
18 * 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 #if HAVE_IP_FIL_COMPAT_H
45 #include <ip_fil_compat.h>
46 #elif HAVE_NETINET_IP_FIL_COMPAT_H
47 #include <netinet/ip_fil_compat.h>
48 #elif HAVE_IP_COMPAT_H
49 #include <ip_compat.h>
50 #elif HAVE_NETINET_IP_COMPAT_H
51 #include <netinet/ip_compat.h>
55 #elif HAVE_NETINET_IP_FIL_H
56 #include <netinet/ip_fil.h>
60 #elif HAVE_NETINET_IP_NAT_H
61 #include <netinet/ip_nat.h>
68 #define comm_close comm_lingering_close
71 static const char *const crlf
= "\r\n";
73 #define REQUEST_BUF_SIZE 4096
74 #define FAILURE_MODE_TIME 300
78 static CWCB clientWriteComplete
;
79 static CWCB clientWriteBodyComplete
;
80 static PF clientReadRequest
;
81 static PF connStateFree
;
82 static PF requestTimeout
;
83 static int clientCheckTransferDone(clientHttpRequest
*);
84 static int clientGotNotEnough(clientHttpRequest
*);
85 static void checkFailureRatio(err_type
, hier_code
);
86 static void clientProcessMiss(clientHttpRequest
*);
87 static void clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
);
88 static clientHttpRequest
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
89 static clientHttpRequest
*parseHttpRequest(ConnStateData
*, method_t
*, int *, char **, size_t *);
90 static RH clientRedirectDone
;
91 static void clientCheckNoCache(clientHttpRequest
*);
92 static void clientCheckNoCacheDone(int answer
, void *data
);
93 static STCB clientHandleIMSReply
;
94 static int clientGetsOldEntry(StoreEntry
* new, StoreEntry
* old
, request_t
* request
);
95 static int checkAccelOnly(clientHttpRequest
*);
97 static IDCB clientIdentDone
;
99 static int clientOnlyIfCached(clientHttpRequest
* http
);
100 static STCB clientSendMoreData
;
101 static STCB clientCacheHit
;
102 static void clientSetKeepaliveFlag(clientHttpRequest
*);
103 static void clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
);
104 static void clientPackTermBound(String boundary
, MemBuf
* mb
);
105 static void clientInterpretRequestHeaders(clientHttpRequest
*);
106 static void clientProcessRequest(clientHttpRequest
*);
107 static void clientProcessExpired(void *data
);
108 static void clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
);
109 static int clientCachable(clientHttpRequest
* http
);
110 static int clientHierarchical(clientHttpRequest
* http
);
111 static int clientCheckContentLength(request_t
* r
);
112 static DEFER httpAcceptDefer
;
113 static log_type
clientProcessRequest2(clientHttpRequest
* http
);
114 static int clientReplyBodyTooLarge(int clen
);
115 static int clientRequestBodyTooLarge(int clen
);
118 checkAccelOnly(clientHttpRequest
* http
)
120 /* return TRUE if someone makes a proxy request to us and
121 * we are in httpd-accel only mode */
122 if (!Config2
.Accel
.on
)
124 if (Config
.onoff
.accel_with_proxy
)
126 if (http
->request
->protocol
== PROTO_CACHEOBJ
)
128 if (http
->flags
.accel
)
135 clientIdentDone(const char *ident
, void *data
)
137 ConnStateData
*conn
= data
;
139 xstrncpy(conn
->ident
, ident
, sizeof(conn
->ident
));
141 xstrncpy(conn
->ident
, "-", sizeof(conn
->ident
));
146 clientAclChecklistCreate(const acl_access
* acl
, const clientHttpRequest
* http
)
149 ConnStateData
*conn
= http
->conn
;
150 ch
= aclChecklistCreate(acl
,
155 * hack for ident ACL. It needs to get full addresses, and a
156 * place to store the ident result on persistent connections...
159 cbdataLock(ch
->conn
);
165 clientAccessCheck(void *data
)
167 clientHttpRequest
*http
= data
;
168 if (checkAccelOnly(http
)) {
169 clientAccessCheckDone(ACCESS_ALLOWED
, http
);
172 http
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.http
, http
);
173 aclNBCheck(http
->acl_checklist
, clientAccessCheckDone
, http
);
177 * returns true if client specified that the object must come from the cache
178 * witout contacting origin server
181 clientOnlyIfCached(clientHttpRequest
* http
)
183 const request_t
*r
= http
->request
;
185 return r
->cache_control
&&
186 EBIT_TEST(r
->cache_control
->mask
, CC_ONLY_IF_CACHED
);
190 clientCreateStoreEntry(clientHttpRequest
* h
, method_t m
, request_flags flags
)
194 * For erroneous requests, we might not have a h->request,
195 * so make a fake one.
197 if (h
->request
== NULL
)
198 h
->request
= requestLink(requestCreate(m
, PROTO_NONE
, null_string
));
199 e
= storeCreateEntry(h
->uri
, h
->log_uri
, flags
, m
);
200 h
->sc
= storeClientListAdd(e
, h
);
202 delaySetStoreClient(h
->sc
, delayClient(h
->request
));
204 storeClientCopy(h
->sc
, e
, 0, 0, CLIENT_SOCK_SZ
,
205 memAllocate(MEM_CLIENT_SOCK_BUF
), clientSendMoreData
, h
);
210 clientAccessCheckDone(int answer
, void *data
)
212 clientHttpRequest
*http
= data
;
215 ErrorState
*err
= NULL
;
216 debug(33, 2) ("The request %s %s is %s, because it matched '%s'\n",
217 RequestMethodStr
[http
->request
->method
], http
->uri
,
218 answer
== ACCESS_ALLOWED
? "ALLOWED" : "DENIED",
219 AclMatchedName
? AclMatchedName
: "NO ACL's");
220 http
->acl_checklist
= NULL
;
221 if (answer
== ACCESS_ALLOWED
) {
222 safe_free(http
->uri
);
223 http
->uri
= xstrdup(urlCanonical(http
->request
));
224 assert(http
->redirect_state
== REDIRECT_NONE
);
225 http
->redirect_state
= REDIRECT_PENDING
;
226 redirectStart(http
, clientRedirectDone
, http
);
228 debug(33, 5) ("Access Denied: %s\n", http
->uri
);
229 debug(33, 5) ("AclMatchedName = %s\n",
230 AclMatchedName
? AclMatchedName
: "<null>");
232 * NOTE: get page_id here, based on AclMatchedName because
233 * if USE_DELAY_POOLS is enabled, then AclMatchedName gets
234 * clobbered in the clientCreateStoreEntry() call
235 * just below. Pedro Ribeiro <pribeiro@isel.pt>
237 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
);
238 http
->log_type
= LOG_TCP_DENIED
;
239 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
241 if (answer
== ACCESS_REQ_PROXY_AUTH
|| aclIsProxyAuth(AclMatchedName
)) {
242 if (!http
->flags
.accel
) {
243 /* Proxy authorisation needed */
244 status
= HTTP_PROXY_AUTHENTICATION_REQUIRED
;
246 /* WWW authorisation needed */
247 status
= HTTP_UNAUTHORIZED
;
250 page_id
= ERR_CACHE_ACCESS_DENIED
;
252 status
= HTTP_FORBIDDEN
;
254 page_id
= ERR_ACCESS_DENIED
;
256 err
= errorCon(page_id
, status
);
257 err
->request
= requestLink(http
->request
);
258 err
->src_addr
= http
->conn
->peer
.sin_addr
;
259 errorAppendEntry(http
->entry
, err
);
264 clientRedirectDone(void *data
, char *result
)
266 clientHttpRequest
*http
= data
;
267 request_t
*new_request
= NULL
;
268 request_t
*old_request
= http
->request
;
269 debug(33, 5) ("clientRedirectDone: '%s' result=%s\n", http
->uri
,
270 result
? result
: "NULL");
271 assert(http
->redirect_state
== REDIRECT_PENDING
);
272 http
->redirect_state
= REDIRECT_DONE
;
274 http_status status
= atoi(result
);
275 if (status
== 301 || status
== 302) {
277 if ((t
= strchr(result
, ':')) != NULL
) {
278 http
->redirect
.status
= status
;
279 http
->redirect
.location
= xstrdup(t
+ 1);
281 debug(33, 1) ("clientRedirectDone: bad input: %s\n", result
);
284 if (strcmp(result
, http
->uri
))
285 new_request
= urlParse(old_request
->method
, result
);
288 safe_free(http
->uri
);
289 http
->uri
= xstrdup(urlCanonical(new_request
));
290 new_request
->http_ver
= old_request
->http_ver
;
291 httpHeaderAppend(&new_request
->header
, &old_request
->header
);
292 new_request
->client_addr
= old_request
->client_addr
;
293 new_request
->my_addr
= old_request
->my_addr
;
294 new_request
->my_port
= old_request
->my_port
;
295 new_request
->flags
.redirected
= 1;
296 if (old_request
->user_ident
[0])
297 xstrncpy(new_request
->user_ident
, old_request
->user_ident
,
299 if (old_request
->body
) {
300 new_request
->body
= xmalloc(old_request
->body_sz
);
301 xmemcpy(new_request
->body
, old_request
->body
, old_request
->body_sz
);
302 new_request
->body_sz
= old_request
->body_sz
;
304 new_request
->content_length
= old_request
->content_length
;
305 new_request
->flags
.proxy_keepalive
= old_request
->flags
.proxy_keepalive
;
306 requestUnlink(old_request
);
307 http
->request
= requestLink(new_request
);
309 clientInterpretRequestHeaders(http
);
311 headersLog(0, 1, request
->method
, request
);
313 fd_note(http
->conn
->fd
, http
->uri
);
314 clientCheckNoCache(http
);
318 clientCheckNoCache(clientHttpRequest
* http
)
320 if (Config
.accessList
.noCache
&& http
->request
->flags
.cachable
) {
321 http
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.noCache
, http
);
322 aclNBCheck(http
->acl_checklist
, clientCheckNoCacheDone
, http
);
324 clientCheckNoCacheDone(http
->request
->flags
.cachable
, http
);
329 clientCheckNoCacheDone(int answer
, void *data
)
331 clientHttpRequest
*http
= data
;
332 http
->request
->flags
.cachable
= answer
;
333 http
->acl_checklist
= NULL
;
334 clientProcessRequest(http
);
338 clientProcessExpired(void *data
)
340 clientHttpRequest
*http
= data
;
341 char *url
= http
->uri
;
342 StoreEntry
*entry
= NULL
;
343 debug(33, 3) ("clientProcessExpired: '%s'\n", http
->uri
);
344 assert(http
->entry
->lastmod
>= 0);
346 * check if we are allowed to contact other servers
347 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
348 * a stale entry *if* it matches client requirements
350 if (clientOnlyIfCached(http
)) {
351 clientProcessOnlyIfCachedMiss(http
);
354 http
->request
->flags
.refresh
= 1;
355 http
->old_entry
= http
->entry
;
356 http
->old_sc
= http
->sc
;
358 * Assert that 'http' is already a client of old_entry. If
359 * it is not, then the beginning of the object data might get
360 * freed from memory before we need to access it.
362 assert(http
->sc
->callback_data
== http
);
363 entry
= storeCreateEntry(url
,
365 http
->request
->flags
,
366 http
->request
->method
);
367 /* NOTE, don't call storeLockObject(), storeCreateEntry() does it */
368 http
->sc
= storeClientListAdd(entry
, http
);
370 /* delay_id is already set on original store client */
371 delaySetStoreClient(http
->sc
, delayClient(http
->request
));
373 http
->request
->lastmod
= http
->old_entry
->lastmod
;
374 debug(33, 5) ("clientProcessExpired: lastmod %d\n", (int) entry
->lastmod
);
376 http
->out
.offset
= 0;
377 fwdStart(http
->conn
->fd
, http
->entry
, http
->request
);
378 /* Register with storage manager to receive updates when data comes in. */
379 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
380 debug(33, 0) ("clientProcessExpired: found ENTRY_ABORTED object\n");
381 storeClientCopy(http
->sc
, entry
,
385 memAllocate(MEM_CLIENT_SOCK_BUF
),
386 clientHandleIMSReply
,
391 clientGetsOldEntry(StoreEntry
* new_entry
, StoreEntry
* old_entry
, request_t
* request
)
393 const http_status status
= new_entry
->mem_obj
->reply
->sline
.status
;
395 debug(33, 5) ("clientGetsOldEntry: YES, broken HTTP reply\n");
398 /* If the reply is a failure then send the old object as a last
400 if (status
>= 500 && status
< 600) {
401 debug(33, 3) ("clientGetsOldEntry: YES, failure reply=%d\n", status
);
404 /* If the reply is anything but "Not Modified" then
405 * we must forward it to the client */
406 if (HTTP_NOT_MODIFIED
!= status
) {
407 debug(33, 5) ("clientGetsOldEntry: NO, reply=%d\n", status
);
410 /* If the client did not send IMS in the request, then it
411 * must get the old object, not this "Not Modified" reply */
412 if (!request
->flags
.ims
) {
413 debug(33, 5) ("clientGetsOldEntry: YES, no client IMS\n");
416 /* If the client IMS time is prior to the entry LASTMOD time we
417 * need to send the old object */
418 if (modifiedSince(old_entry
, request
)) {
419 debug(33, 5) ("clientGetsOldEntry: YES, modified since %d\n",
423 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
429 clientHandleIMSReply(void *data
, char *buf
, ssize_t size
)
431 clientHttpRequest
*http
= data
;
432 StoreEntry
*entry
= http
->entry
;
434 const char *url
= storeUrl(entry
);
435 int unlink_request
= 0;
436 StoreEntry
*oldentry
;
439 debug(33, 3) ("clientHandleIMSReply: %s, %d bytes\n", url
, (int) size
);
441 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
444 if (size
< 0 && !EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
445 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
448 mem
= entry
->mem_obj
;
449 status
= mem
->reply
->sline
.status
;
450 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
451 debug(33, 3) ("clientHandleIMSReply: ABORTED '%s'\n", url
);
452 /* We have an existing entry, but failed to validate it */
453 /* Its okay to send the old one anyway */
454 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
455 storeUnregister(http
->sc
, entry
, http
);
456 storeUnlockObject(entry
);
457 entry
= http
->entry
= http
->old_entry
;
458 http
->sc
= http
->old_sc
;
459 } else if (STORE_PENDING
== entry
->store_status
&& 0 == status
) {
460 debug(33, 3) ("clientHandleIMSReply: Incomplete headers for '%s'\n", url
);
461 if (size
>= CLIENT_SOCK_SZ
) {
462 /* will not get any bigger than that */
463 debug(33, 3) ("clientHandleIMSReply: Reply is too large '%s', using old entry\n", url
);
464 /* use old entry, this repeats the code abovez */
465 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
466 storeUnregister(http
->sc
, entry
, http
);
467 storeUnlockObject(entry
);
468 entry
= http
->entry
= http
->old_entry
;
469 http
->sc
= http
->old_sc
;
472 storeClientCopy(http
->sc
, entry
,
473 http
->out
.offset
+ size
,
477 clientHandleIMSReply
,
481 } else if (clientGetsOldEntry(entry
, http
->old_entry
, http
->request
)) {
482 /* We initiated the IMS request, the client is not expecting
483 * 304, so put the good one back. First, make sure the old entry
484 * headers have been loaded from disk. */
485 oldentry
= http
->old_entry
;
486 http
->log_type
= LOG_TCP_REFRESH_HIT
;
487 if (oldentry
->mem_obj
->request
== NULL
) {
488 oldentry
->mem_obj
->request
= requestLink(mem
->request
);
491 /* Don't memcpy() the whole reply structure here. For example,
492 * www.thegist.com (Netscape/1.13) returns a content-length for
493 * 304's which seems to be the length of the 304 HEADERS!!! and
494 * not the body they refer to. */
495 httpReplyUpdateOnNotModified(oldentry
->mem_obj
->reply
, mem
->reply
);
496 storeTimestampsSet(oldentry
);
497 storeUnregister(http
->sc
, entry
, http
);
498 http
->sc
= http
->old_sc
;
499 storeUnlockObject(entry
);
500 entry
= http
->entry
= oldentry
;
501 entry
->timestamp
= squid_curtime
;
502 if (unlink_request
) {
503 requestUnlink(entry
->mem_obj
->request
);
504 entry
->mem_obj
->request
= NULL
;
507 /* the client can handle this reply, whatever it is */
508 http
->log_type
= LOG_TCP_REFRESH_MISS
;
509 if (HTTP_NOT_MODIFIED
== mem
->reply
->sline
.status
) {
510 httpReplyUpdateOnNotModified(http
->old_entry
->mem_obj
->reply
,
512 storeTimestampsSet(http
->old_entry
);
513 http
->log_type
= LOG_TCP_REFRESH_HIT
;
515 storeUnregister(http
->old_sc
, http
->old_entry
, http
);
516 storeUnlockObject(http
->old_entry
);
519 http
->old_entry
= NULL
; /* done with old_entry */
521 assert(!EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
523 storeClientCopy(http
->sc
, entry
,
531 clientSendMoreData(data
, buf
, size
);
536 modifiedSince(StoreEntry
* entry
, request_t
* request
)
539 MemObject
*mem
= entry
->mem_obj
;
540 time_t mod_time
= entry
->lastmod
;
541 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry
));
543 mod_time
= entry
->timestamp
;
544 debug(33, 3) ("modifiedSince: mod_time = %d\n", (int) mod_time
);
547 /* Find size of the object */
548 object_length
= mem
->reply
->content_length
;
549 if (object_length
< 0)
550 object_length
= contentLen(entry
);
551 if (mod_time
> request
->ims
) {
552 debug(33, 3) ("--> YES: entry newer than client\n");
554 } else if (mod_time
< request
->ims
) {
555 debug(33, 3) ("--> NO: entry older than client\n");
557 } else if (request
->imslen
< 0) {
558 debug(33, 3) ("--> NO: same LMT, no client length\n");
560 } else if (request
->imslen
== object_length
) {
561 debug(33, 3) ("--> NO: same LMT, same length\n");
564 debug(33, 3) ("--> YES: same LMT, different length\n");
570 clientPurgeRequest(clientHttpRequest
* http
)
573 ErrorState
*err
= NULL
;
575 debug(33, 3) ("Config2.onoff.enable_purge = %d\n", Config2
.onoff
.enable_purge
);
576 if (!Config2
.onoff
.enable_purge
) {
577 http
->log_type
= LOG_TCP_DENIED
;
578 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
579 err
->request
= requestLink(http
->request
);
580 err
->src_addr
= http
->conn
->peer
.sin_addr
;
581 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
582 errorAppendEntry(http
->entry
, err
);
585 http
->log_type
= LOG_TCP_MISS
;
586 /* Release both IP and object cache entries */
587 ipcacheInvalidate(http
->request
->host
);
588 if ((entry
= storeGetPublic(http
->uri
, METHOD_GET
)) == NULL
) {
589 http
->http_code
= HTTP_NOT_FOUND
;
592 http
->http_code
= HTTP_OK
;
594 debug(33, 4) ("clientPurgeRequest: Not modified '%s'\n",
597 * Make a new entry to hold the reply to be written
600 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
601 httpReplyReset(r
= http
->entry
->mem_obj
->reply
);
602 httpReplySetHeaders(r
, 1.0, http
->http_code
, NULL
, NULL
, 0, 0, -1);
603 httpReplySwapOut(r
, http
->entry
);
604 storeComplete(http
->entry
);
608 checkNegativeHit(StoreEntry
* e
)
610 if (!EBIT_TEST(e
->flags
, ENTRY_NEGCACHED
))
612 if (e
->expires
<= squid_curtime
)
614 if (e
->store_status
!= STORE_OK
)
620 clientUpdateCounters(clientHttpRequest
* http
)
622 int svc_time
= tvSubMsec(http
->start
, current_time
);
624 HierarchyLogEntry
*H
;
625 statCounter
.client_http
.requests
++;
626 if (isTcpHit(http
->log_type
))
627 statCounter
.client_http
.hits
++;
628 if (http
->log_type
== LOG_TCP_HIT
)
629 statCounter
.client_http
.disk_hits
++;
630 else if (http
->log_type
== LOG_TCP_MEM_HIT
)
631 statCounter
.client_http
.mem_hits
++;
632 if (http
->request
->err_type
!= ERR_NONE
)
633 statCounter
.client_http
.errors
++;
634 statHistCount(&statCounter
.client_http
.all_svc_time
, svc_time
);
636 * The idea here is not to be complete, but to get service times
637 * for only well-defined types. For example, we don't include
638 * LOG_TCP_REFRESH_FAIL_HIT because its not really a cache hit
639 * (we *tried* to validate it, but failed).
641 switch (http
->log_type
) {
642 case LOG_TCP_REFRESH_HIT
:
643 statHistCount(&statCounter
.client_http
.nh_svc_time
, svc_time
);
645 case LOG_TCP_IMS_HIT
:
646 statHistCount(&statCounter
.client_http
.nm_svc_time
, svc_time
);
649 case LOG_TCP_MEM_HIT
:
650 case LOG_TCP_OFFLINE_HIT
:
651 statHistCount(&statCounter
.client_http
.hit_svc_time
, svc_time
);
654 case LOG_TCP_CLIENT_REFRESH_MISS
:
655 statHistCount(&statCounter
.client_http
.miss_svc_time
, svc_time
);
658 /* make compiler warnings go away */
661 H
= &http
->request
->hier
;
664 statCounter
.cd
.times_used
++;
667 statCounter
.icp
.times_used
++;
669 if (0 != i
->stop
.tv_sec
&& 0 != i
->start
.tv_sec
)
670 statHistCount(&statCounter
.icp
.query_svc_time
,
671 tvSubUsec(i
->start
, i
->stop
));
673 statCounter
.icp
.query_timeouts
++;
676 statCounter
.netdb
.times_used
++;
684 httpRequestFree(void *data
)
686 clientHttpRequest
*http
= data
;
687 clientHttpRequest
**H
;
688 ConnStateData
*conn
= http
->conn
;
690 request_t
*request
= http
->request
;
691 MemObject
*mem
= NULL
;
692 debug(33, 3) ("httpRequestFree: %s\n", storeUrl(http
->entry
));
693 if (!clientCheckTransferDone(http
)) {
696 * DW: this seems odd here, is it really needed? It causes
697 * incomplete transfers to get logged with "000" status
698 * code because http->entry becomes NULL.
700 if ((e
= http
->entry
)) {
702 storeUnregister(http
->sc
, e
, http
);
703 storeUnlockObject(e
);
706 if (http
->entry
&& http
->entry
->ping_status
== PING_WAITING
)
707 storeReleaseRequest(http
->entry
);
709 assert(http
->log_type
< LOG_TYPE_MAX
);
711 mem
= http
->entry
->mem_obj
;
712 if (http
->out
.size
|| http
->log_type
) {
713 http
->al
.icp
.opcode
= ICP_INVALID
;
714 http
->al
.url
= http
->log_uri
;
715 debug(33, 9) ("httpRequestFree: al.url='%s'\n", http
->al
.url
);
717 http
->al
.http
.code
= mem
->reply
->sline
.status
;
718 http
->al
.http
.content_type
= strBuf(mem
->reply
->content_type
);
720 http
->al
.cache
.caddr
= conn
->log_addr
;
721 http
->al
.cache
.size
= http
->out
.size
;
722 http
->al
.cache
.code
= http
->log_type
;
723 http
->al
.cache
.msec
= tvSubMsec(http
->start
, current_time
);
728 packerToMemInit(&p
, &mb
);
729 httpHeaderPackInto(&request
->header
, &p
);
730 http
->al
.http
.method
= request
->method
;
731 http
->al
.http
.version
= request
->http_ver
;
732 http
->al
.headers
.request
= xstrdup(mb
.buf
);
733 http
->al
.hier
= request
->hier
;
734 if (request
->user_ident
[0])
735 http
->al
.cache
.ident
= request
->user_ident
;
737 http
->al
.cache
.ident
= conn
->ident
;
741 accessLogLog(&http
->al
);
742 clientUpdateCounters(http
);
743 clientdbUpdate(conn
->peer
.sin_addr
, http
->log_type
, PROTO_HTTP
, http
->out
.size
);
745 if (http
->acl_checklist
)
746 aclChecklistFree(http
->acl_checklist
);
748 checkFailureRatio(request
->err_type
, http
->al
.hier
.code
);
749 safe_free(http
->uri
);
750 safe_free(http
->log_uri
);
751 safe_free(http
->al
.headers
.request
);
752 safe_free(http
->al
.headers
.reply
);
753 safe_free(http
->redirect
.location
);
754 stringClean(&http
->range_iter
.boundary
);
755 if ((e
= http
->entry
)) {
757 storeUnregister(http
->sc
, e
, http
);
759 storeUnlockObject(e
);
761 /* old_entry might still be set if we didn't yet get the reply
762 * code in clientHandleIMSReply() */
763 if ((e
= http
->old_entry
)) {
764 http
->old_entry
= NULL
;
765 storeUnregister(http
->old_sc
, e
, http
);
767 storeUnlockObject(e
);
769 requestUnlink(http
->request
);
770 assert(http
!= http
->next
);
771 assert(http
->conn
->chr
!= NULL
);
772 H
= &http
->conn
->chr
;
781 dlinkDelete(&http
->active
, &ClientActiveRequests
);
785 /* This is a handler normally called by comm_close() */
787 connStateFree(int fd
, void *data
)
789 ConnStateData
*connState
= data
;
790 clientHttpRequest
*http
;
791 debug(33, 3) ("connStateFree: FD %d\n", fd
);
792 assert(connState
!= NULL
);
793 clientdbEstablished(connState
->peer
.sin_addr
, -1); /* decrement */
794 while ((http
= connState
->chr
) != NULL
) {
795 assert(http
->conn
== connState
);
796 assert(connState
->chr
!= connState
->chr
->next
);
797 httpRequestFree(http
);
799 safe_free(connState
->in
.buf
);
800 /* XXX account connState->in.buf */
801 pconnHistCount(0, connState
->nrequests
);
802 cbdataFree(connState
);
804 /* prevent those nasty RST packets */
806 char buf
[SQUID_TCP_SO_RCVBUF
];
807 while (read(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0);
813 clientInterpretRequestHeaders(clientHttpRequest
* http
)
815 request_t
*request
= http
->request
;
816 const HttpHeader
*req_hdr
= &request
->header
;
818 #if defined(USE_USERAGENT_LOG) || defined(USE_REFERER_LOG)
821 request
->imslen
= -1;
822 request
->ims
= httpHeaderGetTime(req_hdr
, HDR_IF_MODIFIED_SINCE
);
823 if (request
->ims
> 0)
824 request
->flags
.ims
= 1;
825 if (httpHeaderHas(req_hdr
, HDR_PRAGMA
)) {
826 String s
= httpHeaderGetList(req_hdr
, HDR_PRAGMA
);
827 if (strListIsMember(&s
, "no-cache", ','))
831 request
->cache_control
= httpHeaderGetCc(req_hdr
);
832 if (request
->cache_control
)
833 if (EBIT_TEST(request
->cache_control
->mask
, CC_NO_CACHE
))
837 if (Config
.onoff
.reload_into_ims
)
838 request
->flags
.nocache_hack
= 1;
839 else if (refresh_nocache_hack
)
840 request
->flags
.nocache_hack
= 1;
843 request
->flags
.nocache
= 1;
845 /* ignore range header in non-GETs */
846 if (request
->method
== METHOD_GET
) {
847 request
->range
= httpHeaderGetRange(req_hdr
);
849 request
->flags
.range
= 1;
851 if (httpHeaderHas(req_hdr
, HDR_AUTHORIZATION
))
852 request
->flags
.auth
= 1;
853 if (request
->login
[0] != '\0')
854 request
->flags
.auth
= 1;
855 if (httpHeaderHas(req_hdr
, HDR_VIA
)) {
856 String s
= httpHeaderGetList(req_hdr
, HDR_VIA
);
858 * ThisCache cannot be a member of Via header, "1.0 ThisCache" can.
859 * Note ThisCache2 has a space prepended to the hostname so we don't
860 * accidentally match super-domains.
862 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
863 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
864 request
, (ObjPackMethod
) & httpRequestPack
);
865 request
->flags
.loopdetect
= 1;
868 fvdbCountVia(strBuf(s
));
872 #if USE_USERAGENT_LOG
873 if ((str
= httpHeaderGetStr(req_hdr
, HDR_USER_AGENT
)))
874 logUserAgent(fqdnFromAddr(http
->conn
->peer
.sin_addr
), str
);
877 if ((str
= httpHeaderGetStr(req_hdr
, HDR_REFERER
)))
878 logReferer(fqdnFromAddr(http
->conn
->peer
.sin_addr
), str
,
882 if (httpHeaderHas(req_hdr
, HDR_X_FORWARDED_FOR
)) {
883 String s
= httpHeaderGetList(req_hdr
, HDR_X_FORWARDED_FOR
);
884 fvdbCountForw(strBuf(s
));
888 if (request
->method
== METHOD_TRACE
) {
889 request
->max_forwards
= httpHeaderGetInt(req_hdr
, HDR_MAX_FORWARDS
);
891 if (clientCachable(http
))
892 request
->flags
.cachable
= 1;
893 if (clientHierarchical(http
))
894 request
->flags
.hierarchical
= 1;
895 debug(33, 5) ("clientInterpretRequestHeaders: REQ_NOCACHE = %s\n",
896 request
->flags
.nocache
? "SET" : "NOT SET");
897 debug(33, 5) ("clientInterpretRequestHeaders: REQ_CACHABLE = %s\n",
898 request
->flags
.cachable
? "SET" : "NOT SET");
899 debug(33, 5) ("clientInterpretRequestHeaders: REQ_HIERARCHICAL = %s\n",
900 request
->flags
.hierarchical
? "SET" : "NOT SET");
904 * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive.
905 * This is the client-side persistent connection flag. We need
906 * to set this relatively early in the request processing
907 * to handle hacks for broken servers and clients.
910 clientSetKeepaliveFlag(clientHttpRequest
* http
)
912 request_t
*request
= http
->request
;
913 const HttpHeader
*req_hdr
= &request
->header
;
914 debug(33, 3) ("clientSetKeepaliveFlag: http_ver = %3.1f\n",
916 debug(33, 3) ("clientSetKeepaliveFlag: method = %s\n",
917 RequestMethodStr
[request
->method
]);
918 if (!Config
.onoff
.client_pconns
)
919 request
->flags
.proxy_keepalive
= 0;
920 else if (httpMsgIsPersistent(request
->http_ver
, req_hdr
))
921 request
->flags
.proxy_keepalive
= 1;
925 clientCheckContentLength(request_t
* r
)
930 /* PUT/POST requires a request entity */
931 return (r
->content_length
>= 0);
934 /* We do not want to see a request entity on GET/HEAD requests */
935 return (r
->content_length
<= 0);
937 /* For other types of requests we don't care */
944 clientCachable(clientHttpRequest
* http
)
946 const char *url
= http
->uri
;
947 request_t
*req
= http
->request
;
948 method_t method
= req
->method
;
949 if (req
->protocol
== PROTO_HTTP
)
950 return httpCachable(method
);
951 /* FTP is always cachable */
952 if (req
->protocol
== PROTO_GOPHER
)
953 return gopherCachable(url
);
954 if (req
->protocol
== PROTO_WAIS
)
956 if (method
== METHOD_CONNECT
)
958 if (method
== METHOD_TRACE
)
960 if (req
->protocol
== PROTO_CACHEOBJ
)
965 /* Return true if we can query our neighbors for this object */
967 clientHierarchical(clientHttpRequest
* http
)
969 const char *url
= http
->uri
;
970 request_t
*request
= http
->request
;
971 method_t method
= request
->method
;
972 const wordlist
*p
= NULL
;
974 /* IMS needs a private key, so we can use the hierarchy for IMS only
975 * if our neighbors support private keys */
976 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
978 if (request
->flags
.auth
)
980 if (method
== METHOD_TRACE
)
982 if (method
!= METHOD_GET
)
984 /* scan hierarchy_stoplist */
985 for (p
= Config
.hierarchy_stoplist
; p
; p
= p
->next
)
986 if (strstr(url
, p
->key
))
988 if (request
->flags
.loopdetect
)
990 if (request
->protocol
== PROTO_HTTP
)
991 return httpCachable(method
);
992 if (request
->protocol
== PROTO_GOPHER
)
993 return gopherCachable(url
);
994 if (request
->protocol
== PROTO_WAIS
)
996 if (request
->protocol
== PROTO_CACHEOBJ
)
1002 isTcpHit(log_type code
)
1004 /* this should be a bitmap for better optimization */
1005 if (code
== LOG_TCP_HIT
)
1007 if (code
== LOG_TCP_IMS_HIT
)
1009 if (code
== LOG_TCP_REFRESH_FAIL_HIT
)
1011 if (code
== LOG_TCP_REFRESH_HIT
)
1013 if (code
== LOG_TCP_NEGATIVE_HIT
)
1015 if (code
== LOG_TCP_MEM_HIT
)
1017 if (code
== LOG_TCP_OFFLINE_HIT
)
1023 * returns true if If-Range specs match reply, false otherwise
1026 clientIfRangeMatch(clientHttpRequest
* http
, HttpReply
* rep
)
1028 const TimeOrTag spec
= httpHeaderGetTimeOrTag(&http
->request
->header
, HDR_IF_RANGE
);
1029 /* check for parsing falure */
1034 ETag rep_tag
= httpHeaderGetETag(&rep
->header
, HDR_ETAG
);
1035 debug(33, 3) ("clientIfRangeMatch: ETags: %s and %s\n",
1036 spec
.tag
.str
, rep_tag
.str
? rep_tag
.str
: "<none>");
1038 return 0; /* entity has no etag to compare with! */
1039 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1040 debug(33, 1) ("clientIfRangeMatch: Weak ETags are not allowed in If-Range: %s ? %s\n",
1041 spec
.tag
.str
, rep_tag
.str
);
1042 return 0; /* must use strong validator for sub-range requests */
1044 return etagIsEqual(&rep_tag
, &spec
.tag
);
1046 /* got modification time? */
1047 if (spec
.time
>= 0) {
1048 return http
->entry
->lastmod
<= spec
.time
;
1050 assert(0); /* should not happen */
1054 /* returns expected content length for multi-range replies
1055 * note: assumes that httpHdrRangeCanonize has already been called
1056 * warning: assumes that HTTP headers for individual ranges at the
1057 * time of the actuall assembly will be exactly the same as
1058 * the headers when clientMRangeCLen() is called */
1060 clientMRangeCLen(clientHttpRequest
* http
)
1063 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1064 const HttpHdrRangeSpec
*spec
;
1067 assert(http
->entry
->mem_obj
);
1070 while ((spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
))) {
1072 /* account for headers for this range */
1074 clientPackRangeHdr(http
->entry
->mem_obj
->reply
,
1075 spec
, http
->range_iter
.boundary
, &mb
);
1078 /* account for range content */
1079 clen
+= spec
->length
;
1081 debug(33, 6) ("clientMRangeCLen: (clen += %d + %d) == %d\n",
1082 mb
.size
, spec
->length
, clen
);
1084 /* account for the terminating boundary */
1086 clientPackTermBound(http
->range_iter
.boundary
, &mb
);
1093 /* adds appropriate Range headers if needed */
1095 clientBuildRangeHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1097 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1098 const char *range_err
= NULL
;
1099 request_t
*request
= http
->request
;
1100 assert(request
->range
);
1101 /* check if we still want to do ranges */
1103 range_err
= "no [parse-able] reply";
1104 else if (rep
->sline
.status
!= HTTP_OK
)
1105 range_err
= "wrong status code";
1106 else if (httpHeaderHas(hdr
, HDR_CONTENT_RANGE
))
1107 range_err
= "origin server does ranges";
1108 else if (rep
->content_length
< 0)
1109 range_err
= "unknown length";
1110 else if (rep
->content_length
!= http
->entry
->mem_obj
->reply
->content_length
)
1111 range_err
= "INCONSISTENT length"; /* a bug? */
1112 else if (httpHeaderHas(&http
->request
->header
, HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1113 range_err
= "If-Range match failed";
1114 else if (!httpHdrRangeCanonize(http
->request
->range
, rep
->content_length
))
1115 range_err
= "canonization failed";
1116 else if (httpHdrRangeIsComplex(http
->request
->range
))
1117 range_err
= "too complex range header";
1118 else if (!request
->flags
.cachable
) /* from we_do_ranges in http.c */
1119 range_err
= "non-cachable request";
1120 /* get rid of our range specs on error */
1122 debug(33, 3) ("clientBuildRangeHeader: will not do ranges: %s.\n", range_err
);
1123 httpHdrRangeDestroy(http
->request
->range
);
1124 http
->request
->range
= NULL
;
1126 const int spec_count
= http
->request
->range
->specs
.count
;
1127 int actual_clen
= -1;
1129 debug(33, 3) ("clientBuildRangeHeader: range spec count: %d virgin clen: %d\n",
1130 spec_count
, rep
->content_length
);
1131 assert(spec_count
> 0);
1132 /* ETags should not be returned with Partial Content replies? */
1133 httpHeaderDelById(hdr
, HDR_ETAG
);
1134 /* append appropriate header(s) */
1135 if (spec_count
== 1) {
1136 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1137 const HttpHdrRangeSpec
*spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
);
1139 /* append Content-Range */
1140 httpHeaderAddContRange(hdr
, *spec
, rep
->content_length
);
1141 /* set new Content-Length to the actual number of bytes
1142 * transmitted in the message-body */
1143 actual_clen
= spec
->length
;
1146 /* generate boundary string */
1147 http
->range_iter
.boundary
= httpHdrRangeBoundaryStr(http
);
1148 /* delete old Content-Type, add ours */
1149 httpHeaderDelById(hdr
, HDR_CONTENT_TYPE
);
1150 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1151 "multipart/byteranges; boundary=\"%s\"",
1152 strBuf(http
->range_iter
.boundary
));
1153 /* Content-Length is not required in multipart responses
1154 * but it is always nice to have one */
1155 actual_clen
= clientMRangeCLen(http
);
1158 /* replace Content-Length header */
1159 assert(actual_clen
>= 0);
1160 httpHeaderDelById(hdr
, HDR_CONTENT_LENGTH
);
1161 httpHeaderPutInt(hdr
, HDR_CONTENT_LENGTH
, actual_clen
);
1162 debug(33, 3) ("clientBuildRangeHeader: actual content length: %d\n", actual_clen
);
1167 * filters out unwanted entries from original reply header
1168 * adds extra entries if we have more info than origin server
1169 * adds Squid specific entries
1172 clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1174 HttpHeader
*hdr
= &rep
->header
;
1175 int is_hit
= isTcpHit(http
->log_type
);
1176 request_t
*request
= http
->request
;
1177 #if DONT_FILTER_THESE
1178 /* but you might want to if you run Squid as an HTTP accelerator */
1179 /* httpHeaderDelById(hdr, HDR_ACCEPT_RANGES); */
1180 httpHeaderDelById(hdr
, HDR_ETAG
);
1182 httpHeaderDelById(hdr
, HDR_PROXY_CONNECTION
);
1183 /* here: Keep-Alive is a field-name, not a connection directive! */
1184 httpHeaderDelByName(hdr
, "Keep-Alive");
1185 /* remove Set-Cookie if a hit */
1187 httpHeaderDelById(hdr
, HDR_SET_COOKIE
);
1188 /* handle Connection header */
1189 if (httpHeaderHas(hdr
, HDR_CONNECTION
)) {
1190 /* anything that matches Connection list member will be deleted */
1191 String strConnection
= httpHeaderGetList(hdr
, HDR_CONNECTION
);
1192 const HttpHeaderEntry
*e
;
1193 HttpHeaderPos pos
= HttpHeaderInitPos
;
1195 * think: on-average-best nesting of the two loops (hdrEntry
1196 * and strListItem) @?@
1199 * maybe we should delete standard stuff ("keep-alive","close")
1200 * from strConnection first?
1202 while ((e
= httpHeaderGetEntry(hdr
, &pos
))) {
1203 if (strListIsMember(&strConnection
, strBuf(e
->name
), ','))
1204 httpHeaderDelAt(hdr
, pos
);
1206 httpHeaderDelById(hdr
, HDR_CONNECTION
);
1207 stringClean(&strConnection
);
1211 clientBuildRangeHeader(http
, rep
);
1213 * Add a estimated Age header on cache hits.
1217 * Remove any existing Age header sent by upstream caches
1218 * (note that the existing header is passed along unmodified
1221 httpHeaderDelById(hdr
, HDR_AGE
);
1223 * This adds the calculated object age. Note that the details of the
1224 * age calculation is performed by adjusting the timestamp in
1225 * storeTimestampsSet(), not here.
1227 * BROWSER WORKAROUND: IE sometimes hangs when receiving a 0 Age
1228 * header, so don't use it unless there is a age to report. Please
1229 * note that Age is only used to make a conservative estimation of
1230 * the objects age, so a Age: 0 header does not add any useful
1231 * information to the reply in any case.
1233 if (http
->entry
->timestamp
> -1)
1234 if (http
->entry
->timestamp
< squid_curtime
)
1235 httpHeaderPutInt(hdr
, HDR_AGE
,
1236 squid_curtime
- http
->entry
->timestamp
);
1238 /* Append X-Cache */
1239 httpHeaderPutStrf(hdr
, HDR_X_CACHE
, "%s from %s",
1240 is_hit
? "HIT" : "MISS", getMyHostname());
1241 #if USE_CACHE_DIGESTS
1242 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1243 httpHeaderPutStrf(hdr
, HDR_X_CACHE_LOOKUP
, "%s from %s:%d",
1244 http
->lookup_type
? http
->lookup_type
: "NONE",
1245 getMyHostname(), ntohs(Config
.Sockaddr
.http
->s
.sin_port
));
1247 if (httpReplyBodySize(request
->method
, rep
) < 0) {
1248 debug(33, 3) ("clientBuildReplyHeader: can't keep-alive, unknown body size\n");
1249 request
->flags
.proxy_keepalive
= 0;
1251 /* Signal keep-alive if needed */
1252 httpHeaderPutStr(hdr
,
1253 http
->flags
.accel
? HDR_CONNECTION
: HDR_PROXY_CONNECTION
,
1254 request
->flags
.proxy_keepalive
? "keep-alive" : "close");
1255 #if ADD_X_REQUEST_URI
1257 * Knowing the URI of the request is useful when debugging persistent
1258 * connections in a client; we cannot guarantee the order of http headers,
1259 * but X-Request-URI is likely to be the very last header to ease use from a
1260 * debugger [hdr->entries.count-1].
1262 httpHeaderPutStr(hdr
, HDR_X_REQUEST_URI
,
1263 http
->entry
->mem_obj
->url
? http
->entry
->mem_obj
->url
: http
->uri
);
1268 clientBuildReply(clientHttpRequest
* http
, const char *buf
, size_t size
)
1270 HttpReply
*rep
= httpReplyCreate();
1271 size_t k
= headersEnd(buf
, size
);
1272 if (k
&& httpReplyParse(rep
, buf
, k
)) {
1273 /* enforce 1.0 reply version */
1274 rep
->sline
.version
= 1.0;
1275 /* do header conversions */
1276 clientBuildReplyHeader(http
, rep
);
1277 /* if we do ranges, change status to "Partial Content" */
1278 if (http
->request
->range
)
1279 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1280 HTTP_PARTIAL_CONTENT
, NULL
);
1282 /* parsing failure, get rid of the invalid reply */
1283 httpReplyDestroy(rep
);
1285 /* if we were going to do ranges, backoff */
1286 if (http
->request
->range
) {
1287 /* this will fail and destroy request->range */
1288 clientBuildRangeHeader(http
, rep
);
1295 * clientCacheHit should only be called until the HTTP reply headers
1296 * have been parsed. Normally this should be a single call, but
1297 * it might take more than one. As soon as we have the headers,
1298 * we hand off to clientSendMoreData, clientProcessExpired, or
1299 * clientProcessMiss.
1302 clientCacheHit(void *data
, char *buf
, ssize_t size
)
1304 clientHttpRequest
*http
= data
;
1305 StoreEntry
*e
= http
->entry
;
1307 request_t
*r
= http
->request
;
1308 debug(33, 3) ("clientCacheHit: %s, %d bytes\n", http
->uri
, (int) size
);
1309 if (http
->entry
== NULL
) {
1310 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1311 debug(33, 3) ("clientCacheHit: request aborted\n");
1313 } else if (size
< 0) {
1314 /* swap in failure */
1315 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1316 debug(33, 3) ("clientCacheHit: swapin failure for %s\n", http
->uri
);
1317 http
->log_type
= LOG_TCP_SWAPFAIL_MISS
;
1318 if ((e
= http
->entry
)) {
1320 storeUnregister(http
->sc
, e
, http
);
1322 storeUnlockObject(e
);
1324 clientProcessMiss(http
);
1329 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
1330 if (mem
->reply
->sline
.status
== 0) {
1332 * we don't have full reply headers yet; either wait for more or
1333 * punt to clientProcessMiss.
1335 if (e
->mem_status
== IN_MEMORY
|| e
->store_status
== STORE_OK
) {
1336 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1337 clientProcessMiss(http
);
1338 } else if (size
== CLIENT_SOCK_SZ
&& http
->out
.offset
== 0) {
1339 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1340 clientProcessMiss(http
);
1342 debug(33, 3) ("clientCacheHit: waiting for HTTP reply headers\n");
1343 storeClientCopy(http
->sc
, e
,
1344 http
->out
.offset
+ size
,
1354 * Got the headers, now grok them
1356 assert(http
->log_type
== LOG_TCP_HIT
);
1357 if (checkNegativeHit(e
)) {
1358 http
->log_type
= LOG_TCP_NEGATIVE_HIT
;
1359 clientSendMoreData(data
, buf
, size
);
1360 } else if (r
->method
== METHOD_HEAD
) {
1362 * RFC 2068 seems to indicate there is no "conditional HEAD"
1363 * request. We cannot validate a cached object for a HEAD
1364 * request, nor can we return 304.
1366 if (e
->mem_status
== IN_MEMORY
)
1367 http
->log_type
= LOG_TCP_MEM_HIT
;
1368 clientSendMoreData(data
, buf
, size
);
1369 } else if (refreshCheckHTTP(e
, r
) && !http
->flags
.internal
) {
1370 debug(33, 5) ("clientCacheHit: in refreshCheck() block\n");
1372 * We hold a stale copy; it needs to be validated
1375 * The 'need_validation' flag is used to prevent forwarding
1376 * loops between siblings. If our copy of the object is stale,
1377 * then we should probably only use parents for the validation
1378 * request. Otherwise two siblings could generate a loop if
1379 * both have a stale version of the object.
1381 r
->flags
.need_validation
= 1;
1382 if (e
->lastmod
< 0) {
1384 * Previous reply didn't have a Last-Modified header,
1385 * we cannot revalidate it.
1387 http
->log_type
= LOG_TCP_MISS
;
1388 clientProcessMiss(http
);
1389 } else if (r
->flags
.nocache
) {
1391 * This did not match a refresh pattern that overrides no-cache
1392 * we should honour the client no-cache header.
1394 http
->log_type
= LOG_TCP_CLIENT_REFRESH_MISS
;
1395 clientProcessMiss(http
);
1396 } else if (r
->protocol
== PROTO_HTTP
) {
1398 * Object needs to be revalidated
1399 * XXX This could apply to FTP as well, if Last-Modified is known.
1401 http
->log_type
= LOG_TCP_REFRESH_MISS
;
1402 clientProcessExpired(http
);
1405 * We don't know how to re-validate other protocols. Handle
1406 * them as if the object has expired.
1408 http
->log_type
= LOG_TCP_MISS
;
1409 clientProcessMiss(http
);
1411 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1412 } else if (r
->flags
.ims
) {
1414 * Handle If-Modified-Since requests from the client
1416 if (mem
->reply
->sline
.status
!= HTTP_OK
) {
1417 debug(33, 4) ("clientCacheHit: Reply code %d != 200\n",
1418 mem
->reply
->sline
.status
);
1419 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1420 http
->log_type
= LOG_TCP_MISS
;
1421 clientProcessMiss(http
);
1422 } else if (modifiedSince(e
, http
->request
)) {
1423 http
->log_type
= LOG_TCP_IMS_HIT
;
1424 clientSendMoreData(data
, buf
, size
);
1426 time_t timestamp
= e
->timestamp
;
1427 MemBuf mb
= httpPacked304Reply(e
->mem_obj
->reply
);
1428 http
->log_type
= LOG_TCP_IMS_HIT
;
1429 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1430 storeUnregister(http
->sc
, e
, http
);
1432 storeUnlockObject(e
);
1433 e
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
1435 * Copy timestamp from the original entry so the 304
1436 * reply has a meaningful Age: header.
1438 e
->timestamp
= timestamp
;
1440 httpReplyParse(e
->mem_obj
->reply
, mb
.buf
, mb
.size
);
1441 storeAppend(e
, mb
.buf
, mb
.size
);
1447 * plain ol' cache hit
1449 if (e
->mem_status
== IN_MEMORY
)
1450 http
->log_type
= LOG_TCP_MEM_HIT
;
1451 else if (Config
.onoff
.offline
)
1452 http
->log_type
= LOG_TCP_OFFLINE_HIT
;
1453 clientSendMoreData(data
, buf
, size
);
1457 /* put terminating boundary for multiparts */
1459 clientPackTermBound(String boundary
, MemBuf
* mb
)
1461 memBufPrintf(mb
, "\r\n--%s--\r\n", strBuf(boundary
));
1462 debug(33, 6) ("clientPackTermBound: buf offset: %d\n", mb
->size
);
1465 /* appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1467 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1475 debug(33, 5) ("clientPackRangeHdr: appending boundary: %s\n", strBuf(boundary
));
1476 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1477 memBufPrintf(mb
, "\r\n--%s\r\n", strBuf(boundary
));
1479 /* stuff the header with required entries and pack it */
1480 httpHeaderInit(&hdr
, hoReply
);
1481 if (httpHeaderHas(&rep
->header
, HDR_CONTENT_TYPE
))
1482 httpHeaderPutStr(&hdr
, HDR_CONTENT_TYPE
, httpHeaderGetStr(&rep
->header
, HDR_CONTENT_TYPE
));
1483 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1484 packerToMemInit(&p
, mb
);
1485 httpHeaderPackInto(&hdr
, &p
);
1487 httpHeaderClean(&hdr
);
1489 /* append <crlf> (we packed a header, not a reply) */
1490 memBufPrintf(mb
, crlf
);
1494 * extracts a "range" from *buf and appends them to mb, updating
1495 * all offsets and such.
1498 clientPackRange(clientHttpRequest
* http
,
1499 HttpHdrRangeIter
* i
,
1504 const ssize_t copy_sz
= i
->debt_size
<= *size
? i
->debt_size
: *size
;
1505 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1509 * intersection of "have" and "need" ranges must not be empty
1511 assert(body_off
< i
->spec
->offset
+ i
->spec
->length
);
1512 assert(body_off
+ *size
> i
->spec
->offset
);
1514 * put boundary and headers at the beginning of a range in a
1517 if (http
->request
->range
->specs
.count
> 1 && i
->debt_size
== i
->spec
->length
) {
1518 assert(http
->entry
->mem_obj
);
1520 http
->entry
->mem_obj
->reply
, /* original reply */
1521 i
->spec
, /* current range */
1522 i
->boundary
, /* boundary, the same for all */
1529 debug(33, 3) ("clientPackRange: appending %d bytes\n", copy_sz
);
1530 memBufAppend(mb
, *buf
, copy_sz
);
1535 i
->debt_size
-= copy_sz
;
1536 body_off
+= copy_sz
;
1538 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1542 assert(*size
>= 0 && i
->debt_size
>= 0);
1545 /* returns true if there is still data available to pack more ranges
1546 * increments iterator "i"
1547 * used by clientPackMoreRanges */
1549 clientCanPackMoreRanges(const clientHttpRequest
* http
, HttpHdrRangeIter
* i
, ssize_t size
)
1551 /* first update "i" if needed */
1552 if (!i
->debt_size
) {
1553 if ((i
->spec
= httpHdrRangeGetSpec(http
->request
->range
, &i
->pos
)))
1554 i
->debt_size
= i
->spec
->length
;
1556 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1557 /* continue condition: need_more_data && have_more_data */
1558 return i
->spec
&& size
> 0;
1561 /* extracts "ranges" from buf and appends them to mb, updating all offsets and such */
1562 /* returns true if we need more data */
1564 clientPackMoreRanges(clientHttpRequest
* http
, const char *buf
, ssize_t size
, MemBuf
* mb
)
1566 HttpHdrRangeIter
*i
= &http
->range_iter
;
1567 /* offset in range specs does not count the prefix of an http msg */
1568 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1570 /* check: reply was parsed and range iterator was initialized */
1571 assert(i
->prefix_size
> 0);
1572 /* filter out data according to range specs */
1573 while (clientCanPackMoreRanges(http
, i
, size
)) {
1574 off_t start
; /* offset of still missing data */
1576 start
= i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
;
1577 debug(33, 3) ("clientPackMoreRanges: in: offset: %d size: %d\n",
1578 (int) body_off
, size
);
1579 debug(33, 3) ("clientPackMoreRanges: out: start: %d spec[%d]: [%d, %d), len: %d debt: %d\n",
1580 (int) start
, (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
, i
->debt_size
);
1581 assert(body_off
<= start
); /* we did not miss it */
1582 /* skip up to start */
1583 if (body_off
+ size
> start
) {
1584 const size_t skip_size
= start
- body_off
;
1589 /* has not reached start yet */
1594 /* put next chunk if any */
1596 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1597 clientPackRange(http
, i
, &buf
, &size
, mb
);
1598 body_off
= http
->out
.offset
- i
->prefix_size
; /* sync */
1601 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1602 debug(33, 3) ("clientPackMoreRanges: buf exhausted: in: offset: %d size: %d need_more: %d\n",
1603 (int) body_off
, size
, i
->debt_size
);
1605 debug(33, 3) ("clientPackMoreRanges: need more: spec[%d]: [%d, %d), len: %d\n",
1606 (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
);
1607 /* skip the data we do not need if possible */
1608 if (i
->debt_size
== i
->spec
->length
) /* at the start of the cur. spec */
1609 body_off
= i
->spec
->offset
;
1611 assert(body_off
== i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
);
1612 } else if (http
->request
->range
->specs
.count
> 1) {
1613 /* put terminating boundary for multiparts */
1614 clientPackTermBound(i
->boundary
, mb
);
1616 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1617 return i
->debt_size
> 0;
1621 clientReplyBodyTooLarge(int clen
)
1623 if (0 == Config
.maxReplyBodySize
)
1624 return 0; /* disabled */
1626 return 0; /* unknown */
1627 if (clen
> Config
.maxReplyBodySize
)
1628 return 1; /* too large */
1633 clientRequestBodyTooLarge(int clen
)
1635 if (0 == Config
.maxRequestBodySize
)
1636 return 0; /* disabled */
1638 return 0; /* unknown, bug? */
1639 if (clen
> Config
.maxRequestBodySize
)
1640 return 1; /* too large */
1645 * accepts chunk of a http message in buf, parses prefix, filters headers and
1646 * such, writes processed message to the client's socket
1649 clientSendMoreData(void *data
, char *buf
, ssize_t size
)
1651 clientHttpRequest
*http
= data
;
1652 StoreEntry
*entry
= http
->entry
;
1653 ConnStateData
*conn
= http
->conn
;
1655 HttpReply
*rep
= NULL
;
1656 const char *body_buf
= buf
;
1657 ssize_t body_size
= size
;
1659 ssize_t check_size
= 0;
1660 debug(33, 5) ("clientSendMoreData: %s, %d bytes\n", http
->uri
, (int) size
);
1661 assert(size
<= CLIENT_SOCK_SZ
);
1662 assert(http
->request
!= NULL
);
1663 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1664 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1665 debug(33, 5) ("clientSendMoreData: FD %d '%s', out.offset=%d \n",
1666 fd
, storeUrl(entry
), (int) http
->out
.offset
);
1667 if (conn
->chr
!= http
) {
1668 /* there is another object in progress, defer this one */
1669 debug(33, 1) ("clientSendMoreData: Deferring %s\n", storeUrl(entry
));
1670 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1672 } else if (entry
&& EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1673 /* call clientWriteComplete so the client socket gets closed */
1674 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1675 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1677 } else if (size
< 0) {
1678 /* call clientWriteComplete so the client socket gets closed */
1679 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1680 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1682 } else if (size
== 0) {
1683 /* call clientWriteComplete so the client socket gets closed */
1684 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1685 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1688 if (http
->out
.offset
== 0) {
1689 if (Config
.onoff
.log_mime_hdrs
) {
1691 if ((k
= headersEnd(buf
, size
))) {
1692 safe_free(http
->al
.headers
.reply
);
1693 http
->al
.headers
.reply
= xcalloc(k
+ 1, 1);
1694 xstrncpy(http
->al
.headers
.reply
, buf
, k
);
1697 rep
= clientBuildReply(http
, buf
, size
);
1698 if (rep
&& clientReplyBodyTooLarge(rep
->content_length
)) {
1699 ErrorState
*err
= errorCon(ERR_TOO_BIG
, HTTP_FORBIDDEN
);
1700 err
->request
= requestLink(http
->request
);
1701 storeUnregister(http
->sc
, http
->entry
, http
);
1703 storeUnlockObject(http
->entry
);
1704 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
1705 null_request_flags
);
1706 errorAppendEntry(http
->entry
, err
);
1707 httpReplyDestroy(rep
);
1710 body_size
= size
- rep
->hdr_sz
;
1711 assert(body_size
>= 0);
1712 body_buf
= buf
+ rep
->hdr_sz
;
1713 http
->range_iter
.prefix_size
= rep
->hdr_sz
;
1714 debug(33, 3) ("clientSendMoreData: Appending %d bytes after %d bytes of headers\n",
1715 body_size
, rep
->hdr_sz
);
1716 } else if (size
< CLIENT_SOCK_SZ
&& entry
->store_status
== STORE_PENDING
) {
1717 /* wait for more to arrive */
1718 storeClientCopy(http
->sc
, entry
,
1719 http
->out
.offset
+ size
,
1727 /* reset range iterator */
1728 http
->range_iter
.pos
= HttpHdrRangeInitPos
;
1729 } else if (!http
->request
->range
) {
1730 /* Avoid copying to MemBuf for non-range requests */
1731 /* Note, if we're here, then 'rep' is known to be NULL */
1732 http
->out
.offset
+= body_size
;
1733 comm_write(fd
, buf
, size
, clientWriteBodyComplete
, http
, NULL
);
1734 /* NULL because clientWriteBodyComplete frees it */
1737 if (http
->request
->method
== METHOD_HEAD
) {
1739 /* do not forward body for HEAD replies */
1741 http
->flags
.done_copying
= 1;
1744 * If we are here, then store_status == STORE_OK and it
1745 * seems we have a HEAD repsponse which is missing the
1746 * empty end-of-headers line (home.mira.net, phttpd/0.99.72
1747 * does this). Because clientBuildReply() fails we just
1748 * call this reply a body, set the done_copying flag and
1751 http
->flags
.done_copying
= 1;
1754 /* write headers and/or body if any */
1755 assert(rep
|| (body_buf
&& body_size
));
1756 /* init mb; put status line and headers if any */
1758 mb
= httpReplyPack(rep
);
1759 http
->out
.offset
+= rep
->hdr_sz
;
1760 check_size
+= rep
->hdr_sz
;
1762 headersLog(0, 0, http
->request
->method
, rep
);
1764 httpReplyDestroy(rep
);
1769 /* append body if any */
1770 if (http
->request
->range
) {
1771 /* Only GET requests should have ranges */
1772 assert(http
->request
->method
== METHOD_GET
);
1773 /* clientPackMoreRanges() updates http->out.offset */
1774 /* force the end of the transfer if we are done */
1775 if (!clientPackMoreRanges(http
, body_buf
, body_size
, &mb
))
1776 http
->flags
.done_copying
= 1;
1777 } else if (body_buf
&& body_size
) {
1778 http
->out
.offset
+= body_size
;
1779 check_size
+= body_size
;
1780 memBufAppend(&mb
, body_buf
, body_size
);
1782 if (!http
->request
->range
&& http
->request
->method
== METHOD_GET
)
1783 assert(check_size
== size
);
1785 comm_write_mbuf(fd
, mb
, clientWriteComplete
, http
);
1786 /* if we don't do it, who will? */
1787 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1791 * clientWriteBodyComplete is called for MEM_CLIENT_SOCK_BUF's
1792 * written directly to the client socket, versus copying to a MemBuf
1793 * and going through comm_write_mbuf. Most non-range responses after
1794 * the headers probably go through here.
1797 clientWriteBodyComplete(int fd
, char *buf
, size_t size
, int errflag
, void *data
)
1800 * NOTE: clientWriteComplete doesn't currently use its "buf"
1801 * (second) argument, so we pass in NULL.
1803 clientWriteComplete(fd
, NULL
, size
, errflag
, data
);
1804 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1808 clientKeepaliveNextRequest(clientHttpRequest
* http
)
1810 ConnStateData
*conn
= http
->conn
;
1812 debug(33, 3) ("clientKeepaliveNextRequest: FD %d\n", conn
->fd
);
1813 conn
->defer
.until
= 0; /* Kick it to read a new request */
1814 httpRequestFree(http
);
1815 if ((http
= conn
->chr
) == NULL
) {
1816 debug(33, 5) ("clientKeepaliveNextRequest: FD %d reading next req\n",
1818 fd_note(conn
->fd
, "Reading next request");
1820 * Set the timeout BEFORE calling clientReadRequest().
1822 commSetTimeout(conn
->fd
, Config
.Timeout
.pconn
, requestTimeout
, conn
);
1823 clientReadRequest(conn
->fd
, conn
); /* Read next request */
1825 * Note, the FD may be closed at this point.
1827 } else if ((entry
= http
->entry
) == NULL
) {
1829 * this request is in progress, maybe doing an ACL or a redirect,
1830 * execution will resume after the operation completes.
1833 debug(33, 1) ("clientKeepaliveNextRequest: FD %d Sending next\n",
1836 if (0 == storeClientCopyPending(http
->sc
, entry
, http
)) {
1837 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1838 debug(33, 0) ("clientKeepaliveNextRequest: ENTRY_ABORTED\n");
1839 storeClientCopy(http
->sc
, entry
,
1843 memAllocate(MEM_CLIENT_SOCK_BUF
),
1851 clientWriteComplete(int fd
, char *bufnotused
, size_t size
, int errflag
, void *data
)
1853 clientHttpRequest
*http
= data
;
1854 StoreEntry
*entry
= http
->entry
;
1856 http
->out
.size
+= size
;
1857 debug(33, 5) ("clientWriteComplete: FD %d, sz %d, err %d, off %d, len %d\n",
1858 fd
, size
, errflag
, (int) http
->out
.offset
, entry
? objectLen(entry
) : 0);
1860 kb_incr(&statCounter
.client_http
.kbytes_out
, size
);
1861 if (isTcpHit(http
->log_type
))
1862 kb_incr(&statCounter
.client_http
.hit_kbytes_out
, size
);
1866 * just close the socket, httpRequestFree will abort if needed
1869 } else if (NULL
== entry
) {
1870 comm_close(fd
); /* yuk */
1871 } else if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1873 } else if ((done
= clientCheckTransferDone(http
)) != 0 || size
== 0) {
1874 debug(33, 5) ("clientWriteComplete: FD %d transfer is DONE\n", fd
);
1875 /* We're finished case */
1876 if (httpReplyBodySize(http
->request
->method
, entry
->mem_obj
->reply
) < 0) {
1877 debug(33, 5) ("clientWriteComplete: closing, content_length < 0\n");
1880 debug(33, 5) ("clientWriteComplete: closing, !done\n");
1882 } else if (clientGotNotEnough(http
)) {
1883 debug(33, 5) ("clientWriteComplete: client didn't get all it expected\n");
1885 } else if (http
->request
->flags
.proxy_keepalive
) {
1886 debug(33, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd
);
1887 clientKeepaliveNextRequest(http
);
1891 } else if (clientReplyBodyTooLarge((int) http
->out
.offset
)) {
1894 /* More data will be coming from primary server; register with
1895 * storage manager. */
1896 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1897 debug(33, 0) ("clientWriteComplete 2: ENTRY_ABORTED\n");
1898 storeClientCopy(http
->sc
, entry
,
1902 memAllocate(MEM_CLIENT_SOCK_BUF
),
1909 * client issued a request with an only-if-cached cache-control directive;
1910 * we did not find a cached object that can be returned without
1911 * contacting other servers;
1912 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
1915 clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
)
1917 char *url
= http
->uri
;
1918 request_t
*r
= http
->request
;
1919 ErrorState
*err
= NULL
;
1920 debug(33, 4) ("clientProcessOnlyIfCachedMiss: '%s %s'\n",
1921 RequestMethodStr
[r
->method
], url
);
1922 http
->al
.http
.code
= HTTP_GATEWAY_TIMEOUT
;
1923 err
= errorCon(ERR_ONLY_IF_CACHED_MISS
, HTTP_GATEWAY_TIMEOUT
);
1924 err
->request
= requestLink(r
);
1925 err
->src_addr
= http
->conn
->peer
.sin_addr
;
1927 storeUnregister(http
->sc
, http
->entry
, http
);
1929 storeUnlockObject(http
->entry
);
1931 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1932 errorAppendEntry(http
->entry
, err
);
1936 * Return true if the first range offset is larger than the configured
1937 * limit, UNLESS the request is a hit AND the bits we want are in
1941 clientCheckRangeOffsetLimit(StoreEntry
* entry
, HttpHdrRange
* range
)
1943 ssize_t range_start
;
1945 * If the range offset limit is disabled, don't force a miss.
1947 if (-1 == Config
.rangeOffsetLimit
)
1950 * If the first range offset is less than the configured limit
1951 * we won't force a cache miss.
1953 range_start
= httpHdrRangeFirstOffset(range
);
1954 if (Config
.rangeOffsetLimit
>= range_start
)
1957 * Now we know it's possibly a hit. If we already have the
1958 * whole object cached, we won't force a miss.
1960 if (STORE_OK
== entry
->store_status
)
1961 return 0; /* we have the whole object */
1963 * Now we have a hit on a PENDING object. We need to see
1964 * if the part we want is already cached. If so, we don't
1967 assert(NULL
!= entry
->mem_obj
);
1968 if (range_start
<= entry
->mem_obj
->inmem_hi
)
1971 * Even though we have a PENDING copy of the object, we
1972 * don't want to wait to reach the first range offset,
1973 * so we force a miss for a new range request to the
1980 clientProcessRequest2(clientHttpRequest
* http
)
1982 request_t
*r
= http
->request
;
1984 e
= http
->entry
= storeGetPublic(http
->uri
, r
->method
);
1985 if (r
->method
== METHOD_HEAD
&& e
== NULL
) {
1986 /* We can generate a HEAD reply from a cached GET object */
1987 e
= http
->entry
= storeGetPublic(http
->uri
, METHOD_GET
);
1989 /* Release negatively cached IP-cache entries on reload */
1990 if (r
->flags
.nocache
)
1991 ipcacheReleaseInvalid(r
->host
);
1993 else if (r
->flags
.nocache_hack
)
1994 ipcacheReleaseInvalid(r
->host
);
1996 #if USE_CACHE_DIGESTS
1997 http
->lookup_type
= e
? "HIT" : "MISS";
2000 /* this object isn't in the cache */
2001 debug(33, 3) ("clientProcessRequest2: storeGet() MISS\n");
2002 return LOG_TCP_MISS
;
2004 if (Config
.onoff
.offline
) {
2005 debug(33, 3) ("clientProcessRequest2: offline HIT\n");
2009 if (!storeEntryValidToSend(e
)) {
2010 debug(33, 3) ("clientProcessRequest2: !storeEntryValidToSend MISS\n");
2012 return LOG_TCP_MISS
;
2014 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
2015 /* Special entries are always hits, no matter what the client says */
2016 debug(33, 3) ("clientProcessRequest2: ENTRY_SPECIAL HIT\n");
2021 if (e
->store_status
== STORE_PENDING
) {
2022 if (r
->flags
.nocache
|| r
->flags
.nocache_hack
) {
2023 debug(33, 3) ("Clearing no-cache for STORE_PENDING request\n\t%s\n",
2025 r
->flags
.nocache
= 0;
2026 r
->flags
.nocache_hack
= 0;
2030 if (r
->flags
.nocache
) {
2031 debug(33, 3) ("clientProcessRequest2: no-cache REFRESH MISS\n");
2033 ipcacheReleaseInvalid(r
->host
);
2034 return LOG_TCP_CLIENT_REFRESH_MISS
;
2036 if (NULL
== r
->range
) {
2038 } else if (httpHdrRangeWillBeComplex(r
->range
)) {
2040 * Some clients break if we return "200 OK" for a Range
2041 * request. We would have to return "200 OK" for a _complex_
2042 * Range request that is also a HIT. Thus, let's prevent HITs
2043 * on complex Range requests
2045 debug(33, 3) ("clientProcessRequest2: complex range MISS\n");
2047 r
->flags
.we_dont_do_ranges
= 1;
2048 return LOG_TCP_MISS
;
2049 } else if (clientCheckRangeOffsetLimit(e
, r
->range
)) {
2050 debug(33, 1) ("clientProcessRequest2: forcing miss due to range_offset_limit\n");
2052 r
->flags
.we_dont_do_ranges
= 1;
2053 return LOG_TCP_MISS
;
2055 debug(33, 3) ("clientProcessRequest2: default HIT\n");
2061 clientProcessRequest(clientHttpRequest
* http
)
2063 char *url
= http
->uri
;
2064 request_t
*r
= http
->request
;
2065 int fd
= http
->conn
->fd
;
2067 debug(33, 4) ("clientProcessRequest: %s '%s'\n",
2068 RequestMethodStr
[r
->method
],
2070 if (r
->method
== METHOD_CONNECT
) {
2071 http
->log_type
= LOG_TCP_MISS
;
2072 sslStart(fd
, url
, r
, &http
->out
.size
);
2074 } else if (r
->method
== METHOD_PURGE
) {
2075 clientPurgeRequest(http
);
2077 } else if (r
->method
== METHOD_TRACE
) {
2078 if (r
->max_forwards
== 0) {
2079 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
2080 storeReleaseRequest(http
->entry
);
2081 storeBuffer(http
->entry
);
2082 rep
= httpReplyCreate();
2083 httpReplySetHeaders(rep
, 1.0, HTTP_OK
, NULL
, "text/plain",
2084 httpRequestPrefixLen(r
), 0, squid_curtime
);
2085 httpReplySwapOut(rep
, http
->entry
);
2086 httpReplyDestroy(rep
);
2087 httpRequestSwapOut(r
, http
->entry
);
2088 storeComplete(http
->entry
);
2092 http
->log_type
= LOG_TCP_MISS
;
2093 } else if (r
->content_length
> 0) {
2094 http
->log_type
= LOG_TCP_MISS
;
2095 /* XXX oof, POST can be cached! */
2096 pumpInit(fd
, r
, http
->uri
);
2098 http
->log_type
= clientProcessRequest2(http
);
2100 debug(33, 4) ("clientProcessRequest: %s for '%s'\n",
2101 log_tags
[http
->log_type
],
2103 http
->out
.offset
= 0;
2104 if (NULL
!= http
->entry
) {
2105 storeLockObject(http
->entry
);
2106 storeCreateMemObject(http
->entry
, http
->uri
, http
->log_uri
);
2107 http
->entry
->mem_obj
->method
= r
->method
;
2108 http
->sc
= storeClientListAdd(http
->entry
, http
);
2110 delaySetStoreClient(http
->sc
, delayClient(r
));
2112 storeClientCopy(http
->sc
, http
->entry
,
2116 memAllocate(MEM_CLIENT_SOCK_BUF
),
2120 /* MISS CASE, http->log_type is already set! */
2121 clientProcessMiss(http
);
2126 * Prepare to fetch the object as it's a cache miss of some kind.
2129 clientProcessMiss(clientHttpRequest
* http
)
2131 char *url
= http
->uri
;
2132 request_t
*r
= http
->request
;
2133 ErrorState
*err
= NULL
;
2134 debug(33, 4) ("clientProcessMiss: '%s %s'\n",
2135 RequestMethodStr
[r
->method
], url
);
2137 * We might have a left-over StoreEntry from a failed cache hit
2141 if (EBIT_TEST(http
->entry
->flags
, ENTRY_SPECIAL
)) {
2142 debug(33, 0) ("clientProcessMiss: miss on a special object (%s).\n", url
);
2143 debug(33, 0) ("\tlog_type = %s\n", log_tags
[http
->log_type
]);
2144 storeEntryDump(http
->entry
, 1);
2146 storeUnregister(http
->sc
, http
->entry
, http
);
2148 storeUnlockObject(http
->entry
);
2151 if (clientOnlyIfCached(http
)) {
2152 clientProcessOnlyIfCachedMiss(http
);
2156 * Deny loops when running in accelerator/transproxy mode.
2158 if (http
->flags
.accel
&& r
->flags
.loopdetect
) {
2159 http
->al
.http
.code
= HTTP_FORBIDDEN
;
2160 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
2161 err
->request
= requestLink(r
);
2162 err
->src_addr
= http
->conn
->peer
.sin_addr
;
2163 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
2164 errorAppendEntry(http
->entry
, err
);
2167 assert(http
->out
.offset
== 0);
2168 http
->entry
= clientCreateStoreEntry(http
, r
->method
, r
->flags
);
2169 if (http
->redirect
.status
) {
2170 HttpReply
*rep
= httpReplyCreate();
2171 #if LOG_TCP_REDIRECTS
2172 http
->log_type
= LOG_TCP_REDIRECT
;
2174 storeReleaseRequest(http
->entry
);
2175 httpRedirectReply(rep
, http
->redirect
.status
, http
->redirect
.location
);
2176 httpReplySwapOut(rep
, http
->entry
);
2177 httpReplyDestroy(rep
);
2178 storeComplete(http
->entry
);
2181 if (http
->flags
.internal
)
2182 r
->protocol
= PROTO_INTERNAL
;
2183 fwdStart(http
->conn
->fd
, http
->entry
, r
);
2186 static clientHttpRequest
*
2187 parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
)
2189 clientHttpRequest
*http
= xcalloc(1, sizeof(clientHttpRequest
));
2190 cbdataAdd(http
, cbdataXfree
, 0);
2192 http
->start
= current_time
;
2193 http
->req_sz
= conn
->in
.offset
;
2194 http
->uri
= xstrdup(uri
);
2195 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2196 http
->range_iter
.boundary
= StringNull
;
2197 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2202 * parseHttpRequest()
2205 * NULL on error or incomplete request
2206 * a clientHttpRequest structure on success
2208 static clientHttpRequest
*
2209 parseHttpRequest(ConnStateData
* conn
, method_t
* method_p
, int *status
,
2210 char **prefix_p
, size_t * req_line_sz_p
)
2215 char *req_hdr
= NULL
;
2220 int free_request
= 0;
2221 size_t header_sz
; /* size of headers, not including first line */
2222 size_t prefix_sz
; /* size of whole request (req-line + headers) */
2226 clientHttpRequest
*http
= NULL
;
2228 struct natlookup natLookup
;
2229 static int natfd
= -1;
2232 if ((req_sz
= headersEnd(conn
->in
.buf
, conn
->in
.offset
)) == 0) {
2233 debug(33, 5) ("Incomplete request, waiting for end of headers\n");
2236 *method_p
= METHOD_NONE
;
2239 assert(req_sz
<= conn
->in
.offset
);
2240 /* Use memcpy, not strdup! */
2241 inbuf
= xmalloc(req_sz
+ 1);
2242 xmemcpy(inbuf
, conn
->in
.buf
, req_sz
);
2243 *(inbuf
+ req_sz
) = '\0';
2245 /* pre-set these values to make aborting simpler */
2247 *method_p
= METHOD_NONE
;
2250 /* Barf on NULL characters in the headers */
2251 if (strlen(inbuf
) != req_sz
) {
2252 debug(33, 1) ("parseHttpRequest: Requestheader contains NULL characters\n");
2253 return parseHttpRequestAbort(conn
, "error:invalid-request");
2255 /* Look for request method */
2256 if ((mstr
= strtok(inbuf
, "\t ")) == NULL
) {
2257 debug(33, 1) ("parseHttpRequest: Can't get request method\n");
2258 return parseHttpRequestAbort(conn
, "error:invalid-request-method");
2260 method
= urlParseMethod(mstr
);
2261 if (method
== METHOD_NONE
) {
2262 debug(33, 1) ("parseHttpRequest: Unsupported method '%s'\n", mstr
);
2263 return parseHttpRequestAbort(conn
, "error:unsupported-request-method");
2265 debug(33, 5) ("parseHttpRequest: Method is '%s'\n", mstr
);
2268 /* look for URL+HTTP/x.x */
2269 if ((url
= strtok(NULL
, "\n")) == NULL
) {
2270 debug(33, 1) ("parseHttpRequest: Missing URL\n");
2271 return parseHttpRequestAbort(conn
, "error:missing-url");
2273 while (xisspace(*url
))
2275 t
= url
+ strlen(url
);
2280 if (xisspace(*t
) && !strncmp(t
+ 1, "HTTP/", 5)) {
2285 while (t
> url
&& xisspace(*t
))
2287 debug(33, 5) ("parseHttpRequest: URI is '%s'\n", url
);
2288 if (token
== NULL
) {
2289 debug(33, 3) ("parseHttpRequest: Missing HTTP identifier\n");
2290 #if RELAXED_HTTP_PARSER
2291 http_ver
= (float) 0.9; /* wild guess */
2293 return parseHttpRequestAbort(conn
, "error:missing-http-ident");
2296 http_ver
= (float) atof(token
+ 5);
2300 * Process headers after request line
2302 req_hdr
= strtok(NULL
, null_string
);
2303 header_sz
= req_sz
- (req_hdr
- inbuf
);
2304 if (0 == header_sz
) {
2305 debug(33, 3) ("parseHttpRequest: header_sz == 0\n");
2309 assert(header_sz
> 0);
2310 debug(33, 3) ("parseHttpRequest: req_hdr = {%s}\n", req_hdr
);
2311 end
= req_hdr
+ header_sz
;
2312 debug(33, 3) ("parseHttpRequest: end = {%s}\n", end
);
2314 prefix_sz
= end
- inbuf
;
2315 *req_line_sz_p
= req_hdr
- inbuf
;
2316 debug(33, 3) ("parseHttpRequest: prefix_sz = %d, req_line_sz = %d\n",
2317 (int) prefix_sz
, (int) *req_line_sz_p
);
2318 assert(prefix_sz
<= conn
->in
.offset
);
2320 /* Ok, all headers are received */
2321 http
= xcalloc(1, sizeof(clientHttpRequest
));
2322 cbdataAdd(http
, cbdataXfree
, 0);
2323 http
->http_ver
= http_ver
;
2325 http
->start
= current_time
;
2326 http
->req_sz
= prefix_sz
;
2327 http
->range_iter
.boundary
= StringNull
;
2328 *prefix_p
= xmalloc(prefix_sz
+ 1);
2329 xmemcpy(*prefix_p
, conn
->in
.buf
, prefix_sz
);
2330 *(*prefix_p
+ prefix_sz
) = '\0';
2331 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2333 debug(33, 5) ("parseHttpRequest: Request Header is\n%s\n", (*prefix_p
) + *req_line_sz_p
);
2334 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2337 /* handle internal objects */
2338 if (internalCheck(url
)) {
2339 /* prepend our name & port */
2340 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2341 http
->flags
.internal
= 1;
2342 http
->flags
.accel
= 1;
2344 /* see if we running in Config2.Accel.on, if so got to convert it to URL */
2345 else if (Config2
.Accel
.on
&& *url
== '/') {
2346 /* prepend the accel prefix */
2347 if (opt_accel_uses_host
&& (t
= mime_get_header(req_hdr
, "Host"))) {
2348 int vport
= (int) Config
.Accel
.port
;
2350 /* If a Host: header was specified, use it to build the URL
2351 * instead of the one in the Config file. */
2353 * XXX Use of the Host: header here opens a potential
2354 * security hole. There are no checks that the Host: value
2355 * corresponds to one of your servers. It might, for example,
2356 * refer to www.playboy.com. The 'dst' and/or 'dst_domain' ACL
2357 * types should be used to prevent httpd-accelerators
2358 * handling requests for non-local servers */
2360 if ((q
= strchr(t
, ':'))) {
2364 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2366 http
->uri
= xcalloc(url_sz
, 1);
2367 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2369 } else if (vhost_mode
) {
2371 /* Put the local socket IP address as the hostname */
2372 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2373 http
->uri
= xcalloc(url_sz
, 1);
2375 vport
= (int) ntohs(http
->conn
->me
.sin_port
);
2377 vport
= (int) Config
.Accel
.port
;
2379 natLookup
.nl_inport
= http
->conn
->me
.sin_port
;
2380 natLookup
.nl_outport
= http
->conn
->peer
.sin_port
;
2381 natLookup
.nl_inip
= http
->conn
->me
.sin_addr
;
2382 natLookup
.nl_outip
= http
->conn
->peer
.sin_addr
;
2383 natLookup
.nl_flags
= IPN_TCP
;
2385 natfd
= open(IPL_NAT
, O_RDONLY
, 0);
2387 debug(50, 1) ("parseHttpRequest: NAT open failed: %s\n",
2389 return parseHttpRequestAbort(conn
, "error:nat-open-failed");
2391 if (ioctl(natfd
, SIOCGNATL
, &natLookup
) < 0) {
2392 if (errno
!= ESRCH
) {
2393 debug(50, 1) ("parseHttpRequest: NAT lookup failed: ioctl(SIOCGNATL)\n");
2396 return parseHttpRequestAbort(conn
, "error:nat-lookup-failed");
2398 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2399 inet_ntoa(http
->conn
->me
.sin_addr
),
2402 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2403 inet_ntoa(natLookup
.nl_realip
),
2406 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2407 inet_ntoa(http
->conn
->me
.sin_addr
),
2410 debug(33, 5) ("VHOST REWRITE: '%s'\n", http
->uri
);
2412 url_sz
= strlen(Config2
.Accel
.prefix
) + strlen(url
) +
2413 Config
.appendDomainLen
+ 1;
2414 http
->uri
= xcalloc(url_sz
, 1);
2415 snprintf(http
->uri
, url_sz
, "%s%s", Config2
.Accel
.prefix
, url
);
2417 http
->flags
.accel
= 1;
2419 /* URL may be rewritten later, so make extra room */
2420 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2421 http
->uri
= xcalloc(url_sz
, 1);
2422 strcpy(http
->uri
, url
);
2423 http
->flags
.accel
= 0;
2425 if (!stringHasCntl(http
->uri
))
2426 http
->log_uri
= xstrndup(http
->uri
, MAX_URL
);
2428 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(http
->uri
), MAX_URL
);
2429 debug(33, 5) ("parseHttpRequest: Complete request received\n");
2438 clientReadDefer(int fdnotused
, void *data
)
2440 ConnStateData
*conn
= data
;
2441 return conn
->defer
.until
> squid_curtime
;
2445 clientReadRequest(int fd
, void *data
)
2447 ConnStateData
*conn
= data
;
2448 int parser_return_code
= 0;
2450 request_t
*request
= NULL
;
2453 clientHttpRequest
*http
= NULL
;
2454 clientHttpRequest
**H
= NULL
;
2455 char *prefix
= NULL
;
2456 ErrorState
*err
= NULL
;
2457 fde
*F
= &fd_table
[fd
];
2458 int len
= conn
->in
.size
- conn
->in
.offset
- 1;
2459 debug(33, 4) ("clientReadRequest: FD %d: reading request...\n", fd
);
2460 statCounter
.syscalls
.sock
.reads
++;
2461 size
= read(fd
, conn
->in
.buf
+ conn
->in
.offset
, len
);
2463 fd_bytes(fd
, size
, FD_READ
);
2464 kb_incr(&statCounter
.client_http
.kbytes_in
, size
);
2467 * Don't reset the timeout value here. The timeout value will be
2468 * set to Config.Timeout.request by httpAccept() and
2469 * clientWriteComplete(), and should apply to the request as a
2470 * whole, not individual read() calls. Plus, it breaks our
2471 * lame half-close detection
2473 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, conn
, 0);
2475 if (conn
->chr
== NULL
) {
2476 /* no current or pending requests */
2479 } else if (!Config
.onoff
.half_closed_clients
) {
2480 /* admin doesn't want to support half-closed client sockets */
2484 /* It might be half-closed, we can't tell */
2485 debug(33, 5) ("clientReadRequest: FD %d closed?\n", fd
);
2486 F
->flags
.socket_eof
= 1;
2487 conn
->defer
.until
= squid_curtime
+ 1;
2489 fd_note(fd
, "half-closed");
2491 } else if (size
< 0) {
2492 if (!ignoreErrno(errno
)) {
2493 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd
, xstrerror());
2496 } else if (conn
->in
.offset
== 0) {
2497 debug(50, 2) ("clientReadRequest: FD %d: no data to process (%s)\n", fd
, xstrerror());
2500 /* Continue to process previously read data */
2503 conn
->in
.offset
+= size
;
2504 /* Skip leading (and trailing) whitespace */
2505 while (conn
->in
.offset
> 0) {
2508 while (conn
->in
.offset
> 0 && xisspace(conn
->in
.buf
[0])) {
2509 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.offset
- 1);
2512 conn
->in
.buf
[conn
->in
.offset
] = '\0'; /* Terminate the string */
2513 if (conn
->in
.offset
== 0)
2515 /* Limit the number of concurrent requests to 2 */
2516 for (H
= &conn
->chr
, nrequests
= 0; *H
; H
= &(*H
)->next
, nrequests
++);
2517 if (nrequests
>= 2) {
2518 debug(33, 3) ("clientReadRequest: FD %d max concurrent requests reached\n", fd
);
2519 debug(33, 5) ("clientReadRequest: FD %d defering new request until one is done\n", fd
);
2520 conn
->defer
.until
= squid_curtime
+ 100; /* Reset when a request is complete */
2523 /* Process request */
2524 http
= parseHttpRequest(conn
,
2526 &parser_return_code
,
2532 assert(http
->req_sz
> 0);
2533 conn
->in
.offset
-= http
->req_sz
;
2534 assert(conn
->in
.offset
>= 0);
2535 debug(33, 5) ("conn->in.offset = %d\n", (int) conn
->in
.offset
);
2537 * If we read past the end of this request, move the remaining
2538 * data to the beginning
2540 if (conn
->in
.offset
> 0)
2541 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ http
->req_sz
, conn
->in
.offset
);
2542 /* add to the client request queue */
2543 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2546 commSetTimeout(fd
, Config
.Timeout
.lifetime
, NULL
, NULL
);
2547 if (parser_return_code
< 0) {
2548 debug(33, 1) ("clientReadRequest: FD %d Invalid Request\n", fd
);
2549 err
= errorCon(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
);
2550 err
->request_hdrs
= xstrdup(conn
->in
.buf
);
2551 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2552 errorAppendEntry(http
->entry
, err
);
2556 if ((request
= urlParse(method
, http
->uri
)) == NULL
) {
2557 debug(33, 5) ("Invalid URL: %s\n", http
->uri
);
2558 err
= errorCon(ERR_INVALID_URL
, HTTP_BAD_REQUEST
);
2559 err
->src_addr
= conn
->peer
.sin_addr
;
2560 err
->url
= xstrdup(http
->uri
);
2561 http
->al
.http
.code
= err
->http_status
;
2562 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2563 errorAppendEntry(http
->entry
, err
);
2567 /* compile headers */
2568 /* we should skip request line! */
2569 if (!httpRequestParseHeader(request
, prefix
+ req_line_sz
))
2570 debug(33, 1) ("Failed to parse request headers: %s\n%s\n",
2572 /* continue anyway? */
2574 request
->flags
.accelerated
= http
->flags
.accel
;
2575 if (!http
->flags
.internal
) {
2576 if (internalCheck(strBuf(request
->urlpath
))) {
2577 if (internalHostnameIs(request
->host
) &&
2578 request
->port
== ntohs(Config
.Sockaddr
.http
->s
.sin_port
)) {
2579 http
->flags
.internal
= 1;
2580 } else if (internalStaticCheck(strBuf(request
->urlpath
))) {
2581 xstrncpy(request
->host
, internalHostname(), SQUIDHOSTNAMELEN
);
2582 request
->port
= ntohs(Config
.Sockaddr
.http
->s
.sin_port
);
2583 http
->flags
.internal
= 1;
2588 * cache the Content-length value in request_t.
2590 request
->content_length
= httpHeaderGetInt(&request
->header
,
2591 HDR_CONTENT_LENGTH
);
2592 request
->flags
.internal
= http
->flags
.internal
;
2594 safe_free(http
->log_uri
);
2595 http
->log_uri
= xstrdup(urlCanonicalClean(request
));
2596 request
->client_addr
= conn
->peer
.sin_addr
;
2597 request
->my_addr
= conn
->me
.sin_addr
;
2598 request
->my_port
= ntohs(conn
->me
.sin_port
);
2599 request
->http_ver
= http
->http_ver
;
2600 if (!urlCheckRequest(request
)) {
2601 err
= errorCon(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
);
2602 err
->src_addr
= conn
->peer
.sin_addr
;
2603 err
->request
= requestLink(request
);
2604 request
->flags
.proxy_keepalive
= 0;
2605 http
->al
.http
.code
= err
->http_status
;
2606 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2607 errorAppendEntry(http
->entry
, err
);
2610 if (0 == clientCheckContentLength(request
)) {
2611 err
= errorCon(ERR_INVALID_REQ
, HTTP_LENGTH_REQUIRED
);
2612 err
->src_addr
= conn
->peer
.sin_addr
;
2613 err
->request
= requestLink(request
);
2614 http
->al
.http
.code
= err
->http_status
;
2615 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2616 errorAppendEntry(http
->entry
, err
);
2619 http
->request
= requestLink(request
);
2621 * We need to set the keepalive flag before doing some
2622 * hacks for POST/PUT requests below. Maybe we could
2623 * set keepalive flag even earlier.
2625 clientSetKeepaliveFlag(http
);
2627 * break here if the request has a content-length
2628 * because there is a reqeust body following and we
2629 * don't want to parse it as though it was new request.
2631 if (request
->content_length
>= 0) {
2632 int copy_len
= XMIN(conn
->in
.offset
, request
->content_length
);
2634 assert(conn
->in
.offset
>= copy_len
);
2635 request
->body_sz
= copy_len
;
2636 request
->body
= xmalloc(request
->body_sz
);
2637 xmemcpy(request
->body
, conn
->in
.buf
, request
->body_sz
);
2638 conn
->in
.offset
-= copy_len
;
2639 if (conn
->in
.offset
)
2640 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ copy_len
, conn
->in
.offset
);
2643 * if we didn't get the full body now, then more will
2644 * be arriving on the client socket. Lets cancel
2645 * the read handler until this request gets forwarded.
2647 if (request
->body_sz
< request
->content_length
)
2648 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2649 if (request
->content_length
< 0)
2651 else if (clientRequestBodyTooLarge(request
->content_length
)) {
2652 err
= errorCon(ERR_TOO_BIG
, HTTP_REQUEST_ENTITY_TOO_LARGE
);
2653 err
->request
= requestLink(request
);
2654 http
->entry
= clientCreateStoreEntry(http
,
2655 METHOD_NONE
, null_request_flags
);
2656 errorAppendEntry(http
->entry
, err
);
2660 clientAccessCheck(http
);
2661 continue; /* while offset > 0 */
2662 } else if (parser_return_code
== 0) {
2664 * Partial request received; reschedule until parseHttpRequest()
2665 * is happy with the input
2667 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2669 if (conn
->in
.offset
>= Config
.maxRequestHeaderSize
) {
2670 /* The request is too large to handle */
2671 debug(33, 1) ("Request header is too large (%d bytes)\n",
2672 (int) conn
->in
.offset
);
2673 debug(33, 1) ("Config 'request_header_max_size'= %d bytes.\n",
2674 Config
.maxRequestHeaderSize
);
2675 err
= errorCon(ERR_TOO_BIG
, HTTP_REQUEST_ENTITY_TOO_LARGE
);
2676 http
= parseHttpRequestAbort(conn
, "error:request-too-large");
2677 /* add to the client request queue */
2678 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2680 http
->entry
= clientCreateStoreEntry(http
, METHOD_NONE
, null_request_flags
);
2681 errorAppendEntry(http
->entry
, err
);
2684 /* Grow the request memory area to accomodate for a large request */
2685 conn
->in
.size
+= REQUEST_BUF_SIZE
;
2686 conn
->in
.buf
= xrealloc(conn
->in
.buf
, conn
->in
.size
);
2687 /* XXX account conn->in.buf */
2688 debug(33, 3) ("Handling a large request, offset=%d inbufsize=%d\n",
2689 (int) conn
->in
.offset
, conn
->in
.size
);
2690 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2697 /* general lifetime handler for HTTP requests */
2699 requestTimeout(int fd
, void *data
)
2701 #if THIS_CONFUSES_PERSISTENT_CONNECTION_AWARE_BROWSERS_AND_USERS
2702 ConnStateData
*conn
= data
;
2704 debug(33, 3) ("requestTimeout: FD %d: lifetime is expired.\n", fd
);
2705 if (fd_table
[fd
].rwstate
) {
2707 * Some data has been sent to the client, just close the FD
2710 } else if (conn
->nrequests
) {
2712 * assume its a persistent connection; just close it
2719 err
= errorCon(ERR_LIFETIME_EXP
, HTTP_REQUEST_TIMEOUT
);
2720 err
->url
= xstrdup("N/A");
2722 * Normally we shouldn't call errorSend() in client_side.c, but
2723 * it should be okay in this case. Presumably if we get here
2724 * this is the first request for the connection, and no data
2725 * has been written yet
2727 assert(conn
->chr
== NULL
);
2730 * if we don't close() here, we still need a timeout handler!
2732 commSetTimeout(fd
, 30, requestTimeout
, conn
);
2734 * Aha, but we don't want a read handler!
2736 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2740 * Just close the connection to not confuse browsers
2741 * using persistent connections. Some browsers opens
2742 * an connection and then does not use it until much
2743 * later (presumeably because the request triggering
2744 * the open has already been completed on another
2747 debug(33, 3) ("requestTimeout: FD %d: lifetime is expired.\n", fd
);
2753 httpAcceptDefer(int fdunused
, void *dataunused
)
2755 static time_t last_warn
= 0;
2756 if (fdNFree() >= RESERVED_FD
)
2758 if (last_warn
+ 15 < squid_curtime
) {
2759 debug(33, 0) ("WARNING! Your cache is running out of filedescriptors\n");
2760 last_warn
= squid_curtime
;
2765 /* Handle a new connection on HTTP socket. */
2767 httpAccept(int sock
, void *data
)
2771 ConnStateData
*connState
= NULL
;
2772 struct sockaddr_in peer
;
2773 struct sockaddr_in me
;
2774 int max
= INCOMING_HTTP_MAX
;
2776 static aclCheck_t identChecklist
;
2778 commSetSelect(sock
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2779 while (max
-- && !httpAcceptDefer(sock
, NULL
)) {
2780 memset(&peer
, '\0', sizeof(struct sockaddr_in
));
2781 memset(&me
, '\0', sizeof(struct sockaddr_in
));
2782 if ((fd
= comm_accept(sock
, &peer
, &me
)) < 0) {
2783 if (!ignoreErrno(errno
))
2784 debug(50, 1) ("httpAccept: FD %d: accept failure: %s\n",
2788 debug(33, 4) ("httpAccept: FD %d: accepted\n", fd
);
2789 connState
= memAllocate(MEM_CONNSTATEDATA
);
2790 connState
->peer
= peer
;
2791 connState
->log_addr
= peer
.sin_addr
;
2792 connState
->log_addr
.s_addr
&= Config
.Addrs
.client_netmask
.s_addr
;
2795 connState
->in
.size
= REQUEST_BUF_SIZE
;
2796 connState
->in
.buf
= xcalloc(connState
->in
.size
, 1);
2797 cbdataAdd(connState
, memFree
, MEM_CONNSTATEDATA
);
2798 /* XXX account connState->in.buf */
2799 comm_add_close_handler(fd
, connStateFree
, connState
);
2800 if (Config
.onoff
.log_fqdn
)
2801 fqdncache_gethostbyaddr(peer
.sin_addr
, FQDN_LOOKUP_IF_MISS
);
2802 commSetTimeout(fd
, Config
.Timeout
.request
, requestTimeout
, connState
);
2804 identChecklist
.src_addr
= peer
.sin_addr
;
2805 identChecklist
.my_addr
= me
.sin_addr
;
2806 identChecklist
.my_port
= ntohs(me
.sin_port
);
2807 if (aclCheckFast(Config
.accessList
.identLookup
, &identChecklist
))
2808 identStart(&me
, &peer
, clientIdentDone
, connState
);
2810 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, connState
, 0);
2811 commSetDefer(fd
, clientReadDefer
, connState
);
2812 clientdbEstablished(peer
.sin_addr
, 1);
2818 #define SENDING_BODY 0
2819 #define SENDING_HDRSONLY 1
2821 clientCheckTransferDone(clientHttpRequest
* http
)
2823 int sending
= SENDING_BODY
;
2824 StoreEntry
*entry
= http
->entry
;
2831 * For now, 'done_copying' is used for special cases like
2832 * Range and HEAD requests.
2834 if (http
->flags
.done_copying
)
2837 * Handle STORE_OK objects.
2838 * objectLen(entry) will be set proprely.
2840 if (entry
->store_status
== STORE_OK
) {
2841 if (http
->out
.offset
>= objectLen(entry
))
2847 * Now, handle STORE_PENDING objects
2849 mem
= entry
->mem_obj
;
2850 assert(mem
!= NULL
);
2851 assert(http
->request
!= NULL
);
2853 if (reply
->hdr_sz
== 0)
2854 return 0; /* haven't found end of headers yet */
2855 else if (reply
->sline
.status
== HTTP_OK
)
2856 sending
= SENDING_BODY
;
2857 else if (reply
->sline
.status
== HTTP_NO_CONTENT
)
2858 sending
= SENDING_HDRSONLY
;
2859 else if (reply
->sline
.status
== HTTP_NOT_MODIFIED
)
2860 sending
= SENDING_HDRSONLY
;
2861 else if (reply
->sline
.status
< HTTP_OK
)
2862 sending
= SENDING_HDRSONLY
;
2863 else if (http
->request
->method
== METHOD_HEAD
)
2864 sending
= SENDING_HDRSONLY
;
2866 sending
= SENDING_BODY
;
2868 * Figure out how much data we are supposed to send.
2869 * If we are sending a body and we don't have a content-length,
2870 * then we must wait for the object to become STORE_OK.
2872 if (sending
== SENDING_HDRSONLY
)
2873 sendlen
= reply
->hdr_sz
;
2874 else if (reply
->content_length
< 0)
2877 sendlen
= reply
->content_length
+ reply
->hdr_sz
;
2879 * Now that we have the expected length, did we send it all?
2881 if (http
->out
.offset
< sendlen
)
2888 clientGotNotEnough(clientHttpRequest
* http
)
2890 int cl
= httpReplyBodySize(http
->request
->method
, http
->entry
->mem_obj
->reply
);
2891 int hs
= http
->entry
->mem_obj
->reply
->hdr_sz
;
2893 if (http
->out
.offset
< cl
+ hs
)
2899 * This function is designed to serve a fairly specific purpose.
2900 * Occasionally our vBNS-connected caches can talk to each other, but not
2901 * the rest of the world. Here we try to detect frequent failures which
2902 * make the cache unusable (e.g. DNS lookup and connect() failures). If
2903 * the failure:success ratio goes above 1.0 then we go into "hit only"
2904 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
2905 * will only fetch HITs from us if they are using the ICP protocol. We
2906 * stay in this mode for 5 minutes.
2908 * Duane W., Sept 16, 1996
2912 checkFailureRatio(err_type etype
, hier_code hcode
)
2914 static double magic_factor
= 100.0;
2917 if (hcode
== HIER_NONE
)
2919 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
2920 n_bad
= magic_factor
- n_good
;
2923 case ERR_CONNECT_FAIL
:
2924 case ERR_READ_ERROR
:
2930 request_failure_ratio
= n_bad
/ n_good
;
2931 if (hit_only_mode_until
> squid_curtime
)
2933 if (request_failure_ratio
< 1.0)
2935 debug(33, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio
);
2936 debug(33, 0) ("Going into hit-only-mode for %d minutes...\n",
2937 FAILURE_MODE_TIME
/ 60);
2938 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
2939 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
2943 clientHttpConnectionsOpen(void)
2945 sockaddr_in_list
*s
;
2947 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
2948 if (MAXHTTPPORTS
== NHttpSockets
) {
2949 debug(1, 1) ("WARNING: You have too many 'http_port' lines.\n");
2950 debug(1, 1) (" The limit is %d\n", MAXHTTPPORTS
);
2954 fd
= comm_open(SOCK_STREAM
,
2957 ntohs(s
->s
.sin_port
),
2964 commSetSelect(fd
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2966 * We need to set a defer handler here so that we don't
2967 * peg the CPU with select() when we hit the FD limit.
2969 commSetDefer(fd
, httpAcceptDefer
, NULL
);
2970 debug(1, 1) ("Accepting HTTP connections at %s, port %d, FD %d.\n",
2971 inet_ntoa(s
->s
.sin_addr
),
2972 (int) ntohs(s
->s
.sin_port
),
2974 HttpSockets
[NHttpSockets
++] = fd
;
2976 if (NHttpSockets
< 1)
2977 fatal("Cannot open HTTP Port");
2981 clientHttpConnectionsClose(void)
2984 for (i
= 0; i
< NHttpSockets
; i
++) {
2985 if (HttpSockets
[i
] >= 0) {
2986 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets
[i
]);
2987 comm_close(HttpSockets
[i
]);
2988 HttpSockets
[i
] = -1;