3 * $Id: client_side.cc,v 1.484 2000/05/12 03:43:00 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 * 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>
45 #include <ip_compat.h>
46 #elif HAVE_NETINET_IP_COMPAT_H
47 #include <netinet/ip_compat.h>
51 #elif HAVE_NETINET_IP_FIL_H
52 #include <netinet/ip_fil.h>
56 #elif HAVE_NETINET_IP_NAT_H
57 #include <netinet/ip_nat.h>
64 #define comm_close comm_lingering_close
67 static const char *const crlf
= "\r\n";
69 #define REQUEST_BUF_SIZE 4096
70 #define FAILURE_MODE_TIME 300
74 static CWCB clientWriteComplete
;
75 static CWCB clientWriteBodyComplete
;
76 static PF clientReadRequest
;
77 static PF connStateFree
;
78 static PF requestTimeout
;
79 static int clientCheckTransferDone(clientHttpRequest
*);
80 static int clientGotNotEnough(clientHttpRequest
*);
81 static void checkFailureRatio(err_type
, hier_code
);
82 static void clientProcessMiss(clientHttpRequest
*);
83 static void clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
);
84 static clientHttpRequest
*parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
);
85 static clientHttpRequest
*parseHttpRequest(ConnStateData
*, method_t
*, int *, char **, size_t *);
86 static RH clientRedirectDone
;
87 static void clientCheckNoCache(clientHttpRequest
*);
88 static void clientCheckNoCacheDone(int answer
, void *data
);
89 static STCB clientHandleIMSReply
;
90 static int clientGetsOldEntry(StoreEntry
* new, StoreEntry
* old
, request_t
* request
);
91 static int checkAccelOnly(clientHttpRequest
*);
93 static IDCB clientIdentDone
;
95 static int clientOnlyIfCached(clientHttpRequest
* http
);
96 static STCB clientSendMoreData
;
97 static STCB clientCacheHit
;
98 static void clientSetKeepaliveFlag(clientHttpRequest
*);
99 static void clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
);
100 static void clientPackTermBound(String boundary
, MemBuf
* mb
);
101 static void clientInterpretRequestHeaders(clientHttpRequest
*);
102 static void clientProcessRequest(clientHttpRequest
*);
103 static void clientProcessExpired(void *data
);
104 static void clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
);
105 static int clientCachable(clientHttpRequest
* http
);
106 static int clientHierarchical(clientHttpRequest
* http
);
107 static int clientCheckContentLength(request_t
* r
);
108 static int httpAcceptDefer(void);
109 static log_type
clientProcessRequest2(clientHttpRequest
* http
);
110 static int clientReplyBodyTooLarge(int clen
);
111 static int clientRequestBodyTooLarge(int clen
);
114 checkAccelOnly(clientHttpRequest
* http
)
116 /* return TRUE if someone makes a proxy request to us and
117 * we are in httpd-accel only mode */
118 if (!Config2
.Accel
.on
)
120 if (Config
.onoff
.accel_with_proxy
)
122 if (http
->request
->protocol
== PROTO_CACHEOBJ
)
124 if (http
->flags
.accel
)
131 clientIdentDone(const char *ident
, void *data
)
133 ConnStateData
*conn
= data
;
135 xstrncpy(conn
->ident
, ident
, sizeof(conn
->ident
));
137 xstrncpy(conn
->ident
, "-", sizeof(conn
->ident
));
142 clientAclChecklistCreate(const acl_access
* acl
, const clientHttpRequest
* http
)
145 ConnStateData
*conn
= http
->conn
;
146 ch
= aclChecklistCreate(acl
,
151 * hack for ident ACL. It needs to get full addresses, and a
152 * place to store the ident result on persistent connections...
155 cbdataLock(ch
->conn
);
161 clientAccessCheck(void *data
)
163 clientHttpRequest
*http
= data
;
164 if (checkAccelOnly(http
)) {
165 clientAccessCheckDone(ACCESS_ALLOWED
, http
);
168 http
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.http
, http
);
169 aclNBCheck(http
->acl_checklist
, clientAccessCheckDone
, http
);
173 * returns true if client specified that the object must come from the cache
174 * witout contacting origin server
177 clientOnlyIfCached(clientHttpRequest
* http
)
179 const request_t
*r
= http
->request
;
181 return r
->cache_control
&&
182 EBIT_TEST(r
->cache_control
->mask
, CC_ONLY_IF_CACHED
);
186 clientCreateStoreEntry(clientHttpRequest
* h
, method_t m
, request_flags flags
)
190 * For erroneous requests, we might not have a h->request,
191 * so make a fake one.
193 if (h
->request
== NULL
)
194 h
->request
= requestLink(requestCreate(m
, PROTO_NONE
, null_string
));
195 e
= storeCreateEntry(h
->uri
, h
->log_uri
, flags
, m
);
196 h
->sc
= storeClientListAdd(e
, h
);
198 delaySetStoreClient(h
->sc
, delayClient(h
->request
));
200 storeClientCopy(h
->sc
, e
, 0, 0, CLIENT_SOCK_SZ
,
201 memAllocate(MEM_CLIENT_SOCK_BUF
), clientSendMoreData
, h
);
206 clientAccessCheckDone(int answer
, void *data
)
208 clientHttpRequest
*http
= data
;
211 ErrorState
*err
= NULL
;
212 debug(33, 2) ("The request %s %s is %s, because it matched '%s'\n",
213 RequestMethodStr
[http
->request
->method
], http
->uri
,
214 answer
== ACCESS_ALLOWED
? "ALLOWED" : "DENIED",
215 AclMatchedName
? AclMatchedName
: "NO ACL's");
216 http
->acl_checklist
= NULL
;
217 if (answer
== ACCESS_ALLOWED
) {
218 safe_free(http
->uri
);
219 http
->uri
= xstrdup(urlCanonical(http
->request
));
220 assert(http
->redirect_state
== REDIRECT_NONE
);
221 http
->redirect_state
= REDIRECT_PENDING
;
222 redirectStart(http
, clientRedirectDone
, http
);
224 debug(33, 5) ("Access Denied: %s\n", http
->uri
);
225 debug(33, 5) ("AclMatchedName = %s\n",
226 AclMatchedName
? AclMatchedName
: "<null>");
228 * NOTE: get page_id here, based on AclMatchedName because
229 * if USE_DELAY_POOLS is enabled, then AclMatchedName gets
230 * clobbered in the clientCreateStoreEntry() call
231 * just below. Pedro Ribeiro <pribeiro@isel.pt>
233 page_id
= aclGetDenyInfoPage(&Config
.denyInfoList
, AclMatchedName
);
234 http
->log_type
= LOG_TCP_DENIED
;
235 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
237 if (answer
== ACCESS_REQ_PROXY_AUTH
|| aclIsProxyAuth(AclMatchedName
)) {
238 if (!http
->flags
.accel
) {
239 /* Proxy authorisation needed */
240 status
= HTTP_PROXY_AUTHENTICATION_REQUIRED
;
242 /* WWW authorisation needed */
243 status
= HTTP_UNAUTHORIZED
;
246 page_id
= ERR_CACHE_ACCESS_DENIED
;
248 status
= HTTP_FORBIDDEN
;
250 page_id
= ERR_ACCESS_DENIED
;
252 err
= errorCon(page_id
, status
);
253 err
->request
= requestLink(http
->request
);
254 err
->src_addr
= http
->conn
->peer
.sin_addr
;
255 errorAppendEntry(http
->entry
, err
);
260 clientRedirectDone(void *data
, char *result
)
262 clientHttpRequest
*http
= data
;
263 request_t
*new_request
= NULL
;
264 request_t
*old_request
= http
->request
;
265 debug(33, 5) ("clientRedirectDone: '%s' result=%s\n", http
->uri
,
266 result
? result
: "NULL");
267 assert(http
->redirect_state
== REDIRECT_PENDING
);
268 http
->redirect_state
= REDIRECT_DONE
;
270 http_status status
= atoi(result
);
271 if (status
== 301 || status
== 302) {
273 if ((t
= strchr(result
, ':')) != NULL
) {
274 http
->redirect
.status
= status
;
275 http
->redirect
.location
= xstrdup(t
+ 1);
277 debug(33, 1) ("clientRedirectDone: bad input: %s\n", result
);
280 if (strcmp(result
, http
->uri
))
281 new_request
= urlParse(old_request
->method
, result
);
284 safe_free(http
->uri
);
285 http
->uri
= xstrdup(urlCanonical(new_request
));
286 new_request
->http_ver
= old_request
->http_ver
;
287 httpHeaderAppend(&new_request
->header
, &old_request
->header
);
288 new_request
->client_addr
= old_request
->client_addr
;
289 new_request
->my_addr
= old_request
->my_addr
;
290 new_request
->my_port
= old_request
->my_port
;
291 new_request
->flags
.redirected
= 1;
292 if (old_request
->body
) {
293 new_request
->body
= xmalloc(old_request
->body_sz
);
294 xmemcpy(new_request
->body
, old_request
->body
, old_request
->body_sz
);
295 new_request
->body_sz
= old_request
->body_sz
;
297 new_request
->content_length
= old_request
->content_length
;
298 requestUnlink(old_request
);
299 http
->request
= requestLink(new_request
);
301 clientInterpretRequestHeaders(http
);
303 headersLog(0, 1, request
->method
, request
);
305 fd_note(http
->conn
->fd
, http
->uri
);
306 clientCheckNoCache(http
);
310 clientCheckNoCache(clientHttpRequest
* http
)
312 if (Config
.accessList
.noCache
&& http
->request
->flags
.cachable
) {
313 http
->acl_checklist
= clientAclChecklistCreate(Config
.accessList
.noCache
, http
);
314 aclNBCheck(http
->acl_checklist
, clientCheckNoCacheDone
, http
);
316 clientCheckNoCacheDone(http
->request
->flags
.cachable
, http
);
321 clientCheckNoCacheDone(int answer
, void *data
)
323 clientHttpRequest
*http
= data
;
324 http
->request
->flags
.cachable
= answer
;
325 http
->acl_checklist
= NULL
;
326 clientProcessRequest(http
);
330 clientProcessExpired(void *data
)
332 clientHttpRequest
*http
= data
;
333 char *url
= http
->uri
;
334 StoreEntry
*entry
= NULL
;
335 debug(33, 3) ("clientProcessExpired: '%s'\n", http
->uri
);
336 assert(http
->entry
->lastmod
>= 0);
338 * check if we are allowed to contact other servers
339 * @?@: Instead of a 504 (Gateway Timeout) reply, we may want to return
340 * a stale entry *if* it matches client requirements
342 if (clientOnlyIfCached(http
)) {
343 clientProcessOnlyIfCachedMiss(http
);
346 http
->request
->flags
.refresh
= 1;
347 http
->old_entry
= http
->entry
;
348 http
->old_sc
= http
->sc
;
350 * Assert that 'http' is already a client of old_entry. If
351 * it is not, then the beginning of the object data might get
352 * freed from memory before we need to access it.
354 assert(http
->sc
->callback_data
== http
);
355 entry
= storeCreateEntry(url
,
357 http
->request
->flags
,
358 http
->request
->method
);
359 /* NOTE, don't call storeLockObject(), storeCreateEntry() does it */
360 http
->sc
= storeClientListAdd(entry
, http
);
362 /* delay_id is already set on original store client */
363 delaySetStoreClient(http
->sc
, delayClient(http
->request
));
365 http
->request
->lastmod
= http
->old_entry
->lastmod
;
366 debug(33, 5) ("clientProcessExpired: lastmod %d\n", (int) entry
->lastmod
);
368 http
->out
.offset
= 0;
369 fwdStart(http
->conn
->fd
, http
->entry
, http
->request
);
370 /* Register with storage manager to receive updates when data comes in. */
371 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
372 debug(33, 0) ("clientProcessExpired: found ENTRY_ABORTED object\n");
373 storeClientCopy(http
->sc
, entry
,
377 memAllocate(MEM_CLIENT_SOCK_BUF
),
378 clientHandleIMSReply
,
383 clientGetsOldEntry(StoreEntry
* new_entry
, StoreEntry
* old_entry
, request_t
* request
)
385 const http_status status
= new_entry
->mem_obj
->reply
->sline
.status
;
387 debug(33, 5) ("clientGetsOldEntry: YES, broken HTTP reply\n");
390 /* If the reply is a failure then send the old object as a last
392 if (status
>= 500 && status
< 600) {
393 debug(33, 3) ("clientGetsOldEntry: YES, failure reply=%d\n", status
);
396 /* If the reply is anything but "Not Modified" then
397 * we must forward it to the client */
398 if (HTTP_NOT_MODIFIED
!= status
) {
399 debug(33, 5) ("clientGetsOldEntry: NO, reply=%d\n", status
);
402 /* If the client did not send IMS in the request, then it
403 * must get the old object, not this "Not Modified" reply */
404 if (!request
->flags
.ims
) {
405 debug(33, 5) ("clientGetsOldEntry: YES, no client IMS\n");
408 /* If the client IMS time is prior to the entry LASTMOD time we
409 * need to send the old object */
410 if (modifiedSince(old_entry
, request
)) {
411 debug(33, 5) ("clientGetsOldEntry: YES, modified since %d\n",
415 debug(33, 5) ("clientGetsOldEntry: NO, new one is fine\n");
421 clientHandleIMSReply(void *data
, char *buf
, ssize_t size
)
423 clientHttpRequest
*http
= data
;
424 StoreEntry
*entry
= http
->entry
;
426 const char *url
= storeUrl(entry
);
427 int unlink_request
= 0;
428 StoreEntry
*oldentry
;
431 debug(33, 3) ("clientHandleIMSReply: %s, %d bytes\n", url
, (int) size
);
433 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
436 if (size
< 0 && !EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
437 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
440 mem
= entry
->mem_obj
;
441 status
= mem
->reply
->sline
.status
;
442 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
443 debug(33, 3) ("clientHandleIMSReply: ABORTED '%s'\n", url
);
444 /* We have an existing entry, but failed to validate it */
445 /* Its okay to send the old one anyway */
446 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
447 storeUnregister(http
->sc
, entry
, http
);
448 storeUnlockObject(entry
);
449 entry
= http
->entry
= http
->old_entry
;
450 http
->sc
= http
->old_sc
;
451 } else if (STORE_PENDING
== entry
->store_status
&& 0 == status
) {
452 debug(33, 3) ("clientHandleIMSReply: Incomplete headers for '%s'\n", url
);
453 if (size
>= CLIENT_SOCK_SZ
) {
454 /* will not get any bigger than that */
455 debug(33, 3) ("clientHandleIMSReply: Reply is too large '%s', using old entry\n", url
);
456 /* use old entry, this repeats the code abovez */
457 http
->log_type
= LOG_TCP_REFRESH_FAIL_HIT
;
458 storeUnregister(http
->sc
, entry
, http
);
459 storeUnlockObject(entry
);
460 entry
= http
->entry
= http
->old_entry
;
461 http
->sc
= http
->old_sc
;
464 storeClientCopy(http
->sc
, entry
,
465 http
->out
.offset
+ size
,
469 clientHandleIMSReply
,
473 } else if (clientGetsOldEntry(entry
, http
->old_entry
, http
->request
)) {
474 /* We initiated the IMS request, the client is not expecting
475 * 304, so put the good one back. First, make sure the old entry
476 * headers have been loaded from disk. */
477 oldentry
= http
->old_entry
;
478 http
->log_type
= LOG_TCP_REFRESH_HIT
;
479 if (oldentry
->mem_obj
->request
== NULL
) {
480 oldentry
->mem_obj
->request
= requestLink(mem
->request
);
483 /* Don't memcpy() the whole reply structure here. For example,
484 * www.thegist.com (Netscape/1.13) returns a content-length for
485 * 304's which seems to be the length of the 304 HEADERS!!! and
486 * not the body they refer to. */
487 httpReplyUpdateOnNotModified(oldentry
->mem_obj
->reply
, mem
->reply
);
488 storeTimestampsSet(oldentry
);
489 storeUnregister(http
->sc
, entry
, http
);
490 http
->sc
= http
->old_sc
;
491 storeUnlockObject(entry
);
492 entry
= http
->entry
= oldentry
;
493 entry
->timestamp
= squid_curtime
;
494 if (unlink_request
) {
495 requestUnlink(entry
->mem_obj
->request
);
496 entry
->mem_obj
->request
= NULL
;
499 /* the client can handle this reply, whatever it is */
500 http
->log_type
= LOG_TCP_REFRESH_MISS
;
501 if (HTTP_NOT_MODIFIED
== mem
->reply
->sline
.status
) {
502 httpReplyUpdateOnNotModified(http
->old_entry
->mem_obj
->reply
,
504 storeTimestampsSet(http
->old_entry
);
505 http
->log_type
= LOG_TCP_REFRESH_HIT
;
507 storeUnregister(http
->old_sc
, http
->old_entry
, http
);
508 storeUnlockObject(http
->old_entry
);
511 http
->old_entry
= NULL
; /* done with old_entry */
513 assert(!EBIT_TEST(entry
->flags
, ENTRY_ABORTED
));
515 storeClientCopy(http
->sc
, entry
,
523 clientSendMoreData(data
, buf
, size
);
528 modifiedSince(StoreEntry
* entry
, request_t
* request
)
531 MemObject
*mem
= entry
->mem_obj
;
532 time_t mod_time
= entry
->lastmod
;
533 debug(33, 3) ("modifiedSince: '%s'\n", storeUrl(entry
));
535 mod_time
= entry
->timestamp
;
536 debug(33, 3) ("modifiedSince: mod_time = %d\n", (int) mod_time
);
539 /* Find size of the object */
540 object_length
= mem
->reply
->content_length
;
541 if (object_length
< 0)
542 object_length
= contentLen(entry
);
543 if (mod_time
> request
->ims
) {
544 debug(33, 3) ("--> YES: entry newer than client\n");
546 } else if (mod_time
< request
->ims
) {
547 debug(33, 3) ("--> NO: entry older than client\n");
549 } else if (request
->imslen
< 0) {
550 debug(33, 3) ("--> NO: same LMT, no client length\n");
552 } else if (request
->imslen
== object_length
) {
553 debug(33, 3) ("--> NO: same LMT, same length\n");
556 debug(33, 3) ("--> YES: same LMT, different length\n");
562 clientPurgeRequest(clientHttpRequest
* http
)
565 ErrorState
*err
= NULL
;
567 debug(33, 1) ("Config2.onoff.enable_purge = %d\n", Config2
.onoff
.enable_purge
);
568 if (!Config2
.onoff
.enable_purge
) {
569 http
->log_type
= LOG_TCP_DENIED
;
570 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
571 err
->request
= requestLink(http
->request
);
572 err
->src_addr
= http
->conn
->peer
.sin_addr
;
573 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
574 errorAppendEntry(http
->entry
, err
);
577 http
->log_type
= LOG_TCP_MISS
;
578 /* Release both IP and object cache entries */
579 ipcacheInvalidate(http
->request
->host
);
580 if ((entry
= storeGetPublic(http
->uri
, METHOD_GET
)) == NULL
) {
581 http
->http_code
= HTTP_NOT_FOUND
;
584 http
->http_code
= HTTP_OK
;
586 debug(33, 4) ("clientPurgeRequest: Not modified '%s'\n",
589 * Make a new entry to hold the reply to be written
592 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
593 httpReplyReset(r
= http
->entry
->mem_obj
->reply
);
594 httpReplySetHeaders(r
, 1.0, http
->http_code
, NULL
, NULL
, 0, 0, -1);
595 httpReplySwapOut(r
, http
->entry
);
596 storeComplete(http
->entry
);
600 checkNegativeHit(StoreEntry
* e
)
602 if (!EBIT_TEST(e
->flags
, ENTRY_NEGCACHED
))
604 if (e
->expires
<= squid_curtime
)
606 if (e
->store_status
!= STORE_OK
)
612 clientUpdateCounters(clientHttpRequest
* http
)
614 int svc_time
= tvSubMsec(http
->start
, current_time
);
616 HierarchyLogEntry
*H
;
617 Counter
.client_http
.requests
++;
618 if (isTcpHit(http
->log_type
))
619 Counter
.client_http
.hits
++;
620 if (http
->log_type
== LOG_TCP_HIT
)
621 Counter
.client_http
.disk_hits
++;
622 else if (http
->log_type
== LOG_TCP_MEM_HIT
)
623 Counter
.client_http
.mem_hits
++;
624 if (http
->request
->err_type
!= ERR_NONE
)
625 Counter
.client_http
.errors
++;
626 statHistCount(&Counter
.client_http
.all_svc_time
, svc_time
);
628 * The idea here is not to be complete, but to get service times
629 * for only well-defined types. For example, we don't include
630 * LOG_TCP_REFRESH_FAIL_HIT because its not really a cache hit
631 * (we *tried* to validate it, but failed).
633 switch (http
->log_type
) {
634 case LOG_TCP_REFRESH_HIT
:
635 statHistCount(&Counter
.client_http
.nh_svc_time
, svc_time
);
637 case LOG_TCP_IMS_HIT
:
638 statHistCount(&Counter
.client_http
.nm_svc_time
, svc_time
);
641 case LOG_TCP_MEM_HIT
:
642 case LOG_TCP_OFFLINE_HIT
:
643 statHistCount(&Counter
.client_http
.hit_svc_time
, svc_time
);
646 case LOG_TCP_CLIENT_REFRESH_MISS
:
647 statHistCount(&Counter
.client_http
.miss_svc_time
, svc_time
);
650 /* make compiler warnings go away */
653 H
= &http
->request
->hier
;
656 Counter
.cd
.times_used
++;
659 Counter
.icp
.times_used
++;
661 if (0 != i
->stop
.tv_sec
&& 0 != i
->start
.tv_sec
)
662 statHistCount(&Counter
.icp
.query_svc_time
,
663 tvSubUsec(i
->start
, i
->stop
));
665 Counter
.icp
.query_timeouts
++;
668 Counter
.netdb
.times_used
++;
676 httpRequestFree(void *data
)
678 clientHttpRequest
*http
= data
;
679 clientHttpRequest
**H
;
680 ConnStateData
*conn
= http
->conn
;
682 request_t
*request
= http
->request
;
683 MemObject
*mem
= NULL
;
684 debug(33, 3) ("httpRequestFree: %s\n", storeUrl(http
->entry
));
685 if (!clientCheckTransferDone(http
)) {
688 * DW: this seems odd here, is it really needed? It causes
689 * incomplete transfers to get logged with "000" status
690 * code because http->entry becomes NULL.
692 if ((e
= http
->entry
)) {
694 storeUnregister(http
->sc
, e
, http
);
695 storeUnlockObject(e
);
698 if (http
->entry
&& http
->entry
->ping_status
== PING_WAITING
)
699 storeReleaseRequest(http
->entry
);
701 assert(http
->log_type
< LOG_TYPE_MAX
);
703 mem
= http
->entry
->mem_obj
;
704 if (http
->out
.size
|| http
->log_type
) {
705 http
->al
.icp
.opcode
= ICP_INVALID
;
706 http
->al
.url
= http
->log_uri
;
707 debug(33, 9) ("httpRequestFree: al.url='%s'\n", http
->al
.url
);
709 http
->al
.http
.code
= mem
->reply
->sline
.status
;
710 http
->al
.http
.content_type
= strBuf(mem
->reply
->content_type
);
712 http
->al
.cache
.caddr
= conn
->log_addr
;
713 http
->al
.cache
.size
= http
->out
.size
;
714 http
->al
.cache
.code
= http
->log_type
;
715 http
->al
.cache
.msec
= tvSubMsec(http
->start
, current_time
);
720 packerToMemInit(&p
, &mb
);
721 httpHeaderPackInto(&request
->header
, &p
);
722 http
->al
.http
.method
= request
->method
;
723 http
->al
.http
.version
= request
->http_ver
;
724 http
->al
.headers
.request
= xstrdup(mb
.buf
);
725 http
->al
.hier
= request
->hier
;
726 if (request
->user_ident
[0])
727 http
->al
.cache
.ident
= request
->user_ident
;
729 http
->al
.cache
.ident
= conn
->ident
;
733 accessLogLog(&http
->al
);
734 clientUpdateCounters(http
);
735 clientdbUpdate(conn
->peer
.sin_addr
, http
->log_type
, PROTO_HTTP
, http
->out
.size
);
737 if (http
->acl_checklist
)
738 aclChecklistFree(http
->acl_checklist
);
740 checkFailureRatio(request
->err_type
, http
->al
.hier
.code
);
741 safe_free(http
->uri
);
742 safe_free(http
->log_uri
);
743 safe_free(http
->al
.headers
.request
);
744 safe_free(http
->al
.headers
.reply
);
745 safe_free(http
->redirect
.location
);
746 stringClean(&http
->range_iter
.boundary
);
747 if ((e
= http
->entry
)) {
749 storeUnregister(http
->sc
, e
, http
);
750 storeUnlockObject(e
);
752 /* old_entry might still be set if we didn't yet get the reply
753 * code in clientHandleIMSReply() */
754 if ((e
= http
->old_entry
)) {
755 http
->old_entry
= NULL
;
756 storeUnregister(http
->sc
, e
, http
);
757 storeUnlockObject(e
);
759 requestUnlink(http
->request
);
760 assert(http
!= http
->next
);
761 assert(http
->conn
->chr
!= NULL
);
762 H
= &http
->conn
->chr
;
771 dlinkDelete(&http
->active
, &ClientActiveRequests
);
775 /* This is a handler normally called by comm_close() */
777 connStateFree(int fd
, void *data
)
779 ConnStateData
*connState
= data
;
780 clientHttpRequest
*http
;
781 debug(33, 3) ("connStateFree: FD %d\n", fd
);
782 assert(connState
!= NULL
);
783 clientdbEstablished(connState
->peer
.sin_addr
, -1); /* decrement */
784 while ((http
= connState
->chr
) != NULL
) {
785 assert(http
->conn
== connState
);
786 assert(connState
->chr
!= connState
->chr
->next
);
787 httpRequestFree(http
);
789 safe_free(connState
->in
.buf
);
790 /* XXX account connState->in.buf */
791 pconnHistCount(0, connState
->nrequests
);
792 cbdataFree(connState
);
794 /* prevent those nasty RST packets */
796 char buf
[SQUID_TCP_SO_RCVBUF
];
797 while (read(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0);
803 clientInterpretRequestHeaders(clientHttpRequest
* http
)
805 request_t
*request
= http
->request
;
806 const HttpHeader
*req_hdr
= &request
->header
;
808 #if USE_USERAGENT_LOG
811 request
->imslen
= -1;
812 request
->ims
= httpHeaderGetTime(req_hdr
, HDR_IF_MODIFIED_SINCE
);
813 if (request
->ims
> 0)
814 request
->flags
.ims
= 1;
815 if (httpHeaderHas(req_hdr
, HDR_PRAGMA
)) {
816 String s
= httpHeaderGetList(req_hdr
, HDR_PRAGMA
);
817 if (strListIsMember(&s
, "no-cache", ','))
821 request
->cache_control
= httpHeaderGetCc(req_hdr
);
822 if (request
->cache_control
)
823 if (EBIT_TEST(request
->cache_control
->mask
, CC_NO_CACHE
))
827 if (Config
.onoff
.reload_into_ims
)
828 request
->flags
.nocache_hack
= 1;
829 else if (refresh_nocache_hack
)
830 request
->flags
.nocache_hack
= 1;
833 request
->flags
.nocache
= 1;
835 /* ignore range header in non-GETs */
836 if (request
->method
== METHOD_GET
) {
837 request
->range
= httpHeaderGetRange(req_hdr
);
839 request
->flags
.range
= 1;
841 if (httpHeaderHas(req_hdr
, HDR_AUTHORIZATION
))
842 request
->flags
.auth
= 1;
843 if (request
->login
[0] != '\0')
844 request
->flags
.auth
= 1;
845 if (httpHeaderHas(req_hdr
, HDR_VIA
)) {
846 String s
= httpHeaderGetList(req_hdr
, HDR_VIA
);
848 * ThisCache cannot be a member of Via header, "1.0 ThisCache" can.
849 * Note ThisCache2 has a space prepended to the hostname so we don't
850 * accidentally match super-domains.
852 if (strListIsSubstr(&s
, ThisCache2
, ',')) {
853 debugObj(33, 1, "WARNING: Forwarding loop detected for:\n",
854 request
, (ObjPackMethod
) & httpRequestPack
);
855 request
->flags
.loopdetect
= 1;
858 fvdbCountVia(strBuf(s
));
862 #if USE_USERAGENT_LOG
863 if ((str
= httpHeaderGetStr(req_hdr
, HDR_USER_AGENT
)))
864 logUserAgent(fqdnFromAddr(http
->conn
->peer
.sin_addr
), str
);
867 if (httpHeaderHas(req_hdr
, HDR_X_FORWARDED_FOR
)) {
868 String s
= httpHeaderGetList(req_hdr
, HDR_X_FORWARDED_FOR
);
869 fvdbCountForw(strBuf(s
));
873 if (request
->method
== METHOD_TRACE
) {
874 request
->max_forwards
= httpHeaderGetInt(req_hdr
, HDR_MAX_FORWARDS
);
876 if (clientCachable(http
))
877 request
->flags
.cachable
= 1;
878 if (clientHierarchical(http
))
879 request
->flags
.hierarchical
= 1;
880 debug(33, 5) ("clientInterpretRequestHeaders: REQ_NOCACHE = %s\n",
881 request
->flags
.nocache
? "SET" : "NOT SET");
882 debug(33, 5) ("clientInterpretRequestHeaders: REQ_CACHABLE = %s\n",
883 request
->flags
.cachable
? "SET" : "NOT SET");
884 debug(33, 5) ("clientInterpretRequestHeaders: REQ_HIERARCHICAL = %s\n",
885 request
->flags
.hierarchical
? "SET" : "NOT SET");
889 * clientSetKeepaliveFlag() sets request->flags.proxy_keepalive.
890 * This is the client-side persistent connection flag. We need
891 * to set this relatively early in the request processing
892 * to handle hacks for broken servers and clients.
895 clientSetKeepaliveFlag(clientHttpRequest
* http
)
897 request_t
*request
= http
->request
;
898 const HttpHeader
*req_hdr
= &request
->header
;
899 debug(33, 3) ("clientSetKeepaliveFlag: http_ver = %3.1f\n",
901 debug(33, 3) ("clientSetKeepaliveFlag: method = %s\n",
902 RequestMethodStr
[request
->method
]);
903 if (!Config
.onoff
.client_pconns
)
904 request
->flags
.proxy_keepalive
= 0;
905 else if (httpMsgIsPersistent(request
->http_ver
, req_hdr
))
906 request
->flags
.proxy_keepalive
= 1;
910 clientCheckContentLength(request_t
* r
)
912 int has_cont_len
= (r
->content_length
>= 0);
916 /* PUT/POST requires a request entity */
920 /* We do not want to see a request entity on GET/HEAD requests */
921 return !has_cont_len
;
923 /* For other types of requests we don't care */
930 clientCachable(clientHttpRequest
* http
)
932 const char *url
= http
->uri
;
933 request_t
*req
= http
->request
;
934 method_t method
= req
->method
;
935 if (req
->protocol
== PROTO_HTTP
)
936 return httpCachable(method
);
937 /* FTP is always cachable */
938 if (req
->protocol
== PROTO_GOPHER
)
939 return gopherCachable(url
);
940 if (req
->protocol
== PROTO_WAIS
)
942 if (method
== METHOD_CONNECT
)
944 if (method
== METHOD_TRACE
)
946 if (req
->protocol
== PROTO_CACHEOBJ
)
951 /* Return true if we can query our neighbors for this object */
953 clientHierarchical(clientHttpRequest
* http
)
955 const char *url
= http
->uri
;
956 request_t
*request
= http
->request
;
957 method_t method
= request
->method
;
958 const wordlist
*p
= NULL
;
960 /* IMS needs a private key, so we can use the hierarchy for IMS only
961 * if our neighbors support private keys */
962 if (request
->flags
.ims
&& !neighbors_do_private_keys
)
964 if (request
->flags
.auth
)
966 if (method
== METHOD_TRACE
)
968 if (method
!= METHOD_GET
)
970 /* scan hierarchy_stoplist */
971 for (p
= Config
.hierarchy_stoplist
; p
; p
= p
->next
)
972 if (strstr(url
, p
->key
))
974 if (request
->flags
.loopdetect
)
976 if (request
->protocol
== PROTO_HTTP
)
977 return httpCachable(method
);
978 if (request
->protocol
== PROTO_GOPHER
)
979 return gopherCachable(url
);
980 if (request
->protocol
== PROTO_WAIS
)
982 if (request
->protocol
== PROTO_CACHEOBJ
)
988 isTcpHit(log_type code
)
990 /* this should be a bitmap for better optimization */
991 if (code
== LOG_TCP_HIT
)
993 if (code
== LOG_TCP_IMS_HIT
)
995 if (code
== LOG_TCP_REFRESH_FAIL_HIT
)
997 if (code
== LOG_TCP_REFRESH_HIT
)
999 if (code
== LOG_TCP_NEGATIVE_HIT
)
1001 if (code
== LOG_TCP_MEM_HIT
)
1003 if (code
== LOG_TCP_OFFLINE_HIT
)
1009 * returns true if If-Range specs match reply, false otherwise
1012 clientIfRangeMatch(clientHttpRequest
* http
, HttpReply
* rep
)
1014 const TimeOrTag spec
= httpHeaderGetTimeOrTag(&http
->request
->header
, HDR_IF_RANGE
);
1015 /* check for parsing falure */
1020 ETag rep_tag
= httpHeaderGetETag(&rep
->header
, HDR_ETAG
);
1021 debug(33, 3) ("clientIfRangeMatch: ETags: %s and %s\n",
1022 spec
.tag
.str
, rep_tag
.str
? rep_tag
.str
: "<none>");
1024 return 0; /* entity has no etag to compare with! */
1025 if (spec
.tag
.weak
|| rep_tag
.weak
) {
1026 debug(33, 1) ("clientIfRangeMatch: Weak ETags are not allowed in If-Range: %s ? %s\n",
1027 spec
.tag
.str
, rep_tag
.str
);
1028 return 0; /* must use strong validator for sub-range requests */
1030 return etagIsEqual(&rep_tag
, &spec
.tag
);
1032 /* got modification time? */
1033 if (spec
.time
>= 0) {
1034 return http
->entry
->lastmod
<= spec
.time
;
1036 assert(0); /* should not happen */
1040 /* returns expected content length for multi-range replies
1041 * note: assumes that httpHdrRangeCanonize has already been called
1042 * warning: assumes that HTTP headers for individual ranges at the
1043 * time of the actuall assembly will be exactly the same as
1044 * the headers when clientMRangeCLen() is called */
1046 clientMRangeCLen(clientHttpRequest
* http
)
1049 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1050 const HttpHdrRangeSpec
*spec
;
1053 assert(http
->entry
->mem_obj
);
1056 while ((spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
))) {
1058 /* account for headers for this range */
1060 clientPackRangeHdr(http
->entry
->mem_obj
->reply
,
1061 spec
, http
->range_iter
.boundary
, &mb
);
1064 /* account for range content */
1065 clen
+= spec
->length
;
1067 debug(33, 6) ("clientMRangeCLen: (clen += %d + %d) == %d\n",
1068 mb
.size
, spec
->length
, clen
);
1070 /* account for the terminating boundary */
1072 clientPackTermBound(http
->range_iter
.boundary
, &mb
);
1079 /* adds appropriate Range headers if needed */
1081 clientBuildRangeHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1083 HttpHeader
*hdr
= rep
? &rep
->header
: 0;
1084 const char *range_err
= NULL
;
1085 request_t
*request
= http
->request
;
1086 int is_hit
= isTcpHit(http
->log_type
);
1087 assert(request
->range
);
1088 /* check if we still want to do ranges */
1090 range_err
= "no [parse-able] reply";
1091 else if (rep
->sline
.status
!= HTTP_OK
)
1092 range_err
= "wrong status code";
1093 else if (httpHeaderHas(hdr
, HDR_CONTENT_RANGE
))
1094 range_err
= "origin server does ranges";
1095 else if (rep
->content_length
< 0)
1096 range_err
= "unknown length";
1097 else if (rep
->content_length
!= http
->entry
->mem_obj
->reply
->content_length
)
1098 range_err
= "INCONSISTENT length"; /* a bug? */
1099 else if (httpHeaderHas(&http
->request
->header
, HDR_IF_RANGE
) && !clientIfRangeMatch(http
, rep
))
1100 range_err
= "If-Range match failed";
1101 else if (!httpHdrRangeCanonize(http
->request
->range
, rep
->content_length
))
1102 range_err
= "canonization failed";
1103 else if (httpHdrRangeIsComplex(http
->request
->range
))
1104 range_err
= "too complex range header";
1105 else if (!request
->flags
.cachable
) /* from we_do_ranges in http.c */
1106 range_err
= "non-cachable request";
1107 else if (!is_hit
&& Config
.rangeOffsetLimit
< httpHdrRangeFirstOffset(request
->range
)
1108 && Config
.rangeOffsetLimit
!= -1) /* from we_do_ranges in http.c */
1109 range_err
= "range outside range_offset_limit";
1110 /* get rid of our range specs on error */
1112 debug(33, 3) ("clientBuildRangeHeader: will not do ranges: %s.\n", range_err
);
1113 httpHdrRangeDestroy(http
->request
->range
);
1114 http
->request
->range
= NULL
;
1116 const int spec_count
= http
->request
->range
->specs
.count
;
1117 int actual_clen
= -1;
1119 debug(33, 3) ("clientBuildRangeHeader: range spec count: %d virgin clen: %d\n",
1120 spec_count
, rep
->content_length
);
1121 assert(spec_count
> 0);
1122 /* ETags should not be returned with Partial Content replies? */
1123 httpHeaderDelById(hdr
, HDR_ETAG
);
1124 /* append appropriate header(s) */
1125 if (spec_count
== 1) {
1126 HttpHdrRangePos pos
= HttpHdrRangeInitPos
;
1127 const HttpHdrRangeSpec
*spec
= httpHdrRangeGetSpec(http
->request
->range
, &pos
);
1129 /* append Content-Range */
1130 httpHeaderAddContRange(hdr
, *spec
, rep
->content_length
);
1131 /* set new Content-Length to the actual number of bytes
1132 * transmitted in the message-body */
1133 actual_clen
= spec
->length
;
1136 /* generate boundary string */
1137 http
->range_iter
.boundary
= httpHdrRangeBoundaryStr(http
);
1138 /* delete old Content-Type, add ours */
1139 httpHeaderDelById(hdr
, HDR_CONTENT_TYPE
);
1140 httpHeaderPutStrf(hdr
, HDR_CONTENT_TYPE
,
1141 "multipart/byteranges; boundary=\"%s\"",
1142 strBuf(http
->range_iter
.boundary
));
1143 /* Content-Length is not required in multipart responses
1144 * but it is always nice to have one */
1145 actual_clen
= clientMRangeCLen(http
);
1148 /* replace Content-Length header */
1149 assert(actual_clen
>= 0);
1150 httpHeaderDelById(hdr
, HDR_CONTENT_LENGTH
);
1151 httpHeaderPutInt(hdr
, HDR_CONTENT_LENGTH
, actual_clen
);
1152 debug(33, 3) ("clientBuildRangeHeader: actual content length: %d\n", actual_clen
);
1157 * filters out unwanted entries from original reply header
1158 * adds extra entries if we have more info than origin server
1159 * adds Squid specific entries
1162 clientBuildReplyHeader(clientHttpRequest
* http
, HttpReply
* rep
)
1164 HttpHeader
*hdr
= &rep
->header
;
1165 int is_hit
= isTcpHit(http
->log_type
);
1166 request_t
*request
= http
->request
;
1167 #if DONT_FILTER_THESE
1168 /* but you might want to if you run Squid as an HTTP accelerator */
1169 /* httpHeaderDelById(hdr, HDR_ACCEPT_RANGES); */
1170 httpHeaderDelById(hdr
, HDR_ETAG
);
1172 httpHeaderDelById(hdr
, HDR_PROXY_CONNECTION
);
1173 /* here: Keep-Alive is a field-name, not a connection directive! */
1174 httpHeaderDelByName(hdr
, "Keep-Alive");
1175 /* remove Set-Cookie if a hit */
1177 httpHeaderDelById(hdr
, HDR_SET_COOKIE
);
1178 /* handle Connection header */
1179 if (httpHeaderHas(hdr
, HDR_CONNECTION
)) {
1180 /* anything that matches Connection list member will be deleted */
1181 String strConnection
= httpHeaderGetList(hdr
, HDR_CONNECTION
);
1182 const HttpHeaderEntry
*e
;
1183 HttpHeaderPos pos
= HttpHeaderInitPos
;
1185 * think: on-average-best nesting of the two loops (hdrEntry
1186 * and strListItem) @?@
1189 * maybe we should delete standard stuff ("keep-alive","close")
1190 * from strConnection first?
1192 while ((e
= httpHeaderGetEntry(hdr
, &pos
))) {
1193 if (strListIsMember(&strConnection
, strBuf(e
->name
), ','))
1194 httpHeaderDelAt(hdr
, pos
);
1196 httpHeaderDelById(hdr
, HDR_CONNECTION
);
1197 stringClean(&strConnection
);
1201 clientBuildRangeHeader(http
, rep
);
1203 * Add a estimated Age header on cache hits.
1207 * Remove any existing Age header sent by upstream caches
1208 * (note that the existing header is passed along unmodified
1211 httpHeaderDelById(hdr
, HDR_AGE
);
1213 * This adds the calculated object age. Note that the details of the
1214 * age calculation is performed by adjusting the timestamp in
1215 * storeTimestampsSet(), not here.
1217 * BROWSER WORKAROUND: IE sometimes hangs when receiving a 0 Age
1218 * header, so don't use it unless there is a age to report. Please
1219 * note that Age is only used to make a conservative estimation of
1220 * the objects age, so a Age: 0 header does not add any useful
1221 * information to the reply in any case.
1223 if (http
->entry
->timestamp
< squid_curtime
)
1224 httpHeaderPutInt(hdr
, HDR_AGE
,
1225 squid_curtime
- http
->entry
->timestamp
);
1227 /* Append X-Cache */
1228 httpHeaderPutStrf(hdr
, HDR_X_CACHE
, "%s from %s",
1229 is_hit
? "HIT" : "MISS", getMyHostname());
1230 #if USE_CACHE_DIGESTS
1231 /* Append X-Cache-Lookup: -- temporary hack, to be removed @?@ @?@ */
1232 httpHeaderPutStrf(hdr
, HDR_X_CACHE_LOOKUP
, "%s from %s:%d",
1233 http
->lookup_type
? http
->lookup_type
: "NONE",
1234 getMyHostname(), ntohs(Config
.Sockaddr
.http
->s
.sin_port
));
1236 if (httpReplyBodySize(request
->method
, rep
) < 0) {
1237 debug(33, 3) ("clientBuildReplyHeader: can't keep-alive, unknown body size\n");
1238 request
->flags
.proxy_keepalive
= 0;
1240 /* Signal keep-alive if needed */
1241 httpHeaderPutStr(hdr
,
1242 http
->flags
.accel
? HDR_CONNECTION
: HDR_PROXY_CONNECTION
,
1243 request
->flags
.proxy_keepalive
? "keep-alive" : "close");
1244 #if ADD_X_REQUEST_URI
1246 * Knowing the URI of the request is useful when debugging persistent
1247 * connections in a client; we cannot guarantee the order of http headers,
1248 * but X-Request-URI is likely to be the very last header to ease use from a
1249 * debugger [hdr->entries.count-1].
1251 httpHeaderPutStr(hdr
, HDR_X_REQUEST_URI
,
1252 http
->entry
->mem_obj
->url
? http
->entry
->mem_obj
->url
: http
->uri
);
1257 clientBuildReply(clientHttpRequest
* http
, const char *buf
, size_t size
)
1259 HttpReply
*rep
= httpReplyCreate();
1260 size_t k
= headersEnd(buf
, size
);
1261 if (k
&& httpReplyParse(rep
, buf
, k
)) {
1262 /* enforce 1.0 reply version */
1263 rep
->sline
.version
= 1.0;
1264 /* do header conversions */
1265 clientBuildReplyHeader(http
, rep
);
1266 /* if we do ranges, change status to "Partial Content" */
1267 if (http
->request
->range
)
1268 httpStatusLineSet(&rep
->sline
, rep
->sline
.version
,
1269 HTTP_PARTIAL_CONTENT
, NULL
);
1271 /* parsing failure, get rid of the invalid reply */
1272 httpReplyDestroy(rep
);
1274 /* if we were going to do ranges, backoff */
1275 if (http
->request
->range
) {
1276 /* this will fail and destroy request->range */
1277 clientBuildRangeHeader(http
, rep
);
1284 * clientCacheHit should only be called until the HTTP reply headers
1285 * have been parsed. Normally this should be a single call, but
1286 * it might take more than one. As soon as we have the headers,
1287 * we hand off to clientSendMoreData, clientProcessExpired, or
1288 * clientProcessMiss.
1291 clientCacheHit(void *data
, char *buf
, ssize_t size
)
1293 clientHttpRequest
*http
= data
;
1294 StoreEntry
*e
= http
->entry
;
1296 request_t
*r
= http
->request
;
1297 debug(33, 3) ("clientCacheHit: %s, %d bytes\n", http
->uri
, (int) size
);
1298 if (http
->entry
== NULL
) {
1299 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1300 debug(33, 3) ("clientCacheHit: request aborted\n");
1302 } else if (size
< 0) {
1303 /* swap in failure */
1304 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1305 debug(33, 3) ("clientCacheHit: swapin failure for %s\n", http
->uri
);
1306 http
->log_type
= LOG_TCP_SWAPFAIL_MISS
;
1307 if ((e
= http
->entry
)) {
1309 storeUnregister(http
->sc
, e
, http
);
1310 storeUnlockObject(e
);
1312 clientProcessMiss(http
);
1317 assert(!EBIT_TEST(e
->flags
, ENTRY_ABORTED
));
1318 if (mem
->reply
->sline
.status
== 0) {
1320 * we don't have full reply headers yet; either wait for more or
1321 * punt to clientProcessMiss.
1323 if (e
->mem_status
== IN_MEMORY
|| e
->store_status
== STORE_OK
) {
1324 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1325 clientProcessMiss(http
);
1326 } else if (size
== CLIENT_SOCK_SZ
&& http
->out
.offset
== 0) {
1327 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1328 clientProcessMiss(http
);
1330 debug(33, 3) ("clientCacheHit: waiting for HTTP reply headers\n");
1331 storeClientCopy(http
->sc
, e
,
1332 http
->out
.offset
+ size
,
1342 * Got the headers, now grok them
1344 assert(http
->log_type
== LOG_TCP_HIT
);
1345 if (checkNegativeHit(e
)) {
1346 http
->log_type
= LOG_TCP_NEGATIVE_HIT
;
1347 clientSendMoreData(data
, buf
, size
);
1348 } else if (r
->method
== METHOD_HEAD
) {
1350 * RFC 2068 seems to indicate there is no "conditional HEAD"
1351 * request. We cannot validate a cached object for a HEAD
1352 * request, nor can we return 304.
1354 if (e
->mem_status
== IN_MEMORY
)
1355 http
->log_type
= LOG_TCP_MEM_HIT
;
1356 clientSendMoreData(data
, buf
, size
);
1357 } else if (refreshCheckHTTP(e
, r
) && !http
->flags
.internal
) {
1358 debug(33, 5) ("clientCacheHit: in refreshCheck() block\n");
1360 * We hold a stale copy; it needs to be validated
1363 * The 'need_validation' flag is used to prevent forwarding
1364 * loops between siblings. If our copy of the object is stale,
1365 * then we should probably only use parents for the validation
1366 * request. Otherwise two siblings could generate a loop if
1367 * both have a stale version of the object.
1369 r
->flags
.need_validation
= 1;
1370 if (e
->lastmod
< 0) {
1372 * Previous reply didn't have a Last-Modified header,
1373 * we cannot revalidate it.
1375 http
->log_type
= LOG_TCP_MISS
;
1376 clientProcessMiss(http
);
1377 } else if (r
->flags
.nocache
) {
1379 * This did not match a refresh pattern that overrides no-cache
1380 * we should honour the client no-cache header.
1382 http
->log_type
= LOG_TCP_CLIENT_REFRESH_MISS
;
1383 clientProcessMiss(http
);
1384 } else if (r
->protocol
== PROTO_HTTP
) {
1386 * Object needs to be revalidated
1387 * XXX This could apply to FTP as well, if Last-Modified is known.
1389 http
->log_type
= LOG_TCP_REFRESH_MISS
;
1390 clientProcessExpired(http
);
1393 * We don't know how to re-validate other protocols. Handle
1394 * them as if the object has expired.
1396 http
->log_type
= LOG_TCP_MISS
;
1397 clientProcessMiss(http
);
1399 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1400 } else if (r
->flags
.ims
) {
1402 * Handle If-Modified-Since requests from the client
1404 if (mem
->reply
->sline
.status
!= HTTP_OK
) {
1405 debug(33, 4) ("clientCacheHit: Reply code %d != 200\n",
1406 mem
->reply
->sline
.status
);
1407 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1408 http
->log_type
= LOG_TCP_MISS
;
1409 clientProcessMiss(http
);
1410 } else if (modifiedSince(e
, http
->request
)) {
1411 http
->log_type
= LOG_TCP_IMS_HIT
;
1412 clientSendMoreData(data
, buf
, size
);
1414 MemBuf mb
= httpPacked304Reply(e
->mem_obj
->reply
);
1415 http
->log_type
= LOG_TCP_IMS_HIT
;
1416 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1417 storeUnregister(http
->sc
, e
, http
);
1418 storeUnlockObject(e
);
1419 e
= clientCreateStoreEntry(http
, http
->request
->method
, null_request_flags
);
1421 httpReplyParse(e
->mem_obj
->reply
, mb
.buf
, mb
.size
);
1422 storeAppend(e
, mb
.buf
, mb
.size
);
1428 * plain ol' cache hit
1430 if (e
->mem_status
== IN_MEMORY
)
1431 http
->log_type
= LOG_TCP_MEM_HIT
;
1432 else if (Config
.onoff
.offline
)
1433 http
->log_type
= LOG_TCP_OFFLINE_HIT
;
1434 clientSendMoreData(data
, buf
, size
);
1438 /* put terminating boundary for multiparts */
1440 clientPackTermBound(String boundary
, MemBuf
* mb
)
1442 memBufPrintf(mb
, "\r\n--%s--\r\n", strBuf(boundary
));
1443 debug(33, 6) ("clientPackTermBound: buf offset: %d\n", mb
->size
);
1446 /* appends a "part" HTTP header (as in a multi-part/range reply) to the buffer */
1448 clientPackRangeHdr(const HttpReply
* rep
, const HttpHdrRangeSpec
* spec
, String boundary
, MemBuf
* mb
)
1456 debug(33, 5) ("clientPackRangeHdr: appending boundary: %s\n", strBuf(boundary
));
1457 /* rfc2046 requires to _prepend_ boundary with <crlf>! */
1458 memBufPrintf(mb
, "\r\n--%s\r\n", strBuf(boundary
));
1460 /* stuff the header with required entries and pack it */
1461 httpHeaderInit(&hdr
, hoReply
);
1462 if (httpHeaderHas(&rep
->header
, HDR_CONTENT_TYPE
))
1463 httpHeaderPutStr(&hdr
, HDR_CONTENT_TYPE
, httpHeaderGetStr(&rep
->header
, HDR_CONTENT_TYPE
));
1464 httpHeaderAddContRange(&hdr
, *spec
, rep
->content_length
);
1465 packerToMemInit(&p
, mb
);
1466 httpHeaderPackInto(&hdr
, &p
);
1468 httpHeaderClean(&hdr
);
1470 /* append <crlf> (we packed a header, not a reply) */
1471 memBufPrintf(mb
, crlf
);
1475 * extracts a "range" from *buf and appends them to mb, updating
1476 * all offsets and such.
1479 clientPackRange(clientHttpRequest
* http
,
1480 HttpHdrRangeIter
* i
,
1485 const ssize_t copy_sz
= i
->debt_size
<= *size
? i
->debt_size
: *size
;
1486 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1490 * intersection of "have" and "need" ranges must not be empty
1492 assert(body_off
< i
->spec
->offset
+ i
->spec
->length
);
1493 assert(body_off
+ *size
> i
->spec
->offset
);
1495 * put boundary and headers at the beginning of a range in a
1498 if (http
->request
->range
->specs
.count
> 1 && i
->debt_size
== i
->spec
->length
) {
1499 assert(http
->entry
->mem_obj
);
1501 http
->entry
->mem_obj
->reply
, /* original reply */
1502 i
->spec
, /* current range */
1503 i
->boundary
, /* boundary, the same for all */
1510 debug(33, 3) ("clientPackRange: appending %d bytes\n", copy_sz
);
1511 memBufAppend(mb
, *buf
, copy_sz
);
1516 i
->debt_size
-= copy_sz
;
1517 body_off
+= copy_sz
;
1519 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1523 assert(*size
>= 0 && i
->debt_size
>= 0);
1526 /* returns true if there is still data available to pack more ranges
1527 * increments iterator "i"
1528 * used by clientPackMoreRanges */
1530 clientCanPackMoreRanges(const clientHttpRequest
* http
, HttpHdrRangeIter
* i
, ssize_t size
)
1532 /* first update "i" if needed */
1533 if (!i
->debt_size
) {
1534 if ((i
->spec
= httpHdrRangeGetSpec(http
->request
->range
, &i
->pos
)))
1535 i
->debt_size
= i
->spec
->length
;
1537 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1538 /* continue condition: need_more_data && have_more_data */
1539 return i
->spec
&& size
> 0;
1542 /* extracts "ranges" from buf and appends them to mb, updating all offsets and such */
1543 /* returns true if we need more data */
1545 clientPackMoreRanges(clientHttpRequest
* http
, const char *buf
, ssize_t size
, MemBuf
* mb
)
1547 HttpHdrRangeIter
*i
= &http
->range_iter
;
1548 /* offset in range specs does not count the prefix of an http msg */
1549 off_t body_off
= http
->out
.offset
- i
->prefix_size
;
1551 /* check: reply was parsed and range iterator was initialized */
1552 assert(i
->prefix_size
> 0);
1553 /* filter out data according to range specs */
1554 while (clientCanPackMoreRanges(http
, i
, size
)) {
1555 off_t start
; /* offset of still missing data */
1557 start
= i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
;
1558 debug(33, 3) ("clientPackMoreRanges: in: offset: %d size: %d\n",
1559 (int) body_off
, size
);
1560 debug(33, 3) ("clientPackMoreRanges: out: start: %d spec[%d]: [%d, %d), len: %d debt: %d\n",
1561 (int) start
, (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
, i
->debt_size
);
1562 assert(body_off
<= start
); /* we did not miss it */
1563 /* skip up to start */
1564 if (body_off
+ size
> start
) {
1565 const size_t skip_size
= start
- body_off
;
1570 /* has not reached start yet */
1575 /* put next chunk if any */
1577 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1578 clientPackRange(http
, i
, &buf
, &size
, mb
);
1579 body_off
= http
->out
.offset
- i
->prefix_size
; /* sync */
1582 assert(!i
->debt_size
== !i
->spec
); /* paranoid sync condition */
1583 debug(33, 3) ("clientPackMoreRanges: buf exhausted: in: offset: %d size: %d need_more: %d\n",
1584 (int) body_off
, size
, i
->debt_size
);
1586 debug(33, 3) ("clientPackMoreRanges: need more: spec[%d]: [%d, %d), len: %d\n",
1587 (int) i
->pos
, i
->spec
->offset
, (int) (i
->spec
->offset
+ i
->spec
->length
), i
->spec
->length
);
1588 /* skip the data we do not need if possible */
1589 if (i
->debt_size
== i
->spec
->length
) /* at the start of the cur. spec */
1590 body_off
= i
->spec
->offset
;
1592 assert(body_off
== i
->spec
->offset
+ i
->spec
->length
- i
->debt_size
);
1593 } else if (http
->request
->range
->specs
.count
> 1) {
1594 /* put terminating boundary for multiparts */
1595 clientPackTermBound(i
->boundary
, mb
);
1597 http
->out
.offset
= body_off
+ i
->prefix_size
; /* sync */
1598 return i
->debt_size
> 0;
1602 clientReplyBodyTooLarge(int clen
)
1604 if (0 == Config
.maxReplyBodySize
)
1605 return 0; /* disabled */
1607 return 0; /* unknown */
1608 if (clen
> Config
.maxReplyBodySize
)
1609 return 1; /* too large */
1614 clientRequestBodyTooLarge(int clen
)
1616 if (0 == Config
.maxRequestBodySize
)
1617 return 0; /* disabled */
1619 return 0; /* unknown, bug? */
1620 if (clen
> Config
.maxRequestBodySize
)
1621 return 1; /* too large */
1626 * accepts chunk of a http message in buf, parses prefix, filters headers and
1627 * such, writes processed message to the client's socket
1630 clientSendMoreData(void *data
, char *buf
, ssize_t size
)
1632 clientHttpRequest
*http
= data
;
1633 StoreEntry
*entry
= http
->entry
;
1634 ConnStateData
*conn
= http
->conn
;
1636 HttpReply
*rep
= NULL
;
1637 const char *body_buf
= buf
;
1638 ssize_t body_size
= size
;
1640 ssize_t check_size
= 0;
1641 debug(33, 5) ("clientSendMoreData: %s, %d bytes\n", http
->uri
, (int) size
);
1642 assert(size
<= CLIENT_SOCK_SZ
);
1643 assert(http
->request
!= NULL
);
1644 dlinkDelete(&http
->active
, &ClientActiveRequests
);
1645 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
1646 debug(33, 5) ("clientSendMoreData: FD %d '%s', out.offset=%d \n",
1647 fd
, storeUrl(entry
), (int) http
->out
.offset
);
1648 if (conn
->chr
!= http
) {
1649 /* there is another object in progress, defer this one */
1650 debug(33, 1) ("clientSendMoreData: Deferring %s\n", storeUrl(entry
));
1651 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1653 } else if (entry
&& EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1654 /* call clientWriteComplete so the client socket gets closed */
1655 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1656 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1658 } else if (size
< 0) {
1659 /* call clientWriteComplete so the client socket gets closed */
1660 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1661 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1663 } else if (size
== 0) {
1664 /* call clientWriteComplete so the client socket gets closed */
1665 clientWriteComplete(fd
, NULL
, 0, COMM_OK
, http
);
1666 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1669 if (http
->out
.offset
== 0) {
1670 if (Config
.onoff
.log_mime_hdrs
) {
1672 if ((k
= headersEnd(buf
, size
))) {
1673 safe_free(http
->al
.headers
.reply
);
1674 http
->al
.headers
.reply
= xcalloc(k
+ 1, 1);
1675 xstrncpy(http
->al
.headers
.reply
, buf
, k
);
1678 rep
= clientBuildReply(http
, buf
, size
);
1679 if (rep
&& clientReplyBodyTooLarge(rep
->content_length
)) {
1680 ErrorState
*err
= errorCon(ERR_TOO_BIG
, HTTP_FORBIDDEN
);
1681 err
->request
= requestLink(http
->request
);
1682 storeUnregister(http
->sc
, http
->entry
, http
);
1683 storeUnlockObject(http
->entry
);
1684 http
->entry
= clientCreateStoreEntry(http
, http
->request
->method
,
1685 null_request_flags
);
1686 errorAppendEntry(http
->entry
, err
);
1687 httpReplyDestroy(rep
);
1690 body_size
= size
- rep
->hdr_sz
;
1691 assert(body_size
>= 0);
1692 body_buf
= buf
+ rep
->hdr_sz
;
1693 http
->range_iter
.prefix_size
= rep
->hdr_sz
;
1694 debug(33, 3) ("clientSendMoreData: Appending %d bytes after %d bytes of headers\n",
1695 body_size
, rep
->hdr_sz
);
1696 } else if (size
< CLIENT_SOCK_SZ
&& entry
->store_status
== STORE_PENDING
) {
1697 /* wait for more to arrive */
1698 storeClientCopy(http
->sc
, entry
,
1699 http
->out
.offset
+ size
,
1707 /* reset range iterator */
1708 http
->range_iter
.pos
= HttpHdrRangeInitPos
;
1709 } else if (!http
->request
->range
) {
1710 /* Avoid copying to MemBuf for non-range requests */
1711 /* Note, if we're here, then 'rep' is known to be NULL */
1712 http
->out
.offset
+= body_size
;
1713 comm_write(fd
, buf
, size
, clientWriteBodyComplete
, http
, NULL
);
1714 /* NULL because clientWriteBodyComplete frees it */
1717 if (http
->request
->method
== METHOD_HEAD
) {
1719 /* do not forward body for HEAD replies */
1721 http
->flags
.done_copying
= 1;
1724 * If we are here, then store_status == STORE_OK and it
1725 * seems we have a HEAD repsponse which is missing the
1726 * empty end-of-headers line (home.mira.net, phttpd/0.99.72
1727 * does this). Because clientBuildReply() fails we just
1728 * call this reply a body, set the done_copying flag and
1731 http
->flags
.done_copying
= 1;
1734 /* write headers and/or body if any */
1735 assert(rep
|| (body_buf
&& body_size
));
1736 /* init mb; put status line and headers if any */
1738 mb
= httpReplyPack(rep
);
1739 http
->out
.offset
+= rep
->hdr_sz
;
1740 check_size
+= rep
->hdr_sz
;
1742 headersLog(0, 0, http
->request
->method
, rep
);
1744 httpReplyDestroy(rep
);
1749 /* append body if any */
1750 if (http
->request
->range
) {
1751 /* Only GET requests should have ranges */
1752 assert(http
->request
->method
== METHOD_GET
);
1753 /* clientPackMoreRanges() updates http->out.offset */
1754 /* force the end of the transfer if we are done */
1755 if (!clientPackMoreRanges(http
, body_buf
, body_size
, &mb
))
1756 http
->flags
.done_copying
= 1;
1757 } else if (body_buf
&& body_size
) {
1758 http
->out
.offset
+= body_size
;
1759 check_size
+= body_size
;
1760 memBufAppend(&mb
, body_buf
, body_size
);
1762 if (!http
->request
->range
&& http
->request
->method
== METHOD_GET
)
1763 assert(check_size
== size
);
1765 comm_write_mbuf(fd
, mb
, clientWriteComplete
, http
);
1766 /* if we don't do it, who will? */
1767 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1771 * clientWriteBodyComplete is called for MEM_CLIENT_SOCK_BUF's
1772 * written directly to the client socket, versus copying to a MemBuf
1773 * and going through comm_write_mbuf. Most non-range responses after
1774 * the headers probably go through here.
1777 clientWriteBodyComplete(int fd
, char *buf
, size_t size
, int errflag
, void *data
)
1780 * NOTE: clientWriteComplete doesn't currently use its "buf"
1781 * (second) argument, so we pass in NULL.
1783 clientWriteComplete(fd
, NULL
, size
, errflag
, data
);
1784 memFree(buf
, MEM_CLIENT_SOCK_BUF
);
1788 clientKeepaliveNextRequest(clientHttpRequest
* http
)
1790 ConnStateData
*conn
= http
->conn
;
1792 debug(33, 3) ("clientKeepaliveNextRequest: FD %d\n", conn
->fd
);
1793 conn
->defer
.until
= 0; /* Kick it to read a new request */
1794 httpRequestFree(http
);
1795 if ((http
= conn
->chr
) == NULL
) {
1796 debug(33, 5) ("clientKeepaliveNextRequest: FD %d reading next req\n",
1798 fd_note(conn
->fd
, "Reading next request");
1800 * Set the timeout BEFORE calling clientReadRequest().
1802 commSetTimeout(conn
->fd
, Config
.Timeout
.pconn
, requestTimeout
, conn
);
1803 clientReadRequest(conn
->fd
, conn
); /* Read next request */
1805 * Note, the FD may be closed at this point.
1807 } else if ((entry
= http
->entry
) == NULL
) {
1809 * this request is in progress, maybe doing an ACL or a redirect,
1810 * execution will resume after the operation completes.
1813 debug(33, 1) ("clientKeepaliveNextRequest: FD %d Sending next\n",
1816 if (0 == storeClientCopyPending(http
->sc
, entry
, http
)) {
1817 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1818 debug(33, 0) ("clientKeepaliveNextRequest: ENTRY_ABORTED\n");
1819 storeClientCopy(http
->sc
, entry
,
1823 memAllocate(MEM_CLIENT_SOCK_BUF
),
1831 clientWriteComplete(int fd
, char *bufnotused
, size_t size
, int errflag
, void *data
)
1833 clientHttpRequest
*http
= data
;
1834 StoreEntry
*entry
= http
->entry
;
1836 http
->out
.size
+= size
;
1837 debug(33, 5) ("clientWriteComplete: FD %d, sz %d, err %d, off %d, len %d\n",
1838 fd
, size
, errflag
, (int) http
->out
.offset
, entry
? objectLen(entry
) : 0);
1840 kb_incr(&Counter
.client_http
.kbytes_out
, size
);
1841 if (isTcpHit(http
->log_type
))
1842 kb_incr(&Counter
.client_http
.hit_kbytes_out
, size
);
1846 * just close the socket, httpRequestFree will abort if needed
1849 } else if (NULL
== entry
) {
1850 comm_close(fd
); /* yuk */
1851 } else if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
)) {
1853 } else if ((done
= clientCheckTransferDone(http
)) != 0 || size
== 0) {
1854 debug(33, 5) ("clientWriteComplete: FD %d transfer is DONE\n", fd
);
1855 /* We're finished case */
1856 if (httpReplyBodySize(http
->request
->method
, entry
->mem_obj
->reply
) < 0) {
1857 debug(33, 5) ("clientWriteComplete: closing, content_length < 0\n");
1860 debug(33, 5) ("clientWriteComplete: closing, !done\n");
1862 } else if (clientGotNotEnough(http
)) {
1863 debug(33, 5) ("clientWriteComplete: client didn't get all it expected\n");
1865 } else if (http
->request
->flags
.proxy_keepalive
) {
1866 debug(33, 5) ("clientWriteComplete: FD %d Keeping Alive\n", fd
);
1867 clientKeepaliveNextRequest(http
);
1871 } else if (clientReplyBodyTooLarge((int) http
->out
.offset
)) {
1874 /* More data will be coming from primary server; register with
1875 * storage manager. */
1876 if (EBIT_TEST(entry
->flags
, ENTRY_ABORTED
))
1877 debug(33, 0) ("clientWriteComplete 2: ENTRY_ABORTED\n");
1878 storeClientCopy(http
->sc
, entry
,
1882 memAllocate(MEM_CLIENT_SOCK_BUF
),
1889 * client issued a request with an only-if-cached cache-control directive;
1890 * we did not find a cached object that can be returned without
1891 * contacting other servers;
1892 * respond with a 504 (Gateway Timeout) as suggested in [RFC 2068]
1895 clientProcessOnlyIfCachedMiss(clientHttpRequest
* http
)
1897 char *url
= http
->uri
;
1898 request_t
*r
= http
->request
;
1899 ErrorState
*err
= NULL
;
1900 debug(33, 4) ("clientProcessOnlyIfCachedMiss: '%s %s'\n",
1901 RequestMethodStr
[r
->method
], url
);
1902 http
->al
.http
.code
= HTTP_GATEWAY_TIMEOUT
;
1903 err
= errorCon(ERR_ONLY_IF_CACHED_MISS
, HTTP_GATEWAY_TIMEOUT
);
1904 err
->request
= requestLink(r
);
1905 err
->src_addr
= http
->conn
->peer
.sin_addr
;
1907 storeUnregister(http
->sc
, http
->entry
, http
);
1908 storeUnlockObject(http
->entry
);
1910 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
1911 errorAppendEntry(http
->entry
, err
);
1915 clientProcessRequest2(clientHttpRequest
* http
)
1917 request_t
*r
= http
->request
;
1919 e
= http
->entry
= storeGetPublic(http
->uri
, r
->method
);
1920 if (r
->method
== METHOD_HEAD
&& e
== NULL
) {
1921 /* We can generate a HEAD reply from a cached GET object */
1922 e
= http
->entry
= storeGetPublic(http
->uri
, METHOD_GET
);
1924 /* Release negatively cached IP-cache entries on reload */
1925 if (r
->flags
.nocache
)
1926 ipcacheReleaseInvalid(r
->host
);
1928 else if (r
->flags
.nocache_hack
)
1929 ipcacheReleaseInvalid(r
->host
);
1931 #if USE_CACHE_DIGESTS
1932 http
->lookup_type
= e
? "HIT" : "MISS";
1935 /* this object isn't in the cache */
1936 debug(33, 3) ("clientProcessRequest2: storeGet() MISS\n");
1937 return LOG_TCP_MISS
;
1939 if (Config
.onoff
.offline
) {
1940 debug(33, 3) ("clientProcessRequest2: offline HIT\n");
1944 if (!storeEntryValidToSend(e
)) {
1945 debug(33, 3) ("clientProcessRequest2: !storeEntryValidToSend MISS\n");
1947 return LOG_TCP_MISS
;
1949 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
)) {
1950 /* Special entries are always hits, no matter what the client says */
1951 debug(33, 3) ("clientProcessRequest2: ENTRY_SPECIAL HIT\n");
1956 if (e
->store_status
== STORE_PENDING
) {
1957 if (r
->flags
.nocache
|| r
->flags
.nocache_hack
) {
1958 debug(33, 3) ("Clearing no-cache for STORE_PENDING request\n\t%s\n",
1960 r
->flags
.nocache
= 0;
1961 r
->flags
.nocache_hack
= 0;
1965 if (r
->flags
.nocache
) {
1966 debug(33, 3) ("clientProcessRequest2: no-cache REFRESH MISS\n");
1968 ipcacheReleaseInvalid(r
->host
);
1969 return LOG_TCP_CLIENT_REFRESH_MISS
;
1971 if (r
->range
&& httpHdrRangeWillBeComplex(r
->range
)) {
1973 * Some clients break if we return "200 OK" for a Range
1974 * request. We would have to return "200 OK" for a _complex_
1975 * Range request that is also a HIT. Thus, let's prevent HITs
1976 * on complex Range requests
1978 debug(33, 3) ("clientProcessRequest2: complex range MISS\n");
1980 return LOG_TCP_MISS
;
1982 debug(33, 3) ("clientProcessRequest2: default HIT\n");
1988 clientProcessRequest(clientHttpRequest
* http
)
1990 char *url
= http
->uri
;
1991 request_t
*r
= http
->request
;
1992 int fd
= http
->conn
->fd
;
1994 debug(33, 4) ("clientProcessRequest: %s '%s'\n",
1995 RequestMethodStr
[r
->method
],
1997 if (r
->method
== METHOD_CONNECT
) {
1998 http
->log_type
= LOG_TCP_MISS
;
1999 sslStart(fd
, url
, r
, &http
->out
.size
);
2001 } else if (r
->method
== METHOD_PURGE
) {
2002 clientPurgeRequest(http
);
2004 } else if (r
->method
== METHOD_TRACE
) {
2005 if (r
->max_forwards
== 0) {
2006 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
2007 storeReleaseRequest(http
->entry
);
2008 storeBuffer(http
->entry
);
2009 rep
= httpReplyCreate();
2010 httpReplySetHeaders(rep
, 1.0, HTTP_OK
, NULL
, "text/plain",
2011 httpRequestPrefixLen(r
), 0, squid_curtime
);
2012 httpReplySwapOut(rep
, http
->entry
);
2013 httpReplyDestroy(rep
);
2014 httpRequestSwapOut(r
, http
->entry
);
2015 storeComplete(http
->entry
);
2019 http
->log_type
= LOG_TCP_MISS
;
2020 } else if (r
->content_length
> 0) {
2021 http
->log_type
= LOG_TCP_MISS
;
2022 /* XXX oof, POST can be cached! */
2023 pumpInit(fd
, r
, http
->uri
);
2025 http
->log_type
= clientProcessRequest2(http
);
2027 debug(33, 4) ("clientProcessRequest: %s for '%s'\n",
2028 log_tags
[http
->log_type
],
2030 http
->out
.offset
= 0;
2031 if (NULL
!= http
->entry
) {
2032 storeLockObject(http
->entry
);
2033 storeCreateMemObject(http
->entry
, http
->uri
, http
->log_uri
);
2034 http
->entry
->mem_obj
->method
= r
->method
;
2035 http
->sc
= storeClientListAdd(http
->entry
, http
);
2037 delaySetStoreClient(http
->sc
, delayClient(r
));
2039 storeClientCopy(http
->sc
, http
->entry
,
2043 memAllocate(MEM_CLIENT_SOCK_BUF
),
2047 /* MISS CASE, http->log_type is already set! */
2048 clientProcessMiss(http
);
2053 * Prepare to fetch the object as it's a cache miss of some kind.
2056 clientProcessMiss(clientHttpRequest
* http
)
2058 char *url
= http
->uri
;
2059 request_t
*r
= http
->request
;
2060 ErrorState
*err
= NULL
;
2061 debug(33, 4) ("clientProcessMiss: '%s %s'\n",
2062 RequestMethodStr
[r
->method
], url
);
2064 * We might have a left-over StoreEntry from a failed cache hit
2068 if (EBIT_TEST(http
->entry
->flags
, ENTRY_SPECIAL
))
2069 debug(33, 0) ("clientProcessMiss: miss on a special object (%s).\n", url
);
2070 storeUnregister(http
->sc
, http
->entry
, http
);
2071 storeUnlockObject(http
->entry
);
2074 if (clientOnlyIfCached(http
)) {
2075 clientProcessOnlyIfCachedMiss(http
);
2079 * Deny loops when running in accelerator/transproxy mode.
2081 if (http
->flags
.accel
&& r
->flags
.loopdetect
) {
2082 http
->al
.http
.code
= HTTP_FORBIDDEN
;
2083 err
= errorCon(ERR_ACCESS_DENIED
, HTTP_FORBIDDEN
);
2084 err
->request
= requestLink(r
);
2085 err
->src_addr
= http
->conn
->peer
.sin_addr
;
2086 http
->entry
= clientCreateStoreEntry(http
, r
->method
, null_request_flags
);
2087 errorAppendEntry(http
->entry
, err
);
2090 assert(http
->out
.offset
== 0);
2091 http
->entry
= clientCreateStoreEntry(http
, r
->method
, r
->flags
);
2092 if (http
->redirect
.status
) {
2093 HttpReply
*rep
= httpReplyCreate();
2094 #if LOG_TCP_REDIRECTS
2095 http
->log_type
= LOG_TCP_REDIRECT
;
2097 storeReleaseRequest(http
->entry
);
2098 httpRedirectReply(rep
, http
->redirect
.status
, http
->redirect
.location
);
2099 httpReplySwapOut(rep
, http
->entry
);
2100 httpReplyDestroy(rep
);
2101 storeComplete(http
->entry
);
2104 if (http
->flags
.internal
)
2105 r
->protocol
= PROTO_INTERNAL
;
2106 fwdStart(http
->conn
->fd
, http
->entry
, r
);
2109 static clientHttpRequest
*
2110 parseHttpRequestAbort(ConnStateData
* conn
, const char *uri
)
2112 clientHttpRequest
*http
= xcalloc(1, sizeof(clientHttpRequest
));
2113 cbdataAdd(http
, cbdataXfree
, 0);
2115 http
->start
= current_time
;
2116 http
->req_sz
= conn
->in
.offset
;
2117 http
->uri
= xstrdup(uri
);
2118 http
->log_uri
= xstrndup(uri
, MAX_URL
);
2119 http
->range_iter
.boundary
= StringNull
;
2120 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2125 * parseHttpRequest()
2128 * NULL on error or incomplete request
2129 * a clientHttpRequest structure on success
2131 static clientHttpRequest
*
2132 parseHttpRequest(ConnStateData
* conn
, method_t
* method_p
, int *status
,
2133 char **prefix_p
, size_t * req_line_sz_p
)
2138 char *req_hdr
= NULL
;
2143 int free_request
= 0;
2144 size_t header_sz
; /* size of headers, not including first line */
2145 size_t prefix_sz
; /* size of whole request (req-line + headers) */
2149 clientHttpRequest
*http
= NULL
;
2151 struct natlookup natLookup
;
2152 static int natfd
= -1;
2155 if ((req_sz
= headersEnd(conn
->in
.buf
, conn
->in
.offset
)) == 0) {
2156 debug(33, 5) ("Incomplete request, waiting for end of headers\n");
2159 *method_p
= METHOD_NONE
;
2162 assert(req_sz
<= conn
->in
.offset
);
2163 /* Use memcpy, not strdup! */
2164 inbuf
= xmalloc(req_sz
+ 1);
2165 xmemcpy(inbuf
, conn
->in
.buf
, req_sz
);
2166 *(inbuf
+ req_sz
) = '\0';
2168 /* pre-set these values to make aborting simpler */
2170 *method_p
= METHOD_NONE
;
2173 /* Barf on NULL characters in the headers */
2174 if (strlen(inbuf
) != req_sz
) {
2175 debug(33, 1) ("parseHttpRequest: Requestheader contains NULL characters\n");
2176 return parseHttpRequestAbort(conn
, "error:invalid-request");
2178 /* Look for request method */
2179 if ((mstr
= strtok(inbuf
, "\t ")) == NULL
) {
2180 debug(33, 1) ("parseHttpRequest: Can't get request method\n");
2181 return parseHttpRequestAbort(conn
, "error:invalid-request-method");
2183 method
= urlParseMethod(mstr
);
2184 if (method
== METHOD_NONE
) {
2185 debug(33, 1) ("parseHttpRequest: Unsupported method '%s'\n", mstr
);
2186 return parseHttpRequestAbort(conn
, "error:unsupported-request-method");
2188 debug(33, 5) ("parseHttpRequest: Method is '%s'\n", mstr
);
2191 /* look for URL+HTTP/x.x */
2192 if ((url
= strtok(NULL
, "\n")) == NULL
) {
2193 debug(33, 1) ("parseHttpRequest: Missing URL\n");
2194 return parseHttpRequestAbort(conn
, "error:missing-url");
2196 while (xisspace(*url
))
2198 t
= url
+ strlen(url
);
2203 if (xisspace(*t
) && !strncmp(t
+ 1, "HTTP/", 5)) {
2208 while (t
> url
&& xisspace(*t
))
2210 debug(33, 5) ("parseHttpRequest: URI is '%s'\n", url
);
2211 if (token
== NULL
) {
2212 debug(33, 3) ("parseHttpRequest: Missing HTTP identifier\n");
2213 #if RELAXED_HTTP_PARSER
2214 http_ver
= (float) 0.9; /* wild guess */
2216 return parseHttpRequestAbort(conn
, "error:missing-http-ident");
2219 http_ver
= (float) atof(token
+ 5);
2223 * Process headers after request line
2225 req_hdr
= strtok(NULL
, null_string
);
2226 header_sz
= req_sz
- (req_hdr
- inbuf
);
2227 if (0 == header_sz
) {
2228 debug(33, 3) ("parseHttpRequest: header_sz == 0\n");
2232 assert(header_sz
> 0);
2233 debug(33, 3) ("parseHttpRequest: req_hdr = {%s}\n", req_hdr
);
2234 end
= req_hdr
+ header_sz
;
2235 debug(33, 3) ("parseHttpRequest: end = {%s}\n", end
);
2237 prefix_sz
= end
- inbuf
;
2238 *req_line_sz_p
= req_hdr
- inbuf
;
2239 debug(33, 3) ("parseHttpRequest: prefix_sz = %d, req_line_sz = %d\n",
2240 (int) prefix_sz
, (int) *req_line_sz_p
);
2241 assert(prefix_sz
<= conn
->in
.offset
);
2243 /* Ok, all headers are received */
2244 http
= xcalloc(1, sizeof(clientHttpRequest
));
2245 cbdataAdd(http
, cbdataXfree
, 0);
2246 http
->http_ver
= http_ver
;
2248 http
->start
= current_time
;
2249 http
->req_sz
= prefix_sz
;
2250 http
->range_iter
.boundary
= StringNull
;
2251 *prefix_p
= xmalloc(prefix_sz
+ 1);
2252 xmemcpy(*prefix_p
, conn
->in
.buf
, prefix_sz
);
2253 *(*prefix_p
+ prefix_sz
) = '\0';
2254 dlinkAdd(http
, &http
->active
, &ClientActiveRequests
);
2256 debug(33, 5) ("parseHttpRequest: Request Header is\n%s\n", (*prefix_p
) + *req_line_sz_p
);
2257 if ((t
= strchr(url
, '#'))) /* remove HTML anchors */
2260 /* handle internal objects */
2261 if (internalCheck(url
)) {
2262 /* prepend our name & port */
2263 http
->uri
= xstrdup(internalLocalUri(NULL
, url
));
2264 http
->flags
.internal
= 1;
2265 http
->flags
.accel
= 1;
2267 /* see if we running in Config2.Accel.on, if so got to convert it to URL */
2268 else if (Config2
.Accel
.on
&& *url
== '/') {
2269 /* prepend the accel prefix */
2270 if (opt_accel_uses_host
&& (t
= mime_get_header(req_hdr
, "Host"))) {
2271 /* If a Host: header was specified, use it to build the URL
2272 * instead of the one in the Config file. */
2274 * XXX Use of the Host: header here opens a potential
2275 * security hole. There are no checks that the Host: value
2276 * corresponds to one of your servers. It might, for example,
2277 * refer to www.playboy.com. The 'dst' and/or 'dst_domain' ACL
2278 * types should be used to prevent httpd-accelerators
2279 * handling requests for non-local servers */
2281 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
+
2283 http
->uri
= xcalloc(url_sz
, 1);
2284 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2285 t
, (int) Config
.Accel
.port
, url
);
2286 } else if (vhost_mode
) {
2287 /* Put the local socket IP address as the hostname */
2288 url_sz
= strlen(url
) + 32 + Config
.appendDomainLen
;
2289 http
->uri
= xcalloc(url_sz
, 1);
2291 natLookup
.nl_inport
= http
->conn
->me
.sin_port
;
2292 natLookup
.nl_outport
= http
->conn
->peer
.sin_port
;
2293 natLookup
.nl_inip
= http
->conn
->me
.sin_addr
;
2294 natLookup
.nl_outip
= http
->conn
->peer
.sin_addr
;
2295 natLookup
.nl_flags
= IPN_TCP
;
2297 natfd
= open(IPL_NAT
, O_RDONLY
, 0);
2299 debug(50, 1) ("parseHttpRequest: NAT open failed: %s\n",
2301 return parseHttpRequestAbort(conn
, "error:nat-open-failed");
2303 if (ioctl(natfd
, SIOCGNATL
, &natLookup
) < 0) {
2304 if (errno
!= ESRCH
) {
2305 debug(50, 1) ("parseHttpRequest: NAT lookup failed: ioctl(SIOCGNATL)\n");
2308 return parseHttpRequestAbort(conn
, "error:nat-lookup-failed");
2310 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2311 inet_ntoa(http
->conn
->me
.sin_addr
),
2312 (int) Config
.Accel
.port
,
2315 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2316 inet_ntoa(natLookup
.nl_realip
),
2317 (int) Config
.Accel
.port
,
2320 snprintf(http
->uri
, url_sz
, "http://%s:%d%s",
2321 inet_ntoa(http
->conn
->me
.sin_addr
),
2322 (int) Config
.Accel
.port
,
2325 debug(33, 5) ("VHOST REWRITE: '%s'\n", http
->uri
);
2327 url_sz
= strlen(Config2
.Accel
.prefix
) + strlen(url
) +
2328 Config
.appendDomainLen
+ 1;
2329 http
->uri
= xcalloc(url_sz
, 1);
2330 snprintf(http
->uri
, url_sz
, "%s%s", Config2
.Accel
.prefix
, url
);
2332 http
->flags
.accel
= 1;
2334 /* URL may be rewritten later, so make extra room */
2335 url_sz
= strlen(url
) + Config
.appendDomainLen
+ 5;
2336 http
->uri
= xcalloc(url_sz
, 1);
2337 strcpy(http
->uri
, url
);
2338 http
->flags
.accel
= 0;
2340 if (!stringHasCntl(http
->uri
))
2341 http
->log_uri
= xstrndup(http
->uri
, MAX_URL
);
2343 http
->log_uri
= xstrndup(rfc1738_escape_unescaped(http
->uri
), MAX_URL
);
2344 debug(33, 5) ("parseHttpRequest: Complete request received\n");
2353 clientReadDefer(int fdnotused
, void *data
)
2355 ConnStateData
*conn
= data
;
2356 return conn
->defer
.until
> squid_curtime
;
2360 clientReadRequest(int fd
, void *data
)
2362 ConnStateData
*conn
= data
;
2363 int parser_return_code
= 0;
2365 request_t
*request
= NULL
;
2368 clientHttpRequest
*http
= NULL
;
2369 clientHttpRequest
**H
= NULL
;
2370 char *prefix
= NULL
;
2371 ErrorState
*err
= NULL
;
2372 fde
*F
= &fd_table
[fd
];
2373 int len
= conn
->in
.size
- conn
->in
.offset
- 1;
2374 debug(33, 4) ("clientReadRequest: FD %d: reading request...\n", fd
);
2375 Counter
.syscalls
.sock
.reads
++;
2376 size
= read(fd
, conn
->in
.buf
+ conn
->in
.offset
, len
);
2378 fd_bytes(fd
, size
, FD_READ
);
2379 kb_incr(&Counter
.client_http
.kbytes_in
, size
);
2382 * Don't reset the timeout value here. The timeout value will be
2383 * set to Config.Timeout.request by httpAccept() and
2384 * clientWriteComplete(), and should apply to the request as a
2385 * whole, not individual read() calls. Plus, it breaks our
2386 * lame half-close detection
2388 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, conn
, 0);
2390 if (conn
->chr
== NULL
) {
2391 /* no current or pending requests */
2394 } else if (!Config
.onoff
.half_closed_clients
) {
2395 /* admin doesn't want to support half-closed client sockets */
2399 /* It might be half-closed, we can't tell */
2400 debug(33, 5) ("clientReadRequest: FD %d closed?\n", fd
);
2401 F
->flags
.socket_eof
= 1;
2402 conn
->defer
.until
= squid_curtime
+ 1;
2404 fd_note(fd
, "half-closed");
2406 } else if (size
< 0) {
2407 if (!ignoreErrno(errno
)) {
2408 debug(50, 2) ("clientReadRequest: FD %d: %s\n", fd
, xstrerror());
2411 } else if (conn
->in
.offset
== 0) {
2412 debug(50, 2) ("clientReadRequest: FD %d: no data to process (%s)\n", fd
, xstrerror());
2415 /* Continue to process previously read data */
2418 conn
->in
.offset
+= size
;
2419 /* Skip leading (and trailing) whitespace */
2420 while (conn
->in
.offset
> 0) {
2423 while (conn
->in
.offset
> 0 && xisspace(conn
->in
.buf
[0])) {
2424 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ 1, conn
->in
.offset
- 1);
2427 conn
->in
.buf
[conn
->in
.offset
] = '\0'; /* Terminate the string */
2428 if (conn
->in
.offset
== 0)
2430 /* Limit the number of concurrent requests to 2 */
2431 for (H
= &conn
->chr
, nrequests
= 0; *H
; H
= &(*H
)->next
, nrequests
++);
2432 if (nrequests
>= 2) {
2433 debug(33, 3) ("clientReadRequest: FD %d max concurrent requests reached\n", fd
);
2434 debug(33, 5) ("clientReadRequest: FD %d defering new request until one is done\n", fd
);
2435 conn
->defer
.until
= squid_curtime
+ 100; /* Reset when a request is complete */
2438 /* Process request */
2439 http
= parseHttpRequest(conn
,
2441 &parser_return_code
,
2447 assert(http
->req_sz
> 0);
2448 conn
->in
.offset
-= http
->req_sz
;
2449 assert(conn
->in
.offset
>= 0);
2450 debug(33, 5) ("conn->in.offset = %d\n", (int) conn
->in
.offset
);
2452 * If we read past the end of this request, move the remaining
2453 * data to the beginning
2455 if (conn
->in
.offset
> 0)
2456 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ http
->req_sz
, conn
->in
.offset
);
2457 /* add to the client request queue */
2458 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2461 commSetTimeout(fd
, Config
.Timeout
.lifetime
, NULL
, NULL
);
2462 if (parser_return_code
< 0) {
2463 debug(33, 1) ("clientReadRequest: FD %d Invalid Request\n", fd
);
2464 err
= errorCon(ERR_INVALID_REQ
, HTTP_BAD_REQUEST
);
2465 err
->request_hdrs
= xstrdup(conn
->in
.buf
);
2466 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2467 errorAppendEntry(http
->entry
, err
);
2471 if ((request
= urlParse(method
, http
->uri
)) == NULL
) {
2472 debug(33, 5) ("Invalid URL: %s\n", http
->uri
);
2473 err
= errorCon(ERR_INVALID_URL
, HTTP_BAD_REQUEST
);
2474 err
->src_addr
= conn
->peer
.sin_addr
;
2475 err
->url
= xstrdup(http
->uri
);
2476 http
->al
.http
.code
= err
->http_status
;
2477 http
->entry
= clientCreateStoreEntry(http
, method
, null_request_flags
);
2478 errorAppendEntry(http
->entry
, err
);
2482 /* compile headers */
2483 /* we should skip request line! */
2484 if (!httpRequestParseHeader(request
, prefix
+ req_line_sz
))
2485 debug(33, 1) ("Failed to parse request headers: %s\n%s\n",
2487 /* continue anyway? */
2489 request
->flags
.accelerated
= http
->flags
.accel
;
2490 if (!http
->flags
.internal
) {
2491 if (internalCheck(strBuf(request
->urlpath
))) {
2492 if (internalHostnameIs(request
->host
) &&
2493 request
->port
== ntohs(Config
.Sockaddr
.http
->s
.sin_port
)) {
2494 http
->flags
.internal
= 1;
2495 } else if (internalStaticCheck(strBuf(request
->urlpath
))) {
2496 xstrncpy(request
->host
, internalHostname(), SQUIDHOSTNAMELEN
);
2497 request
->port
= ntohs(Config
.Sockaddr
.http
->s
.sin_port
);
2498 http
->flags
.internal
= 1;
2503 * cache the Content-length value in request_t.
2505 request
->content_length
= httpHeaderGetInt(&request
->header
,
2506 HDR_CONTENT_LENGTH
);
2507 request
->flags
.internal
= http
->flags
.internal
;
2509 safe_free(http
->log_uri
);
2510 http
->log_uri
= xstrdup(urlCanonicalClean(request
));
2511 request
->client_addr
= conn
->peer
.sin_addr
;
2512 request
->my_addr
= conn
->me
.sin_addr
;
2513 request
->my_port
= ntohs(conn
->me
.sin_port
);
2514 request
->http_ver
= http
->http_ver
;
2515 if (!urlCheckRequest(request
)) {
2516 err
= errorCon(ERR_UNSUP_REQ
, HTTP_NOT_IMPLEMENTED
);
2517 err
->src_addr
= conn
->peer
.sin_addr
;
2518 err
->request
= requestLink(request
);
2519 request
->flags
.proxy_keepalive
= 0;
2520 http
->al
.http
.code
= err
->http_status
;
2521 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2522 errorAppendEntry(http
->entry
, err
);
2525 if (0 == clientCheckContentLength(request
)) {
2526 err
= errorCon(ERR_INVALID_REQ
, HTTP_LENGTH_REQUIRED
);
2527 err
->src_addr
= conn
->peer
.sin_addr
;
2528 err
->request
= requestLink(request
);
2529 http
->al
.http
.code
= err
->http_status
;
2530 http
->entry
= clientCreateStoreEntry(http
, request
->method
, null_request_flags
);
2531 errorAppendEntry(http
->entry
, err
);
2534 http
->request
= requestLink(request
);
2536 * We need to set the keepalive flag before doing some
2537 * hacks for POST/PUT requests below. Maybe we could
2538 * set keepalive flag even earlier.
2540 clientSetKeepaliveFlag(http
);
2542 * break here if the request has a content-length
2543 * because there is a reqeust body following and we
2544 * don't want to parse it as though it was new request.
2546 if (request
->content_length
>= 0) {
2547 int copy_len
= XMIN(conn
->in
.offset
, request
->content_length
);
2549 assert(conn
->in
.offset
>= copy_len
);
2550 request
->body_sz
= copy_len
;
2551 request
->body
= xmalloc(request
->body_sz
);
2552 xmemcpy(request
->body
, conn
->in
.buf
, request
->body_sz
);
2553 conn
->in
.offset
-= copy_len
;
2554 if (conn
->in
.offset
)
2555 xmemmove(conn
->in
.buf
, conn
->in
.buf
+ copy_len
, conn
->in
.offset
);
2558 * if we didn't get the full body now, then more will
2559 * be arriving on the client socket. Lets cancel
2560 * the read handler until this request gets forwarded.
2562 if (request
->body_sz
< request
->content_length
)
2563 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2564 if (request
->content_length
< 0)
2566 else if (clientRequestBodyTooLarge(request
->content_length
)) {
2567 err
= errorCon(ERR_TOO_BIG
, HTTP_REQUEST_ENTITY_TOO_LARGE
);
2568 err
->request
= requestLink(request
);
2569 http
->entry
= clientCreateStoreEntry(http
,
2570 METHOD_NONE
, null_request_flags
);
2571 errorAppendEntry(http
->entry
, err
);
2575 clientAccessCheck(http
);
2576 continue; /* while offset > 0 */
2577 } else if (parser_return_code
== 0) {
2579 * Partial request received; reschedule until parseHttpRequest()
2580 * is happy with the input
2582 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2584 if (conn
->in
.offset
>= Config
.maxRequestHeaderSize
) {
2585 /* The request is too large to handle */
2586 debug(33, 1) ("Request header is too large (%d bytes)\n",
2587 (int) conn
->in
.offset
);
2588 debug(33, 1) ("Config 'request_header_max_size'= %d bytes.\n",
2589 Config
.maxRequestHeaderSize
);
2590 err
= errorCon(ERR_TOO_BIG
, HTTP_REQUEST_ENTITY_TOO_LARGE
);
2591 http
= parseHttpRequestAbort(conn
, "error:request-too-large");
2592 /* add to the client request queue */
2593 for (H
= &conn
->chr
; *H
; H
= &(*H
)->next
);
2595 http
->entry
= clientCreateStoreEntry(http
, METHOD_NONE
, null_request_flags
);
2596 errorAppendEntry(http
->entry
, err
);
2599 /* Grow the request memory area to accomodate for a large request */
2600 conn
->in
.size
+= REQUEST_BUF_SIZE
;
2601 conn
->in
.buf
= xrealloc(conn
->in
.buf
, conn
->in
.size
);
2602 /* XXX account conn->in.buf */
2603 debug(33, 3) ("Handling a large request, offset=%d inbufsize=%d\n",
2604 (int) conn
->in
.offset
, conn
->in
.size
);
2605 k
= conn
->in
.size
- 1 - conn
->in
.offset
;
2612 /* general lifetime handler for HTTP requests */
2614 requestTimeout(int fd
, void *data
)
2616 ConnStateData
*conn
= data
;
2618 debug(33, 3) ("requestTimeout: FD %d: lifetime is expired.\n", fd
);
2619 if (fd_table
[fd
].rwstate
) {
2621 * Some data has been sent to the client, just close the FD
2624 } else if (conn
->nrequests
) {
2626 * assume its a persistent connection; just close it
2633 err
= errorCon(ERR_LIFETIME_EXP
, HTTP_REQUEST_TIMEOUT
);
2634 err
->url
= xstrdup("N/A");
2636 * Normally we shouldn't call errorSend() in client_side.c, but
2637 * it should be okay in this case. Presumably if we get here
2638 * this is the first request for the connection, and no data
2639 * has been written yet
2641 assert(conn
->chr
== NULL
);
2644 * if we don't close() here, we still need a timeout handler!
2646 commSetTimeout(fd
, 30, requestTimeout
, conn
);
2648 * Aha, but we don't want a read handler!
2650 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
2655 httpAcceptDefer(void)
2657 static time_t last_warn
= 0;
2658 if (fdNFree() >= RESERVED_FD
)
2660 if (last_warn
+ 15 < squid_curtime
) {
2661 debug(33, 0) ("WARNING! Your cache is running out of filedescriptors\n");
2662 last_warn
= squid_curtime
;
2667 /* Handle a new connection on HTTP socket. */
2669 httpAccept(int sock
, void *data
)
2673 ConnStateData
*connState
= NULL
;
2674 struct sockaddr_in peer
;
2675 struct sockaddr_in me
;
2676 int max
= INCOMING_HTTP_MAX
;
2678 static aclCheck_t identChecklist
;
2680 commSetSelect(sock
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2681 while (max
-- && !httpAcceptDefer()) {
2682 memset(&peer
, '\0', sizeof(struct sockaddr_in
));
2683 memset(&me
, '\0', sizeof(struct sockaddr_in
));
2684 if ((fd
= comm_accept(sock
, &peer
, &me
)) < 0) {
2685 if (!ignoreErrno(errno
))
2686 debug(50, 1) ("httpAccept: FD %d: accept failure: %s\n",
2690 debug(33, 4) ("httpAccept: FD %d: accepted\n", fd
);
2691 connState
= memAllocate(MEM_CONNSTATEDATA
);
2692 connState
->peer
= peer
;
2693 connState
->log_addr
= peer
.sin_addr
;
2694 connState
->log_addr
.s_addr
&= Config
.Addrs
.client_netmask
.s_addr
;
2697 connState
->in
.size
= REQUEST_BUF_SIZE
;
2698 connState
->in
.buf
= xcalloc(connState
->in
.size
, 1);
2699 cbdataAdd(connState
, memFree
, MEM_CONNSTATEDATA
);
2700 /* XXX account connState->in.buf */
2701 comm_add_close_handler(fd
, connStateFree
, connState
);
2702 if (Config
.onoff
.log_fqdn
)
2703 fqdncache_gethostbyaddr(peer
.sin_addr
, FQDN_LOOKUP_IF_MISS
);
2704 commSetTimeout(fd
, Config
.Timeout
.request
, requestTimeout
, connState
);
2706 identChecklist
.src_addr
= peer
.sin_addr
;
2707 identChecklist
.my_addr
= me
.sin_addr
;
2708 identChecklist
.my_port
= ntohs(me
.sin_port
);
2709 if (aclCheckFast(Config
.accessList
.identLookup
, &identChecklist
))
2710 identStart(&me
, &peer
, clientIdentDone
, connState
);
2712 commSetSelect(fd
, COMM_SELECT_READ
, clientReadRequest
, connState
, 0);
2713 commSetDefer(fd
, clientReadDefer
, connState
);
2714 clientdbEstablished(peer
.sin_addr
, 1);
2720 #define SENDING_BODY 0
2721 #define SENDING_HDRSONLY 1
2723 clientCheckTransferDone(clientHttpRequest
* http
)
2725 int sending
= SENDING_BODY
;
2726 StoreEntry
*entry
= http
->entry
;
2733 * For now, 'done_copying' is used for special cases like
2734 * Range and HEAD requests.
2736 if (http
->flags
.done_copying
)
2739 * Handle STORE_OK objects.
2740 * objectLen(entry) will be set proprely.
2742 if (entry
->store_status
== STORE_OK
) {
2743 if (http
->out
.offset
>= objectLen(entry
))
2749 * Now, handle STORE_PENDING objects
2751 mem
= entry
->mem_obj
;
2752 assert(mem
!= NULL
);
2753 assert(http
->request
!= NULL
);
2755 if (reply
->hdr_sz
== 0)
2756 return 0; /* haven't found end of headers yet */
2757 else if (reply
->sline
.status
== HTTP_OK
)
2758 sending
= SENDING_BODY
;
2759 else if (reply
->sline
.status
== HTTP_NO_CONTENT
)
2760 sending
= SENDING_HDRSONLY
;
2761 else if (reply
->sline
.status
== HTTP_NOT_MODIFIED
)
2762 sending
= SENDING_HDRSONLY
;
2763 else if (reply
->sline
.status
< HTTP_OK
)
2764 sending
= SENDING_HDRSONLY
;
2765 else if (http
->request
->method
== METHOD_HEAD
)
2766 sending
= SENDING_HDRSONLY
;
2768 sending
= SENDING_BODY
;
2770 * Figure out how much data we are supposed to send.
2771 * If we are sending a body and we don't have a content-length,
2772 * then we must wait for the object to become STORE_OK.
2774 if (sending
== SENDING_HDRSONLY
)
2775 sendlen
= reply
->hdr_sz
;
2776 else if (reply
->content_length
< 0)
2779 sendlen
= reply
->content_length
+ reply
->hdr_sz
;
2781 * Now that we have the expected length, did we send it all?
2783 if (http
->out
.offset
< sendlen
)
2790 clientGotNotEnough(clientHttpRequest
* http
)
2792 int cl
= httpReplyBodySize(http
->request
->method
, http
->entry
->mem_obj
->reply
);
2793 int hs
= http
->entry
->mem_obj
->reply
->hdr_sz
;
2795 if (http
->out
.offset
< cl
+ hs
)
2801 * This function is designed to serve a fairly specific purpose.
2802 * Occasionally our vBNS-connected caches can talk to each other, but not
2803 * the rest of the world. Here we try to detect frequent failures which
2804 * make the cache unusable (e.g. DNS lookup and connect() failures). If
2805 * the failure:success ratio goes above 1.0 then we go into "hit only"
2806 * mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
2807 * will only fetch HITs from us if they are using the ICP protocol. We
2808 * stay in this mode for 5 minutes.
2810 * Duane W., Sept 16, 1996
2814 checkFailureRatio(err_type etype
, hier_code hcode
)
2816 static double magic_factor
= 100.0;
2819 if (hcode
== HIER_NONE
)
2821 n_good
= magic_factor
/ (1.0 + request_failure_ratio
);
2822 n_bad
= magic_factor
- n_good
;
2825 case ERR_CONNECT_FAIL
:
2826 case ERR_READ_ERROR
:
2832 request_failure_ratio
= n_bad
/ n_good
;
2833 if (hit_only_mode_until
> squid_curtime
)
2835 if (request_failure_ratio
< 1.0)
2837 debug(33, 0) ("Failure Ratio at %4.2f\n", request_failure_ratio
);
2838 debug(33, 0) ("Going into hit-only-mode for %d minutes...\n",
2839 FAILURE_MODE_TIME
/ 60);
2840 hit_only_mode_until
= squid_curtime
+ FAILURE_MODE_TIME
;
2841 request_failure_ratio
= 0.8; /* reset to something less than 1.0 */
2845 clientHttpConnectionsOpen(void)
2847 sockaddr_in_list
*s
;
2849 for (s
= Config
.Sockaddr
.http
; s
; s
= s
->next
) {
2851 fd
= comm_open(SOCK_STREAM
,
2854 ntohs(s
->s
.sin_port
),
2861 commSetSelect(fd
, COMM_SELECT_READ
, httpAccept
, NULL
, 0);
2862 /*commSetDefer(fd, httpAcceptDefer, NULL); */
2863 debug(1, 1) ("Accepting HTTP connections at %s, port %d, FD %d.\n",
2864 inet_ntoa(s
->s
.sin_addr
),
2865 (int) ntohs(s
->s
.sin_port
),
2867 HttpSockets
[NHttpSockets
++] = fd
;
2869 if (NHttpSockets
< 1)
2870 fatal("Cannot open HTTP Port");
2874 clientHttpConnectionsClose(void)
2877 for (i
= 0; i
< NHttpSockets
; i
++) {
2878 if (HttpSockets
[i
] >= 0) {
2879 debug(1, 1) ("FD %d Closing HTTP connection\n", HttpSockets
[i
]);
2880 comm_close(HttpSockets
[i
]);
2881 HttpSockets
[i
] = -1;