--------------------- PatchSet 3799 Date: 2006/09/29 23:15:14 Author: dwsquid Branch: squid3-icap Tag: (none) Log: syncing with HEAD Members: mkrelease.sh:1.5->1.5.12.1(DEAD) mksnapshot-cron.sh:1.3.2.2->1.3.2.3(DEAD) mksnapshot.sh:1.5->1.5.12.1(DEAD) contrib/nextstep/.cvsignore:1.2->1.2.14.1(DEAD) doc/README.wccpv2:1.1.10.1->1.1.10.2 doc/release-notes/.cvsignore:1.2->1.2.14.1(DEAD) doc/rfc/draft-ietf-radext-digest-auth-06.txt:1.1.14.1->1.1.14.2 doc/rfc/rfc0959.txt:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_ACCESS_DENIED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_CACHE_ACCESS_DENIED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_CACHE_MGR_ACCESS_DENIED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_CANNOT_FORWARD:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_CONNECT_FAIL:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_DNS_FAIL:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_ESI:1.1.10.1->1.1.10.2 errors/Azerbaijani/ERR_FORWARDING_DENIED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_DISABLED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_FAILURE:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_FORBIDDEN:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_NOT_FOUND:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_PUT_CREATED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_PUT_ERROR:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_PUT_MODIFIED:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_FTP_UNAVAILABLE:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_ICAP_FAILURE:1.1.10.1->1.1.10.2 errors/Azerbaijani/ERR_INVALID_REQ:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_INVALID_RESP:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_INVALID_URL:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_LIFETIME_EXP:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_NO_RELAY:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_ONLY_IF_CACHED_MISS:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_READ_ERROR:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_READ_TIMEOUT:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_SHUTTING_DOWN:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_SOCKET_FAILURE:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_TOO_BIG:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_UNSUP_REQ:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_URN_RESOLVE:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_WRITE_ERROR:1.1.12.1->1.1.12.2 errors/Azerbaijani/ERR_ZERO_SIZE_OBJECT:1.1.12.1->1.1.12.2 errors/Azerbaijani/README:1.1.12.1->1.1.12.2 errors/Azerbaijani/generic:1.1.10.1->1.1.10.2 errors/Bulgarian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Catalan/.cvsignore:1.1->1.1.18.1(DEAD) errors/Czech/.cvsignore:1.1->1.1.18.1(DEAD) errors/Danish/.cvsignore:1.1->1.1.18.1(DEAD) errors/Dutch/.cvsignore:1.1->1.1.18.1(DEAD) errors/English/.cvsignore:1.1->1.1.18.1(DEAD) errors/Estonian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Estonian/generic:1.1.10.1->1.1.10.2 errors/Finnish/.cvsignore:1.1->1.1.18.1(DEAD) errors/French/.cvsignore:1.1->1.1.18.1(DEAD) errors/German/.cvsignore:1.1->1.1.18.1(DEAD) errors/Greek/ERR_ESI:1.1.10.1->1.1.10.2 errors/Greek/ERR_ICAP_FAILURE:1.1.10.1->1.1.10.2 errors/Greek/generic:1.1.10.1->1.1.10.2 errors/Hebrew/.cvsignore:1.1->1.1.18.1(DEAD) errors/Hebrew/generic:1.1.10.1->1.1.10.2 errors/Hungarian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Italian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Italian/generic:1.1.10.1->1.1.10.2 errors/Japanese/.cvsignore:1.1->1.1.18.1(DEAD) errors/Korean/.cvsignore:1.1->1.1.18.1(DEAD) errors/Lithuanian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Lithuanian/ERR_ESI:1.1.10.1->1.1.10.2 errors/Lithuanian/generic:1.1.10.1->1.1.10.2 errors/Polish/.cvsignore:1.1->1.1.18.1(DEAD) errors/Portuguese/.cvsignore:1.1->1.1.18.1(DEAD) errors/Romanian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Romanian/generic:1.1.10.1->1.1.10.2 errors/Russian-1251/.cvsignore:1.1->1.1.18.1(DEAD) errors/Russian-1251/generic:1.1.10.1->1.1.10.2 errors/Russian-koi8-r/.cvsignore:1.1->1.1.18.1(DEAD) errors/Russian-koi8-r/generic:1.1.10.1->1.1.10.2 errors/Serbian/.cvsignore:1.1->1.1.18.1(DEAD) errors/Simplify_Chinese/.cvsignore:1.1->1.1.18.1(DEAD) errors/Slovak/.cvsignore:1.1->1.1.18.1(DEAD) errors/Spanish/.cvsignore:1.1->1.1.18.1(DEAD) errors/Swedish/.cvsignore:1.1->1.1.18.1(DEAD) errors/Traditional_Chinese/.cvsignore:1.1->1.1.18.1(DEAD) errors/Turkish/.cvsignore:1.1->1.1.18.1(DEAD) helpers/basic_auth/LDAP/config.test:1.3.8.1->1.3.8.2 helpers/basic_auth/MSNT/config.test:1.2.8.1->1.2.8.2 helpers/basic_auth/NCSA/config.test:1.1.14.1->1.1.14.2 helpers/basic_auth/PAM/config.test:1.1.14.1->1.1.14.2 helpers/basic_auth/SASL/config.test:1.3.8.1->1.3.8.2 helpers/basic_auth/SMB/config.test:1.1.14.1->1.1.14.2 helpers/basic_auth/YP/config.test:1.1.14.1->1.1.14.2 helpers/basic_auth/getpwnam/config.test:1.1.14.1->1.1.14.2 helpers/basic_auth/mswin_sspi/.cvsignore:1.2.6.1->1.2.6.2 helpers/basic_auth/mswin_sspi/config.test:1.2.10.1->1.2.10.2 helpers/basic_auth/multi-domain-NTLM/config.test:1.1.14.1->1.1.14.2 helpers/basic_auth/winbind/.cvsignore:1.2->1.2.14.1(DEAD) helpers/digest_auth/ldap/.cvsignore:1.2.8.1->1.2.8.2 helpers/digest_auth/ldap/Makefile.am:1.1.14.1->1.1.14.2 helpers/digest_auth/ldap/config.test:1.3.8.1->1.3.8.2 helpers/digest_auth/ldap/digest_common.h:1.1.14.1->1.1.14.2 helpers/digest_auth/ldap/digest_pw_auth.c:1.2.14.1->1.2.14.2 helpers/digest_auth/ldap/ldap_backend.c:1.2.8.1->1.2.8.2 helpers/digest_auth/ldap/ldap_backend.h:1.1.14.1->1.1.14.2 helpers/digest_auth/password/config.test:1.1.14.1->1.1.14.2 helpers/digest_auth/password/ldap_backend.c:1.2->1.2.2.1(DEAD) helpers/digest_auth/password/ldap_backend.h:1.1->1.1.4.1(DEAD) helpers/external_acl/ip_user/config.test:1.2.2.1->1.2.2.2 helpers/external_acl/ldap_group/config.test:1.3.8.1->1.3.8.2 helpers/external_acl/mswin_lm_group/.cvsignore:1.2.6.1->1.2.6.2 helpers/external_acl/mswin_lm_group/config.test:1.2.10.1->1.2.10.2 helpers/external_acl/session/.cvsignore:1.2.8.1->1.2.8.2 helpers/external_acl/session/Makefile.am:1.1.12.1->1.1.12.2 helpers/external_acl/session/config.test:1.2.10.1->1.2.10.2 helpers/external_acl/session/squid_session.8:1.1.12.1->1.1.12.2 helpers/external_acl/session/squid_session.c:1.1.12.1->1.1.12.2 helpers/external_acl/unix_group/config.test:1.1.14.1->1.1.14.2 helpers/external_acl/wbinfo_group/config.test:1.2.8.1->1.2.8.2 helpers/external_acl/winbind_group/.cvsignore:1.2->1.2.14.1(DEAD) helpers/negotiate_auth/.cvsignore:1.2.6.1->1.2.6.2 helpers/negotiate_auth/mswin_sspi/.cvsignore:1.2.6.1->1.2.6.2 helpers/negotiate_auth/mswin_sspi/config.test:1.2.10.1->1.2.10.2 helpers/ntlm_auth/SMB/config.test:1.2.10.1->1.2.10.2 helpers/ntlm_auth/fakeauth/config.test:1.1.12.1->1.1.12.2 helpers/ntlm_auth/mswin_sspi/.cvsignore:1.2.6.1->1.2.6.2 helpers/ntlm_auth/mswin_sspi/config.test:1.2.10.1->1.2.10.2 helpers/ntlm_auth/no_check/config.test:1.1.12.1->1.1.12.2 helpers/ntlm_auth/winbind/.cvsignore:1.2->1.2.14.1(DEAD) helpers/ntlm_auth/winbind/patches/.cvsignore:1.1->1.1.18.1(DEAD) include/assert.h:1.2.12.1->1.2.12.2 include/squid_mswin.h:1.3.2.1->1.3.2.2 include/strsep.h:1.2.8.1->1.2.8.2 include/samba/.cvsignore:1.1->1.1.18.1(DEAD) include/samba/nsswitch/.cvsignore:1.1->1.1.18.1(DEAD) lib/assert.c:1.1.12.1->1.1.12.2 lib/strsep.c:1.1.10.1->1.1.10.2 lib/win32lib.c:1.4.2.1->1.4.2.2 lib/cppunit-1.10.0/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/config/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/config/ax_prefix_config_h.m4:1.1.12.1->1.1.12.2 lib/cppunit-1.10.0/doc/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/ClockerPlugIn/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/DumperPlugIn/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/cppunittest/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/hierarchy/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/money/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/examples/simple/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/config/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/extensions/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/plugin/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/portability/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/tools/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/ui/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/ui/mfc/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/ui/qt/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/include/cppunit/ui/text/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/src/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/src/DllPlugInTester/.cvsignore:1.2.8.1->1.2.8.2 lib/cppunit-1.10.0/src/cppunit/.cvsignore:1.2.8.1->1.2.8.2 lib/tests/.cvsignore:1.2.8.1->1.2.8.2 src/ACLHTTPHeaderData.cc:1.2.8.1->1.2.8.2 src/ACLHTTPHeaderData.h:1.2.8.1->1.2.8.2 src/ACLHTTPRepHeader.cc:1.1.10.1->1.1.10.2 src/ACLHTTPRepHeader.h:1.2.8.1->1.2.8.2 src/ACLHTTPReqHeader.cc:1.1.10.1->1.1.10.2 src/ACLHTTPReqHeader.h:1.2.8.1->1.2.8.2 src/AsyncEngine.cc:1.1.10.1->1.1.10.2 src/AsyncEngine.h:1.1.10.1->1.1.10.2 src/BodyReader.cc:1.5.2.1->1.5.2.2 src/BodyReader.h:1.2.2.1->1.2.2.2 src/CacheManager.h:1.1.10.1->1.1.10.2 src/ClientBody.cc:1.3.8.1->1.3.8.2 src/ClientBody.h:1.2.12.1->1.2.12.2 src/CompletionDispatcher.cc:1.1.10.1->1.1.10.2 src/CompletionDispatcher.h:1.2.8.1->1.2.8.2 src/ConfigParser.cc:1.2.8.1->1.2.8.2 src/EventLoop.cc:1.3.8.1->1.3.8.2 src/EventLoop.h:1.3.8.1->1.3.8.2 src/HttpHdrSc.h:1.1.12.1->1.1.12.2 src/HttpHdrScTarget.h:1.1.12.1->1.1.12.2 src/HttpHeaderMask.h:1.1.12.1->1.1.12.2 src/HttpRequestMethod.cc:1.1.12.1->1.1.12.2 src/HttpRequestMethod.h:1.1.12.1->1.1.12.2 src/Packer.h:1.2.8.1->1.2.8.2 src/PeerDigest.h:1.1.10.1->1.1.10.2 src/RemovalPolicy.cc:1.1.10.1->1.1.10.2 src/RemovalPolicy.h:1.1.10.1->1.1.10.2 src/Server.cc:1.4.2.1->1.4.2.2 src/Server.h:1.1.12.1->1.1.12.2 src/SquidTime.h:1.2.6.1->1.2.6.2 src/StoreEntryStream.h:1.2.10.1->1.2.10.2 src/URL.h:1.1.12.1->1.1.12.2 src/URLScheme.cc:1.1.12.1->1.1.12.2 src/URLScheme.h:1.1.12.1->1.1.12.2 src/WinSvc.cc:1.2.4.1->1.2.4.2 src/acl_noncore.cc:1.3.6.1->1.3.6.2 src/cachemgr.cc:1.14.2.1->1.14.2.2(DEAD) src/cachemgr.conf:1.2->1.2.6.1(DEAD) src/cbdata.h:1.1.10.1->1.1.10.2 src/client.cc:1.11->1.11.2.1(DEAD) src/comm_epoll.h:1.1.10.1->1.1.10.2 src/comm_kqueue.h:1.1.10.1->1.1.10.2 src/comm_poll.h:1.1.10.1->1.1.10.2 src/comm_select.h:1.1.10.1->1.1.10.2 src/comm_select_win32.cc:1.3.2.1->1.3.2.2 src/dlink.h:1.1.12.1->1.1.12.2 src/errorpage.h:1.2.8.1->1.2.8.2 src/event.h:1.3.2.1->1.3.2.2 src/forward.h:1.9.2.1->1.9.2.2 src/ipc_win32.cc:1.3.4.1->1.3.4.2 src/leakfinder.cc:1.2->1.2.14.1(DEAD) src/mk-globals-c.awk:1.2.6.1->1.2.6.2 src/mk-string-arrays.awk:1.1.12.1->1.1.12.2 src/pconn.h:1.2.6.1->1.2.6.2 src/time.cc:1.3.6.1->1.3.6.2 src/wccp2.cc:1.9.2.1->1.9.2.2 src/wordlist.cc:1.1.12.1->1.1.12.2 src/wordlist.h:1.1.12.1->1.1.12.2 src/DiskIO/.cvsignore:1.2.8.1->1.2.8.2 src/DiskIO/AIO/.cvsignore:1.2.8.1->1.2.8.2 src/DiskIO/AIO/aio_win32.cc:1.3.4.1->1.3.4.2 src/DiskIO/AIO/aio_win32.h:1.3.4.1->1.3.4.2 src/DiskIO/Blocking/.cvsignore:1.2.8.1->1.2.8.2 src/DiskIO/DiskDaemon/.cvsignore:1.2.8.1->1.2.8.2 src/DiskIO/DiskThreads/.cvsignore:1.2.8.1->1.2.8.2 src/DiskIO/DiskThreads/aiops_win32.cc:1.3.4.1->1.3.4.2 src/ICAP/.cvsignore:1.2.8.1->1.2.8.2 src/auth/negotiate/.cvsignore:1.2.8.1->1.2.8.2 src/tests/.cvsignore:1.2.8.1->1.2.8.2 src/tests/CapturingStoreEntry.h:1.1.10.1->1.1.10.2 src/tests/stub_DelayId.cc:1.1.12.1->1.1.12.2 src/tests/stub_access_log.cc:1.1.12.1->1.1.12.2 src/tests/stub_cache_manager.cc:1.1->1.1.12.1(DEAD) src/tests/stub_client_side_request.cc:1.1.12.1->1.1.12.2 src/tests/stub_mime.cc:1.1.12.1->1.1.12.2 src/tests/testACLMaxUserIP.cc:1.1.12.1->1.1.12.2 src/tests/testACLMaxUserIP.h:1.1.12.1->1.1.12.2 src/tests/testBoilerplate.cc:1.1.12.1->1.1.12.2 src/tests/testBoilerplate.h:1.1.12.1->1.1.12.2 src/tests/testCacheManager.cc:1.1.10.1->1.1.10.2 src/tests/testCacheManager.h:1.1.10.1->1.1.10.2 src/tests/testDiskIO.cc:1.1.6.1->1.1.6.2 src/tests/testDiskIO.h:1.1.6.1->1.1.6.2 src/tests/testEvent.cc:1.3.8.1->1.3.8.2 src/tests/testEvent.h:1.1.10.1->1.1.10.2 src/tests/testEventLoop.cc:1.4.2.1->1.4.2.2 src/tests/testEventLoop.h:1.3.8.1->1.3.8.2 src/tests/testHeader_ACL.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_AsyncEngine.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_CompletionDispatcher.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_ConfigParser.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_EventLoop.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_HttpHeader.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_HttpHeaderRange.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_HttpReply.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_HttpRequestMethod.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_RemovalPolicy.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_SquidTime.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_Store.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_StoreEntryStream.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_URL.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_URLScheme.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_cbdata.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_client_side_request.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_comm.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_dlink.cc:1.1.12.1->1.1.12.2 src/tests/testHeader_errorpage.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_event.cc:1.1.10.1->1.1.10.2 src/tests/testHeader_wordlist.cc:1.1.12.1->1.1.12.2 src/tests/testHttpRequest.cc:1.1.12.1->1.1.12.2 src/tests/testHttpRequest.h:1.1.12.1->1.1.12.2 src/tests/testHttpRequestMethod.cc:1.2.2.1->1.2.2.2 src/tests/testHttpRequestMethod.h:1.1.12.1->1.1.12.2 src/tests/testStoreEntryStream.cc:1.2.6.1->1.2.6.2 src/tests/testStoreEntryStream.h:1.1.12.1->1.1.12.2 src/tests/testStoreSupport.cc:1.1.10.1->1.1.10.2 src/tests/testStoreSupport.h:1.1.10.1->1.1.10.2 src/tests/testString.cc:1.2.6.1->1.2.6.2 src/tests/testString.h:1.1.12.1->1.1.12.2 src/tests/testURL.cc:1.2.2.1->1.2.2.2 src/tests/testURL.h:1.1.12.1->1.1.12.2 src/tests/testURLScheme.cc:1.2.2.1->1.2.2.2 src/tests/testURLScheme.h:1.1.12.1->1.1.12.2 src/tests/test_http_range.cc:1.1.10.1->1.1.10.2 test-suite/http_range_test.cc:1.12->1.12.12.1(DEAD) tools/.cvsignore:1.1.10.1->1.1.10.2 tools/Makefile.am:1.1.12.1->1.1.12.2 tools/cachemgr.cc:1.3.2.1->1.3.2.2 tools/cachemgr.conf:1.1.12.1->1.1.12.2 tools/squidclient.cc:1.5.2.1->1.5.2.2 --- squid3/mkrelease.sh Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,63 +0,0 @@ -#!/bin/sh -ex -if [ $# -ne 1 -a $# -ne 2 ]; then - echo "Usage: $0 revision [destination]" - exit 1 -fi -package=squid -module=squid3 -rev=`echo $1 | sed -e "s/^${package}-//"` -name=${package}-${rev} -tag=`echo ${name} | tr a-z.- A-Z__` -startdir=$PWD/ -dst=${2:-$PWD}/ -RELEASE_TIME=`date +%s` - -tmpdir=${TMPDIR:-${PWD}}/${name}-mkrelease - -CVSROOT=${CVSROOT:-/server/cvs-server/squid} -export CVSROOT - -rm -rf $name.tar.gz $tmpdir -trap "rm -rf $tmpdir" 0 - -cvs -Q export -d $tmpdir -r $tag $module -if [ ! -f $tmpdir/configure ]; then - echo "ERROR! Tag $tag not found in $module" -fi - -cd $tmpdir -eval `grep "^ *VERSION=" configure | sed -e 's/-CVS//'` -eval `grep "^ *PACKAGE=" configure` -if [ ${name} != ${PACKAGE}-${VERSION} ]; then - echo "ERROR! The version numbers does not match!" - echo "${name} != ${PACKAGE}-${VERSION}" - exit 1 -fi -RELEASE=`echo $VERSION | cut -d. -f1,2 | cut -d- -f1` -ed -s configure.in </dev/null - -make_snapshot() -{ { - set -e - cd ../release - mksnap=$1 - tag=$2 - dir=$3 - ver=$4 - save=${5:-3} - dst=$versions/$dir/$ver - $mksnap $tag 2>&1 | grep -v "set owner/group" - for file in `cat $tag.out` ; do - type=`echo $file | sed -e 's/.*\.tar\.gz/.tar.gz/' -e 's/.*\.tar\.bz2/.tar.bz2/' -e 's/.*\.patch/.patch/' -e 's/.*\.diff/.diff/' -e 's/.*-RELEASENOTES.html/-RELEASENOTES.html/' -e 's/^.*ChangeLog.txt$/-ChangeLog.txt/'` - - # move tarball - rm -f $dst/$file - cp -p $file $dst/$file - rm -f $file - - # update snapshot symlink - rm -f $dst/squid-$ver.snapshot$type - ln -s $file $dst/squid-$ver.snapshot$type - - # cleanup old snapshots - ls $dst/*-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$type | sed -e 's/.*\(-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'$type'\)/\1/' | sort -r | tail +$save | while read f; do - rm -f $dst/*-$f - done - done - - # update web page - if [ -x $dst/make.sh ]; then - $dst/make.sh - fi - -} } - -set +e - -../commit/bootstrap squid -make_snapshot ../commit/squid/mksnapshot.sh HEAD v3 HEAD 6 - -rm -f /server/httpd/htdocs/squid-cache.org/CONTRIBUTORS.new -cp ../commit/squid/CONTRIBUTORS /server/httpd/htdocs/squid-cache.org/CONTRIBUTORS.new -chmod 444 /server/httpd/htdocs/squid-cache.org/CONTRIBUTORS.new -mv -f /server/httpd/htdocs/squid-cache.org/CONTRIBUTORS.new /server/httpd/htdocs/squid-cache.org/CONTRIBUTORS.txt - -rm -f /server/httpd/htdocs/squid-cache.org/SPONSORS.new -cp ../commit/squid/SPONSORS /server/httpd/htdocs/squid-cache.org/SPONSORS.new -chmod 444 /server/httpd/htdocs/squid-cache.org/SPONSORS.new -mv -f /server/httpd/htdocs/squid-cache.org/SPONSORS.new /server/httpd/htdocs/squid-cache.org/SPONSORS.txt - -#../commit/bootstrap squid-3.0 -#make_snapshot ../commit/squid/mksnapshot.sh SQUID_3_0 v3 3.0 3 -make_snapshot ../commit/squid/mksnapshot.sh HEAD v3 3.0 3 - -../commit/bootstrap squid-2 -#make_snapshot ../commit/squid-2/mksnapshot.sh HEAD v2 2.6 6 - -../commit/bootstrap squid-2.5 -make_snapshot ../commit/squid-2.5/mksnapshot.sh SQUID_2_5 v2 2.5 3 - -#../commit/squid3-SQUID2.sync --- squid3/mksnapshot.sh Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,62 +0,0 @@ -#!/bin/sh -e -if [ $# -gt 1 ]; then - echo "Usage: $0 [branch]" - exit 1 -fi -module=squid3 -tag=${1:-HEAD} -startdir=$PWD -date=`env TZ=GMT date +%Y%m%d` - -tmpdir=${TMPDIR:-${PWD}}/${module}-${tag}-mksnapshot - -CVSROOT=${CVSROOT:-/server/cvs-server/squid} -export CVSROOT - -rm -rf $tmpdir -trap "rm -rf $tmpdir" 0 - -rm -f ${tag}.out -cvs -Q export -d $tmpdir -r $tag $module -if [ ! -f $tmpdir/configure ]; then - echo "ERROR! Tag $tag not found in $module" -fi - -cd $tmpdir -eval `grep "^ *VERSION=" configure | sed -e 's/-CVS//'` -eval `grep "^ *PACKAGE=" configure` -ed -s configure.in <>${tag}.out -cp -p $tmpdir/${PACKAGE}-${VERSION}-${date}.tar.bz2 . -echo ${PACKAGE}-${VERSION}-${date}.tar.bz2 >>${tag}.out - -relnotes=$tmpdir/doc/release-notes/release-`echo $VERSION | cut -d. -f1,2 | cut -d- -f1`.html -if [ -f $relnotes ]; then - cp -p $relnotes ${PACKAGE}-${VERSION}-${date}-RELEASENOTES.html - echo ${PACKAGE}-${VERSION}-${date}-RELEASENOTES.html >>${tag}.out - ed -s ${PACKAGE}-${VERSION}-${date}-RELEASENOTES.html <>${tag}.out - -if (echo $VERSION | grep PRE) || (echo $VERSION | grep STABLE); then - echo "Differences from ${PACKAGE}-${VERSION} to ${PACKAGE}-${VERSION}-${date}" >${PACKAGE}-${VERSION}-${date}.diff - cvs -q rdiff -u -r SQUID_`echo $VERSION | tr .- __` -r $tag $module >>${PACKAGE}-${VERSION}-${date}.diff - echo ${PACKAGE}-${VERSION}-${date}.diff >>${tag}.out -fi --- squid3/contrib/nextstep/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,3 +0,0 @@ -.cvsignore -Makefile.in -Makefile --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/doc/README.wccpv2 Wed Feb 14 13:38:00 2007 @@ -0,0 +1,62 @@ +This version of squid has been patched with the wccpv2 support patch. To +enable this option, use the --enable-wccpv2 option on the configure script. + +Wccpv2 allows a single cache to associate itself with multiple routers, and +also allows multiple wccp services to be defined. The other advantage of +wccpv2 is that the cisco IOS uses CEF to switch the packets. + +Example simple web cache +------------------------ + +Internet <-> fa0/0 2621 fa0/1 <-> cache, internal network + +squid.conf: + +wccp2_router 192.168.2.1:2048 +wccp2_version 4 +wccp2_forwarding_method 1 +wccp2_return_method 1 +wccp2_service standard 0 + +Router config: + +ip wccp web-cache +! +interface FastEthernet0/0 + description uplink + ip address 192.168.1.200 255.255.255.0 + ip wccp web-cache redirect out + duplex auto + speed auto +! +interface FastEthernet0/1 + description local network + ip address 192.168.2.1 255.255.255.0 + duplex auto + speed auto +! + +Note the cache is on the internal network (Fa0/1), the interception occurs +on the uplink interface(0/0). + +Linux (Kernel 2.6.10, i386) side of things: + +#!/bin/sh +echo "1" > /proc/sys/net/ipv4/ip_forward +echo "0" > /proc/sys/net/ipv4/conf/all/rp_filter +iptunnel add gre1 mode gre remote 192.168.2.1 local 192.168.2.2 dev eth0 +ifconfig gre1 up 127.0.0.2 +iptables -t nat -F +# iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128 +iptables -t nat -A PREROUTING -i gre1 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.2.2:3128 + + +TODO +---- + +* The wccp2 router configuration need to have a better configuration interface + (it currently uses ip:port when only the ip address is needed). +* A shutting-down cache should generate a removal query, informing the router + (and therefore the caches in the group) that this cache is going + away and no new traffic should be forwarded to it. +* Some more documentation, examples, etc. --- squid3/doc/release-notes/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,3 +0,0 @@ -.cvsignore -Makefile.in -Makefile --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/doc/rfc/draft-ietf-radext-digest-auth-06.txt Wed Feb 14 13:38:00 2007 @@ -0,0 +1,2135 @@ + + + + + + +Network Working Group B. Sterman +Internet-Draft Kayote Networks +Expires: April 17, 2006 D. Sadolevsky + SecureOL, Inc. + D. Schwartz + Kayote Networks + D. Williams + Cisco Systems + W. Beck + Deutsche Telekom AG + October 14, 2005 + + + RADIUS Extension for Digest Authentication + draft-ietf-radext-digest-auth-06.txt + +Status of this Memo + + By submitting this Internet-Draft, each author represents that any + applicable patent or other IPR claims of which he or she is aware + have been or will be disclosed, and any of which he or she becomes + aware will be disclosed, in accordance with Section 6 of BCP 79. + + Internet-Drafts are working documents of the Internet Engineering + Task Force (IETF), its areas, and its working groups. Note that + other groups may also distribute working documents as Internet- + Drafts. + + Internet-Drafts are draft documents valid for a maximum of six months + and may be updated, replaced, or obsoleted by other documents at any + time. It is inappropriate to use Internet-Drafts as reference + material or to cite them other than as "work in progress." + + The list of current Internet-Drafts can be accessed at + http://www.ietf.org/ietf/1id-abstracts.txt. + + The list of Internet-Draft Shadow Directories can be accessed at + http://www.ietf.org/shadow.html. + + This Internet-Draft will expire on April 17, 2006. + +Copyright Notice + + Copyright (C) The Internet Society (2005). + +Abstract + + This document defines an extension to the RADIUS protocol to enable + + + +Sterman, et al. Expires April 17, 2006 [Page 1] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + support of Digest Authentication, for use with HTTP-style protocols + like SIP and HTTP. + + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 4 + 1.1. Terminology . . . . . . . . . . . . . . . . . . . . . . . 4 + 1.2. Motivation . . . . . . . . . . . . . . . . . . . . . . . . 4 + 1.3. Overview . . . . . . . . . . . . . . . . . . . . . . . . . 5 + 1.3.1. Scenario 1, RADIUS client chooses nonces . . . . . . . 6 + 1.3.2. Scenario 2, RADIUS server chooses nonces . . . . . . . 7 + 2. Interoperability . . . . . . . . . . . . . . . . . . . . . . . 9 + 3. Detailed Description . . . . . . . . . . . . . . . . . . . . . 9 + 3.1. RADIUS Client Behavior . . . . . . . . . . . . . . . . . . 9 + 3.2. RADIUS Server Behavior . . . . . . . . . . . . . . . . . . 12 + 4. New RADIUS attributes . . . . . . . . . . . . . . . . . . . . 13 + 4.1. Digest-Response attribute . . . . . . . . . . . . . . . . 14 + 4.2. Digest-Realm attribute . . . . . . . . . . . . . . . . . . 14 + 4.3. Digest-Nonce attribute . . . . . . . . . . . . . . . . . . 15 + 4.4. Digest-Response-Auth attribute . . . . . . . . . . . . . . 15 + 4.5. Digest-Nextnonce attribute . . . . . . . . . . . . . . . . 16 + 4.6. Digest-Method attribute . . . . . . . . . . . . . . . . . 16 + 4.7. Digest-URI attribute . . . . . . . . . . . . . . . . . . . 16 + 4.8. Digest-Qop attribute . . . . . . . . . . . . . . . . . . . 17 + 4.9. Digest-Algorithm attribute . . . . . . . . . . . . . . . . 17 + 4.10. Digest-Entity-Body-Hash attribute . . . . . . . . . . . . 18 + 4.11. Digest-CNonce attribute . . . . . . . . . . . . . . . . . 18 + 4.12. Digest-Nonce-Count attribute . . . . . . . . . . . . . . . 19 + 4.13. Digest-Username attribute . . . . . . . . . . . . . . . . 19 + 4.14. Digest-Opaque attribute . . . . . . . . . . . . . . . . . 19 + 4.15. Digest-Auth-Param attribute . . . . . . . . . . . . . . . 20 + 4.16. Digest-AKA-Auts attribute . . . . . . . . . . . . . . . . 20 + 4.17. Digest-Domain attribute . . . . . . . . . . . . . . . . . 21 + 4.18. Digest-Stale attribute . . . . . . . . . . . . . . . . . . 21 + 4.19. Digest-HA1 attribute . . . . . . . . . . . . . . . . . . . 22 + 4.20. SIP-AOR . . . . . . . . . . . . . . . . . . . . . . . . . 22 + 5. Diameter Compatibility . . . . . . . . . . . . . . . . . . . . 23 + 6. Table of Attributes . . . . . . . . . . . . . . . . . . . . . 23 + 7. Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 + 8. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 28 + 9. Security Considerations . . . . . . . . . . . . . . . . . . . 28 + 10. Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . 30 + 11. References . . . . . . . . . . . . . . . . . . . . . . . . . . 30 + 11.1. Normative References . . . . . . . . . . . . . . . . . . . 30 + 11.2. Informative References . . . . . . . . . . . . . . . . . . 30 + Appendix A. Change Log . . . . . . . . . . . . . . . . . . . . . 31 + A.1. Changes from draft-ietf-radext-digest-auth-05 . . . . . . 31 + + + +Sterman, et al. Expires April 17, 2006 [Page 2] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + A.2. Changes from draft-ietf-radext-digest-auth-04 . . . . . . 31 + A.3. Changes from draft-ietf-radext-digest-auth-03 . . . . . . 31 + A.4. Changes from draft-ietf-radext-digest-auth-02 . . . . . . 31 + A.5. Changes from draft-ietf-radext-digest-auth-01 . . . . . . 31 + A.6. Changes from draft-ietf-radext-digest-auth-00 . . . . . . 32 + A.7. Changes from draft-sterman-aaa-sip-04 . . . . . . . . . . 32 + A.8. Changes from draft-sterman-aaa-sip-03 . . . . . . . . . . 32 + A.9. Changes from draft-sterman-aaa-sip-02 . . . . . . . . . . 32 + A.10. Changes from draft-sterman-aaa-sip-01 . . . . . . . . . . 33 + Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . . 34 + Intellectual Property and Copyright Statements . . . . . . . . . . 35 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 3] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + +1. Introduction + +1.1. Terminology + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [RFC2119]. + + The use of normative requirement key words in this document shall + apply only to RADIUS Client and RADIUS Server implementations that + include the features described in this document. This document + creates no normative requirements for existing implementations. + + HTTP-style protocol + The term 'HTTP-style' denotes any protocol that uses HTTP-like + headers and uses HTTP digest authentication as described in + [RFC2617]. Examples are HTTP and SIP. + NAS + Network Access Server, the RADIUS client. + nonce + An unpredictable value used to prevent replay attacks. The + nonce generator may use cryptographic mechanisms to produce + nonces it can recognize without maintaining state. + protection space + The combination of realm and digest URI, the use of which is + authorized by the RADIUS server. + SIP UA + SIP User Agent, an Internet endpoint that uses the Session + Initiation Protocol. + SIP UAS + SIP User Agent Server, a logical entity that generates a + response to a SIP (Session Initiation Protocol) request. + +1.2. Motivation + + The HTTP Digest Authentication mechanism, defined in [RFC2617], was + subsequently adapted to use with SIP in [RFC2543] (obsoleted by + [RFC3261]). Due to the limitations and weaknesses of Digest + Authentication (see [RFC2617], section 4), additional authentication + and encryption mechanisms are defined in SIP [RFC3261], including TLS + [RFC2246] and S/MIME [RFC2633]. However, Digest Authentication has + been widely implemented within SIP clients and to support those + clients there is a need for support of Digest Authentication within + AAA protocols such as RADIUS [RFC2865] and Diameter [RFC3588]. + + This document defines an extension to the RADIUS protocol to enable + support of Digest Authentication, for use with SIP, HTTP, and other + HTTP-style protocols using this authentication method. Support for + + + +Sterman, et al. Expires April 17, 2006 [Page 4] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Digest mechanisms such as AKA [RFC3310] is also supported. A + companion document [I-D.ietf-aaa-diameter-sip-app] defines support + for Digest Authentication within Diameter. + +1.3. Overview + + HTTP digest is a challenge-response protocol used to authenticate a + client's request to access some resource on a server. Figure 1 shows + a single HTTP digest transaction. + + + + + + HTTP/SIP.. + +------------+ (1) +------------+ + | |--------->| | + | HTTP-style | (2) | HTTP-style | + | Client |<---------| server | + | | (3) | | + | |--------->| | + | | (4) | | + | |<---------| | + +------------+ +------------+ + + + + + Figure 1: digest operation without RADIUS + + If the client sends a request without any credentials (1), the server + will reply with an error response (2) containing a nonce. The client + creates a cryptographic digest from parts of the request, from the + nonce it received from the server, and a shared secret. The client + re-transmits the request (3) to the server, but now includes the + digest within the packet. The server does the same digest + calculation as the client and compares the result with the digest it + received in (3). If the digest values are identical, the server + grants access to the resource and sends a positive response to the + client (4). If the digest values differ, the server sends a negative + response to the client (4). + + Instead of maintaining a local user database, the server could use + RADIUS to access a centralized user database. However, RADIUS + [RFC2865] does not include support for HTTP digest authentication. + The RADIUS client can not use the User-Password attribute, since it + does not receive a password from the HTTP-style client. The CHAP- + Challenge and CHAP-Password attributes are also not suitable since + + + +Sterman, et al. Expires April 17, 2006 [Page 5] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + the CHAP algorithm is not compatible with HTTP digest. + + This document defines new attributes that enable the RADIUS server to + perform the digest calculation defined in [RFC2617], providing + support for Digest Authentication as a native authentication + mechanism within RADIUS. + + This document defines new attributes that enable the RADIUS server to + perform the digest calculation defined in [RFC2617]. + + The nonces required by the digest algorithm are either generated by + the RADIUS client or by the RADIUS server. A mix of nonce generation + modes is not supported. This specification assumes that both the + RADIUS client and server are appropriately configured to generate the + nonces in either the RADIUS client or the RADIUS server, but not in + both at the same time. Implementations, though, do not have the + means to verify this behavior. + +1.3.1. Scenario 1, RADIUS client chooses nonces + + + + + + HTTP/SIP RADIUS + + +-----+ (1) +-----+ +-----+ + | |==========>| | | | + | | (2) | | | | + | |<==========| | | | + | | (3) | | | | + | |==========>| | | | + | A | | B | (4) | C | + | | | |---------->| | + | | | | (5) | | + | | | |<----------| | + | | (6) | | | | + | |<==========| | | | + +-----+ +-----+ +-----+ + + ====> HTTP/SIP + ----> RADIUS + + + + Figure 2: RADIUS client chooses nonces + + The roles played by the entities in this scenario are as follows: + + + +Sterman, et al. Expires April 17, 2006 [Page 6] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + A: HTTP client / SIP UA + + B: {HTTP server / HTTP proxy server / SIP proxy server / SIP UAS} + acting also as a RADIUS NAS (RADIUS client) + + C: RADIUS server + + The relevant order of messages sent in this scenario is as follows: + + A sends B an HTTP/SIP request without authorization header (step 1). + B challenges A sending an HTTP/SIP "407 / 401 (Proxy) Authorization + required" response containing a locally generated nonce (step 2). A + sends B an HTTP/SIP request with authorization header (step 3). B + sends C a RADIUS Access-Request with attributes described in this + document (step 4). C responds to B with a RADIUS Access-Accept/ + Access-Reject response (step 5). If credentials were accepted, B + receives an Access-Accept response and the message sent from A is + considered authentic. If B receives an Access-Reject response, + however, B then responds to A with a "407 / 401 (Proxy) Authorization + required" response (step 6). + +1.3.2. Scenario 2, RADIUS server chooses nonces + + While the usage scenario described in Section 1.3.1 minimizes the + load on the RADIUS server, alternatives are required in some + situations. When using AKA [RFC3310] the nonce is partially derived + from a precomputed authentication vector, which is often stored + centrally. + + Figure 3 depicts a scenario in which the RADIUS server chooses + nonces. In this case entities A and B communicate using HTTP or SIP, + while entities B and C communicate using RADIUS." + + + + + + + + + + + + + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 7] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + HTTP/SIP RADIUS + + +-----+ (1) +-----+ +-----+ + | |==========>| | (2) | | + | | | |---------->| | + | | | | (3) | | + | | (4) | |<----------| | + | |<==========| | | | + | | (5) | | | | + | |==========>| | | | + | A | | B | (6) | C | + | | | |---------->| | + | | | | (7) | | + | | | |<----------| | + | | (8) | | | | + | |<==========| | | | + +-----+ +-----+ +-----+ + + ====> HTTP/SIP + ----> RADIUS + + + + Figure 3: RADIUS server chooses nonces + + The roles played by the entities in this scenario are as follows: + + A: HTTP client / SIP UA + + B: {HTTP server / HTTP proxy server / SIP proxy server / SIP UAS} + acting also as a RADIUS NAS + + C: RADIUS server + + The following messages are sent in this scenario: + + A sends B an HTTP/SIP request without an authorization header (step + 1). B sends an Access-Request packet with the newly defined Digest- + Method and Digest-URI attributes but without a Digest-Nonce attribute + to the RADIUS server, C (step 2). C chooses a nonce and responds + with an Access-Challenge (step 3). This Access-Challenge contains + Digest attributes, from which B takes values to construct an HTTP/SIP + "(Proxy) Authorization required" response. The remaining steps are + identical with scenario 1 (Section 1.3.1): B sends this response to A + (step 4). A resends its request with its credentials (step 5). B + sends an Access-Request to C (step 6). C checks the credentials and + replies with Access-Accept or Access-Reject (step 7). Dependent on + the C's result, B processes A's request or rejects it with a "(Proxy) + + + +Sterman, et al. Expires April 17, 2006 [Page 8] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Authorization required" response (step 8). + + +2. Interoperability + + An implementation supporting this extension MUST include a Digest- + Response attribute within an Access-Request packet where Digest + Authentication is desired. An Access-Request MUST NOT contain both a + Digest-Response attribute and another authentication attribute, such + as User-Password, CHAP-Password, or EAP-Message. + + RADIUS clients and servers MUST support both nonce generation modes. + As there is no automatic capability exchange, the operator MUST make + sure that the RADIUS client software uses the correct nonce + generation mode when accessing a specific RADIUS server: + o If the RADIUS server generates nonces, its RADIUS clients MUST NOT + try to generate nonces. + o If the RADIUS server does not generate nonces, its RADIUS clients + MUST generate nonces locally. + o If at least one HTTP-style client requires AKA authentication + [RFC3310], the RADIUS server MUST generate nonces and its RADIUS + clients MUST NOT generate nonces locally. + RADIUS implementations MUST offer respective configuration options. + + +3. Detailed Description + +3.1. RADIUS Client Behavior + + The attributes described in this document are sent in cleartext. + Therefore were a RADIUS client to accept secured connections (https + or sips) from HTTP-style clients, this could result in information + intentionally protected by HTTP-style clients being sent in the clear + during the RADIUS exchange. + + On reception of an HTTP-style request message, the RADIUS client + checks whether it is authorized to authenticate the request. Where + an HTTP-style request traverses several proxies and each of the + proxies requests to authenticate the HTTP-style client, the request + at the HTTP-style server may contain multiple credential sets. + + The RADIUS client can use the 'realm' directive in HTTP to determine + which credentials are applicable. Where none of the realms are of + interest, the RADIUS client MUST behave as though no relevant + credentials were sent. In all situations the RADIUS client MUST send + zero or exactly one credential to the RADIUS server. The RADIUS + client MUST choose the credential of the (Proxy-)Authorization header + if the realm directive matches its locally configured realm. + + + +Sterman, et al. Expires April 17, 2006 [Page 9] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + If such a (Proxy-)Authorization header is present and contains HTTP + digest information, the RADIUS client checks the 'nonce' parameter. + If the RADIUS client generates nonces but did not issue the received + nonce, it responds with a 401 (Unauthorized) or 407 (Proxy + Authentication Required) to the HTTP-style client. In this error + response, the RADIUS client sends a new nonce. + + If the RADIUS client recognizes the nonce or does not generate + nonces, it takes the header directives and puts them into a RADIUS + Access-Request packet. It puts the 'response' directive into a + Digest-Response attribute and the realm / nonce / digest-uri / qop / + algorithm / cnonce / nc / username / opaque directives into the + respective Digest-Realm / Digest-Nonce / Digest-URI / Digest-Qop / + Digest-Algorithm / Digest-CNonce / Digest-Nonce-Count / Digest- + Username / Digest-Opaque attributes. The request method is put into + the Digest-Method attribute. The RADIUS client adds a Message- + Authenticator attribute, defined in [RFC3579] and sends the Access- + Request packet to the RADIUS server. + + The RADIUS server processes the packet and responds with an Access- + Accept or an Access-Reject. + + The RADIUS client constructs an Authentication-Info header: + o If the Access-Accept packet contains a Digest-Response-Auth + attribute, the RADIUS client checks the Digest-Qop attribute: + * If the Digest-Qop attribute's value is 'auth' or not specified, + the RADIUS client puts the Digest-Response-Auth attribute's + content into the Authentication-Info header's 'rspauth' + directive of the HTTP-style response. + * If the Digest-Qop attribute's value is 'auth-int', the RADIUS + client ignores the Access-Accept packet and behaves like it had + received an Access-Reject packet (Digest-Response-Auth can't be + correct as the RADIUS server does not know the contents of the + HTTP-style response's body). + o If the Access-Accept packet contains a Digest-HA1 attribute, the + RADIUS client checks the 'qop' and 'algorithm' directives in the + Authorization header of the HTTP-style request it wants to + authorize: + * If the 'qop' directive is missing or its value is 'auth', the + RADIUS client ignores the Digest-HA1 attribute. It does not + include an Authentication-Info header into its HTTP-style + response. + * If the 'qop' directive's value is 'auth-int' and at least one + of the following conditions is true, the RADIUS client + calculates the contents of the HTTP-style response's 'rspauth' + directive: + + + + + +Sterman, et al. Expires April 17, 2006 [Page 10] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + + The algorithm directive's value is 'MD5-sess' or 'AKAv1-MD5- + sess'. + + The packets between RADIUS client and RADIUS server are + protected with IPsec (see Section 9). + It creates the HTTP-style response message and calculates the + hash of this message's body. It uses the result and the + Digest-URI attribute's value of the corresponding Access- + Request packet to perform the H(A2) calculation. It takes the + Digest-Nonce, Digest-Nonce-Count, Digest-CNonce and Digest-Qop + values of the corresponding Access-Request and the Digest-HA1 + attribute's value to finish the computation of the 'rspauth' + value. + o If the Access-Accept packet contains neither a Digest-Response- + Auth nor a Digest-HA1 attribute, the RADIUS client will not create + an Authentication-Info header for its HTTP-style response. + + The RADIUS server MAY have added a Digest-Nextnonce attribute into an + Access-Accept packet. If the RADIUS client discovers this, it puts + the contents of this attribute into a 'nextnonce' directive. Now it + can send an HTTP-style response. + + If the RADIUS client did receive an HTTP-style request without a + (Proxy-)Authorization header matching its locally configured realm + value, it obtains a new nonce and sends an error response (401 or + 407) containing a (Proxy-)Authenticate header. + + If the RADIUS client receives an Access-Reject from the RADIUS + server, it sends an error response to the HTTP-style request it has + received. If the RADIUS client does not receive a response, it + retransmits or fails over to another RADIUS server as described in + [RFC2865]. + + The RADIUS client has three ways to obtain nonces: it generates them + locally, it has received one in a Digest-Nextnonce attribute of a + previously received Access-Accept packet, or it asks the RADIUS + server for one. To do the latter, it sends an Access-Request + containing a Digest-Method and a Digest-URI attribute but without a + Digest-Nonce attribute. It adds a Message-Authenticator (see + [RFC3579]) attribute to the Access-Request packet. The RADIUS server + chooses a nonce and responds with an Access-Challenge containing a + Digest-Nonce attribute. + + The RADIUS server can send Digest-Qop, Digest-Algorithm, Digest- + Realm, Digest-Domain and Digest-Opaque attributes in the Access- + Challenge carrying the nonce. If these attributes are present, the + client MUST use them. + + If the RADIUS client receives an Access-Challenge packet in response + + + +Sterman, et al. Expires April 17, 2006 [Page 11] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + to an Access-Request containing a Digest-Nonce attribute, the RADIUS + server did not accept the nonce. If a Digest-Stale attribute is + present in the Access-Challenge and has a value of 'true' (without + quotes), the RADIUS client sends an error (401 or 407) response + containing WWW-/Proxy-Authenticate header with the directive 'stale' + and the digest directives derived from the Digest-* attributes. + +3.2. RADIUS Server Behavior + + If the RADIUS server receives an Access-Request packet with a Digest- + Method and a Digest-URI attribute but without a Digest-Nonce + attribute, it chooses a nonce. It puts the nonce into a Digest-Nonce + attribute and sends it in an Access-Challenge packet to the RADIUS + client. The RADIUS server MUST add Digest-Realm, Message- + Authenticator (see [RFC3579]), SHOULD add Digest-Algorithm, one or + more Digest-Qop and MAY add Digest-Domain, Digest-Opaque attributes + to the Access-Challenge packet. If the server cannot choose a nonce, + it replies with an Access-Reject packet. + + If the RADIUS server receives an Access-Request packet containing a + Digest-Response attribute, it looks for the following attributes: + Digest-Realm, Digest-Nonce, Digest-Method, Digest-URI, Digest-Qop, + Digest-Algorithm, Digest-Username. Depending on the content of + Digest-Algorithm and Digest-Qop, it looks for Digest-Entity-Body- + Hash, Digest-CNonce and Digest-AKA-Auts, too. See [RFC2617] and + [RFC3310] for details. If the Digest-Algorithm attribute is missing, + 'MD5' is assumed. If the RADIUS server has issued a Digest-Opaque + attribute along with the nonce, the Access-Request MUST have a + matching Digest-Opaque attribute. + + If mandatory attributes are missing, it MUST respond with an Access- + Reject packet. If the attributes are present, the RADIUS server + calculates the digest response as described in [RFC2617]. To look up + the password, the RADIUS server uses the RADIUS User-Name attribute. + The RADIUS server MUST check if the user identified by the User-Name + attribute + o is authorized to access the protection space defined by the + Digest-URI and Digest-Realm attributes, + o is authorized to use the URI included in the SIP-AOR attribute, if + this attribute is present. + If any of those checks fails, the RADIUS server MUST send an Access- + Reject. + + Correlation between User-Name and SIP-AOR AVP values is required just + to avoid that any user can register or misuse a SIP-AOR allocated to + another user. + + A RADIUS server MUST check if the RADIUS client is authorized to + + + +Sterman, et al. Expires April 17, 2006 [Page 12] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + serve users of the realm mentioned in the Digest-Realm attribute. If + the RADIUS client is not authorized, the RADIUS server MUST send an + Access-Reject. The RADIUS server SHOULD log the event so as to + notify the operator, and MAY take additional action such as sending + an Access-Reject in response to all future requests from this client, + until this behavior is reset by management action. + + All values required for the digest calculation are taken from the + Digest attributes described in this document. If the calculated + digest response equals the value received in the Digest-Response + attribute, the authentication was successful. If not, the RADIUS + server responds with an Access-Reject. + + If the authentication was successful, the RADIUS server adds an + attribute to the Access-Accept packet which can be used by the RADIUS + client to construct an Authentication-Info header: + o If the Digest-Qop attribute's value is 'auth' or unspecified, the + RADIUS server SHOULD put a Digest-Response-Auth attribute into the + Access-Accept packet + o If the Digest-Qop attribute's value is 'auth-int' and at least one + of the following conditions is true, the RADIUS server SHOULD put + a Digest-HA1 attribute into the Access-Accept packet: + * The Digest-Algorithm attribute's value is 'MD5-sess' or 'AKAv1- + MD5-sess'. + * The packets between RADIUS client and RADIUS server are + protected with IPsec (see Section 9). + In all other cases, Digest-Response-Auth or Digest-HA1 MUST NOT be + sent. + + RADIUS servers issuing nonces MAY construct a Digest-Nextnonce + attribute and add it to the Access-Accept packet. This is useful to + limit the lifetime of a nonce and to save a round-trip in future + requests (see nextnonce discussion in [RFC2617], section 3.2.3). The + RADIUS server adds a Message-Authenticator attribute (see [RFC3579]) + and sends the Access-Accept packet to the RADIUS client. + + If the RADIUS server does not accept the nonce received in an Access- + Request packet but authentication was successful, the RADIUS server + MUST send an Access-Challenge packet containing a Digest-Stale + attribute set to 'true' (without quotes). The RADIUS server MUST add + Message-Authenticator (see [RFC3579]), Digest-Nonce, Digest-Realm, + SHOULD add Digest-Algorithm, one or more Digest-Qop and MAY add + Digest-Domain, Digest-Opaque attributes to the Access-Challenge + packet. + + +4. New RADIUS attributes + + + + +Sterman, et al. Expires April 17, 2006 [Page 13] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + If not stated otherwise, the attributes have the following format: + + + + + 0 1 2 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Type | Length | Text ... + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + + +4.1. Digest-Response attribute + + Description + If this attribute is present in an Access-Request message, a + RADIUS server implementing this specification MUST treat the + Access-Request as a request for Digest Authentication. When a + RADIUS client receives a (Proxy-)Authorization header, it puts + the request-digest value into a Digest-Response attribute. + This attribute (which enables the user to prove possession of + the password) MUST only be used in Access-Requests. + Type + [IANA: use 102 if possible] for Digest-Response. + Length + >= 3 + Text + When using HTTP digest, the text field is 32 octets long and + contains a hexadecimal representation of 16 octet digest value + as it was calculated by the authenticated client. Other digest + algorithms MAY define different digest lengths. The text field + MUST be copied from request-digest of digest-response + ([RFC2617]) without quotes. + +4.2. Digest-Realm attribute + + Description + This attribute describes a protection space of the RADIUS + server. See [RFC2617] 1.2 for details. It MUST only be used + in Access-Request and Access-Challenge packets. + Type + [IANA: use 103 if possible] for Digest-Realm + Length + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 14] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + realm directive (realm-value according to [RFC2617]) without + quotes from the HTTP-style request it wants to authenticate. + In Access-Challenge packets, the RADIUS server puts the + expected realm value into this attribute. + +4.3. Digest-Nonce attribute + + Description + This attribute holds a nonce to be used in the HTTP Digest + calculation. If the Access-Request had a Digest-Method and a + Digest-URI but no Digest-Nonce attribute and the RADIUS server + is configured to choose nonces, it MUST put a Digest-Nonce + attribute into its Access-Challenge packet. This attribute + MUST only be used in Access-Request and Access-Challenge + packets. + Type + [IANA: use 104 if possible] for Digest-Nonce + Length + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + nonce directive (nonce-value in [RFC2617]) without quotes from + the HTTP-style request it wants to authenticate. In Access- + Challenge packets, the attribute contains the nonce selected by + the RADIUS server. + +4.4. Digest-Response-Auth attribute + + Description + This attribute enables the RADIUS server to prove possession of + the password. If the previously received Digest-Qop attribute + was 'auth-int' (without quotes), the RADIUS server MUST send a + Digest-HA1 attribute instead of a Digest-Response-Auth + attribute. The Digest-Response-Auth attribute MUST only be + used in Access-Accept packets. The RADIUS client puts the + attribute value without quotes into the rspauth directive of + the Authentication-Info header. + Type + [IANA: use 105 if possible] for Digest-Response-Auth. + Length + >= 3 + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 15] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Text + The RADIUS server calculates a digest according to section + 3.2.3 of [RFC2617] and copies the result into this attribute. + Other digest algorithms than the one defined in [RFC2617] MAY + define digest lengths other than 32. + +4.5. Digest-Nextnonce attribute + + This attribute holds a nonce to be used in the HTTP Digest + calculation. + + Description + If the RADIUS server is configured to choose nonces it MAY put + a Digest-Nextnonce attribute into an Access-Accept packet. If + this attribute is present, the RADIUS client MUST put the + contents of this attribute into the nextnonce directive of an + Authentication-Info header in its HTTP-style response. This + attribute MUST only be used in Access-Accept packets. + Type + [IANA: use 106 if possible] for Digest-Nextnonce + Length + >=3 + Text + It is recommended that this text be base64 or hexadecimal data. + +4.6. Digest-Method attribute + + Description + This attribute holds the method value to be used in the HTTP + Digest calculation. This attribute MUST only be used in + Access-Request packets. + Type + [IANA: use 107 if possible] for Digest-Method + Length + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + request method from the HTTP-style request it wants to + authenticate. + +4.7. Digest-URI attribute + + Description + This attribute is used to transport the contents of the digest- + uri directive or the URI of the HTTP-style request. It MUST + only be used in Access-Request packets. + + + + + +Sterman, et al. Expires April 17, 2006 [Page 16] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Type + [IANA: use 108 if possible] for Digest-URI + Length + >=3 + Text + If the HTTP-style request has an Authorization header, the + RADIUS client puts the value of the "uri" directive in the + (known as "digest-uri-value" in section 3.2.2 of [RFC2617]) + without quotes into this attribute. If there is no + Authorization header, the RADIUS client takes the value of the + request URI from the HTTP-style request it wants to + authenticate. + +4.8. Digest-Qop attribute + + Description + This attribute holds the Quality of Protection parameter that + influences the HTTP Digest calculation. This attribute MUST + only be used in Access-Request and Access-Challenge packets. A + RADIUS client SHOULD insert one of the Digest-Qop attributes it + has received in a previous Access-Challenge packet. RADIUS + servers SHOULD insert at least one Digest-Qop attribute in an + Access-Challenge packet. Digest-Qop is optional in order to + preserve backward compatibility with a minimal implementation + of [RFC2069]. + Type + [IANA: use 109 if possible] for Digest-Qop + Length + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + qop directive (qop-value as described in [RFC2617]) without the + quotes from the HTTP-style request it wants to authenticate. + In Access-Challenge packets, the RADIUS server puts a desired + qop-value into this attribute. If the RADIUS server supports + more than one "quality of protection" value, it puts each qop- + value into a separate Digest-Qop attribute. + +4.9. Digest-Algorithm attribute + + Type + This attribute holds the algorithm parameter that influences + the HTTP Digest calculation. It MUST only be used in Access- + Request and Access-Challenge packets. If this attribute is + missing, "MD5" is assumed. + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 17] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Type + [IANA: use 110 if possible] for Digest-Algorithm + Length + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + algorithm directive (as described in [RFC2617], section 3.2.1) + without the quotes from the HTTP-style request it wants to + authenticate. In Access-Challenge packets, the RADIUS server + SHOULD put the desired algorithm into this attribute. + +4.10. Digest-Entity-Body-Hash attribute + + Description + When using the qop level 'auth-int', a hash of the HTTP-style + message body's contents is required for digest calculation. + Instead of sending the complete body of the message, only its + hash value is sent. This hash value can be used directly in + the digest calculation. + The clarifications described in section 22.4 of [RFC2617] about + the hash of empty entity bodies apply to the Digest-Entity- + Body-Hash attribute. This attribute MUST only be sent in + Access-Request packets. + Type + [IANA: use 111 if possible] for Digest-Entity-Body-Hash + Length + >=3 + Text + The attribute holds the hexadecimal representation of H(entity- + body). This hash is required by certain authentication + mechanisms, such as HTTP Digest with quality of protection set + to "auth-int". RADIUS clients MUST use this attribute to + transport the hash of the entity body when HTTP Digest is the + authentication mechanism and the RADIUS server requires to + verify the integrity of the entity body (e.g., qop parameter + set to "auth-int"). Extensions to this document may define + support for authentication mechanisms other than HTTP Digest. + +4.11. Digest-CNonce attribute + + Description + This attribute holds the client nonce parameter that is used in + the HTTP Digest calculation. It MUST only be used in Access- + Request packets. + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 18] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Type + [IANA: use 112 if possible] for Digest-CNonce + Length + >=3 + Text + This attribute includes the value of the cnonce-value [RFC2617] + without quotes, taken from the HTTP-style request. + +4.12. Digest-Nonce-Count attribute + + Description + This attribute includes the nonce count parameter that is used + to detect replay attacks. The attribute MUST only be used in + Access-Request packets. + Type + [IANA: use 113 if possible] for Digest-Nonce-Count + Length + 10 + Text + In Access-Requests, the RADIUS client takes the value of the nc + directive (nc-value according to [RFC2617]) without quotes from + the HTTP-style request it wants to authenticate. + +4.13. Digest-Username attribute + + Description + This attribute holds the user name used in the HTTP digest + calculation. The RADIUS server MUST use this attribute only + for the purposes of calculating the digest. In order to + determine the appropriate user credentials, the RADIUS server + MUST use the User-Name (1) attribute, and MUST NOT use the + Digest-Username attribute. This attribute MUST only be used in + Access-Request packets. + Type + [IANA: use 114 if possible] for Digest-Username + Length + >= 3 + Text + In Access-Requests, the RADIUS client takes the value of the + username directive (username-value according to [RFC2617]) + without quotes from the HTTP-style request it wants to + authenticate. + +4.14. Digest-Opaque attribute + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 19] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Description + This attribute holds the opaque parameter that is passed to the + HTTP-style client. The HTTP-style client will pass this value + back to the server (i.e. the RADIUS client) without + modification. This attribute is only used when the RADIUS + server chooses nonces and MUST only be used in Access-Request + and Access-Challenge packets. + Type + [IANA: use 115 if possible] for Digest-Opaque + Length + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + opaque directive (opaque-value according to [RFC2617]) without + quotes from the HTTP-style request it wants to authenticate and + puts it into this attribute. In Access-Challenge packets, the + RADIUS server MAY include this attribute. + +4.15. Digest-Auth-Param attribute + + Description + This attribute is a placeholder for future extensions and + corresponds to the "auth-param" parameter defined in section + 3.2.1 of [RFC2617]. The Digest-Auth-Param is the mechanism + whereby the RADIUS client and RADIUS server can exchange auth- + param extension parameters contained within Digest headers that + are not understood by the RADIUS client and for which there are + no corresponding stand-alone attributes. + Unlike the previously listed Digest-* attributes, the Digest- + Auth-Param contains not only the value, but also the parameter + name, since the parameter name is unknown to the RADIUS client. + If the Digest header contains several unknown parameters, then + the RADIUS implementation MUST repeat this attribute and each + instance MUST contain one different unknown Digest parameter/ + value combination. This attribute MUST ONLY be used in Access- + Request, Access-Challenge, or Access-Accept packets. + Type + [IANA: use 116 if possible] for Digest-Auth-Param + Length + >=3 + Text + The text consists of the whole parameter, including its name + and the equal ('=') sign and quotes. + +4.16. Digest-AKA-Auts attribute + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 20] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Description + This attribute holds the auts parameter that is used in the + Digest AKA ([RFC3310]) calculation. It is only used if the + algorithm of the digest-response denotes a version of AKA + digest [RFC3310]. This attribute MUST only be used in Access- + Request packets. + Type + [IANA: use 117 if possible] for Digest-AKA-Auts + Length + >=3 + Text + In Access-Requests, the RADIUS client takes the value of the + auts directive (auts-param according to section 3.4 of + [RFC3310]) without quotes from the HTTP-style request it wants + to authenticate. + +4.17. Digest-Domain attribute + + Description + When a RADIUS client has asked for a nonce, the RADIUS server + MAY send one or more Digest-Domain attributes in its Access- + Challenge packet. The RADIUS client puts them into the quoted, + space-separated list of URIs of the 'domain' directive of a + WWW-Authenticate header. The URIs in the list define the + protection space (see [RFC2617], section 3.2.1). RADIUS + servers MAY send one or more attributes of this type in Access- + Challenge packets. This attribute MUST only be used in Access- + Challenge packets. + Type + [IANA: use 118 if possible] for Digest-Domain + Length + 3 + Text + This attribute consists of a single URI, that defines a + protection space. + +4.18. Digest-Stale attribute + + Description + This attribute is sent by a RADIUS server in order to notify + the RADIUS client whether it has accepted a nonce. If the + nonce presented by the RADIUS client was stale, the value is + 'true' and is 'false' otherwise. The RADIUS client puts the + content of this attribute into a 'stale' directive of the WWW- + Authenticate header in the HTTP-style response to the request + it wants to authenticate. The attribute MUST only be used in + Access-Challenge packets and only if the RADIUS server chooses + nonces. + + + +Sterman, et al. Expires April 17, 2006 [Page 21] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Type + [IANA: use 119 if possible] for Digest-Stale + Length + 3 + Text + The attribute has either the value 'true' or 'false' (both + values without quotes). + +4.19. Digest-HA1 attribute + + Description + This attribute is used to allow the generation of an + Authentication-Info header, even if the HTTP-style response's + body is required for the calculation of the rspauth value. It + SHOULD be used in Access-Accept packets if the required quality + of protection ('qop') is 'auth-int'. + This attribute MUST NOT be sent if the qop parameter was not + specified or has a value of 'auth' (in this case, use Digest- + Response-Auth instead). + The Digest-HA1 attribute MUST only be sent by the RADIUS server + or processed by the RADIUS client if at least one of the + following conditions is true: + + The Digest-Algorithm attribute's value is 'MD5-sess' or + 'AKAv1-MD5-sess'. + + The packets between RADIUS client and RADIUS server are + protected with IPsec (see Section 9). + This attribute MUST only be used in Access-Accept packets. + Type + [IANA: use 120 if possible] for Digest-HA1 + Length + >= 3 + Text + This attribute contains the hexadecimal representation of H(A1) + as described in [RFC2617], section 3.1.3, 3.2.1 and 3.2.2.2. + +4.20. SIP-AOR + + Type + This attribute is used for the authorization of SIP messages. + The SIP-AOR attribute identifies the URI the use of which must + be authenticated and authorized. The RADIUS server uses this + attribute to authorize the processing of the SIP request. The + SIP-AOR can be derived from, e.g., the To header field in a SIP + REGISTER request (user under registration), or the From header + field in other SIP requests. However, the exact mapping of + this attribute to SIP can change due to new developments in the + protocol. This attribute MUST only be used when the RADIUS + client wants to authorize SIP users and MUST only be used in + + + +Sterman, et al. Expires April 17, 2006 [Page 22] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Access-Request packets. + Type + [IANA:use 121 if possible] for SIP-AOR + Length + >=3 + Text + The syntax of this attribute corresponds either to a SIP URI + (with the format defined in [RFC3261] or a TEL URI (with the + format defined in [RFC3966]). + The SIP-AOR attribute holds the complete URI, including + parameters and other parts. It is up to the RADIUS server what + components of the URI are regarded in the authorization + decision. + + +5. Diameter Compatibility + + This document defines support for Digest Authentication in RADIUS. A + companion document "Diameter Session Initiation Protocol (SIP) + Application" [I-D.ietf-aaa-diameter-sip-app] defines support for + Digest Authentication in Diameter, and addresses compatibility issues + between RADIUS and Diameter. + + +6. Table of Attributes + + The following table provides a guide to which attributes may be found + in which kinds of packets, and in what quantity. + + + + + + + + + + + + + + + + + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 23] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + + + + Req Accept Reject Challenge # Attribute + 1 0 0 0 1 User-Name + 1 1 1 1 80 Message-Authenticator + 0-1 0 0 0 TBD Digest-Response + 0-1 0 0 1 TBD Digest-Realm + 0-1 0 0 1 TBD Digest-Nonce + 0 0-1 0 0 TBD Digest-Response-Auth + (see Note 1, 2) + 0 0-1 0 0 TBD Digest-Nextnonce + 0-1 0 0 0 TBD Digest-Method + 0-1 0 0 0 TBD Digest-URI + 0-1 0 0 1+ TBD Digest-Qop + 0-1 0 0 0-1 TBD Digest-Algorithm (see + Note 3) + 0-1 0 0 0 TBD Digest-Entity-Body-Hash + 0-1 0 0 0 TBD Digest-CNonce + 0-1 0 0 0 TBD Digest-Nonce-Count + 0-1 0 0 0 TBD Digest-Username + 0-1 0 0 0-1 TBD Digest-Opaque + 0+ 0+ 0 0+ TBD Digest-Auth-Param + 0-1 0 0 0 TBD Digest-AKA-Auts + 0 0 0 0+ TBD Digest-Domain + 0 0 0 0-1 TBD Digest-Stale + 0 0-1 0 0 TBD Digest-HA1 (see Note 1, + 2) + 0-1 0 0 0 TBD SIP-AOR + + Table 1 + + + + + + [Note 1] Digest-HA1 MUST be used instead of Digest-Response-Auth if + Digest-Qop is 'auth-int'. + [Note 2] Digest-Response-Auth MUST be used instead of Digest-HA1 if + Digest-Qop is 'auth'. + [Note 3] If Digest-Algorithm is missing, 'MD5' is assumed + + +7. Example + + This is an example sniffed from the traffic between a softphone (A), + a Proxy Server (B) and example.com RADIUS server (C). The + communication between the Proxy Server and a SIP PSTN gateway is + + + +Sterman, et al. Expires April 17, 2006 [Page 24] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + omitted for brevity. The SIP messages are not shown completely. + + + + A->B + + INVITE sip:97226491335@example.com SIP/2.0 + From: + To: + + + B->A + + SIP/2.0 100 Trying + + + B->A + + SIP/2.0 407 Proxy Authentication Required + Proxy-Authenticate: Digest realm="example.com" + ,nonce="3bada1a0", algorithm="md5" + Content-Length: 0 + + + A->B + + ACK sip:97226491335@example.com SIP/2.0 + + + A->B + + INVITE sip:97226491335@example.com SIP/2.0 + Proxy-Authorization: Digest algorithm="md5",nonce="3bada1a0" + ,opaque="",realm="example.com" + ,response="f3ce87e6984557cd0fecc26f3c5e97a4" + ,uri="sip:97226491335@10.0.69.38",username="12345678" + From: + To: + + + B->C + + Code = 1 (Access-Request) + Attributes: + NAS-IP-Address = a 0 45 26 (10.0.69.38) + NAS-Port-Type = 5 (Virtual) + User-Name = "12345678" + Digest-Response = "f3ce87e6984557cd0fecc26f3c5e97a4" + + + +Sterman, et al. Expires April 17, 2006 [Page 25] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + Digest-Realm = "example.com" + Digest-Nonce = "3bada1a0" + Digest-Method = "INVITE" + Digest-URI = "sip:97226491335@example.com" + Digest-Algorithm = "md5" + Digest-Username = "12345678" + SIP-AOR = "sip:12345678@example.com" + + + C->B + + Code = 2 (Access-Accept) + Attributes: + Digest-Response-Auth = + "6303c41b0e2c3e524e413cafe8cce954" + + + B->A + + SIP/2.0 180 Ringing + + + B->A + + SIP/2.0 200 OK + + + A->B + + ACK sip:97226491335@example.com SIP/2.0 + + + + A second example shows the traffic between a web browser (A), web + server (B) and a RADIUS server (C). + + + + A->B + + GET /index.html HTTP/1.1 + + + B->A + + HTTP/1.1 407 Authentication Required + WWW-Authenticate: Digest realm="example.com", + domain="/index.html", + + + +Sterman, et al. Expires April 17, 2006 [Page 26] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + nonce="a3086ac8", algorithm="md5" + Content-Length: 0 + + + A->B + + GET /index.html HTTP/1.1 + Authorization: Digest algorithm="md5",nonce="a3086ac8" + ,opaque="",realm="example.com" + ,response="f052b68058b2987aba493857ae1ab002" + ,uri="/index.html",username="12345678" + + + B->C + + Code = 1 (Access-Request) + Attributes: + NAS-IP-Address = a 0 45 26 (10.0.69.38) + NAS-Port-Type = 5 (Virtual) + User-Name = "12345678" + Digest-Response = "f052b68058b2987aba493857ae1ab002" + Digest-Realm = "example.com" + Digest-Nonce = "a3086ac8" + Digest-Method = "GET" + Digest-URI = "/index.html"" + Digest-Algorithm = "md5" + Digest-Username = "12345678" + + + C->B + + Code = 2 (Access-Accept) + Attributes: + Digest-Response-Auth = + "e644aa513effbfe1caff67103ff6433c" + + + B->A + + HTTP/1.1 200 OK + ... + + + ... + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 27] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + +8. IANA Considerations + + This document serves as IANA registration request for a number of + values from the RADIUS attribute type number space: + + +-------------------------+------------------------+ + | placeholder | value assigned by IANA | + +-------------------------+------------------------+ + | Digest-Response | TBD | + | Digest-Realm | TBD | + | Digest-Nonce | TBD | + | Digest-Nextnonce | TBD | + | Digest-Response-Auth | TBD | + | Digest-Method | TBD | + | Digest-URI | TBD | + | Digest-Qop | TBD | + | Digest-Algorithm | TBD | + | Digest-Entity-Body-Hash | TBD | + | Digest-CNonce | TBD | + | Digest-Nonce-Count | TBD | + | Digest-Username | TBD | + | Digest-Opaque | TBD | + | Digest-Auth-Param | TBD | + | Digest-AKA-Auts | TBD | + | Digest-Domain | TBD | + | Digest-Stale | TBD | + | Digest-HA1 | TBD | + | SIP-AOR | TBD | + +-------------------------+------------------------+ + + Table 2 + + +9. Security Considerations + + The RADIUS extensions described in this document enable RADIUS to + transport the data that required to perform a digest calculation. As + a result, RADIUS inherits the vulnerabilities of HTTP Digest (see + [RFC2617], section 4) in addition to RADIUS security vulnerabilities + described in [RFC2865] Section 8 and [RFC3579] Section 4. + + An attacker compromising a RADIUS client or proxy can carry out man- + in-the-middle attacks even if the paths between A, B and B, C + (Figure 2) have been secured with TLS or IPsec. + + The RADIUS server MUST check the Digest-Realm attribute it has + received from a client. If the RADIUS client is not authorized to + serve HTTP-style clients of that realm, it might be compromised. + + + +Sterman, et al. Expires April 17, 2006 [Page 28] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + RADIUS clients implementing the extension described in this document + may authenticate HTTP-style requests received over the Internet. As + compared with use of RADIUS to authenticate link layer network + access, an attacker may find it easier to cover their tracks in such + a scenario. + + An attacker can attempt a denial of service attack on one or more + RADIUS servers by sending a large number of HTTP-style requests. To + make simple denial of service attacks more difficult, the nonce + issuer (RADIUS client or server) MUST check if it has generated the + nonce received from an HTTP-style client. This SHOULD be done + statelessly. For example, a nonce could consist of a + cryptographically random part and some kind of signature provided by + the RADIUS client, as described in [RFC2617], section 3.2.1. + + RADIUS servers SHOULD include Digest-Qop and Digest-Algorithm + attributes in Access-Challenge messages. A man in the middle can + modify or remove those attributes in a bidding down attack, causing + the RADIUS client to use a weaker authentication scheme than + intended. + + The Message-Authenticator attribute, described in [RFC3579] section + 3.2 MUST be included in Access-Request, Access-Challenge, Access- + Reject and Access-Accept messages that contain attributes described + in this specification. + + The Digest-HA1 attribute contains no random components if the + algorithm is 'MD5' or 'AKAv1-MD5'. This makes offline dictionary + attacks easier and enables replay attacks. + + HTTP-style clients can use TLS with server side certificates together + with HTTP-Digest Authentication. Instead of TLS, IPsec can be used, + too. TLS or IPsec secure the connection while Digest Authentication + authenticates the user. The RADIUS transaction can be regarded as + one leg on the path between the HTTP-style client and the HTTP-style + server. To prevent RADIUS from representing the weak link, a RADIUS + client receiving an HTTP-style request via TLS or IPsec could use an + equally secure connection to the RADIUS server. There are several + ways to achieve this, for example: + o the RADIUS client may reject HTTP-style requests received over TLS + or IPsec + o the RADIUS client require that traffic be sent and received over + IPsec. + RADIUS over IPsec, if used, MUST conform to the requirements + described in [RFC3579] section 4.2. + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 29] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + +10. Acknowledgments + + We would like to acknowledge Kevin Mcdermott (Cisco Systems) /or + providing comments and experimental implementation. + + Many thanks to all reviewers, especially to Miguel Garcia, Jari + Arkko, Avi Lior and Jun Wang. + + +11. References + +11.1. Normative References + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., + Leach, P., Luotonen, A., and L. Stewart, "HTTP + Authentication: Basic and Digest Access Authentication", + RFC 2617, June 1999. + + [RFC2865] Rigney, C., Willens, S., Rubens, A., and W. Simpson, + "Remote Authentication Dial In User Service (RADIUS)", + RFC 2865, June 2000. + + [RFC3261] Rosenberg, J., Schulzrinne, H., Camarillo, G., Johnston, + A., Peterson, J., Sparks, R., Handley, M., and E. + Schooler, "SIP: Session Initiation Protocol", RFC 3261, + June 2002. + + [RFC3310] Niemi, A., Arkko, J., and V. Torvinen, "Hypertext Transfer + Protocol (HTTP) Digest Authentication Using Authentication + and Key Agreement (AKA)", RFC 3310, September 2002. + + [RFC3579] Aboba, B. and P. Calhoun, "RADIUS (Remote Authentication + Dial In User Service) Support For Extensible + Authentication Protocol (EAP)", RFC 3579, September 2003. + + [RFC3966] Schulzrinne, H., "The tel URI for Telephone Numbers", + RFC 3966, December 2004. + +11.2. Informative References + + [I-D.ietf-aaa-diameter-sip-app] + Garcia-Martin, M., "Diameter Session Initiation Protocol + (SIP) Application", draft-ietf-aaa-diameter-sip-app-09 + (work in progress), September 2005. + + + + +Sterman, et al. Expires April 17, 2006 [Page 30] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + [RFC2069] Franks, J., Hallam-Baker, P., Hostetler, J., Leach, P., + Luotonen, A., Sink, E., and L. Stewart, "An Extension to + HTTP : Digest Access Authentication", RFC 2069, + January 1997. + + [RFC2246] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", + RFC 2246, January 1999. + + [RFC2543] Handley, M., Schulzrinne, H., Schooler, E., and J. + Rosenberg, "SIP: Session Initiation Protocol", RFC 2543, + March 1999. + + [RFC2633] Ramsdell, B., "S/MIME Version 3 Message Specification", + RFC 2633, June 1999. + + [RFC3588] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and J. + Arkko, "Diameter Base Protocol", RFC 3588, September 2003. + + +Appendix A. Change Log + + RFC editor: please remove this section prior to RFC publication. + +A.1. Changes from draft-ietf-radext-digest-auth-05 + + o Removed interdependency between sips/https and RADIUS connection + security. + +A.2. Changes from draft-ietf-radext-digest-auth-04 + + o Short Diameter compatibility section + +A.3. Changes from draft-ietf-radext-digest-auth-03 + + o new 'Interoperability' section, requiring support for both nonce + generation modes. + o removed Diameter migration path section (again) + o reference to server behavior in Security Considerations section + o fixed text/table mismatch regarding Digest-Domain attributes + +A.4. Changes from draft-ietf-radext-digest-auth-02 + + o added Diameter migration path section (again) + o various typos + +A.5. Changes from draft-ietf-radext-digest-auth-01 + + + + + +Sterman, et al. Expires April 17, 2006 [Page 31] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + + o removed Diameter migration path section + o Included Digest-URI and Digest-Realm in the authorization + decision, not just in the digest calculation + o RADIUS server must check if a RADIUS client is authorized to serve + the realm mentioned in Digest-Realm + o moved 'Detailed Description' sections in front of 'New RADIUS + attributes' section + o replaced 'IPsec or otherwise secured connection' with IPsec + o changed MAY to SHOULD for Digest-Algorithm in Access-Challenge + o changed type of Digest-Entity-Body-Hash to text (all other H(..) + result attributes are hex and text, too) + o new abstract + o Terminology section changed + o 'Changes' section as appendix + +A.6. Changes from draft-ietf-radext-digest-auth-00 + + o SIP-AOR attribute added + o clarified use of Digest-Qop + o attribute overview table added + +A.7. Changes from draft-sterman-aaa-sip-04 + + o clarified usage of Digest-HA1 + o clarified usage of Digest-Stale (is sent in an Access-Challenge + now) + o clarified allowed attribute usage for message types + o changed attribute type to 'Text' where the corresponding Diameter + AVPs have a UTF8String + o added Diameter client - RADIUS server handling + +A.8. Changes from draft-sterman-aaa-sip-03 + + o addressed 'auth-int' issue + o New Digest-Nextnonce attribute + o revised abstract, motivational section and examples + o Access-Challenge instead of 'Access-Accept carrying a Digest-Nonce + attribute' + o shortened SIP messages in example, removed real-world addresses + and product names + +A.9. Changes from draft-sterman-aaa-sip-02 + + o Relaxed restrictions for Digest-Domain, Digest-Realm, Digest- + Opaque, Digest-Qop and Digest-Algorithm + o Additional security considerations for Digest-Domain, Digest-Qop + and Digest-Algorithm usage in Access-Accept messages + + + + +Sterman, et al. Expires April 17, 2006 [Page 32] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + +A.10. Changes from draft-sterman-aaa-sip-01 + + o Replaced Sub-attributes with flat attributes + o aligned naming with [I-D.ietf-aaa-diameter-sip-app] + o Added how a server must treat unknown attributes. + o Added a section 'Migration path to Diameter' + o Added an optional attribute for support of the digest scheme + described in informational [RFC3310]. + o Added a mode of operation where the RADIUS server chooses the + nonce. This was required for AKA [RFC3310], but can be useful for + ordinary Digest Authentication when the qop directive is not used. + This required the addition of several attributes. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Sterman, et al. Expires April 17, 2006 [Page 33] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + +Authors' Addresses + + Baruch Sterman + Kayote Networks + P.O. Box 1373 + Efrat 90435 + Israel + + Email: baruch@kayote.com + + + Daniel Sadolevsky + SecureOL, Inc. + Jerusalem Technology Park + P.O. Box 16120 + Jerusalem 91160 + Israel + + Email: dscreat@dscreat.com + + + David Schwartz + Kayote Networks + P.O. Box 1373 + Efrat 90435 + Israel + + Email: david@kayote.com + + + David Williams + Cisco Systems + 7025 Kit Creek Road + P.O. Box 14987 + Research Triangle Park NC 27709 + USA + + Email: dwilli@cisco.com + + + Wolfgang Beck + Deutsche Telekom AG + Am Kavalleriesand 3 + Darmstadt 64295 + Germany + + Email: beckw@t-systems.com + + + + +Sterman, et al. Expires April 17, 2006 [Page 34] + + + + + + +Internet-Draft RADIUS Digest Authentication October 2005 + + +Intellectual Property Statement + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + + +Disclaimer of Validity + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET + ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE + INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + +Copyright Statement + + Copyright (C) The Internet Society (2005). This document is subject + to the rights, licenses and restrictions contained in BCP 78, and + except as set forth therein, the authors retain all their rights. + + +Acknowledgment + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + +Sterman, et al. Expires April 17, 2006 [Page 35] + + + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/doc/rfc/rfc0959.txt Wed Feb 14 13:38:00 2007 @@ -0,0 +1,3933 @@ + + +Network Working Group J. Postel +Request for Comments: 959 J. Reynolds + ISI +Obsoletes RFC: 765 (IEN 149) October 1985 + + FILE TRANSFER PROTOCOL (FTP) + + +Status of this Memo + + This memo is the official specification of the File Transfer + Protocol (FTP). Distribution of this memo is unlimited. + + The following new optional commands are included in this edition of + the specification: + + CDUP (Change to Parent Directory), SMNT (Structure Mount), STOU + (Store Unique), RMD (Remove Directory), MKD (Make Directory), PWD + (Print Directory), and SYST (System). + + Note that this specification is compatible with the previous edition. + +1. INTRODUCTION + + The objectives of FTP are 1) to promote sharing of files (computer + programs and/or data), 2) to encourage indirect or implicit (via + programs) use of remote computers, 3) to shield a user from + variations in file storage systems among hosts, and 4) to transfer + data reliably and efficiently. FTP, though usable directly by a user + at a terminal, is designed mainly for use by programs. + + The attempt in this specification is to satisfy the diverse needs of + users of maxi-hosts, mini-hosts, personal workstations, and TACs, + with a simple, and easily implemented protocol design. + + This paper assumes knowledge of the Transmission Control Protocol + (TCP) [2] and the Telnet Protocol [3]. These documents are contained + in the ARPA-Internet protocol handbook [1]. + +2. OVERVIEW + + In this section, the history, the terminology, and the FTP model are + discussed. The terms defined in this section are only those that + have special significance in FTP. Some of the terminology is very + specific to the FTP model; some readers may wish to turn to the + section on the FTP model while reviewing the terminology. + + + + + + + +Postel & Reynolds [Page 1] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 2.1. HISTORY + + FTP has had a long evolution over the years. Appendix III is a + chronological compilation of Request for Comments documents + relating to FTP. These include the first proposed file transfer + mechanisms in 1971 that were developed for implementation on hosts + at M.I.T. (RFC 114), plus comments and discussion in RFC 141. + + RFC 172 provided a user-level oriented protocol for file transfer + between host computers (including terminal IMPs). A revision of + this as RFC 265, restated FTP for additional review, while RFC 281 + suggested further changes. The use of a "Set Data Type" + transaction was proposed in RFC 294 in January 1982. + + RFC 354 obsoleted RFCs 264 and 265. The File Transfer Protocol + was now defined as a protocol for file transfer between HOSTs on + the ARPANET, with the primary function of FTP defined as + transfering files efficiently and reliably among hosts and + allowing the convenient use of remote file storage capabilities. + RFC 385 further commented on errors, emphasis points, and + additions to the protocol, while RFC 414 provided a status report + on the working server and user FTPs. RFC 430, issued in 1973, + (among other RFCs too numerous to mention) presented further + comments on FTP. Finally, an "official" FTP document was + published as RFC 454. + + By July 1973, considerable changes from the last versions of FTP + were made, but the general structure remained the same. RFC 542 + was published as a new "official" specification to reflect these + changes. However, many implementations based on the older + specification were not updated. + + In 1974, RFCs 607 and 614 continued comments on FTP. RFC 624 + proposed further design changes and minor modifications. In 1975, + RFC 686 entitled, "Leaving Well Enough Alone", discussed the + differences between all of the early and later versions of FTP. + RFC 691 presented a minor revision of RFC 686, regarding the + subject of print files. + + Motivated by the transition from the NCP to the TCP as the + underlying protocol, a phoenix was born out of all of the above + efforts in RFC 765 as the specification of FTP for use on TCP. + + This current edition of the FTP specification is intended to + correct some minor documentation errors, to improve the + explanation of some protocol features, and to add some new + optional commands. + + +Postel & Reynolds [Page 2] + + + +RFC 959 October 1985 +File Transfer Protocol + + + In particular, the following new optional commands are included in + this edition of the specification: + + CDUP - Change to Parent Directory + + SMNT - Structure Mount + + STOU - Store Unique + + RMD - Remove Directory + + MKD - Make Directory + + PWD - Print Directory + + SYST - System + + This specification is compatible with the previous edition. A + program implemented in conformance to the previous specification + should automatically be in conformance to this specification. + + 2.2. TERMINOLOGY + + ASCII + + The ASCII character set is as defined in the ARPA-Internet + Protocol Handbook. In FTP, ASCII characters are defined to be + the lower half of an eight-bit code set (i.e., the most + significant bit is zero). + + access controls + + Access controls define users' access privileges to the use of a + system, and to the files in that system. Access controls are + necessary to prevent unauthorized or accidental use of files. + It is the prerogative of a server-FTP process to invoke access + controls. + + byte size + + There are two byte sizes of interest in FTP: the logical byte + size of the file, and the transfer byte size used for the + transmission of the data. The transfer byte size is always 8 + bits. The transfer byte size is not necessarily the byte size + in which data is to be stored in a system, nor the logical byte + size for interpretation of the structure of the data. + + + +Postel & Reynolds [Page 3] + + + +RFC 959 October 1985 +File Transfer Protocol + + + control connection + + The communication path between the USER-PI and SERVER-PI for + the exchange of commands and replies. This connection follows + the Telnet Protocol. + + data connection + + A full duplex connection over which data is transferred, in a + specified mode and type. The data transferred may be a part of + a file, an entire file or a number of files. The path may be + between a server-DTP and a user-DTP, or between two + server-DTPs. + + data port + + The passive data transfer process "listens" on the data port + for a connection from the active transfer process in order to + open the data connection. + + DTP + + The data transfer process establishes and manages the data + connection. The DTP can be passive or active. + + End-of-Line + + The end-of-line sequence defines the separation of printing + lines. The sequence is Carriage Return, followed by Line Feed. + + EOF + + The end-of-file condition that defines the end of a file being + transferred. + + EOR + + The end-of-record condition that defines the end of a record + being transferred. + + error recovery + + A procedure that allows a user to recover from certain errors + such as failure of either host system or transfer process. In + FTP, error recovery may involve restarting a file transfer at a + given checkpoint. + + + +Postel & Reynolds [Page 4] + + + +RFC 959 October 1985 +File Transfer Protocol + + + FTP commands + + A set of commands that comprise the control information flowing + from the user-FTP to the server-FTP process. + + file + + An ordered set of computer data (including programs), of + arbitrary length, uniquely identified by a pathname. + + mode + + The mode in which data is to be transferred via the data + connection. The mode defines the data format during transfer + including EOR and EOF. The transfer modes defined in FTP are + described in the Section on Transmission Modes. + + NVT + + The Network Virtual Terminal as defined in the Telnet Protocol. + + NVFS + + The Network Virtual File System. A concept which defines a + standard network file system with standard commands and + pathname conventions. + + page + + A file may be structured as a set of independent parts called + pages. FTP supports the transmission of discontinuous files as + independent indexed pages. + + pathname + + Pathname is defined to be the character string which must be + input to a file system by a user in order to identify a file. + Pathname normally contains device and/or directory names, and + file name specification. FTP does not yet specify a standard + pathname convention. Each user must follow the file naming + conventions of the file systems involved in the transfer. + + PI + + The protocol interpreter. The user and server sides of the + protocol have distinct roles implemented in a user-PI and a + server-PI. + + +Postel & Reynolds [Page 5] + + + +RFC 959 October 1985 +File Transfer Protocol + + + record + + A sequential file may be structured as a number of contiguous + parts called records. Record structures are supported by FTP + but a file need not have record structure. + + reply + + A reply is an acknowledgment (positive or negative) sent from + server to user via the control connection in response to FTP + commands. The general form of a reply is a completion code + (including error codes) followed by a text string. The codes + are for use by programs and the text is usually intended for + human users. + + server-DTP + + The data transfer process, in its normal "active" state, + establishes the data connection with the "listening" data port. + It sets up parameters for transfer and storage, and transfers + data on command from its PI. The DTP can be placed in a + "passive" state to listen for, rather than initiate a + connection on the data port. + + server-FTP process + + A process or set of processes which perform the function of + file transfer in cooperation with a user-FTP process and, + possibly, another server. The functions consist of a protocol + interpreter (PI) and a data transfer process (DTP). + + server-PI + + The server protocol interpreter "listens" on Port L for a + connection from a user-PI and establishes a control + communication connection. It receives standard FTP commands + from the user-PI, sends replies, and governs the server-DTP. + + type + + The data representation type used for data transfer and + storage. Type implies certain transformations between the time + of data storage and data transfer. The representation types + defined in FTP are described in the Section on Establishing + Data Connections. + + + + +Postel & Reynolds [Page 6] + + + +RFC 959 October 1985 +File Transfer Protocol + + + user + + A person or a process on behalf of a person wishing to obtain + file transfer service. The human user may interact directly + with a server-FTP process, but use of a user-FTP process is + preferred since the protocol design is weighted towards + automata. + + user-DTP + + The data transfer process "listens" on the data port for a + connection from a server-FTP process. If two servers are + transferring data between them, the user-DTP is inactive. + + user-FTP process + + A set of functions including a protocol interpreter, a data + transfer process and a user interface which together perform + the function of file transfer in cooperation with one or more + server-FTP processes. The user interface allows a local + language to be used in the command-reply dialogue with the + user. + + user-PI + + The user protocol interpreter initiates the control connection + from its port U to the server-FTP process, initiates FTP + commands, and governs the user-DTP if that process is part of + the file transfer. + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 7] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 2.3. THE FTP MODEL + + With the above definitions in mind, the following model (shown in + Figure 1) may be diagrammed for an FTP service. + + ------------- + |/---------\| + || User || -------- + ||Interface|<--->| User | + |\----^----/| -------- + ---------- | | | + |/------\| FTP Commands |/----V----\| + ||Server|<---------------->| User || + || PI || FTP Replies || PI || + |\--^---/| |\----^----/| + | | | | | | + -------- |/--V---\| Data |/----V----\| -------- + | File |<--->|Server|<---------------->| User |<--->| File | + |System| || DTP || Connection || DTP || |System| + -------- |\------/| |\---------/| -------- + ---------- ------------- + + Server-FTP USER-FTP + + NOTES: 1. The data connection may be used in either direction. + 2. The data connection need not exist all of the time. + + Figure 1 Model for FTP Use + + In the model described in Figure 1, the user-protocol interpreter + initiates the control connection. The control connection follows + the Telnet protocol. At the initiation of the user, standard FTP + commands are generated by the user-PI and transmitted to the + server process via the control connection. (The user may + establish a direct control connection to the server-FTP, from a + TAC terminal for example, and generate standard FTP commands + independently, bypassing the user-FTP process.) Standard replies + are sent from the server-PI to the user-PI over the control + connection in response to the commands. + + The FTP commands specify the parameters for the data connection + (data port, transfer mode, representation type, and structure) and + the nature of file system operation (store, retrieve, append, + delete, etc.). The user-DTP or its designate should "listen" on + the specified data port, and the server initiate the data + connection and data transfer in accordance with the specified + parameters. It should be noted that the data port need not be in + + +Postel & Reynolds [Page 8] + + + +RFC 959 October 1985 +File Transfer Protocol + + + the same host that initiates the FTP commands via the control + connection, but the user or the user-FTP process must ensure a + "listen" on the specified data port. It ought to also be noted + that the data connection may be used for simultaneous sending and + receiving. + + In another situation a user might wish to transfer files between + two hosts, neither of which is a local host. The user sets up + control connections to the two servers and then arranges for a + data connection between them. In this manner, control information + is passed to the user-PI but data is transferred between the + server data transfer processes. Following is a model of this + server-server interaction. + + + Control ------------ Control + ---------->| User-FTP |<----------- + | | User-PI | | + | | "C" | | + V ------------ V + -------------- -------------- + | Server-FTP | Data Connection | Server-FTP | + | "A" |<---------------------->| "B" | + -------------- Port (A) Port (B) -------------- + + + Figure 2 + + The protocol requires that the control connections be open while + data transfer is in progress. It is the responsibility of the + user to request the closing of the control connections when + finished using the FTP service, while it is the server who takes + the action. The server may abort data transfer if the control + connections are closed without command. + + The Relationship between FTP and Telnet: + + The FTP uses the Telnet protocol on the control connection. + This can be achieved in two ways: first, the user-PI or the + server-PI may implement the rules of the Telnet Protocol + directly in their own procedures; or, second, the user-PI or + the server-PI may make use of the existing Telnet module in the + system. + + Ease of implementaion, sharing code, and modular programming + argue for the second approach. Efficiency and independence + + + +Postel & Reynolds [Page 9] + + + +RFC 959 October 1985 +File Transfer Protocol + + + argue for the first approach. In practice, FTP relies on very + little of the Telnet Protocol, so the first approach does not + necessarily involve a large amount of code. + +3. DATA TRANSFER FUNCTIONS + + Files are transferred only via the data connection. The control + connection is used for the transfer of commands, which describe the + functions to be performed, and the replies to these commands (see the + Section on FTP Replies). Several commands are concerned with the + transfer of data between hosts. These data transfer commands include + the MODE command which specify how the bits of the data are to be + transmitted, and the STRUcture and TYPE commands, which are used to + define the way in which the data are to be represented. The + transmission and representation are basically independent but the + "Stream" transmission mode is dependent on the file structure + attribute and if "Compressed" transmission mode is used, the nature + of the filler byte depends on the representation type. + + 3.1. DATA REPRESENTATION AND STORAGE + + Data is transferred from a storage device in the sending host to a + storage device in the receiving host. Often it is necessary to + perform certain transformations on the data because data storage + representations in the two systems are different. For example, + NVT-ASCII has different data storage representations in different + systems. DEC TOPS-20s's generally store NVT-ASCII as five 7-bit + ASCII characters, left-justified in a 36-bit word. IBM Mainframe's + store NVT-ASCII as 8-bit EBCDIC codes. Multics stores NVT-ASCII + as four 9-bit characters in a 36-bit word. It is desirable to + convert characters into the standard NVT-ASCII representation when + transmitting text between dissimilar systems. The sending and + receiving sites would have to perform the necessary + transformations between the standard representation and their + internal representations. + + A different problem in representation arises when transmitting + binary data (not character codes) between host systems with + different word lengths. It is not always clear how the sender + should send data, and the receiver store it. For example, when + transmitting 32-bit bytes from a 32-bit word-length system to a + 36-bit word-length system, it may be desirable (for reasons of + efficiency and usefulness) to store the 32-bit bytes + right-justified in a 36-bit word in the latter system. In any + case, the user should have the option of specifying data + representation and transformation functions. It should be noted + + + +Postel & Reynolds [Page 10] + + + +RFC 959 October 1985 +File Transfer Protocol + + + that FTP provides for very limited data type representations. + Transformations desired beyond this limited capability should be + performed by the user directly. + + 3.1.1. DATA TYPES + + Data representations are handled in FTP by a user specifying a + representation type. This type may implicitly (as in ASCII or + EBCDIC) or explicitly (as in Local byte) define a byte size for + interpretation which is referred to as the "logical byte size." + Note that this has nothing to do with the byte size used for + transmission over the data connection, called the "transfer + byte size", and the two should not be confused. For example, + NVT-ASCII has a logical byte size of 8 bits. If the type is + Local byte, then the TYPE command has an obligatory second + parameter specifying the logical byte size. The transfer byte + size is always 8 bits. + + 3.1.1.1. ASCII TYPE + + This is the default type and must be accepted by all FTP + implementations. It is intended primarily for the transfer + of text files, except when both hosts would find the EBCDIC + type more convenient. + + The sender converts the data from an internal character + representation to the standard 8-bit NVT-ASCII + representation (see the Telnet specification). The receiver + will convert the data from the standard form to his own + internal form. + + In accordance with the NVT standard, the sequence + should be used where necessary to denote the end of a line + of text. (See the discussion of file structure at the end + of the Section on Data Representation and Storage.) + + Using the standard NVT-ASCII representation means that data + must be interpreted as 8-bit bytes. + + The Format parameter for ASCII and EBCDIC types is discussed + below. + + + + + + + + +Postel & Reynolds [Page 11] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 3.1.1.2. EBCDIC TYPE + + This type is intended for efficient transfer between hosts + which use EBCDIC for their internal character + representation. + + For transmission, the data are represented as 8-bit EBCDIC + characters. The character code is the only difference + between the functional specifications of EBCDIC and ASCII + types. + + End-of-line (as opposed to end-of-record--see the discussion + of structure) will probably be rarely used with EBCDIC type + for purposes of denoting structure, but where it is + necessary the character should be used. + + 3.1.1.3. IMAGE TYPE + + The data are sent as contiguous bits which, for transfer, + are packed into the 8-bit transfer bytes. The receiving + site must store the data as contiguous bits. The structure + of the storage system might necessitate the padding of the + file (or of each record, for a record-structured file) to + some convenient boundary (byte, word or block). This + padding, which must be all zeros, may occur only at the end + of the file (or at the end of each record) and there must be + a way of identifying the padding bits so that they may be + stripped off if the file is retrieved. The padding + transformation should be well publicized to enable a user to + process a file at the storage site. + + Image type is intended for the efficient storage and + retrieval of files and for the transfer of binary data. It + is recommended that this type be accepted by all FTP + implementations. + + 3.1.1.4. LOCAL TYPE + + The data is transferred in logical bytes of the size + specified by the obligatory second parameter, Byte size. + The value of Byte size must be a decimal integer; there is + no default value. The logical byte size is not necessarily + the same as the transfer byte size. If there is a + difference in byte sizes, then the logical bytes should be + packed contiguously, disregarding transfer byte boundaries + and with any necessary padding at the end. + + + +Postel & Reynolds [Page 12] + + + +RFC 959 October 1985 +File Transfer Protocol + + + When the data reaches the receiving host, it will be + transformed in a manner dependent on the logical byte size + and the particular host. This transformation must be + invertible (i.e., an identical file can be retrieved if the + same parameters are used) and should be well publicized by + the FTP implementors. + + For example, a user sending 36-bit floating-point numbers to + a host with a 32-bit word could send that data as Local byte + with a logical byte size of 36. The receiving host would + then be expected to store the logical bytes so that they + could be easily manipulated; in this example putting the + 36-bit logical bytes into 64-bit double words should + suffice. + + In another example, a pair of hosts with a 36-bit word size + may send data to one another in words by using TYPE L 36. + The data would be sent in the 8-bit transmission bytes + packed so that 9 transmission bytes carried two host words. + + 3.1.1.5. FORMAT CONTROL + + The types ASCII and EBCDIC also take a second (optional) + parameter; this is to indicate what kind of vertical format + control, if any, is associated with a file. The following + data representation types are defined in FTP: + + A character file may be transferred to a host for one of + three purposes: for printing, for storage and later + retrieval, or for processing. If a file is sent for + printing, the receiving host must know how the vertical + format control is represented. In the second case, it must + be possible to store a file at a host and then retrieve it + later in exactly the same form. Finally, it should be + possible to move a file from one host to another and process + the file at the second host without undue trouble. A single + ASCII or EBCDIC format does not satisfy all these + conditions. Therefore, these types have a second parameter + specifying one of the following three formats: + + 3.1.1.5.1. NON PRINT + + This is the default format to be used if the second + (format) parameter is omitted. Non-print format must be + accepted by all FTP implementations. + + + + +Postel & Reynolds [Page 13] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The file need contain no vertical format information. If + it is passed to a printer process, this process may + assume standard values for spacing and margins. + + Normally, this format will be used with files destined + for processing or just storage. + + 3.1.1.5.2. TELNET FORMAT CONTROLS + + The file contains ASCII/EBCDIC vertical format controls + (i.e., , , , , ) which the printer + process will interpret appropriately. , in exactly + this sequence, also denotes end-of-line. + + 3.1.1.5.2. CARRIAGE CONTROL (ASA) + + The file contains ASA (FORTRAN) vertical format control + characters. (See RFC 740 Appendix C; and Communications + of the ACM, Vol. 7, No. 10, p. 606, October 1964.) In a + line or a record formatted according to the ASA Standard, + the first character is not to be printed. Instead, it + should be used to determine the vertical movement of the + paper which should take place before the rest of the + record is printed. + + The ASA Standard specifies the following control + characters: + + Character Vertical Spacing + + blank Move paper up one line + 0 Move paper up two lines + 1 Move paper to top of next page + + No movement, i.e., overprint + + Clearly there must be some way for a printer process to + distinguish the end of the structural entity. If a file + has record structure (see below) this is no problem; + records will be explicitly marked during transfer and + storage. If the file has no record structure, the + end-of-line sequence is used to separate printing lines, + but these format effectors are overridden by the ASA + controls. + + + + + + +Postel & Reynolds [Page 14] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 3.1.2. DATA STRUCTURES + + In addition to different representation types, FTP allows the + structure of a file to be specified. Three file structures are + defined in FTP: + + file-structure, where there is no internal structure and + the file is considered to be a + continuous sequence of data bytes, + + record-structure, where the file is made up of sequential + records, + + and page-structure, where the file is made up of independent + indexed pages. + + File-structure is the default to be assumed if the STRUcture + command has not been used but both file and record structures + must be accepted for "text" files (i.e., files with TYPE ASCII + or EBCDIC) by all FTP implementations. The structure of a file + will affect both the transfer mode of a file (see the Section + on Transmission Modes) and the interpretation and storage of + the file. + + The "natural" structure of a file will depend on which host + stores the file. A source-code file will usually be stored on + an IBM Mainframe in fixed length records but on a DEC TOPS-20 + as a stream of characters partitioned into lines, for example + by . If the transfer of files between such disparate + sites is to be useful, there must be some way for one site to + recognize the other's assumptions about the file. + + With some sites being naturally file-oriented and others + naturally record-oriented there may be problems if a file with + one structure is sent to a host oriented to the other. If a + text file is sent with record-structure to a host which is file + oriented, then that host should apply an internal + transformation to the file based on the record structure. + Obviously, this transformation should be useful, but it must + also be invertible so that an identical file may be retrieved + using record structure. + + In the case of a file being sent with file-structure to a + record-oriented host, there exists the question of what + criteria the host should use to divide the file into records + which can be processed locally. If this division is necessary, + the FTP implementation should use the end-of-line sequence, + + +Postel & Reynolds [Page 15] + + + +RFC 959 October 1985 +File Transfer Protocol + + + for ASCII, or for EBCDIC text files, as the + delimiter. If an FTP implementation adopts this technique, it + must be prepared to reverse the transformation if the file is + retrieved with file-structure. + + 3.1.2.1. FILE STRUCTURE + + File structure is the default to be assumed if the STRUcture + command has not been used. + + In file-structure there is no internal structure and the + file is considered to be a continuous sequence of data + bytes. + + 3.1.2.2. RECORD STRUCTURE + + Record structures must be accepted for "text" files (i.e., + files with TYPE ASCII or EBCDIC) by all FTP implementations. + + In record-structure the file is made up of sequential + records. + + 3.1.2.3. PAGE STRUCTURE + + To transmit files that are discontinuous, FTP defines a page + structure. Files of this type are sometimes known as + "random access files" or even as "holey files". In these + files there is sometimes other information associated with + the file as a whole (e.g., a file descriptor), or with a + section of the file (e.g., page access controls), or both. + In FTP, the sections of the file are called pages. + + To provide for various page sizes and associated + information, each page is sent with a page header. The page + header has the following defined fields: + + Header Length + + The number of logical bytes in the page header + including this byte. The minimum header length is 4. + + Page Index + + The logical page number of this section of the file. + This is not the transmission sequence number of this + page, but the index used to identify this page of the + file. + + +Postel & Reynolds [Page 16] + + + +RFC 959 October 1985 +File Transfer Protocol + + + Data Length + + The number of logical bytes in the page data. The + minimum data length is 0. + + Page Type + + The type of page this is. The following page types + are defined: + + 0 = Last Page + + This is used to indicate the end of a paged + structured transmission. The header length must + be 4, and the data length must be 0. + + 1 = Simple Page + + This is the normal type for simple paged files + with no page level associated control + information. The header length must be 4. + + 2 = Descriptor Page + + This type is used to transmit the descriptive + information for the file as a whole. + + 3 = Access Controlled Page + + This type includes an additional header field + for paged files with page level access control + information. The header length must be 5. + + Optional Fields + + Further header fields may be used to supply per page + control information, for example, per page access + control. + + All fields are one logical byte in length. The logical byte + size is specified by the TYPE command. See Appendix I for + further details and a specific case at the page structure. + + A note of caution about parameters: a file must be stored and + retrieved with the same parameters if the retrieved version is to + + + + +Postel & Reynolds [Page 17] + + + +RFC 959 October 1985 +File Transfer Protocol + + + be identical to the version originally transmitted. Conversely, + FTP implementations must return a file identical to the original + if the parameters used to store and retrieve a file are the same. + + 3.2. ESTABLISHING DATA CONNECTIONS + + The mechanics of transferring data consists of setting up the data + connection to the appropriate ports and choosing the parameters + for transfer. Both the user and the server-DTPs have a default + data port. The user-process default data port is the same as the + control connection port (i.e., U). The server-process default + data port is the port adjacent to the control connection port + (i.e., L-1). + + The transfer byte size is 8-bit bytes. This byte size is relevant + only for the actual transfer of the data; it has no bearing on + representation of the data within a host's file system. + + The passive data transfer process (this may be a user-DTP or a + second server-DTP) shall "listen" on the data port prior to + sending a transfer request command. The FTP request command + determines the direction of the data transfer. The server, upon + receiving the transfer request, will initiate the data connection + to the port. When the connection is established, the data + transfer begins between DTP's, and the server-PI sends a + confirming reply to the user-PI. + + Every FTP implementation must support the use of the default data + ports, and only the USER-PI can initiate a change to non-default + ports. + + It is possible for the user to specify an alternate data port by + use of the PORT command. The user may want a file dumped on a TAC + line printer or retrieved from a third party host. In the latter + case, the user-PI sets up control connections with both + server-PI's. One server is then told (by an FTP command) to + "listen" for a connection which the other will initiate. The + user-PI sends one server-PI a PORT command indicating the data + port of the other. Finally, both are sent the appropriate + transfer commands. The exact sequence of commands and replies + sent between the user-controller and the servers is defined in the + Section on FTP Replies. + + In general, it is the server's responsibility to maintain the data + connection--to initiate it and to close it. The exception to this + + + + +Postel & Reynolds [Page 18] + + + +RFC 959 October 1985 +File Transfer Protocol + + + is when the user-DTP is sending the data in a transfer mode that + requires the connection to be closed to indicate EOF. The server + MUST close the data connection under the following conditions: + + 1. The server has completed sending data in a transfer mode + that requires a close to indicate EOF. + + 2. The server receives an ABORT command from the user. + + 3. The port specification is changed by a command from the + user. + + 4. The control connection is closed legally or otherwise. + + 5. An irrecoverable error condition occurs. + + Otherwise the close is a server option, the exercise of which the + server must indicate to the user-process by either a 250 or 226 + reply only. + + 3.3. DATA CONNECTION MANAGEMENT + + Default Data Connection Ports: All FTP implementations must + support use of the default data connection ports, and only the + User-PI may initiate the use of non-default ports. + + Negotiating Non-Default Data Ports: The User-PI may specify a + non-default user side data port with the PORT command. The + User-PI may request the server side to identify a non-default + server side data port with the PASV command. Since a connection + is defined by the pair of addresses, either of these actions is + enough to get a different data connection, still it is permitted + to do both commands to use new ports on both ends of the data + connection. + + Reuse of the Data Connection: When using the stream mode of data + transfer the end of the file must be indicated by closing the + connection. This causes a problem if multiple files are to be + transfered in the session, due to need for TCP to hold the + connection record for a time out period to guarantee the reliable + communication. Thus the connection can not be reopened at once. + + There are two solutions to this problem. The first is to + negotiate a non-default port. The second is to use another + transfer mode. + + A comment on transfer modes. The stream transfer mode is + + +Postel & Reynolds [Page 19] + + + +RFC 959 October 1985 +File Transfer Protocol + + + inherently unreliable, since one can not determine if the + connection closed prematurely or not. The other transfer modes + (Block, Compressed) do not close the connection to indicate the + end of file. They have enough FTP encoding that the data + connection can be parsed to determine the end of the file. + Thus using these modes one can leave the data connection open + for multiple file transfers. + + 3.4. TRANSMISSION MODES + + The next consideration in transferring data is choosing the + appropriate transmission mode. There are three modes: one which + formats the data and allows for restart procedures; one which also + compresses the data for efficient transfer; and one which passes + the data with little or no processing. In this last case the mode + interacts with the structure attribute to determine the type of + processing. In the compressed mode, the representation type + determines the filler byte. + + All data transfers must be completed with an end-of-file (EOF) + which may be explicitly stated or implied by the closing of the + data connection. For files with record structure, all the + end-of-record markers (EOR) are explicit, including the final one. + For files transmitted in page structure a "last-page" page type is + used. + + NOTE: In the rest of this section, byte means "transfer byte" + except where explicitly stated otherwise. + + For the purpose of standardized transfer, the sending host will + translate its internal end of line or end of record denotation + into the representation prescribed by the transfer mode and file + structure, and the receiving host will perform the inverse + translation to its internal denotation. An IBM Mainframe record + count field may not be recognized at another host, so the + end-of-record information may be transferred as a two byte control + code in Stream mode or as a flagged bit in a Block or Compressed + mode descriptor. End-of-line in an ASCII or EBCDIC file with no + record structure should be indicated by or , + respectively. Since these transformations imply extra work for + some systems, identical systems transferring non-record structured + text files might wish to use a binary representation and stream + mode for the transfer. + + + + + + +Postel & Reynolds [Page 20] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The following transmission modes are defined in FTP: + + 3.4.1. STREAM MODE + + The data is transmitted as a stream of bytes. There is no + restriction on the representation type used; record structures + are allowed. + + In a record structured file EOR and EOF will each be indicated + by a two-byte control code. The first byte of the control code + will be all ones, the escape character. The second byte will + have the low order bit on and zeros elsewhere for EOR and the + second low order bit on for EOF; that is, the byte will have + value 1 for EOR and value 2 for EOF. EOR and EOF may be + indicated together on the last byte transmitted by turning both + low order bits on (i.e., the value 3). If a byte of all ones + was intended to be sent as data, it should be repeated in the + second byte of the control code. + + If the structure is a file structure, the EOF is indicated by + the sending host closing the data connection and all bytes are + data bytes. + + 3.4.2. BLOCK MODE + + The file is transmitted as a series of data blocks preceded by + one or more header bytes. The header bytes contain a count + field, and descriptor code. The count field indicates the + total length of the data block in bytes, thus marking the + beginning of the next data block (there are no filler bits). + The descriptor code defines: last block in the file (EOF) last + block in the record (EOR), restart marker (see the Section on + Error Recovery and Restart) or suspect data (i.e., the data + being transferred is suspected of errors and is not reliable). + This last code is NOT intended for error control within FTP. + It is motivated by the desire of sites exchanging certain types + of data (e.g., seismic or weather data) to send and receive all + the data despite local errors (such as "magnetic tape read + errors"), but to indicate in the transmission that certain + portions are suspect). Record structures are allowed in this + mode, and any representation type may be used. + + The header consists of the three bytes. Of the 24 bits of + header information, the 16 low order bits shall represent byte + count, and the 8 high order bits shall represent descriptor + codes as shown below. + + + +Postel & Reynolds [Page 21] + + + +RFC 959 October 1985 +File Transfer Protocol + + + Block Header + + +----------------+----------------+----------------+ + | Descriptor | Byte Count | + | 8 bits | 16 bits | + +----------------+----------------+----------------+ + + + The descriptor codes are indicated by bit flags in the + descriptor byte. Four codes have been assigned, where each + code number is the decimal value of the corresponding bit in + the byte. + + Code Meaning + + 128 End of data block is EOR + 64 End of data block is EOF + 32 Suspected errors in data block + 16 Data block is a restart marker + + With this encoding, more than one descriptor coded condition + may exist for a particular block. As many bits as necessary + may be flagged. + + The restart marker is embedded in the data stream as an + integral number of 8-bit bytes representing printable + characters in the language being used over the control + connection (e.g., default--NVT-ASCII). (Space, in the + appropriate language) must not be used WITHIN a restart marker. + + For example, to transmit a six-character marker, the following + would be sent: + + +--------+--------+--------+ + |Descrptr| Byte count | + |code= 16| = 6 | + +--------+--------+--------+ + + +--------+--------+--------+ + | Marker | Marker | Marker | + | 8 bits | 8 bits | 8 bits | + +--------+--------+--------+ + + +--------+--------+--------+ + | Marker | Marker | Marker | + | 8 bits | 8 bits | 8 bits | + +--------+--------+--------+ + + +Postel & Reynolds [Page 22] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 3.4.3. COMPRESSED MODE + + There are three kinds of information to be sent: regular data, + sent in a byte string; compressed data, consisting of + replications or filler; and control information, sent in a + two-byte escape sequence. If n>0 bytes (up to 127) of regular + data are sent, these n bytes are preceded by a byte with the + left-most bit set to 0 and the right-most 7 bits containing the + number n. + + Byte string: + + 1 7 8 8 + +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ + |0| n | | d(1) | ... | d(n) | + +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ + ^ ^ + |---n bytes---| + of data + + String of n data bytes d(1),..., d(n) + Count n must be positive. + + To compress a string of n replications of the data byte d, the + following 2 bytes are sent: + + Replicated Byte: + + 2 6 8 + +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ + |1 0| n | | d | + +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ + + A string of n filler bytes can be compressed into a single + byte, where the filler byte varies with the representation + type. If the type is ASCII or EBCDIC the filler byte is + (Space, ASCII code 32, EBCDIC code 64). If the type is Image + or Local byte the filler is a zero byte. + + Filler String: + + 2 6 + +-+-+-+-+-+-+-+-+ + |1 1| n | + +-+-+-+-+-+-+-+-+ + + The escape sequence is a double byte, the first of which is the + + +Postel & Reynolds [Page 23] + + + +RFC 959 October 1985 +File Transfer Protocol + + + escape byte (all zeros) and the second of which contains + descriptor codes as defined in Block mode. The descriptor + codes have the same meaning as in Block mode and apply to the + succeeding string of bytes. + + Compressed mode is useful for obtaining increased bandwidth on + very large network transmissions at a little extra CPU cost. + It can be most effectively used to reduce the size of printer + files such as those generated by RJE hosts. + + 3.5. ERROR RECOVERY AND RESTART + + There is no provision for detecting bits lost or scrambled in data + transfer; this level of error control is handled by the TCP. + However, a restart procedure is provided to protect users from + gross system failures (including failures of a host, an + FTP-process, or the underlying network). + + The restart procedure is defined only for the block and compressed + modes of data transfer. It requires the sender of data to insert + a special marker code in the data stream with some marker + information. The marker information has meaning only to the + sender, but must consist of printable characters in the default or + negotiated language of the control connection (ASCII or EBCDIC). + The marker could represent a bit-count, a record-count, or any + other information by which a system may identify a data + checkpoint. The receiver of data, if it implements the restart + procedure, would then mark the corresponding position of this + marker in the receiving system, and return this information to the + user. + + In the event of a system failure, the user can restart the data + transfer by identifying the marker point with the FTP restart + procedure. The following example illustrates the use of the + restart procedure. + + The sender of the data inserts an appropriate marker block in the + data stream at a convenient point. The receiving host marks the + corresponding data point in its file system and conveys the last + known sender and receiver marker information to the user, either + directly or over the control connection in a 110 reply (depending + on who is the sender). In the event of a system failure, the user + or controller process restarts the server at the last server + marker by sending a restart command with server's marker code as + its argument. The restart command is transmitted over the control + + + + +Postel & Reynolds [Page 24] + + + +RFC 959 October 1985 +File Transfer Protocol + + + connection and is immediately followed by the command (such as + RETR, STOR or LIST) which was being executed when the system + failure occurred. + +4. FILE TRANSFER FUNCTIONS + + The communication channel from the user-PI to the server-PI is + established as a TCP connection from the user to the standard server + port. The user protocol interpreter is responsible for sending FTP + commands and interpreting the replies received; the server-PI + interprets commands, sends replies and directs its DTP to set up the + data connection and transfer the data. If the second party to the + data transfer (the passive transfer process) is the user-DTP, then it + is governed through the internal protocol of the user-FTP host; if it + is a second server-DTP, then it is governed by its PI on command from + the user-PI. The FTP replies are discussed in the next section. In + the description of a few of the commands in this section, it is + helpful to be explicit about the possible replies. + + 4.1. FTP COMMANDS + + 4.1.1. ACCESS CONTROL COMMANDS + + The following commands specify access control identifiers + (command codes are shown in parentheses). + + USER NAME (USER) + + The argument field is a Telnet string identifying the user. + The user identification is that which is required by the + server for access to its file system. This command will + normally be the first command transmitted by the user after + the control connections are made (some servers may require + this). Additional identification information in the form of + a password and/or an account command may also be required by + some servers. Servers may allow a new USER command to be + entered at any point in order to change the access control + and/or accounting information. This has the effect of + flushing any user, password, and account information already + supplied and beginning the login sequence again. All + transfer parameters are unchanged and any file transfer in + progress is completed under the old access control + parameters. + + + + + + +Postel & Reynolds [Page 25] + + + +RFC 959 October 1985 +File Transfer Protocol + + + PASSWORD (PASS) + + The argument field is a Telnet string specifying the user's + password. This command must be immediately preceded by the + user name command, and, for some sites, completes the user's + identification for access control. Since password + information is quite sensitive, it is desirable in general + to "mask" it or suppress typeout. It appears that the + server has no foolproof way to achieve this. It is + therefore the responsibility of the user-FTP process to hide + the sensitive password information. + + ACCOUNT (ACCT) + + The argument field is a Telnet string identifying the user's + account. The command is not necessarily related to the USER + command, as some sites may require an account for login and + others only for specific access, such as storing files. In + the latter case the command may arrive at any time. + + There are reply codes to differentiate these cases for the + automation: when account information is required for login, + the response to a successful PASSword command is reply code + 332. On the other hand, if account information is NOT + required for login, the reply to a successful PASSword + command is 230; and if the account information is needed for + a command issued later in the dialogue, the server should + return a 332 or 532 reply depending on whether it stores + (pending receipt of the ACCounT command) or discards the + command, respectively. + + CHANGE WORKING DIRECTORY (CWD) + + This command allows the user to work with a different + directory or dataset for file storage or retrieval without + altering his login or accounting information. Transfer + parameters are similarly unchanged. The argument is a + pathname specifying a directory or other system dependent + file group designator. + + CHANGE TO PARENT DIRECTORY (CDUP) + + This command is a special case of CWD, and is included to + simplify the implementation of programs for transferring + directory trees between operating systems having different + + + + +Postel & Reynolds [Page 26] + + + +RFC 959 October 1985 +File Transfer Protocol + + + syntaxes for naming the parent directory. The reply codes + shall be identical to the reply codes of CWD. See + Appendix II for further details. + + STRUCTURE MOUNT (SMNT) + + This command allows the user to mount a different file + system data structure without altering his login or + accounting information. Transfer parameters are similarly + unchanged. The argument is a pathname specifying a + directory or other system dependent file group designator. + + REINITIALIZE (REIN) + + This command terminates a USER, flushing all I/O and account + information, except to allow any transfer in progress to be + completed. All parameters are reset to the default settings + and the control connection is left open. This is identical + to the state in which a user finds himself immediately after + the control connection is opened. A USER command may be + expected to follow. + + LOGOUT (QUIT) + + This command terminates a USER and if file transfer is not + in progress, the server closes the control connection. If + file transfer is in progress, the connection will remain + open for result response and the server will then close it. + If the user-process is transferring files for several USERs + but does not wish to close and then reopen connections for + each, then the REIN command should be used instead of QUIT. + + An unexpected close on the control connection will cause the + server to take the effective action of an abort (ABOR) and a + logout (QUIT). + + 4.1.2. TRANSFER PARAMETER COMMANDS + + All data transfer parameters have default values, and the + commands specifying data transfer parameters are required only + if the default parameter values are to be changed. The default + value is the last specified value, or if no value has been + specified, the standard default value is as stated here. This + implies that the server must "remember" the applicable default + values. The commands may be in any order except that they must + precede the FTP service request. The following commands + specify data transfer parameters: + + +Postel & Reynolds [Page 27] + + + +RFC 959 October 1985 +File Transfer Protocol + + + DATA PORT (PORT) + + The argument is a HOST-PORT specification for the data port + to be used in data connection. There are defaults for both + the user and server data ports, and under normal + circumstances this command and its reply are not needed. If + this command is used, the argument is the concatenation of a + 32-bit internet host address and a 16-bit TCP port address. + This address information is broken into 8-bit fields and the + value of each field is transmitted as a decimal number (in + character string representation). The fields are separated + by commas. A port command would be: + + PORT h1,h2,h3,h4,p1,p2 + + where h1 is the high order 8 bits of the internet host + address. + + PASSIVE (PASV) + + This command requests the server-DTP to "listen" on a data + port (which is not its default data port) and to wait for a + connection rather than initiate one upon receipt of a + transfer command. The response to this command includes the + host and port address this server is listening on. + + REPRESENTATION TYPE (TYPE) + + The argument specifies the representation type as described + in the Section on Data Representation and Storage. Several + types take a second parameter. The first parameter is + denoted by a single Telnet character, as is the second + Format parameter for ASCII and EBCDIC; the second parameter + for local byte is a decimal integer to indicate Bytesize. + The parameters are separated by a (Space, ASCII code + 32). + + The following codes are assigned for type: + + \ / + A - ASCII | | N - Non-print + |-><-| T - Telnet format effectors + E - EBCDIC| | C - Carriage Control (ASA) + / \ + I - Image + + L - Local byte Byte size + + +Postel & Reynolds [Page 28] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The default representation type is ASCII Non-print. If the + Format parameter is changed, and later just the first + argument is changed, Format then returns to the Non-print + default. + + FILE STRUCTURE (STRU) + + The argument is a single Telnet character code specifying + file structure described in the Section on Data + Representation and Storage. + + The following codes are assigned for structure: + + F - File (no record structure) + R - Record structure + P - Page structure + + The default structure is File. + + TRANSFER MODE (MODE) + + The argument is a single Telnet character code specifying + the data transfer modes described in the Section on + Transmission Modes. + + The following codes are assigned for transfer modes: + + S - Stream + B - Block + C - Compressed + + The default transfer mode is Stream. + + 4.1.3. FTP SERVICE COMMANDS + + The FTP service commands define the file transfer or the file + system function requested by the user. The argument of an FTP + service command will normally be a pathname. The syntax of + pathnames must conform to server site conventions (with + standard defaults applicable), and the language conventions of + the control connection. The suggested default handling is to + use the last specified device, directory or file name, or the + standard default defined for local users. The commands may be + in any order except that a "rename from" command must be + followed by a "rename to" command and the restart command must + be followed by the interrupted service command (e.g., STOR or + RETR). The data, when transferred in response to FTP service + + +Postel & Reynolds [Page 29] + + + +RFC 959 October 1985 +File Transfer Protocol + + + commands, shall always be sent over the data connection, except + for certain informative replies. The following commands + specify FTP service requests: + + RETRIEVE (RETR) + + This command causes the server-DTP to transfer a copy of the + file, specified in the pathname, to the server- or user-DTP + at the other end of the data connection. The status and + contents of the file at the server site shall be unaffected. + + STORE (STOR) + + This command causes the server-DTP to accept the data + transferred via the data connection and to store the data as + a file at the server site. If the file specified in the + pathname exists at the server site, then its contents shall + be replaced by the data being transferred. A new file is + created at the server site if the file specified in the + pathname does not already exist. + + STORE UNIQUE (STOU) + + This command behaves like STOR except that the resultant + file is to be created in the current directory under a name + unique to that directory. The 250 Transfer Started response + must include the name generated. + + APPEND (with create) (APPE) + + This command causes the server-DTP to accept the data + transferred via the data connection and to store the data in + a file at the server site. If the file specified in the + pathname exists at the server site, then the data shall be + appended to that file; otherwise the file specified in the + pathname shall be created at the server site. + + ALLOCATE (ALLO) + + This command may be required by some servers to reserve + sufficient storage to accommodate the new file to be + transferred. The argument shall be a decimal integer + representing the number of bytes (using the logical byte + size) of storage to be reserved for the file. For files + sent with record or page structure a maximum record or page + size (in logical bytes) might also be necessary; this is + indicated by a decimal integer in a second argument field of + + +Postel & Reynolds [Page 30] + + + +RFC 959 October 1985 +File Transfer Protocol + + + the command. This second argument is optional, but when + present should be separated from the first by the three + Telnet characters R . This command shall be + followed by a STORe or APPEnd command. The ALLO command + should be treated as a NOOP (no operation) by those servers + which do not require that the maximum size of the file be + declared beforehand, and those servers interested in only + the maximum record or page size should accept a dummy value + in the first argument and ignore it. + + RESTART (REST) + + The argument field represents the server marker at which + file transfer is to be restarted. This command does not + cause file transfer but skips over the file to the specified + data checkpoint. This command shall be immediately followed + by the appropriate FTP service command which shall cause + file transfer to resume. + + RENAME FROM (RNFR) + + This command specifies the old pathname of the file which is + to be renamed. This command must be immediately followed by + a "rename to" command specifying the new file pathname. + + RENAME TO (RNTO) + + This command specifies the new pathname of the file + specified in the immediately preceding "rename from" + command. Together the two commands cause a file to be + renamed. + + ABORT (ABOR) + + This command tells the server to abort the previous FTP + service command and any associated transfer of data. The + abort command may require "special action", as discussed in + the Section on FTP Commands, to force recognition by the + server. No action is to be taken if the previous command + has been completed (including data transfer). The control + connection is not to be closed by the server, but the data + connection must be closed. + + There are two cases for the server upon receipt of this + command: (1) the FTP service command was already completed, + or (2) the FTP service command is still in progress. + + + +Postel & Reynolds [Page 31] + + + +RFC 959 October 1985 +File Transfer Protocol + + + In the first case, the server closes the data connection + (if it is open) and responds with a 226 reply, indicating + that the abort command was successfully processed. + + In the second case, the server aborts the FTP service in + progress and closes the data connection, returning a 426 + reply to indicate that the service request terminated + abnormally. The server then sends a 226 reply, + indicating that the abort command was successfully + processed. + + DELETE (DELE) + + This command causes the file specified in the pathname to be + deleted at the server site. If an extra level of protection + is desired (such as the query, "Do you really wish to + delete?"), it should be provided by the user-FTP process. + + REMOVE DIRECTORY (RMD) + + This command causes the directory specified in the pathname + to be removed as a directory (if the pathname is absolute) + or as a subdirectory of the current working directory (if + the pathname is relative). See Appendix II. + + MAKE DIRECTORY (MKD) + + This command causes the directory specified in the pathname + to be created as a directory (if the pathname is absolute) + or as a subdirectory of the current working directory (if + the pathname is relative). See Appendix II. + + PRINT WORKING DIRECTORY (PWD) + + This command causes the name of the current working + directory to be returned in the reply. See Appendix II. + + LIST (LIST) + + This command causes a list to be sent from the server to the + passive DTP. If the pathname specifies a directory or other + group of files, the server should transfer a list of files + in the specified directory. If the pathname specifies a + file then the server should send current information on the + file. A null argument implies the user's current working or + default directory. The data transfer is over the data + connection in type ASCII or type EBCDIC. (The user must + + +Postel & Reynolds [Page 32] + + + +RFC 959 October 1985 +File Transfer Protocol + + + ensure that the TYPE is appropriately ASCII or EBCDIC). + Since the information on a file may vary widely from system + to system, this information may be hard to use automatically + in a program, but may be quite useful to a human user. + + NAME LIST (NLST) + + This command causes a directory listing to be sent from + server to user site. The pathname should specify a + directory or other system-specific file group descriptor; a + null argument implies the current directory. The server + will return a stream of names of files and no other + information. The data will be transferred in ASCII or + EBCDIC type over the data connection as valid pathname + strings separated by or . (Again the user must + ensure that the TYPE is correct.) This command is intended + to return information that can be used by a program to + further process the files automatically. For example, in + the implementation of a "multiple get" function. + + SITE PARAMETERS (SITE) + + This command is used by the server to provide services + specific to his system that are essential to file transfer + but not sufficiently universal to be included as commands in + the protocol. The nature of these services and the + specification of their syntax can be stated in a reply to + the HELP SITE command. + + SYSTEM (SYST) + + This command is used to find out the type of operating + system at the server. The reply shall have as its first + word one of the system names listed in the current version + of the Assigned Numbers document [4]. + + STATUS (STAT) + + This command shall cause a status response to be sent over + the control connection in the form of a reply. The command + may be sent during a file transfer (along with the Telnet IP + and Synch signals--see the Section on FTP Commands) in which + case the server will respond with the status of the + operation in progress, or it may be sent between file + transfers. In the latter case, the command may have an + argument field. If the argument is a pathname, the command + is analogous to the "list" command except that data shall be + + +Postel & Reynolds [Page 33] + + + +RFC 959 October 1985 +File Transfer Protocol + + + transferred over the control connection. If a partial + pathname is given, the server may respond with a list of + file names or attributes associated with that specification. + If no argument is given, the server should return general + status information about the server FTP process. This + should include current values of all transfer parameters and + the status of connections. + + HELP (HELP) + + This command shall cause the server to send helpful + information regarding its implementation status over the + control connection to the user. The command may take an + argument (e.g., any command name) and return more specific + information as a response. The reply is type 211 or 214. + It is suggested that HELP be allowed before entering a USER + command. The server may use this reply to specify + site-dependent parameters, e.g., in response to HELP SITE. + + NOOP (NOOP) + + This command does not affect any parameters or previously + entered commands. It specifies no action other than that the + server send an OK reply. + + The File Transfer Protocol follows the specifications of the Telnet + protocol for all communications over the control connection. Since + the language used for Telnet communication may be a negotiated + option, all references in the next two sections will be to the + "Telnet language" and the corresponding "Telnet end-of-line code". + Currently, one may take these to mean NVT-ASCII and . No other + specifications of the Telnet protocol will be cited. + + FTP commands are "Telnet strings" terminated by the "Telnet end of + line code". The command codes themselves are alphabetic characters + terminated by the character (Space) if parameters follow and + Telnet-EOL otherwise. The command codes and the semantics of + commands are described in this section; the detailed syntax of + commands is specified in the Section on Commands, the reply sequences + are discussed in the Section on Sequencing of Commands and Replies, + and scenarios illustrating the use of commands are provided in the + Section on Typical FTP Scenarios. + + FTP commands may be partitioned as those specifying access-control + identifiers, data transfer parameters, or FTP service requests. + Certain commands (such as ABOR, STAT, QUIT) may be sent over the + control connection while a data transfer is in progress. Some + + +Postel & Reynolds [Page 34] + + + +RFC 959 October 1985 +File Transfer Protocol + + + servers may not be able to monitor the control and data connections + simultaneously, in which case some special action will be necessary + to get the server's attention. The following ordered format is + tentatively recommended: + + 1. User system inserts the Telnet "Interrupt Process" (IP) signal + in the Telnet stream. + + 2. User system sends the Telnet "Synch" signal. + + 3. User system inserts the command (e.g., ABOR) in the Telnet + stream. + + 4. Server PI, after receiving "IP", scans the Telnet stream for + EXACTLY ONE FTP command. + + (For other servers this may not be necessary but the actions listed + above should have no unusual effect.) + + 4.2. FTP REPLIES + + Replies to File Transfer Protocol commands are devised to ensure + the synchronization of requests and actions in the process of file + transfer, and to guarantee that the user process always knows the + state of the Server. Every command must generate at least one + reply, although there may be more than one; in the latter case, + the multiple replies must be easily distinguished. In addition, + some commands occur in sequential groups, such as USER, PASS and + ACCT, or RNFR and RNTO. The replies show the existence of an + intermediate state if all preceding commands have been successful. + A failure at any point in the sequence necessitates the repetition + of the entire sequence from the beginning. + + The details of the command-reply sequence are made explicit in + a set of state diagrams below. + + An FTP reply consists of a three digit number (transmitted as + three alphanumeric characters) followed by some text. The number + is intended for use by automata to determine what state to enter + next; the text is intended for the human user. It is intended + that the three digits contain enough encoded information that the + user-process (the User-PI) will not need to examine the text and + may either discard it or pass it on to the user, as appropriate. + In particular, the text may be server-dependent, so there are + likely to be varying texts for each reply code. + + A reply is defined to contain the 3-digit code, followed by Space + + +Postel & Reynolds [Page 35] + + + +RFC 959 October 1985 +File Transfer Protocol + + + , followed by one line of text (where some maximum line length + has been specified), and terminated by the Telnet end-of-line + code. There will be cases however, where the text is longer than + a single line. In these cases the complete text must be bracketed + so the User-process knows when it may stop reading the reply (i.e. + stop processing input on the control connection) and go do other + things. This requires a special format on the first line to + indicate that more than one line is coming, and another on the + last line to designate it as the last. At least one of these must + contain the appropriate reply code to indicate the state of the + transaction. To satisfy all factions, it was decided that both + the first and last line codes should be the same. + + Thus the format for multi-line replies is that the first line + will begin with the exact required reply code, followed + immediately by a Hyphen, "-" (also known as Minus), followed by + text. The last line will begin with the same code, followed + immediately by Space , optionally some text, and the Telnet + end-of-line code. + + For example: + 123-First line + Second line + 234 A line beginning with numbers + 123 The last line + + The user-process then simply needs to search for the second + occurrence of the same reply code, followed by (Space), at + the beginning of a line, and ignore all intermediary lines. If + an intermediary line begins with a 3-digit number, the Server + must pad the front to avoid confusion. + + This scheme allows standard system routines to be used for + reply information (such as for the STAT reply), with + "artificial" first and last lines tacked on. In rare cases + where these routines are able to generate three digits and a + Space at the beginning of any line, the beginning of each + text line should be offset by some neutral text, like Space. + + This scheme assumes that multi-line replies may not be nested. + + The three digits of the reply each have a special significance. + This is intended to allow a range of very simple to very + sophisticated responses by the user-process. The first digit + denotes whether the response is good, bad or incomplete. + (Referring to the state diagram), an unsophisticated user-process + will be able to determine its next action (proceed as planned, + + +Postel & Reynolds [Page 36] + + + +RFC 959 October 1985 +File Transfer Protocol + + + redo, retrench, etc.) by simply examining this first digit. A + user-process that wants to know approximately what kind of error + occurred (e.g. file system error, command syntax error) may + examine the second digit, reserving the third digit for the finest + gradation of information (e.g., RNTO command without a preceding + RNFR). + + There are five values for the first digit of the reply code: + + 1yz Positive Preliminary reply + + The requested action is being initiated; expect another + reply before proceeding with a new command. (The + user-process sending another command before the + completion reply would be in violation of protocol; but + server-FTP processes should queue any commands that + arrive while a preceding command is in progress.) This + type of reply can be used to indicate that the command + was accepted and the user-process may now pay attention + to the data connections, for implementations where + simultaneous monitoring is difficult. The server-FTP + process may send at most, one 1yz reply per command. + + 2yz Positive Completion reply + + The requested action has been successfully completed. A + new request may be initiated. + + 3yz Positive Intermediate reply + + The command has been accepted, but the requested action + is being held in abeyance, pending receipt of further + information. The user should send another command + specifying this information. This reply is used in + command sequence groups. + + 4yz Transient Negative Completion reply + + The command was not accepted and the requested action did + not take place, but the error condition is temporary and + the action may be requested again. The user should + return to the beginning of the command sequence, if any. + It is difficult to assign a meaning to "transient", + particularly when two distinct sites (Server- and + User-processes) have to agree on the interpretation. + Each reply in the 4yz category might have a slightly + different time value, but the intent is that the + + +Postel & Reynolds [Page 37] + + + +RFC 959 October 1985 +File Transfer Protocol + + + user-process is encouraged to try again. A rule of thumb + in determining if a reply fits into the 4yz or the 5yz + (Permanent Negative) category is that replies are 4yz if + the commands can be repeated without any change in + command form or in properties of the User or Server + (e.g., the command is spelled the same with the same + arguments used; the user does not change his file access + or user name; the server does not put up a new + implementation.) + + 5yz Permanent Negative Completion reply + + The command was not accepted and the requested action did + not take place. The User-process is discouraged from + repeating the exact request (in the same sequence). Even + some "permanent" error conditions can be corrected, so + the human user may want to direct his User-process to + reinitiate the command sequence by direct action at some + point in the future (e.g., after the spelling has been + changed, or the user has altered his directory status.) + + The following function groupings are encoded in the second + digit: + + x0z Syntax - These replies refer to syntax errors, + syntactically correct commands that don't fit any + functional category, unimplemented or superfluous + commands. + + x1z Information - These are replies to requests for + information, such as status or help. + + x2z Connections - Replies referring to the control and + data connections. + + x3z Authentication and accounting - Replies for the login + process and accounting procedures. + + x4z Unspecified as yet. + + x5z File system - These replies indicate the status of the + Server file system vis-a-vis the requested transfer or + other file system action. + + The third digit gives a finer gradation of meaning in each of + the function categories, specified by the second digit. The + list of replies below will illustrate this. Note that the text + + +Postel & Reynolds [Page 38] + + + +RFC 959 October 1985 +File Transfer Protocol + + + associated with each reply is recommended, rather than + mandatory, and may even change according to the command with + which it is associated. The reply codes, on the other hand, + must strictly follow the specifications in the last section; + that is, Server implementations should not invent new codes for + situations that are only slightly different from the ones + described here, but rather should adapt codes already defined. + + A command such as TYPE or ALLO whose successful execution + does not offer the user-process any new information will + cause a 200 reply to be returned. If the command is not + implemented by a particular Server-FTP process because it + has no relevance to that computer system, for example ALLO + at a TOPS20 site, a Positive Completion reply is still + desired so that the simple User-process knows it can proceed + with its course of action. A 202 reply is used in this case + with, for example, the reply text: "No storage allocation + necessary." If, on the other hand, the command requests a + non-site-specific action and is unimplemented, the response + is 502. A refinement of that is the 504 reply for a command + that is implemented, but that requests an unimplemented + parameter. + + 4.2.1 Reply Codes by Function Groups + + 200 Command okay. + 500 Syntax error, command unrecognized. + This may include errors such as command line too long. + 501 Syntax error in parameters or arguments. + 202 Command not implemented, superfluous at this site. + 502 Command not implemented. + 503 Bad sequence of commands. + 504 Command not implemented for that parameter. + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 39] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 110 Restart marker reply. + In this case, the text is exact and not left to the + particular implementation; it must read: + MARK yyyy = mmmm + Where yyyy is User-process data stream marker, and mmmm + server's equivalent marker (note the spaces between markers + and "="). + 211 System status, or system help reply. + 212 Directory status. + 213 File status. + 214 Help message. + On how to use the server or the meaning of a particular + non-standard command. This reply is useful only to the + human user. + 215 NAME system type. + Where NAME is an official system name from the list in the + Assigned Numbers document. + + 120 Service ready in nnn minutes. + 220 Service ready for new user. + 221 Service closing control connection. + Logged out if appropriate. + 421 Service not available, closing control connection. + This may be a reply to any command if the service knows it + must shut down. + 125 Data connection already open; transfer starting. + 225 Data connection open; no transfer in progress. + 425 Can't open data connection. + 226 Closing data connection. + Requested file action successful (for example, file + transfer or file abort). + 426 Connection closed; transfer aborted. + 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). + + 230 User logged in, proceed. + 530 Not logged in. + 331 User name okay, need password. + 332 Need account for login. + 532 Need account for storing files. + + + + + + + + + + +Postel & Reynolds [Page 40] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 150 File status okay; about to open data connection. + 250 Requested file action okay, completed. + 257 "PATHNAME" created. + 350 Requested file action pending further information. + 450 Requested file action not taken. + File unavailable (e.g., file busy). + 550 Requested action not taken. + File unavailable (e.g., file not found, no access). + 451 Requested action aborted. Local error in processing. + 551 Requested action aborted. Page type unknown. + 452 Requested action not taken. + Insufficient storage space in system. + 552 Requested file action aborted. + Exceeded storage allocation (for current directory or + dataset). + 553 Requested action not taken. + File name not allowed. + + + 4.2.2 Numeric Order List of Reply Codes + + 110 Restart marker reply. + In this case, the text is exact and not left to the + particular implementation; it must read: + MARK yyyy = mmmm + Where yyyy is User-process data stream marker, and mmmm + server's equivalent marker (note the spaces between markers + and "="). + 120 Service ready in nnn minutes. + 125 Data connection already open; transfer starting. + 150 File status okay; about to open data connection. + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 41] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 200 Command okay. + 202 Command not implemented, superfluous at this site. + 211 System status, or system help reply. + 212 Directory status. + 213 File status. + 214 Help message. + On how to use the server or the meaning of a particular + non-standard command. This reply is useful only to the + human user. + 215 NAME system type. + Where NAME is an official system name from the list in the + Assigned Numbers document. + 220 Service ready for new user. + 221 Service closing control connection. + Logged out if appropriate. + 225 Data connection open; no transfer in progress. + 226 Closing data connection. + Requested file action successful (for example, file + transfer or file abort). + 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). + 230 User logged in, proceed. + 250 Requested file action okay, completed. + 257 "PATHNAME" created. + + 331 User name okay, need password. + 332 Need account for login. + 350 Requested file action pending further information. + + 421 Service not available, closing control connection. + This may be a reply to any command if the service knows it + must shut down. + 425 Can't open data connection. + 426 Connection closed; transfer aborted. + 450 Requested file action not taken. + File unavailable (e.g., file busy). + 451 Requested action aborted: local error in processing. + 452 Requested action not taken. + Insufficient storage space in system. + + + + + + + + + + + +Postel & Reynolds [Page 42] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 500 Syntax error, command unrecognized. + This may include errors such as command line too long. + 501 Syntax error in parameters or arguments. + 502 Command not implemented. + 503 Bad sequence of commands. + 504 Command not implemented for that parameter. + 530 Not logged in. + 532 Need account for storing files. + 550 Requested action not taken. + File unavailable (e.g., file not found, no access). + 551 Requested action aborted: page type unknown. + 552 Requested file action aborted. + Exceeded storage allocation (for current directory or + dataset). + 553 Requested action not taken. + File name not allowed. + + +5. DECLARATIVE SPECIFICATIONS + + 5.1. MINIMUM IMPLEMENTATION + + In order to make FTP workable without needless error messages, the + following minimum implementation is required for all servers: + + TYPE - ASCII Non-print + MODE - Stream + STRUCTURE - File, Record + COMMANDS - USER, QUIT, PORT, + TYPE, MODE, STRU, + for the default values + RETR, STOR, + NOOP. + + The default values for transfer parameters are: + + TYPE - ASCII Non-print + MODE - Stream + STRU - File + + All hosts must accept the above as the standard defaults. + + + + + + + + +Postel & Reynolds [Page 43] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 5.2. CONNECTIONS + + The server protocol interpreter shall "listen" on Port L. The + user or user protocol interpreter shall initiate the full-duplex + control connection. Server- and user- processes should follow the + conventions of the Telnet protocol as specified in the + ARPA-Internet Protocol Handbook [1]. Servers are under no + obligation to provide for editing of command lines and may require + that it be done in the user host. The control connection shall be + closed by the server at the user's request after all transfers and + replies are completed. + + The user-DTP must "listen" on the specified data port; this may be + the default user port (U) or a port specified in the PORT command. + The server shall initiate the data connection from his own default + data port (L-1) using the specified user data port. The direction + of the transfer and the port used will be determined by the FTP + service command. + + Note that all FTP implementation must support data transfer using + the default port, and that only the USER-PI may initiate the use + of non-default ports. + + When data is to be transferred between two servers, A and B (refer + to Figure 2), the user-PI, C, sets up control connections with + both server-PI's. One of the servers, say A, is then sent a PASV + command telling him to "listen" on his data port rather than + initiate a connection when he receives a transfer service command. + When the user-PI receives an acknowledgment to the PASV command, + which includes the identity of the host and port being listened + on, the user-PI then sends A's port, a, to B in a PORT command; a + reply is returned. The user-PI may then send the corresponding + service commands to A and B. Server B initiates the connection + and the transfer proceeds. The command-reply sequence is listed + below where the messages are vertically synchronous but + horizontally asynchronous: + + + + + + + + + + + + + +Postel & Reynolds [Page 44] + + + +RFC 959 October 1985 +File Transfer Protocol + + + User-PI - Server A User-PI - Server B + ------------------ ------------------ + + C->A : Connect C->B : Connect + C->A : PASV + A->C : 227 Entering Passive Mode. A1,A2,A3,A4,a1,a2 + C->B : PORT A1,A2,A3,A4,a1,a2 + B->C : 200 Okay + C->A : STOR C->B : RETR + B->A : Connect to HOST-A, PORT-a + + Figure 3 + + The data connection shall be closed by the server under the + conditions described in the Section on Establishing Data + Connections. If the data connection is to be closed following a + data transfer where closing the connection is not required to + indicate the end-of-file, the server must do so immediately. + Waiting until after a new transfer command is not permitted + because the user-process will have already tested the data + connection to see if it needs to do a "listen"; (remember that the + user must "listen" on a closed data port BEFORE sending the + transfer request). To prevent a race condition here, the server + sends a reply (226) after closing the data connection (or if the + connection is left open, a "file transfer completed" reply (250) + and the user-PI should wait for one of these replies before + issuing a new transfer command). + + Any time either the user or server see that the connection is + being closed by the other side, it should promptly read any + remaining data queued on the connection and issue the close on its + own side. + + 5.3. COMMANDS + + The commands are Telnet character strings transmitted over the + control connections as described in the Section on FTP Commands. + The command functions and semantics are described in the Section + on Access Control Commands, Transfer Parameter Commands, FTP + Service Commands, and Miscellaneous Commands. The command syntax + is specified here. + + The commands begin with a command code followed by an argument + field. The command codes are four or fewer alphabetic characters. + Upper and lower case alphabetic characters are to be treated + identically. Thus, any of the following may represent the + retrieve command: + + +Postel & Reynolds [Page 45] + + + +RFC 959 October 1985 +File Transfer Protocol + + + RETR Retr retr ReTr rETr + + This also applies to any symbols representing parameter values, + such as A or a for ASCII TYPE. The command codes and the argument + fields are separated by one or more spaces. + + The argument field consists of a variable length character string + ending with the character sequence (Carriage Return, Line + Feed) for NVT-ASCII representation; for other negotiated languages + a different end of line character might be used. It should be + noted that the server is to take no action until the end of line + code is received. + + The syntax is specified below in NVT-ASCII. All characters in the + argument field are ASCII characters including any ASCII + represented decimal integers. Square brackets denote an optional + argument field. If the option is not taken, the appropriate + default is implied. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 46] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 5.3.1. FTP COMMANDS + + The following are the FTP commands: + + USER + PASS + ACCT + CWD + CDUP + SMNT + QUIT + REIN + PORT + PASV + TYPE + STRU + MODE + RETR + STOR + STOU + APPE + ALLO + [ R ] + REST + RNFR + RNTO + ABOR + DELE + RMD + MKD + PWD + LIST [ ] + NLST [ ] + SITE + SYST + STAT [ ] + HELP [ ] + NOOP + + + + + + + + + + + +Postel & Reynolds [Page 47] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 5.3.2. FTP COMMAND ARGUMENTS + + The syntax of the above argument fields (using BNF notation + where applicable) is: + + ::= + ::= + ::= + ::= | + ::= any of the 128 ASCII characters except and + + ::= + ::= | + ::= printable characters, any + ASCII code 33 through 126 + ::= + ::= , + ::= ,,, + ::= , + ::= any decimal integer 1 through 255 + ::= N | T | C + ::= A [ ] + | E [ ] + | I + | L + ::= F | R | P + ::= S | B | C + ::= + ::= any decimal integer + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 48] + + + +RFC 959 October 1985 +File Transfer Protocol + + + 5.4. SEQUENCING OF COMMANDS AND REPLIES + + The communication between the user and server is intended to be an + alternating dialogue. As such, the user issues an FTP command and + the server responds with a prompt primary reply. The user should + wait for this initial primary success or failure response before + sending further commands. + + Certain commands require a second reply for which the user should + also wait. These replies may, for example, report on the progress + or completion of file transfer or the closing of the data + connection. They are secondary replies to file transfer commands. + + One important group of informational replies is the connection + greetings. Under normal circumstances, a server will send a 220 + reply, "awaiting input", when the connection is completed. The + user should wait for this greeting message before sending any + commands. If the server is unable to accept input right away, a + 120 "expected delay" reply should be sent immediately and a 220 + reply when ready. The user will then know not to hang up if there + is a delay. + + Spontaneous Replies + + Sometimes "the system" spontaneously has a message to be sent + to a user (usually all users). For example, "System going down + in 15 minutes". There is no provision in FTP for such + spontaneous information to be sent from the server to the user. + It is recommended that such information be queued in the + server-PI and delivered to the user-PI in the next reply + (possibly making it a multi-line reply). + + The table below lists alternative success and failure replies for + each command. These must be strictly adhered to; a server may + substitute text in the replies, but the meaning and action implied + by the code numbers and by the specific command reply sequence + cannot be altered. + + Command-Reply Sequences + + In this section, the command-reply sequence is presented. Each + command is listed with its possible replies; command groups are + listed together. Preliminary replies are listed first (with + their succeeding replies indented and under them), then + positive and negative completion, and finally intermediary + + + + +Postel & Reynolds [Page 49] + + + +RFC 959 October 1985 +File Transfer Protocol + + + replies with the remaining commands from the sequence + following. This listing forms the basis for the state + diagrams, which will be presented separately. + + Connection Establishment + 120 + 220 + 220 + 421 + Login + USER + 230 + 530 + 500, 501, 421 + 331, 332 + PASS + 230 + 202 + 530 + 500, 501, 503, 421 + 332 + ACCT + 230 + 202 + 530 + 500, 501, 503, 421 + CWD + 250 + 500, 501, 502, 421, 530, 550 + CDUP + 200 + 500, 501, 502, 421, 530, 550 + SMNT + 202, 250 + 500, 501, 502, 421, 530, 550 + Logout + REIN + 120 + 220 + 220 + 421 + 500, 502 + QUIT + 221 + 500 + + + + +Postel & Reynolds [Page 50] + + + +RFC 959 October 1985 +File Transfer Protocol + + + Transfer parameters + PORT + 200 + 500, 501, 421, 530 + PASV + 227 + 500, 501, 502, 421, 530 + MODE + 200 + 500, 501, 504, 421, 530 + TYPE + 200 + 500, 501, 504, 421, 530 + STRU + 200 + 500, 501, 504, 421, 530 + File action commands + ALLO + 200 + 202 + 500, 501, 504, 421, 530 + REST + 500, 501, 502, 421, 530 + 350 + STOR + 125, 150 + (110) + 226, 250 + 425, 426, 451, 551, 552 + 532, 450, 452, 553 + 500, 501, 421, 530 + STOU + 125, 150 + (110) + 226, 250 + 425, 426, 451, 551, 552 + 532, 450, 452, 553 + 500, 501, 421, 530 + RETR + 125, 150 + (110) + 226, 250 + 425, 426, 451 + 450, 550 + 500, 501, 421, 530 + + + + +Postel & Reynolds [Page 51] + + + +RFC 959 October 1985 +File Transfer Protocol + + + LIST + 125, 150 + 226, 250 + 425, 426, 451 + 450 + 500, 501, 502, 421, 530 + NLST + 125, 150 + 226, 250 + 425, 426, 451 + 450 + 500, 501, 502, 421, 530 + APPE + 125, 150 + (110) + 226, 250 + 425, 426, 451, 551, 552 + 532, 450, 550, 452, 553 + 500, 501, 502, 421, 530 + RNFR + 450, 550 + 500, 501, 502, 421, 530 + 350 + RNTO + 250 + 532, 553 + 500, 501, 502, 503, 421, 530 + DELE + 250 + 450, 550 + 500, 501, 502, 421, 530 + RMD + 250 + 500, 501, 502, 421, 530, 550 + MKD + 257 + 500, 501, 502, 421, 530, 550 + PWD + 257 + 500, 501, 502, 421, 550 + ABOR + 225, 226 + 500, 501, 502, 421 + + + + + + +Postel & Reynolds [Page 52] + + + +RFC 959 October 1985 +File Transfer Protocol + + + Informational commands + SYST + 215 + 500, 501, 502, 421 + STAT + 211, 212, 213 + 450 + 500, 501, 502, 421, 530 + HELP + 211, 214 + 500, 501, 502, 421 + Miscellaneous commands + SITE + 200 + 202 + 500, 501, 530 + NOOP + 200 + 500 421 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 53] + + + +RFC 959 October 1985 +File Transfer Protocol + + +6. STATE DIAGRAMS + + Here we present state diagrams for a very simple minded FTP + implementation. Only the first digit of the reply codes is used. + There is one state diagram for each group of FTP commands or command + sequences. + + The command groupings were determined by constructing a model for + each command then collecting together the commands with structurally + identical models. + + For each command or command sequence there are three possible + outcomes: success (S), failure (F), and error (E). In the state + diagrams below we use the symbol B for "begin", and the symbol W for + "wait for reply". + + We first present the diagram that represents the largest group of FTP + commands: + + + 1,3 +---+ + ----------->| E | + | +---+ + | + +---+ cmd +---+ 2 +---+ + | B |---------->| W |---------->| S | + +---+ +---+ +---+ + | + | 4,5 +---+ + ----------->| F | + +---+ + + + This diagram models the commands: + + ABOR, ALLO, DELE, CWD, CDUP, SMNT, HELP, MODE, NOOP, PASV, + QUIT, SITE, PORT, SYST, STAT, RMD, MKD, PWD, STRU, and TYPE. + + + + + + + + + + + + +Postel & Reynolds [Page 54] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The other large group of commands is represented by a very similar + diagram: + + + 3 +---+ + ----------->| E | + | +---+ + | + +---+ cmd +---+ 2 +---+ + | B |---------->| W |---------->| S | + +---+ --->+---+ +---+ + | | | + | | | 4,5 +---+ + | 1 | ----------->| F | + ----- +---+ + + + This diagram models the commands: + + APPE, LIST, NLST, REIN, RETR, STOR, and STOU. + + Note that this second model could also be used to represent the first + group of commands, the only difference being that in the first group + the 100 series replies are unexpected and therefore treated as error, + while the second group expects (some may require) 100 series replies. + Remember that at most, one 100 series reply is allowed per command. + + The remaining diagrams model command sequences, perhaps the simplest + of these is the rename sequence: + + + +---+ RNFR +---+ 1,2 +---+ + | B |---------->| W |---------->| E | + +---+ +---+ -->+---+ + | | | + 3 | | 4,5 | + -------------- ------ | + | | | +---+ + | ------------->| S | + | | 1,3 | | +---+ + | 2| -------- + | | | | + V | | | + +---+ RNTO +---+ 4,5 ----->+---+ + | |---------->| W |---------->| F | + +---+ +---+ +---+ + + + +Postel & Reynolds [Page 55] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The next diagram is a simple model of the Restart command: + + + +---+ REST +---+ 1,2 +---+ + | B |---------->| W |---------->| E | + +---+ +---+ -->+---+ + | | | + 3 | | 4,5 | + -------------- ------ | + | | | +---+ + | ------------->| S | + | | 3 | | +---+ + | 2| -------- + | | | | + V | | | + +---+ cmd +---+ 4,5 ----->+---+ + | |---------->| W |---------->| F | + +---+ -->+---+ +---+ + | | + | 1 | + ------ + + + Where "cmd" is APPE, STOR, or RETR. + + We note that the above three models are similar. The Restart differs + from the Rename two only in the treatment of 100 series replies at + the second stage, while the second group expects (some may require) + 100 series replies. Remember that at most, one 100 series reply is + allowed per command. + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 56] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The most complicated diagram is for the Login sequence: + + + 1 + +---+ USER +---+------------->+---+ + | B |---------->| W | 2 ---->| E | + +---+ +---+------ | -->+---+ + | | | | | + 3 | | 4,5 | | | + -------------- ----- | | | + | | | | | + | | | | | + | --------- | + | 1| | | | + V | | | | + +---+ PASS +---+ 2 | ------>+---+ + | |---------->| W |------------->| S | + +---+ +---+ ---------->+---+ + | | | | | + 3 | |4,5| | | + -------------- -------- | + | | | | | + | | | | | + | ----------- + | 1,3| | | | + V | 2| | | + +---+ ACCT +---+-- | ----->+---+ + | |---------->| W | 4,5 -------->| F | + +---+ +---+------------->+---+ + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 57] + + + +RFC 959 October 1985 +File Transfer Protocol + + + Finally, we present a generalized diagram that could be used to model + the command and reply interchange: + + + ------------------------------------ + | | + Begin | | + | V | + | +---+ cmd +---+ 2 +---+ | + -->| |------->| |---------->| | | + | | | W | | S |-----| + -->| | -->| |----- | | | + | +---+ | +---+ 4,5 | +---+ | + | | | | | | | + | | | 1| |3 | +---+ | + | | | | | | | | | + | | ---- | ---->| F |----- + | | | | | + | | | +---+ + ------------------- + | + | + V + End + + + + + + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 58] + + + +RFC 959 October 1985 +File Transfer Protocol + + +7. TYPICAL FTP SCENARIO + + User at host U wanting to transfer files to/from host S: + + In general, the user will communicate to the server via a mediating + user-FTP process. The following may be a typical scenario. The + user-FTP prompts are shown in parentheses, '---->' represents + commands from host U to host S, and '<----' represents replies from + host S to host U. + + LOCAL COMMANDS BY USER ACTION INVOLVED + + ftp (host) multics Connect to host S, port L, + establishing control connections. + <---- 220 Service ready . + username Doe USER Doe----> + <---- 331 User name ok, + need password. + password mumble PASS mumble----> + <---- 230 User logged in. + retrieve (local type) ASCII + (local pathname) test 1 User-FTP opens local file in ASCII. + (for. pathname) test.pl1 RETR test.pl1 ----> + <---- 150 File status okay; + about to open data + connection. + Server makes data connection + to port U. + + <---- 226 Closing data connection, + file transfer successful. + type Image TYPE I ----> + <---- 200 Command OK + store (local type) image + (local pathname) file dump User-FTP opens local file in Image. + (for.pathname) >udd>cn>fd STOR >udd>cn>fd ----> + <---- 550 Access denied + terminate QUIT ----> + Server closes all + connections. + +8. CONNECTION ESTABLISHMENT + + The FTP control connection is established via TCP between the user + process port U and the server process port L. This protocol is + assigned the service port 21 (25 octal), that is L=21. + + + +Postel & Reynolds [Page 59] + + + +RFC 959 October 1985 +File Transfer Protocol + + +APPENDIX I - PAGE STRUCTURE + + The need for FTP to support page structure derives principally from + the need to support efficient transmission of files between TOPS-20 + systems, particularly the files used by NLS. + + The file system of TOPS-20 is based on the concept of pages. The + operating system is most efficient at manipulating files as pages. + The operating system provides an interface to the file system so that + many applications view files as sequential streams of characters. + However, a few applications use the underlying page structures + directly, and some of these create holey files. + + A TOPS-20 disk file consists of four things: a pathname, a page + table, a (possibly empty) set of pages, and a set of attributes. + + The pathname is specified in the RETR or STOR command. It includes + the directory name, file name, file name extension, and generation + number. + + The page table contains up to 2**18 entries. Each entry may be + EMPTY, or may point to a page. If it is not empty, there are also + some page-specific access bits; not all pages of a file need have the + same access protection. + + A page is a contiguous set of 512 words of 36 bits each. + + The attributes of the file, in the File Descriptor Block (FDB), + contain such things as creation time, write time, read time, writer's + byte-size, end-of-file pointer, count of reads and writes, backup + system tape numbers, etc. + + Note that there is NO requirement that entries in the page table be + contiguous. There may be empty page table slots between occupied + ones. Also, the end of file pointer is simply a number. There is no + requirement that it in fact point at the "last" datum in the file. + Ordinary sequential I/O calls in TOPS-20 will cause the end of file + pointer to be left after the last datum written, but other operations + may cause it not to be so, if a particular programming system so + requires. + + In fact, in both of these special cases, "holey" files and + end-of-file pointers NOT at the end of the file, occur with NLS data + files. + + + + + +Postel & Reynolds [Page 60] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The TOPS-20 paged files can be sent with the FTP transfer parameters: + TYPE L 36, STRU P, and MODE S (in fact, any mode could be used). + + Each page of information has a header. Each header field, which is a + logical byte, is a TOPS-20 word, since the TYPE is L 36. + + The header fields are: + + Word 0: Header Length. + + The header length is 5. + + Word 1: Page Index. + + If the data is a disk file page, this is the number of that + page in the file's page map. Empty pages (holes) in the file + are simply not sent. Note that a hole is NOT the same as a + page of zeros. + + Word 2: Data Length. + + The number of data words in this page, following the header. + Thus, the total length of the transmission unit is the Header + Length plus the Data Length. + + Word 3: Page Type. + + A code for what type of chunk this is. A data page is type 3, + the FDB page is type 2. + + Word 4: Page Access Control. + + The access bits associated with the page in the file's page + map. (This full word quantity is put into AC2 of an SPACS by + the program reading from net to disk.) + + After the header are Data Length data words. Data Length is + currently either 512 for a data page or 31 for an FDB. Trailing + zeros in a disk file page may be discarded, making Data Length less + than 512 in that case. + + + + + + + + + +Postel & Reynolds [Page 61] + + + +RFC 959 October 1985 +File Transfer Protocol + + +APPENDIX II - DIRECTORY COMMANDS + + Since UNIX has a tree-like directory structure in which directories + are as easy to manipulate as ordinary files, it is useful to expand + the FTP servers on these machines to include commands which deal with + the creation of directories. Since there are other hosts on the + ARPA-Internet which have tree-like directories (including TOPS-20 and + Multics), these commands are as general as possible. + + Four directory commands have been added to FTP: + + MKD pathname + + Make a directory with the name "pathname". + + RMD pathname + + Remove the directory with the name "pathname". + + PWD + + Print the current working directory name. + + CDUP + + Change to the parent of the current working directory. + + The "pathname" argument should be created (removed) as a + subdirectory of the current working directory, unless the "pathname" + string contains sufficient information to specify otherwise to the + server, e.g., "pathname" is an absolute pathname (in UNIX and + Multics), or pathname is something like "" to + TOPS-20. + + REPLY CODES + + The CDUP command is a special case of CWD, and is included to + simplify the implementation of programs for transferring directory + trees between operating systems having different syntaxes for + naming the parent directory. The reply codes for CDUP be + identical to the reply codes of CWD. + + The reply codes for RMD be identical to the reply codes for its + file analogue, DELE. + + The reply codes for MKD, however, are a bit more complicated. A + freshly created directory will probably be the object of a future + + +Postel & Reynolds [Page 62] + + + +RFC 959 October 1985 +File Transfer Protocol + + + CWD command. Unfortunately, the argument to MKD may not always be + a suitable argument for CWD. This is the case, for example, when + a TOPS-20 subdirectory is created by giving just the subdirectory + name. That is, with a TOPS-20 server FTP, the command sequence + + MKD MYDIR + CWD MYDIR + + will fail. The new directory may only be referred to by its + "absolute" name; e.g., if the MKD command above were issued while + connected to the directory , the new subdirectory + could only be referred to by the name . + + Even on UNIX and Multics, however, the argument given to MKD may + not be suitable. If it is a "relative" pathname (i.e., a pathname + which is interpreted relative to the current directory), the user + would need to be in the same current directory in order to reach + the subdirectory. Depending on the application, this may be + inconvenient. It is not very robust in any case. + + To solve these problems, upon successful completion of an MKD + command, the server should return a line of the form: + + 257"" + + That is, the server will tell the user what string to use when + referring to the created directory. The directory name can + contain any character; embedded double-quotes should be escaped by + double-quotes (the "quote-doubling" convention). + + For example, a user connects to the directory /usr/dm, and creates + a subdirectory, named pathname: + + CWD /usr/dm + 200 directory changed to /usr/dm + MKD pathname + 257 "/usr/dm/pathname" directory created + + An example with an embedded double quote: + + MKD foo"bar + 257 "/usr/dm/foo""bar" directory created + CWD /usr/dm/foo"bar + 200 directory changed to /usr/dm/foo"bar + + + + + +Postel & Reynolds [Page 63] + + + +RFC 959 October 1985 +File Transfer Protocol + + + The prior existence of a subdirectory with the same name is an + error, and the server must return an "access denied" error reply + in that case. + + CWD /usr/dm + 200 directory changed to /usr/dm + MKD pathname + 521-"/usr/dm/pathname" directory already exists; + 521 taking no action. + + The failure replies for MKD are analogous to its file creating + cousin, STOR. Also, an "access denied" return is given if a file + name with the same name as the subdirectory will conflict with the + creation of the subdirectory (this is a problem on UNIX, but + shouldn't be one on TOPS-20). + + Essentially because the PWD command returns the same type of + information as the successful MKD command, the successful PWD + command uses the 257 reply code as well. + + SUBTLETIES + + Because these commands will be most useful in transferring + subtrees from one machine to another, carefully observe that the + argument to MKD is to be interpreted as a sub-directory of the + current working directory, unless it contains enough information + for the destination host to tell otherwise. A hypothetical + example of its use in the TOPS-20 world: + + CWD + 200 Working directory changed + MKD overrainbow + 257 "" directory created + CWD overrainbow + 431 No such directory + CWD + 200 Working directory changed + + CWD + 200 Working directory changed to + MKD + 257 "" directory created + CWD + + Note that the first example results in a subdirectory of the + connected directory. In contrast, the argument in the second + example contains enough information for TOPS-20 to tell that the + + +Postel & Reynolds [Page 64] + + + +RFC 959 October 1985 +File Transfer Protocol + + + directory is a top-level directory. Note also that + in the first example the user "violated" the protocol by + attempting to access the freshly created directory with a name + other than the one returned by TOPS-20. Problems could have + resulted in this case had there been an directory; + this is an ambiguity inherent in some TOPS-20 implementations. + Similar considerations apply to the RMD command. The point is + this: except where to do so would violate a host's conventions for + denoting relative versus absolute pathnames, the host should treat + the operands of the MKD and RMD commands as subdirectories. The + 257 reply to the MKD command must always contain the absolute + pathname of the created directory. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 65] + + + +RFC 959 October 1985 +File Transfer Protocol + + +APPENDIX III - RFCs on FTP + + Bhushan, Abhay, "A File Transfer Protocol", RFC 114 (NIC 5823), + MIT-Project MAC, 16 April 1971. + + Harslem, Eric, and John Heafner, "Comments on RFC 114 (A File + Transfer Protocol)", RFC 141 (NIC 6726), RAND, 29 April 1971. + + Bhushan, Abhay, et al, "The File Transfer Protocol", RFC 172 + (NIC 6794), MIT-Project MAC, 23 June 1971. + + Braden, Bob, "Comments on DTP and FTP Proposals", RFC 238 (NIC 7663), + UCLA/CCN, 29 September 1971. + + Bhushan, Abhay, et al, "The File Transfer Protocol", RFC 265 + (NIC 7813), MIT-Project MAC, 17 November 1971. + + McKenzie, Alex, "A Suggested Addition to File Transfer Protocol", + RFC 281 (NIC 8163), BBN, 8 December 1971. + + Bhushan, Abhay, "The Use of "Set Data Type" Transaction in File + Transfer Protocol", RFC 294 (NIC 8304), MIT-Project MAC, + 25 January 1972. + + Bhushan, Abhay, "The File Transfer Protocol", RFC 354 (NIC 10596), + MIT-Project MAC, 8 July 1972. + + Bhushan, Abhay, "Comments on the File Transfer Protocol (RFC 354)", + RFC 385 (NIC 11357), MIT-Project MAC, 18 August 1972. + + Hicks, Greg, "User FTP Documentation", RFC 412 (NIC 12404), Utah, + 27 November 1972. + + Bhushan, Abhay, "File Transfer Protocol (FTP) Status and Further + Comments", RFC 414 (NIC 12406), MIT-Project MAC, 20 November 1972. + + Braden, Bob, "Comments on File Transfer Protocol", RFC 430 + (NIC 13299), UCLA/CCN, 7 February 1973. + + Thomas, Bob, and Bob Clements, "FTP Server-Server Interaction", + RFC 438 (NIC 13770), BBN, 15 January 1973. + + Braden, Bob, "Print Files in FTP", RFC 448 (NIC 13299), UCLA/CCN, + 27 February 1973. + + McKenzie, Alex, "File Transfer Protocol", RFC 454 (NIC 14333), BBN, + 16 February 1973. + + +Postel & Reynolds [Page 66] + + + +RFC 959 October 1985 +File Transfer Protocol + + + Bressler, Bob, and Bob Thomas, "Mail Retrieval via FTP", RFC 458 + (NIC 14378), BBN-NET and BBN-TENEX, 20 February 1973. + + Neigus, Nancy, "File Transfer Protocol", RFC 542 (NIC 17759), BBN, + 12 July 1973. + + Krilanovich, Mark, and George Gregg, "Comments on the File Transfer + Protocol", RFC 607 (NIC 21255), UCSB, 7 January 1974. + + Pogran, Ken, and Nancy Neigus, "Response to RFC 607 - Comments on the + File Transfer Protocol", RFC 614 (NIC 21530), BBN, 28 January 1974. + + Krilanovich, Mark, George Gregg, Wayne Hathaway, and Jim White, + "Comments on the File Transfer Protocol", RFC 624 (NIC 22054), UCSB, + Ames Research Center, SRI-ARC, 28 February 1974. + + Bhushan, Abhay, "FTP Comments and Response to RFC 430", RFC 463 + (NIC 14573), MIT-DMCG, 21 February 1973. + + Braden, Bob, "FTP Data Compression", RFC 468 (NIC 14742), UCLA/CCN, + 8 March 1973. + + Bhushan, Abhay, "FTP and Network Mail System", RFC 475 (NIC 14919), + MIT-DMCG, 6 March 1973. + + Bressler, Bob, and Bob Thomas "FTP Server-Server Interaction - II", + RFC 478 (NIC 14947), BBN-NET and BBN-TENEX, 26 March 1973. + + White, Jim, "Use of FTP by the NIC Journal", RFC 479 (NIC 14948), + SRI-ARC, 8 March 1973. + + White, Jim, "Host-Dependent FTP Parameters", RFC 480 (NIC 14949), + SRI-ARC, 8 March 1973. + + Padlipsky, Mike, "An FTP Command-Naming Problem", RFC 506 + (NIC 16157), MIT-Multics, 26 June 1973. + + Day, John, "Memo to FTP Group (Proposal for File Access Protocol)", + RFC 520 (NIC 16819), Illinois, 25 June 1973. + + Merryman, Robert, "The UCSD-CC Server-FTP Facility", RFC 532 + (NIC 17451), UCSD-CC, 22 June 1973. + + Braden, Bob, "TENEX FTP Problem", RFC 571 (NIC 18974), UCLA/CCN, + 15 November 1973. + + + + +Postel & Reynolds [Page 67] + + + +RFC 959 October 1985 +File Transfer Protocol + + + McKenzie, Alex, and Jon Postel, "Telnet and FTP Implementation - + Schedule Change", RFC 593 (NIC 20615), BBN and MITRE, + 29 November 1973. + + Sussman, Julie, "FTP Error Code Usage for More Reliable Mail + Service", RFC 630 (NIC 30237), BBN, 10 April 1974. + + Postel, Jon, "Revised FTP Reply Codes", RFC 640 (NIC 30843), + UCLA/NMC, 5 June 1974. + + Harvey, Brian, "Leaving Well Enough Alone", RFC 686 (NIC 32481), + SU-AI, 10 May 1975. + + Harvey, Brian, "One More Try on the FTP", RFC 691 (NIC 32700), SU-AI, + 28 May 1975. + + Lieb, J., "CWD Command of FTP", RFC 697 (NIC 32963), 14 July 1975. + + Harrenstien, Ken, "FTP Extension: XSEN", RFC 737 (NIC 42217), SRI-KL, + 31 October 1977. + + Harrenstien, Ken, "FTP Extension: XRSQ/XRCP", RFC 743 (NIC 42758), + SRI-KL, 30 December 1977. + + Lebling, P. David, "Survey of FTP Mail and MLFL", RFC 751, MIT, + 10 December 1978. + + Postel, Jon, "File Transfer Protocol Specification", RFC 765, ISI, + June 1980. + + Mankins, David, Dan Franklin, and Buzz Owen, "Directory Oriented FTP + Commands", RFC 776, BBN, December 1980. + + Padlipsky, Michael, "FTP Unique-Named Store Command", RFC 949, MITRE, + July 1985. + + + + + + + + + + + + + + +Postel & Reynolds [Page 68] + + + +RFC 959 October 1985 +File Transfer Protocol + + +REFERENCES + + [1] Feinler, Elizabeth, "Internet Protocol Transition Workbook", + Network Information Center, SRI International, March 1982. + + [2] Postel, Jon, "Transmission Control Protocol - DARPA Internet + Program Protocol Specification", RFC 793, DARPA, September 1981. + + [3] Postel, Jon, and Joyce Reynolds, "Telnet Protocol + Specification", RFC 854, ISI, May 1983. + + [4] Reynolds, Joyce, and Jon Postel, "Assigned Numbers", RFC 943, + ISI, April 1985. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel & Reynolds [Page 69] + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_ACCESS_DENIED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,26 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +GiriÅŸ qadaÄŸandır. + +

    +Hal-hazirda giriş nəzarəti qaydaları sorğunuzun cavablandırılmasına qadağa qoyur. +Qadağanın düz olmadığı təqdirdə, xahiş edirik, İnternet servis xidmətçinizə müraciət +edəsiniz. +

+

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_CACHE_ACCESS_DENIED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,33 @@ + + +SÆHV:KeÅŸdÉ™n istifadÉ™ qadaÄŸandır. + + + +

SÆHV

+

Keşdən istifadə qadağandır

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +KeÅŸdÉ™n istifaÉ™ qadaÄŸandır + +
+

+ +

Üzr istəyirik, Siz aşağıdakı: +

    %U
+unvanına, keşdə identifikasiyanı keçməyəcəyiniz təqdirdə sorğu verə bilməzsiniz. +

+ +

+Bunun üçün sizə Netscape 2.0 və ya daha yuxarı versiyalı, Microsoft Internet +Explorer 3.0 və ya daha yuxarı versiyalı, ya da HTTP/1.1protokoluna uyğun brauzer tələb olunur. İdentifikasiya ilə çətinlik olduğu halda, xahiş edirik, KEŞİN sistem administratoru ilə əlaqə saxlayın və ya şifrənizi +dəyişdirin. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_CACHE_MGR_ACCESS_DENIED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,32 @@ + + +SÆHV: KeÅŸ idarÉ™etmÉ™sinÉ™ giriÅŸ qadaÄŸandır + + + +

SÆHV

+

Keş idarəetməsinə giriş qadağandır

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +KeÅŸ idarÉ™etmÉ™sinÉ™ giriÅŸ qadaÄŸandır + +
+

+ +

Üzr istəyirik, Siz aşağıdakı: +

    %U
+unvanına, keşdə identifikasiyanı keçməyəcəyiniz təqdirdə sorğu verə bilməzsiniz. +

+ +

+Bunun üçün sizə Netscape 2.0 və ya daha yuxarı versiyalı, Microsoft Internet +Explorer 3.0 və ya daha yuxarı versiyalı, ya da HTTP/1.1protokoluna uyğun brauzer tələb olunur. İdentifikasiya ilə çətinlik olduğu halda, xahiş edirik, KEŞİN sistem administratoru ilə əlaqə saxlayın və ya Siz administrator olduğunuz halda keş idarəetmə interfeysi ilə bağlı sənədləri oxuyun və keş jurnalını daha ətraflı səhv qeydləri üçün yoxlayın. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_CANNOT_FORWARD Wed Feb 14 13:38:00 2007 @@ -0,0 +1,27 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı.

+
+

URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +Hal-hazırda sorÄŸunuzu yönlÉ™dirmÉ™k mümkün deyildir. + +
+ +

+Sorğu hədəf serverə, və ya digər yuxarı səviyyəli keş serverələrə göndərilə bilməz.Səhvin mümkün səbəbləri: +

    +
  • KeÅŸ administratoru bu keÅŸin hÉ™dÉ™f serverlÉ™ri birbaÅŸa sorÄŸulamasını qadaÄŸan etmiÅŸdir vÉ™ ya +
  • Bütün yuxarı sÉ™viyyÉ™li keÅŸ-serverlÉ™r hal-hazırda É™lçatmazdılar. +
+

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_CONNECT_FAIL Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı.

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +ÆlaqÉ™ yaratmaq mümkün olmadı. + +
+ +

+Sistemdən gələn cavab: +

    %E
+ +

+Hədəf server və ya şəbəkə cavab vermir.Xahiş edirik, sorğunu təkrarlayın. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_DNS_FAIL Wed Feb 14 13:38:00 2007 @@ -0,0 +1,35 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +
+%U +

+Aşağıdakı səhv baş vermişdir: +

+Uzaqda yerləşən kompyuterin İP adresini təyin mumkun olmadı +%H +
+ + +

+Domen Adları serverindən gələn cavab: +

+%z +
+ +

+Bu o deməkdir ki: +

+Keş URL-də göstərilmiş serveri təyin edə bilmir.
+Adresin düzgün yazıldığını yoxlayın.
+
+

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_ESI Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +ERROR: The requested URL could not be retrieved + + +

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

+ESI Processing failed. +
+ +

+The ESI processor returned: +

+%Z +
+ +

+This means that: +

+ The surrogate was not able to process the ESI template. Please report this error to the webmaster. 
+
+

Your webmaster is %w. --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FORWARDING_DENIED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,25 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı.

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +YönlÉ™ndirmÉ™ qadaÄŸandır. + +
+ +

+Sibling tipli əlaqə yaratmaq cəhdinə görə keş sorğunuzu yönləndirməyəcəkdir. Güman ki, %i müştərisi tələblərə uyğun olmayan keşdir. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_DISABLED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +FTP protokolu qadaÄŸandır. + +
+ +

+Bu keş FTP protokolunu təmin etmir. +

+ +

+Sizin keÅŸ administratorunuz %w +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_FAILURE Wed Feb 14 13:38:00 2007 @@ -0,0 +1,25 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı FTP protokolu uzrə aşağıdakı səhv baş vermişdir: +%U +

+Keş FTP-nin növbəti əmrini göndərmişdir: +


+	%f
+
+və alınan cavab +

+	%F
+
+

+Mümkün səbəblərdən biri sorğu zamanı istifadə olunan FTP adresin RFC 1738 standartlarına uyğun gəlməməsidir. Problemlə bağlı informasiyanı %B adresində axtarın. +

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_FORBIDDEN Wed Feb 14 13:38:00 2007 @@ -0,0 +1,27 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı FTP protokolu uzrə aşağıdakı səhv baş vermişdir: +%U +

+SQUID FTP-nin növbəti əmrini göndərmişdir: +


+	%f
+
+və alınan cavab +

+	%F
+
+

+	%g
+
+ +

+Sizin keÅŸ administratorunuz %w + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_NOT_FOUND Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı FTP protokolu uzrə aşağıdakı səhv baş vermişdir: +%U +

+Keş FTP-nin növbəti əmrini göndərmişdir: +


+	%f
+
+və alınan cavab +

+	%F
+
+

+	%g
+
+

+Mümkün sÉ™bÉ™blÉ™rdÉ™n biri sorÄŸu zamanı istifadÉ™ olunan FTP adresin RFC 1738 standartlarına uyÄŸun gÉ™lmÉ™mÉ™sidir. ÆgÉ™r sÉ™bÉ™b budursa faylı%B adresindÉ™ tapa bilersiniz. +

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_PUT_CREATED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,12 @@ + + +FTP PUT müvəfəqiyyətlə başa çatdı: Fayl yarandı + + +

ÆmÉ™liyyat müvÉ™fÉ™qiyyÉ™tlÉ™ baÅŸa çatdı

+

Fayl yarandı

+
+

+

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_PUT_ERROR Wed Feb 14 13:38:00 2007 @@ -0,0 +1,27 @@ + + +SÆHV: FTP PUT/yüklÉ™mÉ™ uÄŸursuzluqla baÅŸa çatdı + + +

SÆHV

+

FTP PUT/yükləmə uğursuzluqla başa çatdı.

+
+

+Faylı adresə yükləyərkən: +%U +

+SQUID növbəti FTP əmri göndərmişdir: +


+        %f
+
+və alınan cavab +

+        %F
+
+

+

+Fayl yolunu, fayla olan icazələrinizi, boş yeri yoxlayın və bir daha təkrar edin.
+
+

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_PUT_MODIFIED Wed Feb 14 13:38:00 2007 @@ -0,0 +1,12 @@ + + +FTP PUT müvəfəqiyyətlə başa çatdı: Fayl yeniləndi + + +

ÆmÉ™liyyat müvÉ™fÉ™qiyyÉ™tlÉ™ baÅŸa çatdı.

+

Fayl yeniləndi.

+
+

+

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_FTP_UNAVAILABLE Wed Feb 14 13:38:00 2007 @@ -0,0 +1,26 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı FTP serverin həddən ziyadə yüklü olduğu məlum olub: +%U +

+Keş FTP-nin növbəti əmrini göndərmişdir: +


+	%f
+
+və alınan cavab +

+	%F
+
+

+	%g
+
+

+Sizin keÅŸ administratorunuz %w + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_ICAP_FAILURE Wed Feb 14 13:38:00 2007 @@ -0,0 +1,33 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +ICAP protocol error. + +
+ +

+The system returned: +

    %E
+ +

+This means that: +Some aspect of the ICAP communication failed. Possible problems: +

    +
  • ICAP server is not reachable. +
  • Illegal response from ICAP server. +
+

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_INVALID_REQ Wed Feb 14 13:38:00 2007 @@ -0,0 +1,34 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı.

+
+

+Sorğu yerinə yetirilən zaman: +

+%R
+
+

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +SÉ™hv sorÄŸu. + +
+ +

+HTTP sorğunun bəzi aspektləri səhvdir. Mümkün problemlər: +

    +
  • (GET, POST) sorÄŸusunun metodu mÉ™lum deyil vÉ™ ya umumiyyÉ™tlÉ™ yoxdur. +
  • URL yoxdur +
  • HTTP identifikator yoxdur(HTTP/1.0) +
  • SorÄŸu hÉ™ddÉ™n ziyadÉ™ böyükdür +
  • POST vÉ™ PUT sorÄŸuları üçün Content-Length göstÉ™rilmÉ™miÅŸdir +
  • Server adında qadaÄŸan edilmiÅŸ simvol; altxÉ™tt yol verilmÉ™zdir +
+

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_INVALID_RESP Wed Feb 14 13:38:00 2007 @@ -0,0 +1,24 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı.

+
+

+Sorğu yerinə yetirilən zaman: +

+%R
+
+

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +SÉ™hv cavab. + +
+ +

+SorÄŸu göndÉ™rilÉ™n serverdÉ™n gÉ™lÉ™n cavab anlaşılmazdı vÉ™ ya dÉ™yiÅŸdirilib. SÉ™hifÉ™ operatoru ilÉ™ É™laqÉ™ yaradın. TÉ™lÉ™b olunduÄŸu halda keÅŸ administratoru sizÉ™ daha geniÅŸ mÉ™lumat verÉ™ bilÉ™r. Sizin keÅŸ administratorunuz %w --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_INVALID_URL Wed Feb 14 13:38:00 2007 @@ -0,0 +1,29 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı.

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +SÉ™hv URL: + +
+ +

+URL-nin bəzi aspektləri səhvdir. Mümkün problemlər: +

    +
  • GiriÅŸ protokol yoxdur vÉ™ ya sÉ™hvdir ("http://'' vÉ™ ya oxÅŸar olmalıdır) +
  • Server adı yoxdur +
  • Server adında qadaÄŸan edilmiÅŸ simvol; altxÉ™tt vÉ™ s. yol verilmÉ™zdir. +
+

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_LIFETIME_EXP Wed Feb 14 13:38:00 2007 @@ -0,0 +1,24 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +QoÅŸulma müddÉ™ti bitdi. + +
+ +

+Keş maksimum qoşulma müddəti həddini keçmə səbəbindən əlaqəni kəsdi. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_NO_RELAY Wed Feb 14 13:38:00 2007 @@ -0,0 +1,24 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +Wais ötürücü tÉ™yin edilmÉ™miÅŸdir. + +
+ +

+Bu keş serveri üçün WAIS ötürücü təyin edilməyib. Administratora əlaqə saxlayın. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_ONLY_IF_CACHED_MISS Wed Feb 14 13:38:00 2007 @@ -0,0 +1,25 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +Obyekt keÅŸdÉ™ tapılmadı vÉ™ only-if-cachedÉ™mri tÉ™yin olunmuÅŸdur. + +
+ +

+Siz only-if-cached əmri ilə sorğu göndərmisiniz. +Obyekt keşdə tapılmadı, və ya only-if-cachedəmri ilə qadağan olunmuş obyektin yenilənməsi tələb olunur. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_READ_ERROR Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +Oxunma sÉ™hvi + +
+ +

+Sistem cavab verir: +

    %E
+ +

+Məlumatlar şəbəkədən oxunan zaman səhv baş vermişdir. Xahiş edirik, sorğunuzu təkrar edin. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_READ_TIMEOUT Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +GözlÉ™mÉ™ müddÉ™ti bitmiÅŸdir. + +
+ +

+Sistemin cavabı: +

    %E
+ +

+Məlumatlar şəbəkədən oxunan zaman gözləmə müddəti bitmişdir. Şəbəkə və ya server işləmir, yaxud həddən ziyadə yüklənmişdir. Xahiş edirik, sorğunu təkrar edin. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_SHUTTING_DOWN Wed Feb 14 13:38:00 2007 @@ -0,0 +1,20 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • +

    +Keş hal-hazırda işini dayandırır və bu səbəbdən sizin sorğunuzu cavablandıra bilməyəcək. Xahiş edirik, sorğunuzu tezliklə bir daha təkrarlayın.

+

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_SOCKET_FAILURE Wed Feb 14 13:38:00 2007 @@ -0,0 +1,29 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +É™laqÉ™ xÉ™tası. + +
+ +

+: +

    %E
+ +

+SQUID əlaqə yarada bilmir, mümkün səbəblərdən biri, server həddindən ziyadə yüklənmiş olmasıdır. +Xahiş edirik,sorğunu təkrar edin. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_TOO_BIG Wed Feb 14 13:38:00 2007 @@ -0,0 +1,23 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: + + +

+Sorğu və ya cavab həddən ziyadə böyükdür.
+ÆgÉ™r siz POST vÉ™ ya PUT sorÄŸusunu edirsinizsÉ™, sizin göndÉ™rmÉ™k istÉ™diniz fayl hÉ™ddÉ™n ziyadÉ™ böyükdür. ÆgÉ™r siz GET sorÄŸusunu edirsinizsÉ™, sizin yüklÉ™mÉ™k istÉ™diyiniz fayl hÉ™ddÉ™n ziyadÉ™ böyükdür. Bu limitlÉ™r sizin keÅŸi idarÉ™ edÉ™n Internet xidmÉ™ti provayderi tÉ™rÉ™findÉ™n tÉ™yin olunmuÅŸdur. ÆgÉ™r bunun sÉ™hv olduÄŸunu düşünürsünüzsÉ™ onlarla É™laqÉ™ saxlayın. +

+ +
+Sizin keÅŸ administratorunuz %w + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_UNSUP_REQ Wed Feb 14 13:38:00 2007 @@ -0,0 +1,26 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +DÉ™stÉ™klÉ™nmÉ™yÉ™n sorÄŸu metodu vÉ™ protokol. + +
+ +

+SQUID bütün sorğu metodları və bütün protokollardəstəkləmir. +Məsələn,Gopher protokolu üzrə siz POST sorğu metodunu yerinə yetirə bilməzsiniz. +

+ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_URN_RESOLVE Wed Feb 14 13:38:00 2007 @@ -0,0 +1,26 @@ + + +SÆHV: SorÄŸulanan URN ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URN üçün URL ilə əlaqə yaradılmadı

+
+

+URN ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +URN tapılmadı +
    +(Cannot Resolve URN) +
    +
+ +

+%T texnologiyasından çox şey gözləməyə dəyməz :) +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_WRITE_ERROR Wed Feb 14 13:38:00 2007 @@ -0,0 +1,28 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +Yazma sÉ™hvi + +
+ +

+Sistemin cavabı: +

    %E
+ +

+İnformasiya şəbəkəyə ötürülərkən xəta olmuşdur.Xahiş edirik, sorğunu təkrar edin. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/ERR_ZERO_SIZE_OBJECT Wed Feb 14 13:38:00 2007 @@ -0,0 +1,24 @@ + + +SÆHV: SorÄŸulanan URL ilÉ™ É™laqÉ™ yaradılmadı + + +

SÆHV

+

Sorğulanan URL ilə əlaqə yaradılmadı

+
+

+URL ilə əlaqə zamanı: +%U +

+Aşağıdakı səhv baş vermişdir: +

    +
  • + +Sıfır uzunluqlu cavab + +
+ +

+SQUID bu sorğu üçün heç bir məlumat almadı. +

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/README Wed Feb 14 13:38:00 2007 @@ -0,0 +1,2 @@ +Thank you to Rauf Kuliyev for +creating these error pages in Azerbaijani! --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Azerbaijani/generic Wed Feb 14 13:38:00 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Bulgarian/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Catalan/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Czech/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Danish/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Dutch/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/English/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Estonian/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Estonian/generic Wed Feb 14 13:38:00 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Finnish/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/French/.cvsignore Wed Feb 14 13:38:00 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/German/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Greek/ERR_ESI Wed Feb 14 13:38:01 2007 @@ -0,0 +1,28 @@ + + +ERROR: The requested URL could not be retrieved + + +

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

+ESI Processing failed. +
+ +

+The ESI processor returned: +

+%Z +
+ +

+This means that: +

+ The surrogate was not able to process the ESI template. Please report this error to the webmaster. 
+
+

Your webmaster is %w. --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Greek/ERR_ICAP_FAILURE Wed Feb 14 13:38:01 2007 @@ -0,0 +1,33 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +ICAP protocol error. + +
+ +

+The system returned: +

    %E
+ +

+This means that: +Some aspect of the ICAP communication failed. Possible problems: +

    +
  • ICAP server is not reachable. +
  • Illegal response from ICAP server. +
+

+ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Greek/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Hebrew/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Hebrew/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Hungarian/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Italian/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Italian/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERRORE: La URL richiesta non può essere recuperata + + +

ERRORE

+

La URL richiesta non può essere recuperata

+
+

+Mentre si cercava di recuperare la URL: +%U +

+È avvenuto il seguente errore: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+Il sistema ha riportato: +

    %E
+ +

+Questo significa che: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Japanese/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Korean/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Lithuanian/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Lithuanian/ERR_ESI Wed Feb 14 13:38:01 2007 @@ -0,0 +1,28 @@ + + +ERROR: The requested URL could not be retrieved + + +

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

+ESI Processing failed. +
+ +

+The ESI processor returned: +

+%Z +
+ +

+This means that: +

+ The surrogate was not able to process the ESI template. Please report this error to the webmaster. 
+
+

Your webmaster is %w. --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Lithuanian/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Polish/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Portuguese/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Romanian/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Romanian/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Russian-1251/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Russian-1251/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Russian-koi8-r/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/errors/Russian-koi8-r/generic Wed Feb 14 13:38:01 2007 @@ -0,0 +1,31 @@ + + +ERROR: The requested URL could not be retrieved + + +

ERROR

+

The requested URL could not be retrieved

+
+

+While trying to retrieve the URL: +%U +

+The following error was encountered: +

    +
  • + +@SHORT_DESCRIPTION@ + +
+ +

+The system returned: +

    %E
+ +

+This means that: +

+    @LONG_DESCRIPTION@
+
+

+ --- squid3/errors/Serbian/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Simplify_Chinese/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Slovak/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Spanish/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Swedish/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Traditional_Chinese/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/errors/Turkish/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/LDAP/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/ldap.h ]; then + exit 0 +fi +if [ -f /usr/include/winldap.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/MSNT/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,9 @@ +#!/bin/sh +# Don't build on Windows +if [ -f /usr/include/w32api/windows.h ]; then + exit 1 +fi +if [ -f /usr/include/windows.h ]; then + exit 1 +fi +exit 0 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/NCSA/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/PAM/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -f /usr/include/security/pam_appl.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/SASL/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -f /usr/include/sasl.h -o -f /usr/include/sasl/sasl.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/SMB/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -x ${SAMBAPREFIX:-/usr/local/samba}/bin/smbclient ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/YP/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -f /usr/include/rpcsvc/yp_prot.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/getpwnam/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -f /usr/include/pwd.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/mswin_sspi/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +mswin_auth.exe +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/mswin_sspi/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/w32api/windows.h ]; then + exit 0 +fi +if [ -f /usr/include/windows.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/basic_auth/multi-domain-NTLM/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 --- squid3/helpers/basic_auth/winbind/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,4 +0,0 @@ -.cvsignore -Makefile.in -Makefile -.deps --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +digest_ldap_auth +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/Makefile.am Wed Feb 14 13:38:01 2007 @@ -0,0 +1,17 @@ +# +# Makefile for the Squid Object Cache server +# +# $Id: Makefile.am,v 1.1.14.2 2006/09/29 23:15:49 dwsquid Exp $ +# +# Uncomment and customize the following to suit your needs: +# + +libexec_PROGRAMS = digest_ldap_auth +digest_ldap_auth_SOURCES = digest_pw_auth.c \ + digest_common.h \ + ldap_backend.c \ + ldap_backend.h +INCLUDES = -I. -I$(top_builddir)/include -I$(top_srcdir)/include \ + -I$(top_srcdir)/src/ + +LDADD = -L$(top_builddir)/lib -lmiscutil $(LIB_LDAP) $(LIB_LBER) $(CRYPTLIB) $(XTRA_LIBS) $(SSLLIB) --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/ldap.h ]; then + exit 0 +fi +if [ -f /usr/include/winldap.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/digest_common.h Wed Feb 14 13:38:01 2007 @@ -0,0 +1,57 @@ +/* + * digest_common.h + * + * AUTHOR: Robert Collins. + * + * Digest helper API details. + * + * Copyright (c) 2003 Robert Collins + */ + +#ifndef _SQUID_DIGEST_COMMON_H_ +#define _SQUID_DIGEST_COMMON_H_ + +#include "config.h" +#if HAVE_STDIO_H +#include +#endif +#if HAVE_STDLIB_H +#include +#endif +#if HAVE_UNISTD_H +#include +#endif +#if HAVE_STRING_H +#include +#endif +#if HAVE_SYS_TYPES_H +#include +#endif +#if HAVE_SYS_STAT_H +#include +#endif +#if HAVE_CRYPT_H +#include +#endif + +#include "util.h" +#include "hash.h" +#include "rfc2617.h" + +typedef struct _request_data { + char *user; + char *realm; + char *password; + HASHHEX HHA1; + int parsed; + int error; +} RequestData; + +/* to use a backend, include your backend.h file + * and define thusly: + * #define ProcessArguments(A, B) MyHandleArguments(A,B) + * #define GetHHA1(A) MyGetHHA1(A) + */ +typedef void HandleArguments(int, char **); +typedef void HHA1Creator(RequestData *); +#endif /* _SQUID_DIGEST_COMMON_H_ */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/digest_pw_auth.c Wed Feb 14 13:38:01 2007 @@ -0,0 +1,102 @@ +/* + * digest_pw_auth.c + * + * AUTHOR: Robert Collins. Based on ncsa_auth.c by Arjan de Vet + * + * LDAP backend extension by Flavio Pescuma, MARA Systems AB + * + * Example digest authentication program for Squid, based on the original + * proxy_auth code from client_side.c, written by + * Jon Thackray . + * + * - comment lines are possible and should start with a '#'; + * - empty or blank lines are possible; + * - file format is username:password + * + * To build a directory integrated backend, you need to be able to + * calculate the HA1 returned to squid. To avoid storing a plaintext + * password you can calculate MD5(username:realm:password) when the + * user changes their password, and store the tuple username:realm:HA1. + * then find the matching username:realm when squid asks for the + * HA1. + * + * This implementation could be improved by using such a triple for + * the file format. However storing such a triple does little to + * improve security: If compromised the username:realm:HA1 combination + * is "plaintext equivalent" - for the purposes of digest authentication + * they allow the user access. Password syncronisation is not tackled + * by digest - just preventing on the wire compromise. + * + * Copyright (c) 2003 Robert Collins + */ + +#include "digest_common.h" +#include "ldap_backend.h" +#define PROGRAM_NAME "digest_ldap_auth" + + +void +GetHHA1(RequestData * requestData) +{ + LDAPHHA1(requestData); +} + +static void +ParseBuffer(char *buf, RequestData * requestData) +{ + char *p; + requestData->parsed = 0; + if ((p = strchr(buf, '\n')) != NULL) + *p = '\0'; /* strip \n */ + if ((requestData->user = strtok(buf, "\"")) == NULL) + return; + if ((requestData->realm = strtok(NULL, "\"")) == NULL) + return; + if ((requestData->realm = strtok(NULL, "\"")) == NULL) + return; + requestData->parsed = -1; +} + +static void +OutputHHA1(RequestData * requestData) +{ + requestData->error = 0; + GetHHA1(requestData); + if (requestData->error) { + printf("ERR No such user\n"); + return; + } + printf("%s\n", requestData->HHA1); +} + +static void +DoOneRequest(char *buf) +{ + RequestData requestData; + ParseBuffer(buf, &requestData); + if (!requestData.parsed) { + printf("ERR\n"); + return; + } + OutputHHA1(&requestData); +} + +void +ProcessArguments(int argc, char **argv) +{ + int i; + i = LDAPArguments(argc, argv); + if (i) + exit(i); +} + +int +main(int argc, char **argv) +{ + char buf[256]; + setbuf(stdout, NULL); + ProcessArguments(argc, argv); + while (fgets(buf, 256, stdin) != NULL) + DoOneRequest(buf); + exit(0); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/ldap_backend.c Wed Feb 14 13:38:01 2007 @@ -0,0 +1,655 @@ +/* + * + * + * + * ldap_backend.c + * AUTHOR: Flavio Pescuma, MARA Systems AB + */ + +#define LDAP_DEPRECATED 1 + +#include +#include +#include +#include +#include "ldap_backend.h" + +#ifdef _SQUID_MSWIN_ /* Native Windows port and MinGW */ + +#define snprintf _snprintf +#include +#include +#ifndef LDAPAPI +#define LDAPAPI __cdecl +#endif +#ifdef LDAP_VERSION3 +#ifndef LDAP_OPT_X_TLS +#define LDAP_OPT_X_TLS 0x6000 +#endif +/* Some tricks to allow dynamic bind with ldap_start_tls_s entry point at + run time. + */ +#undef ldap_start_tls_s +#if LDAP_UNICODE +#define LDAP_START_TLS_S "ldap_start_tls_sW" +typedef WINLDAPAPI ULONG (LDAPAPI * PFldap_start_tls_s) (IN PLDAP, OUT PULONG, OUT LDAPMessage **, IN PLDAPControlW *, IN PLDAPControlW *); +#else +#define LDAP_START_TLS_S "ldap_start_tls_sA" +typedef WINLDAPAPI ULONG (LDAPAPI * PFldap_start_tls_s) (IN PLDAP, OUT PULONG, OUT LDAPMessage **, IN PLDAPControlA *, IN PLDAPControlA *); +#endif /* LDAP_UNICODE */ +PFldap_start_tls_s Win32_ldap_start_tls_s; +#define ldap_start_tls_s(l,s,c) Win32_ldap_start_tls_s(l,NULL,NULL,s,c) +#endif /* LDAP_VERSION3 */ + +#else + +#include +#include + +#endif +#define PROGRAM_NAME "digest_pw_auth(LDAP_backend)" + +/* Globals */ + +static LDAP *ld = NULL; +static char *passattr = NULL; +static char *ldapServer = NULL; +static char *userbasedn = NULL; +static char *userdnattr = NULL; +static char *usersearchfilter = NULL; +static char *binddn = NULL; +static char *bindpasswd = NULL; +static char *delimiter = ":"; +static int encrpass = 0; +static int searchscope = LDAP_SCOPE_SUBTREE; +static int persistent = 0; +static int noreferrals = 0; +static int debug = 0; +static int port = LDAP_PORT; +static int strip_nt_domain = 0; +static int aliasderef = LDAP_DEREF_NEVER; +#if defined(NETSCAPE_SSL) +static char *sslpath = NULL; +static int sslinit = 0; +#endif +static int connect_timeout = 0; +static int timelimit = LDAP_NO_LIMIT; + +#ifdef LDAP_VERSION3 +/* Added for TLS support and version 3 */ +static int use_tls = 0; +static int version = -1; +#endif + +static void ldapconnect(void); +static int readSecret(char *filename); + +/* Yuck.. we need to glue to different versions of the API */ + +#if defined(LDAP_API_VERSION) && LDAP_API_VERSION > 1823 +static void +squid_ldap_set_aliasderef(int deref) +{ + ldap_set_option(ld, LDAP_OPT_DEREF, &deref); +} +static void +squid_ldap_set_referrals(int referrals) +{ + int *value = referrals ? LDAP_OPT_ON : LDAP_OPT_OFF; + ldap_set_option(ld, LDAP_OPT_REFERRALS, value); +} +static void +squid_ldap_set_timelimit(int timelimit) +{ + ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &timelimit); +} +static void +squid_ldap_set_connect_timeout(int timelimit) +{ +#if defined(LDAP_OPT_NETWORK_TIMEOUT) + struct timeval tv; + tv.tv_sec = timelimit; + tv.tv_usec = 0; + ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv); +#elif defined(LDAP_X_OPT_CONNECT_TIMEOUT) + timelimit *= 1000; + ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timelimit); +#endif +} + +#else +static int +squid_ldap_errno(LDAP * ld) +{ + return ld->ld_errno; +} +static void +squid_ldap_set_aliasderef(int deref) +{ + ld->ld_deref = deref; +} +static void +squid_ldap_set_referrals(int referrals) +{ + if (referrals) + ld->ld_options |= ~LDAP_OPT_REFERRALS; + else + ld->ld_options &= ~LDAP_OPT_REFERRALS; +} +static void +squid_ldap_set_timelimit(int timelimit) +{ + ld->ld_timelimit = timelimit; +} +static void +squid_ldap_set_connect_timeout(int timelimit) +{ + fprintf(stderr, "Connect timeouts not supported in your LDAP library\n"); +} +static void +squid_ldap_memfree(char *p) +{ + free(p); +} + +#endif + +#ifdef LDAP_API_FEATURE_X_OPENLDAP +#if LDAP_VENDOR_VERSION > 194 +#define HAS_URI_SUPPORT 1 +#endif +#endif + +static int +ldap_escape_value(char *escaped, int size, const char *src) +{ + int n = 0; + while (size > 4 && *src) { + switch (*src) { + case '*': + case '(': + case ')': + case '\\': + n += 3; + size -= 3; + if (size > 0) { + *escaped++ = '\\'; + snprintf(escaped, 3, "%02x", (int) *src++); + escaped += 2; + } + break; + default: + *escaped++ = *src++; + n++; + size--; + } + } + *escaped = '\0'; + return n; +} + +static char * +getpassword(char *login, char *realm) +{ + LDAPMessage *res = NULL; + LDAPMessage *entry; + char **values = NULL; + char **value = NULL; + char *password = NULL; + int retry = 0; + char filter[8192]; + char searchbase[8192]; + int rc = -1; + if (ld) { + if (usersearchfilter) { + char escaped_login[1024]; + snprintf(searchbase, sizeof(searchbase), "%s", userbasedn); + ldap_escape_value(escaped_login, sizeof(escaped_login), login); + snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); + + retrysrch: + if (debug) + fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); + + rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res); + if (rc != LDAP_SUCCESS) { + if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { + /* Everything is fine. This is expected when referrals + * are disabled. + */ + rc = LDAP_SUCCESS; + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); +#if defined(NETSCAPE_SSL) + if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { + int sslerr = PORT_GetError(); + fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); + } +#endif + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error, trying to recover'%s'\n", ldap_err2string(rc)); + ldap_msgfree(res); + /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ + if (!retry) { + retry++; + ldap_unbind(ld); + ld = NULL; + ldapconnect(); + goto retrysrch; + } + return NULL; + + } + } + } else if (userdnattr) { + sprintf(searchbase, "%s=%s, %s", userdnattr, login, userbasedn); + + retrydnattr: + if (debug) + fprintf(stderr, "searchbase '%s'\n", searchbase); + rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res); + } + if (rc == LDAP_SUCCESS) { + entry = ldap_first_entry(ld, res); + if (entry) + values = ldap_get_values(ld, entry, passattr); + else { + ldap_msgfree(res); + return NULL; + } + if (!values) { + if (debug) + printf("No attribute value found\n"); + ldap_msgfree(res); + return NULL; + } + value = values; + while (*value) { + if (encrpass) { + if (strcmp(strtok(*value, delimiter), realm) == 0) { + password = strtok(NULL, delimiter); + break; + } + } else { + password = *value; + break; + } + value++; + } + if (debug) + printf("password: %s\n", password); + if (password) + password = strdup(password); + ldap_value_free(values); + ldap_msgfree(res); + return password; + } else { + fprintf(stderr, PROGRAM_NAME " WARNING, LDAP error '%s'\n", ldap_err2string(rc)); + /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ + if (!retry) { + retry++; + ldap_unbind(ld); + ld = NULL; + ldapconnect(); + goto retrydnattr; + } + return NULL; + } + } + return NULL; +} + + + +static void +ldapconnect(void) +{ + int rc; + +/* On Windows ldap_start_tls_s is available starting from Windows XP, + so we need to bind at run-time with the function entry point + */ +#ifdef _SQUID_MSWIN_ + if (use_tls) { + + HMODULE WLDAP32Handle; + + WLDAP32Handle = GetModuleHandle("wldap32"); + if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { + fprintf( stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); + exit(1); + } + } +#endif + + if (ld == NULL) { +#if HAS_URI_SUPPORT + if (strstr(ldapServer, "://") != NULL) { + rc = ldap_initialize(&ld, ldapServer); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); + } + } else +#endif +#if NETSCAPE_SSL + if (sslpath) { + if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { + fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", + sslpath); + exit(1); + } else { + sslinit++; + } + if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { + fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", + ldapServer, port); + exit(1); + } + } else +#endif + if ((ld = ldap_init(ldapServer, port)) == NULL) { + fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); + } + if (connect_timeout) + squid_ldap_set_connect_timeout(connect_timeout); + +#ifdef LDAP_VERSION3 + if (version == -1) { + version = LDAP_VERSION2; + } + if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) + != LDAP_SUCCESS) { + fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", + version); + ldap_unbind(ld); + ld = NULL; + } + if (use_tls && (version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { + fprintf(stderr, "Could not Activate TLS connection\n"); + ldap_unbind(ld); + ld = NULL; + } +#endif + squid_ldap_set_timelimit(timelimit); + squid_ldap_set_referrals(!noreferrals); + squid_ldap_set_aliasderef(aliasderef); + if (binddn && bindpasswd && *binddn && *bindpasswd) { + rc = ldap_simple_bind_s(ld, binddn, bindpasswd); + if (rc != LDAP_SUCCESS) { + fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); + ldap_unbind(ld); + ld = NULL; + } + } + if (debug) + fprintf(stderr, "Connected OK\n"); + } +} +int +LDAPArguments(int argc, char **argv) +{ + setbuf(stdout, NULL); + + while (argc > 1 && argv[1][0] == '-') { + char *value = ""; + char option = argv[1][1]; + switch (option) { + case 'P': + case 'R': + case 'z': + case 'Z': + case 'g': + case 'e': + case 'S': + break; + default: + if (strlen(argv[1]) > 2) { + value = argv[1] + 2; + } else if (argc > 2) { + value = argv[2]; + argv++; + argc--; + } else + value = ""; + break; + } + argv++; + argc--; + switch (option) { + case 'H': +#if !HAS_URI_SUPPORT + fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); + return 1; +#endif + /* Fall thru to -h */ + case 'h': + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + break; + case 'A': + passattr = value; + break; + case 'e': + encrpass = 1; + break; + case 'l': + delimiter = value; + break; + case 'b': + userbasedn = value; + break; + case 'F': + usersearchfilter = value; + break; + case 'u': + userdnattr = value; + break; + case 's': + if (strcmp(value, "base") == 0) + searchscope = LDAP_SCOPE_BASE; + else if (strcmp(value, "one") == 0) + searchscope = LDAP_SCOPE_ONELEVEL; + else if (strcmp(value, "sub") == 0) + searchscope = LDAP_SCOPE_SUBTREE; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); + return 1; + } + break; + case 'S': +#if defined(NETSCAPE_SSL) + sslpath = value; + if (port == LDAP_PORT) + port = LDAPS_PORT; +#else + fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); + return 1; +#endif + break; + case 'c': + connect_timeout = atoi(value); + break; + case 't': + timelimit = atoi(value); + break; + case 'a': + if (strcmp(value, "never") == 0) + aliasderef = LDAP_DEREF_NEVER; + else if (strcmp(value, "always") == 0) + aliasderef = LDAP_DEREF_ALWAYS; + else if (strcmp(value, "search") == 0) + aliasderef = LDAP_DEREF_SEARCHING; + else if (strcmp(value, "find") == 0) + aliasderef = LDAP_DEREF_FINDING; + else { + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); + return 1; + } + break; + case 'D': + binddn = value; + break; + case 'w': + bindpasswd = value; + break; + case 'W': + readSecret(value); + break; + case 'P': + persistent = !persistent; + break; + case 'p': + port = atoi(value); + break; + case 'R': + noreferrals = !noreferrals; + break; +#ifdef LDAP_VERSION3 + case 'v': + switch (atoi(value)) { + case 2: + version = LDAP_VERSION2; + break; + case 3: + version = LDAP_VERSION3; + break; + default: + fprintf(stderr, "Protocol version should be 2 or 3\n"); + return 1; + } + break; + case 'Z': + if (version == LDAP_VERSION2) { + fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", + version); + return 1; + } + version = LDAP_VERSION3; + use_tls = 1; + break; +#endif + case 'd': + debug = 1; + break; + case 'E': + strip_nt_domain = 1; + break; + default: + fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); + return 1; + } + } + + while (argc > 1) { + char *value = argv[1]; + if (ldapServer) { + int len = strlen(ldapServer) + 1 + strlen(value) + 1; + char *newhost = malloc(len); + snprintf(newhost, len, "%s %s", ldapServer, value); + free(ldapServer); + ldapServer = newhost; + } else { + ldapServer = strdup(value); + } + argc--; + argv++; + } + + if (!ldapServer) + ldapServer = "localhost"; + + if (!userbasedn || !passattr) { + fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); + fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n"); + fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that devides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n"); + fprintf(stderr, "\t-b basedn (REQUIRED)\t\t\tbase dn under where to search for users\n"); + fprintf(stderr, "\t-e Encrypted passwords(REQUIRED)\tPassword are stored encrypted using HHA1\n"); + fprintf(stderr, "\t-F filter\t\t\t\tuser search filter pattern. %%s = login\n"); + fprintf(stderr, "\t-u attribute\t\t\t\tattribute to use in combination with the basedn to create the user DN\n"); + fprintf(stderr, "\t-s base|one|sub\t\t\t\tsearch scope\n"); + fprintf(stderr, "\t-D binddn\t\t\t\tDN to bind as to perform searches\n"); + fprintf(stderr, "\t-w bindpasswd\t\t\t\tpassword for binddn\n"); + fprintf(stderr, "\t-W secretfile\t\t\t\tread password for binddn from file secretfile\n"); +#if HAS_URI_SUPPORT + fprintf(stderr, "\t-H URI\t\t\t\t\tLDAPURI (defaults to ldap://localhost)\n"); +#endif + fprintf(stderr, "\t-h server\t\t\t\tLDAP server (defaults to localhost)\n"); + fprintf(stderr, "\t-p port\t\t\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); + fprintf(stderr, "\t-P\t\t\t\t\tpersistent LDAP connection\n"); +#if defined(NETSCAPE_SSL) + fprintf(stderr, "\t-E sslcertpath\t\t\t\tenable LDAP over SSL\n"); +#endif + fprintf(stderr, "\t-c timeout\t\t\t\tconnect timeout\n"); + fprintf(stderr, "\t-t timelimit\t\t\t\tsearch time limit\n"); + fprintf(stderr, "\t-R\t\t\t\t\tdo not follow referrals\n"); + fprintf(stderr, "\t-a never|always|search|find\t\twhen to dereference aliases\n"); +#ifdef LDAP_VERSION3 + fprintf(stderr, "\t-v 2|3\t\t\t\t\tLDAP version\n"); + fprintf(stderr, "\t-Z\t\t\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); +#endif + fprintf(stderr, "\t-S\t\t\t\t\tStrip NT domain from usernames\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); + return -1; + } + return 0; +} +static int +readSecret(char *filename) +{ + char buf[BUFSIZ]; + char *e = 0; + FILE *f; + + if (!(f = fopen(filename, "r"))) { + fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); + return 1; + } + if (!fgets(buf, sizeof(buf) - 1, f)) { + fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); + fclose(f); + return 1; + } + /* strip whitespaces on end */ + if ((e = strrchr(buf, '\n'))) + *e = 0; + if ((e = strrchr(buf, '\r'))) + *e = 0; + + bindpasswd = (char *) calloc(sizeof(char), strlen(buf) + 1); + if (bindpasswd) { + strcpy(bindpasswd, buf); + } else { + fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); + } + + fclose(f); + + return 0; +} + +void +LDAPHHA1(RequestData * requestData) +{ + char *password = ""; + ldapconnect(); + password = getpassword(requestData->user, requestData->realm); + if (password != NULL) { + if (encrpass) + xstrncpy(requestData->HHA1, &password[6], sizeof(requestData->HHA1)); + else { + HASH HA1; + DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1); + } + free(password); + } else { + requestData->error = -1; + } + +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/ldap/ldap_backend.h Wed Feb 14 13:38:01 2007 @@ -0,0 +1,9 @@ +/* + * text_backend.h + * + * AUTHOR: Flavio Pescuma. + * + */ +#include "digest_common.h" +extern int LDAPArguments(int argc, char **argv); +extern void LDAPHHA1(RequestData * requestData); --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/digest_auth/password/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 --- squid3/helpers/digest_auth/password/ldap_backend.c Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,653 +0,0 @@ -/* - * - * - * - * ldap_backend.c - * AUTHOR: Flavio Pescuma, MARA Systems AB - */ -#include -#include -#include -#include -#include "ldap_backend.h" - -#ifdef _SQUID_MSWIN_ /* Native Windows port and MinGW */ - -#define snprintf _snprintf -#include -#include -#ifndef LDAPAPI -#define LDAPAPI __cdecl -#endif -#ifdef LDAP_VERSION3 -#ifndef LDAP_OPT_X_TLS -#define LDAP_OPT_X_TLS 0x6000 -#endif -/* Some tricks to allow dynamic bind with ldap_start_tls_s entry point at - run time. - */ -#undef ldap_start_tls_s -#if LDAP_UNICODE -#define LDAP_START_TLS_S "ldap_start_tls_sW" -typedef WINLDAPAPI ULONG (LDAPAPI * PFldap_start_tls_s) (IN PLDAP, OUT PULONG, OUT LDAPMessage **, IN PLDAPControlW *, IN PLDAPControlW *); -#else -#define LDAP_START_TLS_S "ldap_start_tls_sA" -typedef WINLDAPAPI ULONG (LDAPAPI * PFldap_start_tls_s) (IN PLDAP, OUT PULONG, OUT LDAPMessage **, IN PLDAPControlA *, IN PLDAPControlA *); -#endif /* LDAP_UNICODE */ -PFldap_start_tls_s Win32_ldap_start_tls_s; -#define ldap_start_tls_s(l,s,c) Win32_ldap_start_tls_s(l,NULL,NULL,s,c) -#endif /* LDAP_VERSION3 */ - -#else - -#include -#include - -#endif -#define PROGRAM_NAME "digest_pw_auth(LDAP_backend)" - -/* Globals */ - -static LDAP *ld = NULL; -static char *passattr = NULL; -static char *ldapServer = NULL; -static char *userbasedn = NULL; -static char *userdnattr = NULL; -static char *usersearchfilter = NULL; -static char *binddn = NULL; -static char *bindpasswd = NULL; -static char *delimiter = ":"; -static int encrpass = 0; -static int searchscope = LDAP_SCOPE_SUBTREE; -static int persistent = 0; -static int noreferrals = 0; -static int debug = 0; -static int port = LDAP_PORT; -static int strip_nt_domain = 0; -static int aliasderef = LDAP_DEREF_NEVER; -#if defined(NETSCAPE_SSL) -static char *sslpath = NULL; -static int sslinit = 0; -#endif -static int connect_timeout = 0; -static int timelimit = LDAP_NO_LIMIT; - -#ifdef LDAP_VERSION3 -/* Added for TLS support and version 3 */ -static int use_tls = 0; -static int version = -1; -#endif - -static void ldapconnect(void); -static int readSecret(char *filename); - -/* Yuck.. we need to glue to different versions of the API */ - -#if defined(LDAP_API_VERSION) && LDAP_API_VERSION > 1823 -static void -squid_ldap_set_aliasderef(int deref) -{ - ldap_set_option(ld, LDAP_OPT_DEREF, &deref); -} -static void -squid_ldap_set_referrals(int referrals) -{ - int *value = referrals ? LDAP_OPT_ON : LDAP_OPT_OFF; - ldap_set_option(ld, LDAP_OPT_REFERRALS, value); -} -static void -squid_ldap_set_timelimit(int timelimit) -{ - ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &timelimit); -} -static void -squid_ldap_set_connect_timeout(int timelimit) -{ -#if defined(LDAP_OPT_NETWORK_TIMEOUT) - struct timeval tv; - tv.tv_sec = timelimit; - tv.tv_usec = 0; - ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &tv); -#elif defined(LDAP_X_OPT_CONNECT_TIMEOUT) - timelimit *= 1000; - ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timelimit); -#endif -} - -#else -static int -squid_ldap_errno(LDAP * ld) -{ - return ld->ld_errno; -} -static void -squid_ldap_set_aliasderef(int deref) -{ - ld->ld_deref = deref; -} -static void -squid_ldap_set_referrals(int referrals) -{ - if (referrals) - ld->ld_options |= ~LDAP_OPT_REFERRALS; - else - ld->ld_options &= ~LDAP_OPT_REFERRALS; -} -static void -squid_ldap_set_timelimit(int timelimit) -{ - ld->ld_timelimit = timelimit; -} -static void -squid_ldap_set_connect_timeout(int timelimit) -{ - fprintf(stderr, "Connect timeouts not supported in your LDAP library\n"); -} -static void -squid_ldap_memfree(char *p) -{ - free(p); -} - -#endif - -#ifdef LDAP_API_FEATURE_X_OPENLDAP -#if LDAP_VENDOR_VERSION > 194 -#define HAS_URI_SUPPORT 1 -#endif -#endif - -static int -ldap_escape_value(char *escaped, int size, const char *src) -{ - int n = 0; - while (size > 4 && *src) { - switch (*src) { - case '*': - case '(': - case ')': - case '\\': - n += 3; - size -= 3; - if (size > 0) { - *escaped++ = '\\'; - snprintf(escaped, 3, "%02x", (int) *src++); - escaped += 2; - } - break; - default: - *escaped++ = *src++; - n++; - size--; - } - } - *escaped = '\0'; - return n; -} - -static char * -getpassword(char *login, char *realm) -{ - LDAPMessage *res = NULL; - LDAPMessage *entry; - char **values = NULL; - char **value = NULL; - char *password = NULL; - int retry = 0; - char filter[8192]; - char searchbase[8192]; - int rc = -1; - if (ld) { - if (usersearchfilter) { - char escaped_login[1024]; - snprintf(searchbase, sizeof(searchbase), "%s", userbasedn); - ldap_escape_value(escaped_login, sizeof(escaped_login), login); - snprintf(filter, sizeof(filter), usersearchfilter, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login, escaped_login); - - retrysrch: - if (debug) - fprintf(stderr, "user filter '%s', searchbase '%s'\n", filter, searchbase); - - rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res); - if (rc != LDAP_SUCCESS) { - if (noreferrals && rc == LDAP_PARTIAL_RESULTS) { - /* Everything is fine. This is expected when referrals - * are disabled. - */ - rc = LDAP_SUCCESS; - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error '%s'\n", ldap_err2string(rc)); -#if defined(NETSCAPE_SSL) - if (sslpath && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR))) { - int sslerr = PORT_GetError(); - fprintf(stderr, PROGRAM_NAME ": WARNING, SSL error %d (%s)\n", sslerr, ldapssl_err2string(sslerr)); - } -#endif - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP search error, trying to recover'%s'\n", ldap_err2string(rc)); - ldap_msgfree(res); - /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ - if (!retry) { - retry++; - ldap_unbind(ld); - ld = NULL; - ldapconnect(); - goto retrysrch; - } - return NULL; - - } - } - } else if (userdnattr) { - sprintf(searchbase, "%s=%s, %s", userdnattr, login, userbasedn); - - retrydnattr: - if (debug) - fprintf(stderr, "searchbase '%s'\n", searchbase); - rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res); - } - if (rc == LDAP_SUCCESS) { - entry = ldap_first_entry(ld, res); - if (entry) - values = ldap_get_values(ld, entry, passattr); - else { - ldap_msgfree(res); - return NULL; - } - if (!values) { - if (debug) - printf("No attribute value found\n"); - ldap_msgfree(res); - return NULL; - } - value = values; - while (*value) { - if (encrpass) { - if (strcmp(strtok(*value, delimiter), realm) == 0) { - password = strtok(NULL, delimiter); - break; - } - } else { - password = *value; - break; - } - value++; - } - if (debug) - printf("password: %s\n", password); - if (password) - password = strdup(password); - ldap_value_free(values); - ldap_msgfree(res); - return password; - } else { - fprintf(stderr, PROGRAM_NAME " WARNING, LDAP error '%s'\n", ldap_err2string(rc)); - /* try to connect to the LDAP server agin, maybe my persisten conexion failed. */ - if (!retry) { - retry++; - ldap_unbind(ld); - ld = NULL; - ldapconnect(); - goto retrydnattr; - } - return NULL; - } - } - return NULL; -} - - - -static void -ldapconnect(void) -{ - int rc; - -/* On Windows ldap_start_tls_s is available starting from Windows XP, - so we need to bind at run-time with the function entry point - */ -#ifdef _SQUID_MSWIN_ - if (use_tls) { - - HMODULE WLDAP32Handle; - - WLDAP32Handle = GetModuleHandle("wldap32"); - if ((Win32_ldap_start_tls_s = (PFldap_start_tls_s) GetProcAddress(WLDAP32Handle, LDAP_START_TLS_S)) == NULL) { - fprintf( stderr, PROGRAM_NAME ": ERROR: TLS (-Z) not supported on this platform.\n"); - exit(1); - } - } -#endif - - if (ld == NULL) { -#if HAS_URI_SUPPORT - if (strstr(ldapServer, "://") != NULL) { - rc = ldap_initialize(&ld, ldapServer); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer); - } - } else -#endif -#if NETSCAPE_SSL - if (sslpath) { - if (!sslinit && (ldapssl_client_init(sslpath, NULL) != LDAP_SUCCESS)) { - fprintf(stderr, "\nUnable to initialise SSL with cert path %s\n", - sslpath); - exit(1); - } else { - sslinit++; - } - if ((ld = ldapssl_init(ldapServer, port, 1)) == NULL) { - fprintf(stderr, "\nUnable to connect to SSL LDAP server: %s port:%d\n", - ldapServer, port); - exit(1); - } - } else -#endif - if ((ld = ldap_init(ldapServer, port)) == NULL) { - fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port); - } - if (connect_timeout) - squid_ldap_set_connect_timeout(connect_timeout); - -#ifdef LDAP_VERSION3 - if (version == -1) { - version = LDAP_VERSION2; - } - if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) - != LDAP_SUCCESS) { - fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", - version); - ldap_unbind(ld); - ld = NULL; - } - if (use_tls && (version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) { - fprintf(stderr, "Could not Activate TLS connection\n"); - ldap_unbind(ld); - ld = NULL; - } -#endif - squid_ldap_set_timelimit(timelimit); - squid_ldap_set_referrals(!noreferrals); - squid_ldap_set_aliasderef(aliasderef); - if (binddn && bindpasswd && *binddn && *bindpasswd) { - rc = ldap_simple_bind_s(ld, binddn, bindpasswd); - if (rc != LDAP_SUCCESS) { - fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc)); - ldap_unbind(ld); - ld = NULL; - } - } - if (debug) - fprintf(stderr, "Connected OK\n"); - } -} -int -LDAPArguments(int argc, char **argv) -{ - setbuf(stdout, NULL); - - while (argc > 1 && argv[1][0] == '-') { - char *value = ""; - char option = argv[1][1]; - switch (option) { - case 'P': - case 'R': - case 'z': - case 'Z': - case 'g': - case 'e': - case 'S': - break; - default: - if (strlen(argv[1]) > 2) { - value = argv[1] + 2; - } else if (argc > 2) { - value = argv[2]; - argv++; - argc--; - } else - value = ""; - break; - } - argv++; - argc--; - switch (option) { - case 'H': -#if !HAS_URI_SUPPORT - fprintf(stderr, "ERROR: Your LDAP library does not have URI support\n"); - return 1; -#endif - /* Fall thru to -h */ - case 'h': - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - break; - case 'A': - passattr = value; - break; - case 'e': - encrpass = 1; - break; - case 'l': - delimiter = value; - break; - case 'b': - userbasedn = value; - break; - case 'F': - usersearchfilter = value; - break; - case 'u': - userdnattr = value; - break; - case 's': - if (strcmp(value, "base") == 0) - searchscope = LDAP_SCOPE_BASE; - else if (strcmp(value, "one") == 0) - searchscope = LDAP_SCOPE_ONELEVEL; - else if (strcmp(value, "sub") == 0) - searchscope = LDAP_SCOPE_SUBTREE; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown search scope '%s'\n", value); - return 1; - } - break; - case 'S': -#if defined(NETSCAPE_SSL) - sslpath = value; - if (port == LDAP_PORT) - port = LDAPS_PORT; -#else - fprintf(stderr, PROGRAM_NAME " ERROR: -E unsupported with this LDAP library\n"); - return 1; -#endif - break; - case 'c': - connect_timeout = atoi(value); - break; - case 't': - timelimit = atoi(value); - break; - case 'a': - if (strcmp(value, "never") == 0) - aliasderef = LDAP_DEREF_NEVER; - else if (strcmp(value, "always") == 0) - aliasderef = LDAP_DEREF_ALWAYS; - else if (strcmp(value, "search") == 0) - aliasderef = LDAP_DEREF_SEARCHING; - else if (strcmp(value, "find") == 0) - aliasderef = LDAP_DEREF_FINDING; - else { - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown alias dereference method '%s'\n", value); - return 1; - } - break; - case 'D': - binddn = value; - break; - case 'w': - bindpasswd = value; - break; - case 'W': - readSecret(value); - break; - case 'P': - persistent = !persistent; - break; - case 'p': - port = atoi(value); - break; - case 'R': - noreferrals = !noreferrals; - break; -#ifdef LDAP_VERSION3 - case 'v': - switch (atoi(value)) { - case 2: - version = LDAP_VERSION2; - break; - case 3: - version = LDAP_VERSION3; - break; - default: - fprintf(stderr, "Protocol version should be 2 or 3\n"); - return 1; - } - break; - case 'Z': - if (version == LDAP_VERSION2) { - fprintf(stderr, "TLS (-Z) is incompatible with version %d\n", - version); - return 1; - } - version = LDAP_VERSION3; - use_tls = 1; - break; -#endif - case 'd': - debug = 1; - break; - case 'E': - strip_nt_domain = 1; - break; - default: - fprintf(stderr, PROGRAM_NAME " ERROR: Unknown command line option '%c'\n", option); - return 1; - } - } - - while (argc > 1) { - char *value = argv[1]; - if (ldapServer) { - int len = strlen(ldapServer) + 1 + strlen(value) + 1; - char *newhost = malloc(len); - snprintf(newhost, len, "%s %s", ldapServer, value); - free(ldapServer); - ldapServer = newhost; - } else { - ldapServer = strdup(value); - } - argc--; - argv++; - } - - if (!ldapServer) - ldapServer = "localhost"; - - if (!userbasedn || !passattr) { - fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n"); - fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n"); - fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that devides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n"); - fprintf(stderr, "\t-b basedn (REQUIRED)\t\t\tbase dn under where to search for users\n"); - fprintf(stderr, "\t-e Encrypted passwords(REQUIRED)\tPassword are stored encrypted using HHA1\n"); - fprintf(stderr, "\t-F filter\t\t\t\tuser search filter pattern. %%s = login\n"); - fprintf(stderr, "\t-u attribute\t\t\t\tattribute to use in combination with the basedn to create the user DN\n"); - fprintf(stderr, "\t-s base|one|sub\t\t\t\tsearch scope\n"); - fprintf(stderr, "\t-D binddn\t\t\t\tDN to bind as to perform searches\n"); - fprintf(stderr, "\t-w bindpasswd\t\t\t\tpassword for binddn\n"); - fprintf(stderr, "\t-W secretfile\t\t\t\tread password for binddn from file secretfile\n"); -#if HAS_URI_SUPPORT - fprintf(stderr, "\t-H URI\t\t\t\t\tLDAPURI (defaults to ldap://localhost)\n"); -#endif - fprintf(stderr, "\t-h server\t\t\t\tLDAP server (defaults to localhost)\n"); - fprintf(stderr, "\t-p port\t\t\t\t\tLDAP server port (defaults to %d)\n", LDAP_PORT); - fprintf(stderr, "\t-P\t\t\t\t\tpersistent LDAP connection\n"); -#if defined(NETSCAPE_SSL) - fprintf(stderr, "\t-E sslcertpath\t\t\t\tenable LDAP over SSL\n"); -#endif - fprintf(stderr, "\t-c timeout\t\t\t\tconnect timeout\n"); - fprintf(stderr, "\t-t timelimit\t\t\t\tsearch time limit\n"); - fprintf(stderr, "\t-R\t\t\t\t\tdo not follow referrals\n"); - fprintf(stderr, "\t-a never|always|search|find\t\twhen to dereference aliases\n"); -#ifdef LDAP_VERSION3 - fprintf(stderr, "\t-v 2|3\t\t\t\t\tLDAP version\n"); - fprintf(stderr, "\t-Z\t\t\t\t\tTLS encrypt the LDAP connection, requires\n\t\t\t\tLDAP version 3\n"); -#endif - fprintf(stderr, "\t-S\t\t\t\t\tStrip NT domain from usernames\n"); - fprintf(stderr, "\n"); - fprintf(stderr, "\tIf you need to bind as a user to perform searches then use the\n\t-D binddn -w bindpasswd or -D binddn -W secretfile options\n\n"); - return -1; - } - return 0; -} -static int -readSecret(char *filename) -{ - char buf[BUFSIZ]; - char *e = 0; - FILE *f; - - if (!(f = fopen(filename, "r"))) { - fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename); - return 1; - } - if (!fgets(buf, sizeof(buf) - 1, f)) { - fprintf(stderr, PROGRAM_NAME " ERROR: Secret file %s is empty\n", filename); - fclose(f); - return 1; - } - /* strip whitespaces on end */ - if ((e = strrchr(buf, '\n'))) - *e = 0; - if ((e = strrchr(buf, '\r'))) - *e = 0; - - bindpasswd = (char *) calloc(sizeof(char), strlen(buf) + 1); - if (bindpasswd) { - strcpy(bindpasswd, buf); - } else { - fprintf(stderr, PROGRAM_NAME " ERROR: can not allocate memory\n"); - } - - fclose(f); - - return 0; -} - -void -LDAPHHA1(RequestData * requestData) -{ - char *password = ""; - /* LDAPArguments(argc,argv); */ - ldapconnect(); - password = getpassword(requestData->user, requestData->realm); - if (password != NULL) { - if (encrpass) - xstrncpy(requestData->HHA1, &password[6], sizeof(requestData->HHA1)); - else { - HASH HA1; - DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1); - } - free(password); - } else { - requestData->error = -1; - } - -} --- squid3/helpers/digest_auth/password/ldap_backend.h Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,9 +0,0 @@ -/* - * text_backend.h - * - * AUTHOR: Flavio Pescuma. - * - */ -#include "digest_common.h" -extern int LDAPArguments(int argc, char **argv); -extern void LDAPHHA1(RequestData * requestData); --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/ip_user/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -f /usr/include/sys/socket.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/ldap_group/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/ldap.h ]; then + exit 0 +fi +if [ -f /usr/include/winldap.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/mswin_lm_group/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +mswin_check_lm_group.exe +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/mswin_lm_group/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/w32api/windows.h ]; then + exit 0 +fi +if [ -f /usr/include/windows.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/session/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +squid_session +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/session/Makefile.am Wed Feb 14 13:38:01 2007 @@ -0,0 +1,16 @@ +# +# Makefile for the Squid LDAP authentication helper +# +# $Id: Makefile.am,v 1.1.12.2 2006/09/29 23:15:50 dwsquid Exp $ +# +# Uncomment and customize the following to suit your needs: +# + +libexec_PROGRAMS = squid_session +man_MANS = squid_session.8 +EXTRA_DIST = squid_session.8 +squid_session_SOURCES = squid_session.c + +LDADD = $(LIB_DB) + +INCLUDES = -I. -I$(top_builddir)/include -I$(top_srcdir)/include --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/session/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,10 @@ +#!/bin/sh + +# Actual intended test +if [ -f /usr/include/db_185.h ]; then + exit 0 +fi +if [ -f /usr/include/db.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/session/squid_session.8 Wed Feb 14 13:38:01 2007 @@ -0,0 +1,49 @@ +.TH squid_session 8 "19 March 2006" "Version 1.0" +. +.SH NAME +squid_session - Squid session tracking external acl group helper +. +.SH SYNOPSIS +squid_session [-t idle_timeout] [-b dbpath] [-a] +. +.SH DESCRIPTION +This helper maintains a concept of sessions by monitoring requests +and timing out sessions if no requests have been seen for the idle timeout +timer. +.P +Intended use is for displaying "terms of use" pages, ad popups etc. +. +.TP +.BI "-t " "idletimeout " "(default 3600)" +Specifies the session idle timeout timer. +. +.TP +.BI "-b " "dbpath" +Path to persistent database. If not specified the session details +will be kept in memory only and all sessions will reset each time +Squid restarts it's helpers (Squid restart or rotation of logs). +. +.TP +.B "-a" +Active mode. In this mode sessions are started by evaluating an +acl with the argument LOGIN, or terminated by the argument LOGOUT. +.P +Without this flag the helper automatically starts the session after +the first request. +. +.SH AUTHOR +This helper and documentation was written by +.I Henrik Nordstrom +. +.SH QUESTIONS +Any questions on usage can be sent to +.IR "Squid Users " . +. +.SH REPORTING BUGS +Report bugs or bug-fixes to +.I Squid Bugs +or ideas for new improvements to +.I Squid Developers +. +.SH "SEE ALSO" +.BR squid ( 8 ) --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/session/squid_session.c Wed Feb 14 13:38:01 2007 @@ -0,0 +1,173 @@ +/* + * squid_session: Squid external acl helper for tracking sessions + * + * Copyright (C) 2006 Henrik Nordstrom + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(HAVE_DB_185_H) +#include +#elif defined(HAVE_DB_H) +#include +#else +#include +#endif + +static int session_ttl = 3600; +char *db_path = NULL; +const char *program_name; + +DB *db = NULL; + +static void init_db(void) +{ + db = dbopen(db_path, O_CREAT | O_RDWR, 0666, DB_BTREE, NULL); + if (!db) { + fprintf(stderr, "%s: Failed to open session db '%s'\n", program_name, db_path); + exit(1); + } +} + +static void shutdown_db(void) +{ + db->close(db); +} + +int session_is_active = 0; + +static int session_active(const char *details) +{ + DBT key, data; + key.data = (void *)details; + key.size = strlen(details); + if (db->get(db, &key, &data, 0) == 0) { + time_t timestamp; + if (data.size != sizeof(timestamp)) { + fprintf(stderr, "%s: CORRUPTED DATABASE (%s)\n", program_name, details); + db->del(db, &key, 0); + return 0; + } + memcpy(×tamp, data.data, sizeof(timestamp)); + if (timestamp + session_ttl >= time(NULL)) + return 1; + } + return 0; +} + +static void session_login(const char *details) +{ + DBT key, data; + time_t now = time(NULL); + key.data = (void *)details; + key.size = strlen(details); + data.data = &now; + data.size = sizeof(now); + db->put(db, &key, &data, 0); +} + +static void session_logout(const char *details) +{ + DBT key; + key.data = (void *)details; + key.size = strlen(details); + db->del(db, &key, 0); +} + +static void usage(void) +{ + fprintf(stderr, "Usage: %s [-t session_timeout] [-b dbpath] [-a]\n", program_name); + fprintf(stderr, " -t sessiontimeout Idle timeout after which sessions will be forgotten\n"); + fprintf(stderr, " -b dbpath Path where persistent session database will be kept\n"); + fprintf(stderr, " -a Active mode requiring LOGIN argument to start a session\n"); +} +int main(int argc, char **argv) +{ + char request[256]; + int opt; + int default_action = 1; + + program_name = argv[0]; + + while ((opt = getopt(argc, argv, "t:b:a?")) != -1) { + switch(opt) { + case 't': + session_ttl = strtol(optarg, NULL, 0); + break; + case 'b': + db_path = optarg; + break; + case 'a': + default_action = 0; + break; + case '?': + usage(); + exit(0); + break; + } + } + + setbuf(stdout, NULL); + + init_db(); + + while (fgets(request, sizeof(request), stdin)) { + const char *index, *detail; + char *lastdetail; + int action = 0; + index = strtok(request, " \n"); + detail = strtok(NULL, "\n"); + lastdetail = strrchr(detail, ' '); + if (lastdetail) { + if (strcmp(lastdetail, " LOGIN") == 0) { + *lastdetail++ = '\0'; + action = 1; + } else if (strcmp(lastdetail, " LOGOUT") == 0) { + action = -1; + *lastdetail++ = '\0'; + } + } + if (action == -1) { + session_logout(detail); + printf("%s OK message=\"Bye\"\n", index); + } else if (action == 1) { + session_login(detail); + printf("%s OK message=\"Welcome\"\n", index); + } else if (session_active(detail)) { + session_login(detail); + printf("%s OK\n", index); + } else if (default_action == 1) { + session_login(detail); + printf("%s ERR message=\"Welcome\"\n", index); + } else { + printf("%s ERR message=\"No session available\"\n", index); + } + } + shutdown_db(); + return 0; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/unix_group/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +#!/bin/sh +if [ -f /usr/include/pwd.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/external_acl/wbinfo_group/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -x ${SAMBAPREFIX:-/usr/local/samba}/bin/wbinfo -a -x /usr/bin/perl ]; then + exit 0 +fi +if [ -x /usr/bin/wbinfo -a -x /usr/bin/perl ]; then + exit 0 +fi +exit 1 --- squid3/helpers/external_acl/winbind_group/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,4 +0,0 @@ -.cvsignore -Makefile.in -Makefile -.deps --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/negotiate_auth/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/negotiate_auth/mswin_sspi/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +mswin_negotiate_auth.exe +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/negotiate_auth/mswin_sspi/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/w32api/windows.h ]; then + exit 0 +fi +if [ -f /usr/include/windows.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/ntlm_auth/SMB/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,9 @@ +#!/bin/sh +# Don't build on Windows +if [ -f /usr/include/w32api/windows.h ]; then + exit 1 +fi +if [ -f /usr/include/windows.h ]; then + exit 1 +fi +exit 0 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/ntlm_auth/fakeauth/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/ntlm_auth/mswin_sspi/.cvsignore Wed Feb 14 13:38:01 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +mswin_ntlm_auth.exe +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/ntlm_auth/mswin_sspi/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,8 @@ +#!/bin/sh +if [ -f /usr/include/w32api/windows.h ]; then + exit 0 +fi +if [ -f /usr/include/windows.h ]; then + exit 0 +fi +exit 1 --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/helpers/ntlm_auth/no_check/config.test Wed Feb 14 13:38:01 2007 @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 --- squid3/helpers/ntlm_auth/winbind/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,4 +0,0 @@ -.cvsignore -Makefile.in -Makefile -.deps --- squid3/helpers/ntlm_auth/winbind/patches/.cvsignore Wed Feb 14 13:38:01 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/include/assert.h Wed Feb 14 13:38:01 2007 @@ -0,0 +1,49 @@ + +/* + * $Id: assert.h,v 1.2.12.2 2006/09/29 23:15:53 dwsquid Exp $ + * + * AUTHOR: Duane Wessels + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_ASSERT_H +#define SQUID_ASSERT_H + +#include "config.h" + +#if defined(NODEBUG) +#define assert(EX) ((void)0) +#elif STDC_HEADERS +#define assert(EX) ((EX)?((void)0):xassert( # EX , __FILE__, __LINE__)) +#else +#define assert(EX) ((EX)?((void)0):xassert("EX", __FILE__, __LINE__)) +#endif +SQUIDCEXTERN void xassert(const char *, const char *, int); + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/include/squid_mswin.h Wed Feb 14 13:38:01 2007 @@ -0,0 +1,747 @@ +/* + * $Id: squid_mswin.h,v 1.3.2.2 2006/09/29 23:15:53 dwsquid Exp $ + * + * AUTHOR: Andrey Shorin + * AUTHOR: Guido Serassio + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#define ACL WindowsACL +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#if _MSC_VER == 1400 +#define _CRT_SECURE_NO_DEPRECATE +#pragma warning( disable : 4290 ) +#pragma warning( disable : 4996 ) +#endif +#endif + +#if defined _FILE_OFFSET_BITS && _FILE_OFFSET_BITS == 64 +# define __USE_FILE_OFFSET64 1 +#endif + +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ + +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned __int64 uint64_t; + +typedef long pid_t; + +#if defined __USE_FILE_OFFSET64 +typedef int64_t off_t; +typedef uint64_t ino_t; + +#else +typedef long off_t; +typedef unsigned long ino_t; + +#endif + +#define INT64_MAX _I64_MAX +#define INT64_MIN _I64_MIN +#define PRId64 "I64d" + +#include "default_config_file.h" +/* Some tricks for MS Compilers */ +#define __STDC__ 1 +#pragma include_alias(, ) +#define THREADLOCAL __declspec(thread) + +#elif defined(__GNUC__) /* gcc environment */ + +#define THREADLOCAL __attribute__((section(".tls"))) + +#endif + +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#define alloca _alloca +#endif +#define chdir _chdir +#define dup _dup +#define dup2 _dup2 +#define fdopen _fdopen +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#define fileno _fileno +#define fstat _fstati64 +#endif +#define ftruncate WIN32_ftruncate +#define getcwd _getcwd +#define getpid _getpid +#define getrusage WIN32_getrusage +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#define lseek _lseeki64 +#define memccpy _memccpy +#define mkdir(p) _mkdir(p) +#define mktemp _mktemp +#endif +#define pclose _pclose +#define pipe WIN32_pipe +#define popen _popen +#define putenv _putenv +#define setmode _setmode +#define sleep(t) Sleep((t)*1000) +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#define snprintf _snprintf +#define stat _stati64 +#define strcasecmp _stricmp +#define strdup _strdup +#define strlwr _strlwr +#define strncasecmp _strnicmp +#define tempnam _tempnam +#endif +#define truncate WIN32_truncate +#define umask _umask +#define unlink _unlink +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#define vsnprintf _vsnprintf +#endif + +#define O_RDONLY _O_RDONLY +#define O_WRONLY _O_WRONLY +#define O_RDWR _O_RDWR +#define O_APPEND _O_APPEND + +#define O_CREAT _O_CREAT +#define O_TRUNC _O_TRUNC +#define O_EXCL _O_EXCL + +#define O_TEXT _O_TEXT +#define O_BINARY _O_BINARY +#define O_RAW _O_BINARY +#define O_TEMPORARY _O_TEMPORARY +#define O_NOINHERIT _O_NOINHERIT +#define O_SEQUENTIAL _O_SEQUENTIAL +#define O_RANDOM _O_RANDOM +#define O_NDELAY 0 + +#define S_IFMT _S_IFMT +#define S_IFDIR _S_IFDIR +#define S_IFCHR _S_IFCHR +#define S_IFREG _S_IFREG +#define S_IREAD _S_IREAD +#define S_IWRITE _S_IWRITE +#define S_IEXEC _S_IEXEC + +#define S_IRWXO 007 +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#define S_ISDIR(m) (((m) & _S_IFDIR) == _S_IFDIR) +#endif + +#define SIGHUP 1 /* hangup */ +#define SIGKILL 9 /* kill (cannot be caught or ignored) */ +#define SIGBUS 10 /* bus error */ +#define SIGPIPE 13 /* write on a pipe with no one to read it */ +#define SIGCHLD 20 /* to parent on child stop or exit */ +#define SIGUSR1 30 /* user defined signal 1 */ +#define SIGUSR2 31 /* user defined signal 2 */ + +typedef unsigned short int ushort; +typedef int uid_t; +typedef int gid_t; + +struct passwd { + char *pw_name; /* user name */ + char *pw_passwd; /* user password */ + uid_t pw_uid; /* user id */ + gid_t pw_gid; /* group id */ + char *pw_gecos; /* real name */ + char *pw_dir; /* home directory */ + char *pw_shell; /* shell program */ +}; + +struct group { + char *gr_name; /* group name */ + char *gr_passwd; /* group password */ + gid_t gr_gid; /* group id */ + char **gr_mem; /* group members */ +}; + +struct statfs { + long f_type; /* type of filesystem (see below) */ + long f_bsize; /* optimal transfer block size */ + long f_blocks; /* total data blocks in file system */ + long f_bfree; /* free blocks in fs */ + long f_bavail; /* free blocks avail to non-superuser */ + long f_files; /* total file nodes in file system */ + long f_ffree; /* free file nodes in fs */ + long f_fsid; /* file system id */ + long f_namelen; /* maximum length of filenames */ + long f_spare[6]; /* spare for later */ +}; + +struct timezone + { + int tz_minuteswest; /* minutes west of Greenwich */ + int tz_dsttime; /* type of dst correction */ + }; + +#define CHANGE_FD_SETSIZE 1 +#if CHANGE_FD_SETSIZE && SQUID_MAXFD > DEFAULT_FD_SETSIZE +#define FD_SETSIZE SQUID_MAXFD +#endif + +#include +#include +#include +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +/* Hack to suppress compiler warnings on FD_SET() & FD_CLR() */ +#pragma warning (push) +#pragma warning (disable:4142) +#endif +/* prevent inclusion of wingdi.h */ +#define NOGDI +#include +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#pragma warning (pop) +#include "readdir.h" +#else +#include +#include +#include +#endif + +typedef char * caddr_t; + +#undef FD_CLOSE +#undef FD_OPEN +#undef FD_READ +#undef FD_WRITE +#define EISCONN WSAEISCONN +#define EINPROGRESS WSAEINPROGRESS +#define EWOULDBLOCK WSAEWOULDBLOCK +#define EALREADY WSAEALREADY +#define ETIMEDOUT WSAETIMEDOUT +#define ECONNREFUSED WSAECONNREFUSED +#define ECONNRESET WSAECONNRESET +#define ENOTCONN WSAENOTCONN +#define ERESTART WSATRY_AGAIN + +#undef h_errno +#define h_errno errno /* we'll set it ourselves */ + +#undef FD_CLR +#define FD_CLR(fd, set) do { \ + u_int __i; \ + SOCKET __sock = fd_table[fd].win32.handle; \ + for (__i = 0; __i < ((fd_set FAR *)(set))->fd_count ; __i++) { \ + if (((fd_set FAR *)(set))->fd_array[__i] == __sock) { \ + while (__i < ((fd_set FAR *)(set))->fd_count-1) { \ + ((fd_set FAR *)(set))->fd_array[__i] = \ + ((fd_set FAR *)(set))->fd_array[__i+1]; \ + __i++; \ + } \ + ((fd_set FAR *)(set))->fd_count--; \ + break; \ + } \ + } \ +} while(0) + +#undef FD_SET +#define FD_SET(fd, set) do { \ + u_int __i; \ + SOCKET __sock = fd_table[fd].win32.handle; \ + for (__i = 0; __i < ((fd_set FAR *)(set))->fd_count; __i++) { \ + if (((fd_set FAR *)(set))->fd_array[__i] == (__sock)) { \ + break; \ + } \ + } \ + if (__i == ((fd_set FAR *)(set))->fd_count) { \ + if (((fd_set FAR *)(set))->fd_count < FD_SETSIZE) { \ + ((fd_set FAR *)(set))->fd_array[__i] = (__sock); \ + ((fd_set FAR *)(set))->fd_count++; \ + } \ + } \ +} while(0) + +#undef FD_ISSET +#define FD_ISSET(fd, set) Win32__WSAFDIsSet(fd, (fd_set FAR *)(set)) + +/* internal to Microsoft CRTLIB */ +typedef struct { + long osfhnd; /* underlying OS file HANDLE */ + char osfile; /* attributes of file (e.g., open in text mode?) */ + char pipech; /* one char buffer for handles opened on pipes */ +#ifdef _MT + int lockinitflag; + CRITICAL_SECTION lock; +#endif /* _MT */ + } ioinfo; +#define IOINFO_L2E 5 +#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E) +#define _pioinfo(i) ( __pioinfo[(i) >> IOINFO_L2E] + ((i) & (IOINFO_ARRAY_ELTS - 1)) ) +#define _osfile(i) ( _pioinfo(i)->osfile ) +#define _osfhnd(i) ( _pioinfo(i)->osfhnd ) +#define FOPEN 0x01 /* file handle open */ + +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ + +SQUIDCEXTERN _CRTIMP ioinfo * __pioinfo[]; +SQUIDCEXTERN int __cdecl _free_osfhnd(int); + +#elif defined(__MINGW32__) /* MinGW environment */ + +__MINGW_IMPORT ioinfo * __pioinfo[]; +SQUIDCEXTERN int _free_osfhnd(int); + +#endif + +SQUIDCEXTERN THREADLOCAL int ws32_result; + +#define strerror(e) WIN32_strerror(e) + +#ifdef __cplusplus + +inline +int close(int fd) +{ + char l_so_type[sizeof(int)]; + int l_so_type_siz = sizeof(l_so_type); + SOCKET sock = _get_osfhandle(fd); + + if (::getsockopt(sock, SOL_SOCKET, SO_TYPE, l_so_type, &l_so_type_siz) == 0){ + int result = 0; + if (closesocket(sock) == SOCKET_ERROR) { + errno = WSAGetLastError(); + result = 1; + } + _free_osfhnd(fd); + _osfile(fd) = 0; + return result; + } + else + return _close(fd); +} + +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ + +#ifndef _S_IREAD +#define _S_IREAD 0x0100 +#endif + +#ifndef _S_IWRITE +#define _S_IWRITE 0x0080 +#endif + +inline +int open(const char *filename, int oflag, int pmode = 0) +{ + return _open(filename, oflag, pmode & (_S_IREAD | _S_IWRITE)); +} +#endif + +inline +int read(int fd, void * buf, size_t siz) +{ + char l_so_type[sizeof(int)]; + int l_so_type_siz = sizeof(l_so_type); + SOCKET sock = _get_osfhandle(fd); + + if (::getsockopt(sock, SOL_SOCKET, SO_TYPE, l_so_type, &l_so_type_siz) == 0) + return ::recv(sock, (char FAR *) buf, (int)siz, 0); + else + return _read(fd, buf, (unsigned int)siz); +} + +inline +int write(int fd, const void * buf, size_t siz) +{ + char l_so_type[sizeof(int)]; + int l_so_type_siz = sizeof(l_so_type); + SOCKET sock = _get_osfhandle(fd); + + if (::getsockopt(sock, SOL_SOCKET, SO_TYPE, l_so_type, &l_so_type_siz) == 0) + return ::send(sock, (char FAR *) buf, siz, 0); + else + return _write(fd, buf, siz); +} + +inline +char *index(const char *s, int c) +{ + return (char *)strchr(s,c); +} + +namespace Squid { + +inline +int accept(int s, struct sockaddr * a, int * l) +{ + SOCKET result; + if ((result = ::accept(_get_osfhandle(s), a, l)) == INVALID_SOCKET) { + if (WSAEMFILE == (errno = WSAGetLastError())) + errno = EMFILE; + return -1; + } + else + return _open_osfhandle(result, 0); +} + +inline +int bind(int s, struct sockaddr * n, int l) +{ + if (::bind(_get_osfhandle(s),n,l) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +inline +int connect(int s, const struct sockaddr * n, int l) +{ + if (::connect(_get_osfhandle(s),n,l) == SOCKET_ERROR) { + if (WSAEMFILE == (errno = WSAGetLastError())) + errno = EMFILE; + return -1; + } + else + return 0; +} + +inline +struct hostent * gethostbyname (const char *n) +{ + HOSTENT FAR * result; + if ((result = ::gethostbyname(n)) == NULL) + errno = WSAGetLastError(); + return result; +} +#define gethostbyname(n) Squid::gethostbyname(n) + +inline +SERVENT FAR* getservbyname (const char * n, const char * p) +{ + SERVENT FAR * result; + if ((result = ::getservbyname(n, p)) == NULL) + errno = WSAGetLastError(); + return result; +} +#define getservbyname(n,p) Squid::getservbyname(n,p) + +inline +HOSTENT FAR * gethostbyaddr(const char * a, int l, int t) +{ + HOSTENT FAR * result; + if ((result = ::gethostbyaddr(a, l, t)) == NULL) + errno = WSAGetLastError(); + return result; +} +#define gethostbyaddr(a,l,t) Squid::gethostbyaddr(a,l,t) + +inline +int getsockname(int s, struct sockaddr * n, int * l) +{ + if ((::getsockname(_get_osfhandle(s), n, l)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +inline +int gethostname(char * n, size_t l) +{ + if ((::gethostname(n, l)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} +#define gethostname(n,l) Squid::gethostname(n,l) + +inline +int getsockopt(int s, int l, int o, void * v, int * n) +{ + Sleep(1); + if ((::getsockopt(_get_osfhandle(s), l, o,(char *) v, n)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +/* Simple ioctl() emulation */ +inline +int ioctl(int s, int c, void * a) +{ + if ((::ioctlsocket(_get_osfhandle(s), c, (u_long FAR *)a)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +inline +int ioctlsocket(int s, long c, u_long FAR * a) +{ + if ((::ioctlsocket(_get_osfhandle(s), c, a)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +inline +int listen(int s, int b) +{ + if (::listen(_get_osfhandle(s), b) == SOCKET_ERROR) { + if (WSAEMFILE == (errno = WSAGetLastError())) + errno = EMFILE; + return -1; + } + else + return 0; +} +#define listen(s,b) Squid::listen(s,b) + +inline +int recv(int s, void * b, size_t l, int f) +{ + int result; + if ((result = ::recv(_get_osfhandle(s), (char *)b, l, f)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return result; +} + +inline +int recvfrom(int s, void * b, size_t l, int f, struct sockaddr * fr, int * fl) +{ + int result; + if ((result = ::recvfrom(_get_osfhandle(s), (char *)b, l, f, fr, fl)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return result; +} + +inline +int select(int n, fd_set * r, fd_set * w, fd_set * e, struct timeval * t) +{ + int result; + if ((result = ::select(n,r,w,e,t)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return result; +} +#define select(n,r,w,e,t) Squid::select(n,r,w,e,t) + +inline +int send(int s, const void * b, size_t l, int f) +{ + int result; + if ((result = ::send(_get_osfhandle(s), (char *)b, l, f)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return result; +} + +inline +int sendto(int s, const void * b, size_t l, int f, const struct sockaddr * t, int tl) +{ + int result; + if ((result = ::sendto(_get_osfhandle(s), (char *)b, l, f, t, tl)) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return result; +} + +inline +int setsockopt(SOCKET s, int l, int o, const char * v, int n) +{ + SOCKET socket; + + socket = ((s == INVALID_SOCKET) ? s : (SOCKET)_get_osfhandle((int)s)); + + if (::setsockopt(socket, l, o, v, n) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} +#define setsockopt(s,l,o,v,n) Squid::setsockopt(s,l,o,v,n) + +inline +int shutdown(int s, int h) +{ + if (::shutdown(_get_osfhandle(s),h) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +inline +int socket(int f, int t, int p) +{ + SOCKET result; + if ((result = ::socket(f, t, p)) == INVALID_SOCKET) { + if (WSAEMFILE == (errno = WSAGetLastError())) + errno = EMFILE; + return -1; + } + else + return _open_osfhandle(result, 0); +} +#define socket(f,t,p) Squid::socket(f,t,p) + +inline +int WSAAsyncSelect(int s, HWND h, unsigned int w, long e) +{ + if (::WSAAsyncSelect(_get_osfhandle(s), h, w, e) == SOCKET_ERROR) { + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +#undef WSADuplicateSocket +inline +int WSADuplicateSocket(int s, DWORD n, LPWSAPROTOCOL_INFO l) +{ +#ifdef UNICODE + if (::WSADuplicateSocketW(_get_osfhandle(s), n, l) == SOCKET_ERROR) { +#else + if (::WSADuplicateSocketA(_get_osfhandle(s), n, l) == SOCKET_ERROR) { +#endif + errno = WSAGetLastError(); + return -1; + } + else + return 0; +} + +#undef WSASocket +inline +int WSASocket(int a, int t, int p, LPWSAPROTOCOL_INFO i, GROUP g, DWORD f) +{ + SOCKET result; +#ifdef UNICODE + if ((result = ::WSASocketW(a, t, p, i, g, f)) == INVALID_SOCKET) { +#else + if ((result = ::WSASocketA(a, t, p, i, g, f)) == INVALID_SOCKET) { +#endif + if (WSAEMFILE == (errno = WSAGetLastError())) + errno = EMFILE; + return -1; + } + else + return _open_osfhandle(result, 0); +} + +} /* namespace Squid */ + +#else /* #ifdef __cplusplus */ +#define connect(s,n,l) \ + (SOCKET_ERROR == connect(_get_osfhandle(s),n,l) ? \ + (WSAEMFILE == (errno = WSAGetLastError()) ? errno = EMFILE : -1, -1) : 0) +#define gethostbyname(n) \ + (NULL == ((HOSTENT FAR*)(ws32_result = (int)gethostbyname(n))) ? \ + (errno = WSAGetLastError()), (HOSTENT FAR*)NULL : (HOSTENT FAR*)ws32_result) +#define gethostname(n,l) \ + (SOCKET_ERROR == gethostname(n,l) ? \ + (errno = WSAGetLastError()), -1 : 0) +#define recv(s,b,l,f) \ + (SOCKET_ERROR == (ws32_result = recv(_get_osfhandle(s),b,l,f)) ? \ + (errno = WSAGetLastError()), -1 : ws32_result) +#define sendto(s,b,l,f,t,tl) \ + (SOCKET_ERROR == (ws32_result = sendto(_get_osfhandle(s),b,l,f,t,tl)) ? \ + (errno = WSAGetLastError()), -1 : ws32_result) +#define select(n,r,w,e,t) \ + (SOCKET_ERROR == (ws32_result = select(n,r,w,e,t)) ? \ + (errno = WSAGetLastError()), -1 : ws32_result) +#define socket(f,t,p) \ + (INVALID_SOCKET == ((SOCKET)(ws32_result = (int)socket(f,t,p))) ? \ + ((WSAEMFILE == (errno = WSAGetLastError()) ? errno = EMFILE : -1), -1) : \ + (SOCKET)_open_osfhandle(ws32_result,0)) +#define write _write /* Needed in util.c */ +#define open _open /* Needed in win32lib.c */ +#endif /* #ifdef __cplusplus */ + +#define RUSAGE_SELF 0 /* calling process */ +#define RUSAGE_CHILDREN -1 /* terminated child processes */ + +struct rusage { + struct timeval ru_utime; /* user time used */ + struct timeval ru_stime; /* system time used */ + long ru_maxrss; /* integral max resident set size */ + long ru_ixrss; /* integral shared text memory size */ + long ru_idrss; /* integral unshared data size */ + long ru_isrss; /* integral unshared stack size */ + long ru_minflt; /* page reclaims */ + long ru_majflt; /* page faults */ + long ru_nswap; /* swaps */ + long ru_inblock; /* block input operations */ + long ru_oublock; /* block output operations */ + long ru_msgsnd; /* messages sent */ + long ru_msgrcv; /* messages received */ + long ru_nsignals; /* signals received */ + long ru_nvcsw; /* voluntary context switches */ + long ru_nivcsw; /* involuntary context switches */ +}; + +#undef ACL + +SQUIDCEXTERN int chroot (const char *); +SQUIDCEXTERN int ftruncate(int, off_t); +SQUIDCEXTERN int gettimeofday(struct timeval * ,void *); +SQUIDCEXTERN int kill(pid_t, int); +SQUIDCEXTERN int statfs(const char *, struct statfs *); +SQUIDCEXTERN int truncate(const char *, off_t); +SQUIDCEXTERN const char * wsastrerror(int); +SQUIDCEXTERN struct passwd *getpwnam(char *); +SQUIDCEXTERN struct group *getgrnam(char *); +SQUIDCEXTERN uid_t geteuid(void); +SQUIDCEXTERN uid_t getuid(void); +SQUIDCEXTERN int setuid(uid_t); +SQUIDCEXTERN int seteuid(uid_t); +SQUIDCEXTERN gid_t getgid(void); +SQUIDCEXTERN gid_t getegid(void); +SQUIDCEXTERN int setgid(gid_t); +SQUIDCEXTERN int setegid(gid_t); +SQUIDCEXTERN const char *WIN32_strerror(int); +SQUIDCEXTERN void WIN32_maperror(unsigned long); --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/include/strsep.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,53 @@ +/* Copyright (C) 2004 Free Software Foundation, Inc. + * Written by Yoann Vandoorselaere + * + * The file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA. + */ + +#ifndef GNULIB_STRSEP_H_ +#define GNULIB_STRSEP_H_ + +#if HAVE_STRSEP + +/* + * Get strsep() declaration. + */ +#include + +#else + +/* Searches the next delimiter (char listed in DELIM) starting at *STRINGP. + If one is found, it is overwritten with a NUL, and *STRINGP is advanced + to point to the next char after it. Otherwise, *STRINGP is set to NULL. + If *STRINGP was already NULL, nothing happens. + Returns the old value of *STRINGP. + + This is a variant of strtok() that is multithread-safe and supports + empty fields. + + Caveat: It modifies the original string. + Caveat: These functions cannot be used on constant strings. + Caveat: The identity of the delimiting character is lost. + Caveat: It doesn't work with multibyte strings unless all of the delimiter + characters are ASCII characters < 0x30. + + See also strtok_r(). */ + +SQUIDCEXTERN char *strsep (char **stringp, const char *delim); + +#endif + +#endif /* GNULIB_STRSEP_H_ */ --- squid3/include/samba/.cvsignore Wed Feb 14 13:38:02 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- squid3/include/samba/nsswitch/.cvsignore Wed Feb 14 13:38:02 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,2 +0,0 @@ -.cvsignore -Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/assert.c Wed Feb 14 13:38:02 2007 @@ -0,0 +1,45 @@ + +/* + * $Id: assert.c,v 1.1.12.2 2006/09/29 23:15:54 dwsquid Exp $ + * + * AUTHOR: Henrik Nordstrom + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "config.h" + +#include +#include + +#include "assert.h" + +void xassert(const char *expr, const char *file, int line) { + fprintf(stderr, "assertion failed: %s:%d: \"%s\"\n", file, line, expr); + abort(); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/strsep.c Wed Feb 14 13:38:02 2007 @@ -0,0 +1,58 @@ +/* + * $Id: strsep.c,v 1.1.10.2 2006/09/29 23:15:54 dwsquid Exp $ + */ + +/* Copyright (C) 2004 Free Software Foundation, Inc. + * Written by Yoann Vandoorselaere + * + * The file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +/* Specification. */ +#include "strsep.h" + +#include + +char * +strsep (char **stringp, const char *delim) +{ + char *start = *stringp; + char *ptr; + + if (!start) + return NULL; + + if (!*delim) + ptr = start + strlen (start); + else + { + ptr = strpbrk (start, delim); + if (!ptr) + { + *stringp = NULL; + return start; + } + } + + *ptr = '\0'; + *stringp = ptr + 1; + + return start; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/win32lib.c Wed Feb 14 13:38:02 2007 @@ -0,0 +1,622 @@ + +/* + * $Id: win32lib.c,v 1.4.2.2 2006/09/29 23:15:54 dwsquid Exp $ + * + * Windows support + * AUTHOR: Guido Serassio + * inspired by previous work by Romeo Anghelache & Eric Stern. + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "util.h" + +/* The following code section is part of an EXPERIMENTAL native */ +/* Windows NT/2000 Squid port - Compiles only on MS Visual C++ */ +#if defined(_SQUID_MSWIN_) + +#undef strerror +#define sys_nerr _sys_nerr + +#undef assert +#include +#include +#include +#include "squid_windows.h" +#include +#include +#if HAVE_WIN32_PSAPI +#include +#endif + +THREADLOCAL int ws32_result; +LPCRITICAL_SECTION dbg_mutex = NULL; + +void GetProcessName(pid_t, char *); + +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +size_t +getpagesize() +{ + return 4096; +} +#endif + +uid_t +geteuid(void) +{ + return 100; +} + +uid_t +getuid(void) +{ + return 100; +} + +int +setuid(uid_t uid) +{ + return 0; +} + +int +seteuid(uid_t euid) +{ + return 0; +} + +gid_t +getegid(void) +{ + return 100; +} + +gid_t +getgid(void) +{ + return 100; +} + +int +setgid(gid_t gid) +{ + return 0; +} + +int +setegid(gid_t egid) +{ + return 0; +} + +int +chroot(const char *dirname) +{ + if (SetCurrentDirectory(dirname)) + return 0; + else + return GetLastError(); +} + +void +GetProcessName(pid_t pid, char *ProcessName) +{ + HANDLE hProcess; + + strcpy(ProcessName, "unknown"); +#if HAVE_WIN32_PSAPI + /* Get a handle to the process. */ + hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | + PROCESS_VM_READ, + FALSE, pid); + /* Get the process name. */ + if (NULL != hProcess) { + HMODULE hMod; + DWORD cbNeeded; + + if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) + GetModuleBaseName(hProcess, hMod, ProcessName, sizeof(ProcessName)); + else { + CloseHandle(hProcess); + return; + } + } else + return; + CloseHandle(hProcess); +#endif +} + +int +kill(pid_t pid, int sig) +{ + HANDLE hProcess; + char MyProcessName[MAX_PATH]; + char ProcessNameToCheck[MAX_PATH]; + + if (sig == 0) { + if ((hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | + PROCESS_VM_READ, + FALSE, pid)) == NULL) + return -1; + else { + CloseHandle(hProcess); + GetProcessName(getpid(), MyProcessName); + GetProcessName(pid, ProcessNameToCheck); + if (strcmp(MyProcessName, ProcessNameToCheck) == 0) + return 0; + return -1; + } + } else + return 0; +} + +int +gettimeofday(struct timeval *pcur_time, void *tzp) +{ + struct _timeb current; + struct timezone *tz = (struct timezone *) tzp; + + _ftime(¤t); + + pcur_time->tv_sec = current.time; + pcur_time->tv_usec = current.millitm * 1000L; + if (tz) { + tz->tz_minuteswest = current.timezone; /* minutes west of Greenwich */ + tz->tz_dsttime = current.dstflag; /* type of dst correction */ + } + return 0; +} + +int +statfs(const char *path, struct statfs *sfs) +{ + char drive[4]; + DWORD spc, bps, freec, totalc; + DWORD vsn, maxlen, flags; + + if (!sfs) { + errno = EINVAL; + return -1; + } + strncpy(drive, path, 2); + drive[2] = '\0'; + strcat(drive, "\\"); + + if (!GetDiskFreeSpace(drive, &spc, &bps, &freec, &totalc)) { + errno = ENOENT; + return -1; + } + if (!GetVolumeInformation(drive, NULL, 0, &vsn, &maxlen, &flags, NULL, 0)) { + errno = ENOENT; + return -1; + } + sfs->f_type = flags; + sfs->f_bsize = spc * bps; + sfs->f_blocks = totalc; + sfs->f_bfree = sfs->f_bavail = freec; + sfs->f_files = -1; + sfs->f_ffree = -1; + sfs->f_fsid = vsn; + sfs->f_namelen = maxlen; + return 0; +} + +int +WIN32_ftruncate(int fd, off_t size) +{ + HANDLE hfile; + unsigned int curpos; + + if (fd < 0) + return -1; + + hfile = (HANDLE) _get_osfhandle(fd); + curpos = SetFilePointer(hfile, 0, NULL, FILE_CURRENT); + if (curpos == 0xFFFFFFFF + || SetFilePointer(hfile, size, NULL, FILE_BEGIN) == 0xFFFFFFFF + || !SetEndOfFile(hfile)) { + int error = GetLastError(); + + switch (error) { + case ERROR_INVALID_HANDLE: + errno = EBADF; + break; + default: + errno = EIO; + break; + } + + return -1; + } + return 0; +} + +int +WIN32_truncate(const char *pathname, off_t length) +{ + int fd; + int res = -1; + + fd = open(pathname, O_RDWR); + + if (fd == -1) + errno = EBADF; + else { + res = WIN32_ftruncate(fd, length); + _close(fd); + } + + return res; +} + +static struct _wsaerrtext { + int err; + const char *errconst; + const char *errdesc; +} _wsaerrtext[] = { + + { + WSA_E_CANCELLED, "WSA_E_CANCELLED", "Lookup cancelled." + }, + { + WSA_E_NO_MORE, "WSA_E_NO_MORE", "No more data available." + }, + { + WSAEACCES, "WSAEACCES", "Permission denied." + }, + { + WSAEADDRINUSE, "WSAEADDRINUSE", "Address already in use." + }, + { + WSAEADDRNOTAVAIL, "WSAEADDRNOTAVAIL", "Cannot assign requested address." + }, + { + WSAEAFNOSUPPORT, "WSAEAFNOSUPPORT", "Address family not supported by protocol family." + }, + { + WSAEALREADY, "WSAEALREADY", "Operation already in progress." + }, + { + WSAEBADF, "WSAEBADF", "Bad file number." + }, + { + WSAECANCELLED, "WSAECANCELLED", "Operation cancelled." + }, + { + WSAECONNABORTED, "WSAECONNABORTED", "Software caused connection abort." + }, + { + WSAECONNREFUSED, "WSAECONNREFUSED", "Connection refused." + }, + { + WSAECONNRESET, "WSAECONNRESET", "Connection reset by peer." + }, + { + WSAEDESTADDRREQ, "WSAEDESTADDRREQ", "Destination address required." + }, + { + WSAEDQUOT, "WSAEDQUOT", "Disk quota exceeded." + }, + { + WSAEFAULT, "WSAEFAULT", "Bad address." + }, + { + WSAEHOSTDOWN, "WSAEHOSTDOWN", "Host is down." + }, + { + WSAEHOSTUNREACH, "WSAEHOSTUNREACH", "No route to host." + }, + { + WSAEINPROGRESS, "WSAEINPROGRESS", "Operation now in progress." + }, + { + WSAEINTR, "WSAEINTR", "Interrupted function call." + }, + { + WSAEINVAL, "WSAEINVAL", "Invalid argument." + }, + { + WSAEINVALIDPROCTABLE, "WSAEINVALIDPROCTABLE", "Invalid procedure table from service provider." + }, + { + WSAEINVALIDPROVIDER, "WSAEINVALIDPROVIDER", "Invalid service provider version number." + }, + { + WSAEISCONN, "WSAEISCONN", "Socket is already connected." + }, + { + WSAELOOP, "WSAELOOP", "Too many levels of symbolic links." + }, + { + WSAEMFILE, "WSAEMFILE", "Too many open files." + }, + { + WSAEMSGSIZE, "WSAEMSGSIZE", "Message too long." + }, + { + WSAENAMETOOLONG, "WSAENAMETOOLONG", "File name is too long." + }, + { + WSAENETDOWN, "WSAENETDOWN", "Network is down." + }, + { + WSAENETRESET, "WSAENETRESET", "Network dropped connection on reset." + }, + { + WSAENETUNREACH, "WSAENETUNREACH", "Network is unreachable." + }, + { + WSAENOBUFS, "WSAENOBUFS", "No buffer space available." + }, + { + WSAENOMORE, "WSAENOMORE", "No more data available." + }, + { + WSAENOPROTOOPT, "WSAENOPROTOOPT", "Bad protocol option." + }, + { + WSAENOTCONN, "WSAENOTCONN", "Socket is not connected." + }, + { + WSAENOTEMPTY, "WSAENOTEMPTY", "Directory is not empty." + }, + { + WSAENOTSOCK, "WSAENOTSOCK", "Socket operation on nonsocket." + }, + { + WSAEOPNOTSUPP, "WSAEOPNOTSUPP", "Operation not supported." + }, + { + WSAEPFNOSUPPORT, "WSAEPFNOSUPPORT", "Protocol family not supported." + }, + { + WSAEPROCLIM, "WSAEPROCLIM", "Too many processes." + }, + { + WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT", "Protocol not supported." + }, + { + WSAEPROTOTYPE, "WSAEPROTOTYPE", "Protocol wrong type for socket." + }, + { + WSAEPROVIDERFAILEDINIT, "WSAEPROVIDERFAILEDINIT", "Unable to initialise a service provider." + }, + { + WSAEREFUSED, "WSAEREFUSED", "Refused." + }, + { + WSAEREMOTE, "WSAEREMOTE", "Too many levels of remote in path." + }, + { + WSAESHUTDOWN, "WSAESHUTDOWN", "Cannot send after socket shutdown." + }, + { + WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT", "Socket type not supported." + }, + { + WSAESTALE, "WSAESTALE", "Stale NFS file handle." + }, + { + WSAETIMEDOUT, "WSAETIMEDOUT", "Connection timed out." + }, + { + WSAETOOMANYREFS, "WSAETOOMANYREFS", "Too many references." + }, + { + WSAEUSERS, "WSAEUSERS", "Too many users." + }, + { + WSAEWOULDBLOCK, "WSAEWOULDBLOCK", "Resource temporarily unavailable." + }, + { + WSANOTINITIALISED, "WSANOTINITIALISED", "Successful WSAStartup not yet performed." + }, + { + WSASERVICE_NOT_FOUND, "WSASERVICE_NOT_FOUND", "Service not found." + }, + { + WSASYSCALLFAILURE, "WSASYSCALLFAILURE", "System call failure." + }, + { + WSASYSNOTREADY, "WSASYSNOTREADY", "Network subsystem is unavailable." + }, + { + WSATYPE_NOT_FOUND, "WSATYPE_NOT_FOUND", "Class type not found." + }, + { + WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED", "Winsock.dll version out of range." + }, + { + WSAEDISCON, "WSAEDISCON", "Graceful shutdown in progress." + } +}; + +/* + * wsastrerror() - description of WSAGetLastError() + */ +const char * +wsastrerror(int err) +{ + static char xwsaerror_buf[BUFSIZ]; + int i, errind = -1; + + if (err == 0) + return "(0) No error."; + for (i = 0; i < sizeof(_wsaerrtext) / sizeof(struct _wsaerrtext); i++) { + if (_wsaerrtext[i].err != err) + continue; + errind = i; + break; + } + if (errind == -1) + snprintf(xwsaerror_buf, BUFSIZ, "Unknown"); + else + snprintf(xwsaerror_buf, BUFSIZ, "%s, %s", _wsaerrtext[errind].errconst, _wsaerrtext[errind].errdesc); + return xwsaerror_buf; +} + +struct passwd * +getpwnam(char *unused) +{ + static struct passwd pwd = + {NULL, NULL, 100, 100, NULL, NULL, NULL}; + return &pwd; +} + +struct group * +getgrnam(char *unused) +{ + static struct group grp = + {NULL, NULL, 100, NULL}; + return &grp; +} + +/* + * WIN32_strerror with argument for late notification */ + +const char * +WIN32_strerror(int err) +{ + static char xbstrerror_buf[BUFSIZ]; + + if (err < 0 || err >= sys_nerr) + strncpy(xbstrerror_buf, wsastrerror(err), BUFSIZ); + else + strncpy(xbstrerror_buf, strerror(err), BUFSIZ); + return xbstrerror_buf; +} + +#if defined(__MINGW32__) /* MinGW environment */ +int +_free_osfhnd(int filehandle) +{ + if (((unsigned) filehandle < SQUID_MAXFD) && + (_osfile(filehandle) & FOPEN) && + (_osfhnd(filehandle) != (long) INVALID_HANDLE_VALUE)) { + switch (filehandle) { + case 0: + SetStdHandle(STD_INPUT_HANDLE, NULL); + break; + case 1: + SetStdHandle(STD_OUTPUT_HANDLE, NULL); + break; + case 2: + SetStdHandle(STD_ERROR_HANDLE, NULL); + break; + } + _osfhnd(filehandle) = (long) INVALID_HANDLE_VALUE; + return (0); + } else { + errno = EBADF; /* bad handle */ + _doserrno = 0L; /* not an OS error */ + return -1; + } +} +#endif + +struct errorentry { + unsigned long WIN32_code; + int POSIX_errno; +}; + +static struct errorentry errortable[] = +{ + {ERROR_INVALID_FUNCTION, EINVAL}, + {ERROR_FILE_NOT_FOUND, ENOENT}, + {ERROR_PATH_NOT_FOUND, ENOENT}, + {ERROR_TOO_MANY_OPEN_FILES, EMFILE}, + {ERROR_ACCESS_DENIED, EACCES}, + {ERROR_INVALID_HANDLE, EBADF}, + {ERROR_ARENA_TRASHED, ENOMEM}, + {ERROR_NOT_ENOUGH_MEMORY, ENOMEM}, + {ERROR_INVALID_BLOCK, ENOMEM}, + {ERROR_BAD_ENVIRONMENT, E2BIG}, + {ERROR_BAD_FORMAT, ENOEXEC}, + {ERROR_INVALID_ACCESS, EINVAL}, + {ERROR_INVALID_DATA, EINVAL}, + {ERROR_INVALID_DRIVE, ENOENT}, + {ERROR_CURRENT_DIRECTORY, EACCES}, + {ERROR_NOT_SAME_DEVICE, EXDEV}, + {ERROR_NO_MORE_FILES, ENOENT}, + {ERROR_LOCK_VIOLATION, EACCES}, + {ERROR_BAD_NETPATH, ENOENT}, + {ERROR_NETWORK_ACCESS_DENIED, EACCES}, + {ERROR_BAD_NET_NAME, ENOENT}, + {ERROR_FILE_EXISTS, EEXIST}, + {ERROR_CANNOT_MAKE, EACCES}, + {ERROR_FAIL_I24, EACCES}, + {ERROR_INVALID_PARAMETER, EINVAL}, + {ERROR_NO_PROC_SLOTS, EAGAIN}, + {ERROR_DRIVE_LOCKED, EACCES}, + {ERROR_BROKEN_PIPE, EPIPE}, + {ERROR_DISK_FULL, ENOSPC}, + {ERROR_INVALID_TARGET_HANDLE, EBADF}, + {ERROR_INVALID_HANDLE, EINVAL}, + {ERROR_WAIT_NO_CHILDREN, ECHILD}, + {ERROR_CHILD_NOT_COMPLETE, ECHILD}, + {ERROR_DIRECT_ACCESS_HANDLE, EBADF}, + {ERROR_NEGATIVE_SEEK, EINVAL}, + {ERROR_SEEK_ON_DEVICE, EACCES}, + {ERROR_DIR_NOT_EMPTY, ENOTEMPTY}, + {ERROR_NOT_LOCKED, EACCES}, + {ERROR_BAD_PATHNAME, ENOENT}, + {ERROR_MAX_THRDS_REACHED, EAGAIN}, + {ERROR_LOCK_FAILED, EACCES}, + {ERROR_ALREADY_EXISTS, EEXIST}, + {ERROR_FILENAME_EXCED_RANGE, ENOENT}, + {ERROR_NESTING_NOT_ALLOWED, EAGAIN}, + {ERROR_NOT_ENOUGH_QUOTA, ENOMEM} +}; + +#define MIN_EXEC_ERROR ERROR_INVALID_STARTING_CODESEG +#define MAX_EXEC_ERROR ERROR_INFLOOP_IN_RELOC_CHAIN + +#define MIN_EACCES_RANGE ERROR_WRITE_PROTECT +#define MAX_EACCES_RANGE ERROR_SHARING_BUFFER_EXCEEDED + +void +WIN32_maperror(unsigned long WIN32_oserrno) +{ + int i; + + _doserrno = WIN32_oserrno; + for (i = 0; i < (sizeof(errortable) / sizeof(struct errorentry)); ++i) { + if (WIN32_oserrno == errortable[i].WIN32_code) { + errno = errortable[i].POSIX_errno; + return; + } + } + if (WIN32_oserrno >= MIN_EACCES_RANGE && WIN32_oserrno <= MAX_EACCES_RANGE) + errno = EACCES; + else if (WIN32_oserrno >= MIN_EXEC_ERROR && WIN32_oserrno <= MAX_EXEC_ERROR) + errno = ENOEXEC; + else + errno = EINVAL; +} +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,9 @@ +Makefile +config.log +config.status +cppunit-config +libtool +autom4te.cache +configure.lineno +_configs.sed +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/config/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,3 @@ +config.h +stamp-h1 +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/config/ax_prefix_config_h.m4 Wed Feb 14 13:38:02 2007 @@ -0,0 +1,173 @@ +dnl @synopsis AX_PREFIX_CONFIG_H [(OUTPUT-HEADER [,PREFIX [,ORIG-HEADER]])] +dnl +dnl This is a new variant from ac_prefix_config_ this one will use a +dnl lowercase-prefix if the config-define was starting with a +dnl lowercase-char, e.g. "#define const", "#define restrict", or +dnl "#define off_t", (and this one can live in another directory, e.g. +dnl testpkg/config.h therefore I decided to move the output-header to +dnl be the first arg) +dnl +dnl takes the usual config.h generated header file; looks for each of +dnl the generated "#define SOMEDEF" lines, and prefixes the defined +dnl name (ie. makes it "#define PREFIX_SOMEDEF". The result is written +dnl to the output config.header file. The PREFIX is converted to +dnl uppercase for the conversions. +dnl +dnl Defaults: +dnl +dnl OUTPUT-HEADER = $PACKAGE-config.h +dnl PREFIX = $PACKAGE +dnl ORIG-HEADER, from AM_CONFIG_HEADER(config.h) +dnl +dnl Your configure.ac script should contain both macros in this order, +dnl and unlike the earlier variations of this prefix-macro it is okay +dnl to place the AX_PREFIX_CONFIG_H call before the AC_OUTPUT +dnl invokation. +dnl +dnl Example: +dnl +dnl AC_INIT(config.h.in) # config.h.in as created by "autoheader" +dnl AM_INIT_AUTOMAKE(testpkg, 0.1.1) # makes #undef VERSION and PACKAGE +dnl AM_CONFIG_HEADER(config.h) # prep config.h from config.h.in +dnl AX_PREFIX_CONFIG_H(mylib/_config.h) # prep mylib/_config.h from it.. +dnl AC_MEMORY_H # makes "#undef NEED_MEMORY_H" +dnl AC_C_CONST_H # makes "#undef const" +dnl AC_OUTPUT(Makefile) # creates the "config.h" now +dnl # and also mylib/_config.h +dnl +dnl if the argument to AX_PREFIX_CONFIG_H would have been omitted then +dnl the default outputfile would have been called simply +dnl "testpkg-config.h", but even under the name "mylib/_config.h" it +dnl contains prefix-defines like +dnl +dnl #ifndef TESTPKG_VERSION +dnl #define TESTPKG_VERSION "0.1.1" +dnl #endif +dnl #ifndef TESTPKG_NEED_MEMORY_H +dnl #define TESTPKG_NEED_MEMORY_H 1 +dnl #endif +dnl #ifndef _testpkg_const +dnl #define _testpkg_const _const +dnl #endif +dnl +dnl and this "mylib/_config.h" can be installed along with other +dnl header-files, which is most convenient when creating a shared +dnl library (that has some headers) where some functionality is +dnl dependent on the OS-features detected at compile-time. No need to +dnl invent some "mylib-confdefs.h.in" manually. :-) +dnl +dnl Note that some AC_DEFINEs that end up in the config.h file are +dnl actually self-referential - e.g. AC_C_INLINE, AC_C_CONST, and the +dnl AC_TYPE_OFF_T say that they "will define inline|const|off_t if the +dnl system does not do it by itself". You might want to clean up about +dnl these - consider an extra mylib/conf.h that reads something like: +dnl +dnl #include +dnl #ifndef _testpkg_const +dnl #define _testpkg_const const +dnl #endif +dnl +dnl and then start using _testpkg_const in the header files. That is +dnl also a good thing to differentiate whether some library-user has +dnl starting to take up with a different compiler, so perhaps it could +dnl read something like this: +dnl +dnl #ifdef _MSC_VER +dnl #include +dnl #else +dnl #include +dnl #endif +dnl #ifndef _testpkg_const +dnl #define _testpkg_const const +dnl #endif +dnl +dnl @category Misc +dnl @author Guido Draheim +dnl @author Mårten Svantesson +dnl @version 2005-06-08 +dnl @license GPLWithACException + +AC_DEFUN([AX_PREFIX_CONFIG_H],[AC_REQUIRE([AC_CONFIG_HEADER]) +AC_CONFIG_COMMANDS([ifelse($1,,$PACKAGE-config.h,$1)],[dnl +AS_VAR_PUSHDEF([_OUT],[ac_prefix_conf_OUT])dnl +AS_VAR_PUSHDEF([_DEF],[ac_prefix_conf_DEF])dnl +AS_VAR_PUSHDEF([_PKG],[ac_prefix_conf_PKG])dnl +AS_VAR_PUSHDEF([_LOW],[ac_prefix_conf_LOW])dnl +AS_VAR_PUSHDEF([_UPP],[ac_prefix_conf_UPP])dnl +AS_VAR_PUSHDEF([_INP],[ac_prefix_conf_INP])dnl +m4_pushdef([_script],[conftest.prefix])dnl +m4_pushdef([_symbol],[m4_cr_Letters[]m4_cr_digits[]_])dnl +_OUT=`printf '%s\n' ifelse($1, , $PACKAGE-config.h, $1)` +_DEF=`printf '%s\n' _$_OUT | sed -e "y:m4_cr_letters:m4_cr_LETTERS[]:" -e "s/@<:@^m4_cr_Letters@:>@/_/g"` +_PKG=`printf '%s\n' ifelse($2, , $PACKAGE, $2)` +_LOW=`printf '%s\n' _$_PKG | sed -e "y:m4_cr_LETTERS-:m4_cr_letters[]_:"` +_UPP=`printf '%s\n' $_PKG | sed -e "y:m4_cr_letters-:m4_cr_LETTERS[]_:" -e "/^@<:@m4_cr_digits@:>@/s/^/_/"` +_INP=`printf '%s\n' "ifelse($3,,,$3)" | sed -e 's/ *//'` +if test ".$_INP" = "."; then + for ac_file in : $CONFIG_HEADERS; do test "_$ac_file" = _: && continue + case "$ac_file" in + *.h) _INP=$ac_file ;; + *) + esac + test ".$_INP" != "." && break + done +fi +if test ".$_INP" = "."; then + case "$_OUT" in + */*) _INP=`basename "$_OUT"` + ;; + *-*) _INP=`printf '%s\n' "$_OUT" | sed -e "s/@<:@_symbol@:>@*-//"` + ;; + *) _INP=config.h + ;; + esac +fi +if test -z "$_PKG" ; then + AC_MSG_ERROR([no prefix for _PREFIX_PKG_CONFIG_H]) +else + if test ! -f "$_INP" ; then if test -f "$srcdir/$_INP" ; then + _INP="$srcdir/$_INP" + fi fi + AC_MSG_NOTICE(creating $_OUT - prefix $_UPP for $_INP defines) + if test -f $_INP ; then + printf '%s\n' "s/@%:@undef *\\(@<:@m4_cr_LETTERS[]_@:>@\\)/@%:@undef $_UPP""_\\1/" > _script + printf '%s\n' "s/@%:@undef *\\(@<:@m4_cr_letters@:>@\\)/@%:@undef $_LOW""_\\1/" >> _script + printf '%s\n' "s/@%:@def[]ine *\\(@<:@m4_cr_LETTERS[]_@:>@@<:@_symbol@:>@*\\)\\(.*\\)/@%:@ifndef $_UPP""_\\1 \\" >> _script + printf '%s\n' "@%:@def[]ine $_UPP""_\\1 \\2 \\" >> _script + printf '%s\n' "@%:@endif/" >>_script + printf '%s\n' "s/@%:@def[]ine *\\(@<:@m4_cr_letters@:>@@<:@_symbol@:>@*\\)\\(.*\\)/@%:@ifndef $_LOW""_\\1 \\" >> _script + printf '%s\n' "@%:@define $_LOW""_\\1 \\2 \\" >> _script + printf '%s\n' "@%:@endif/" >> _script + # now executing _script on _DEF input to create _OUT output file + printf '%s\n' "@%:@ifndef $_DEF" >$tmp/pconfig.h + printf '%s\n' "@%:@def[]ine $_DEF 1" >>$tmp/pconfig.h + printf '%s\n' ' ' >>$tmp/pconfig.h + printf '%s\n' /'*' $_OUT. Generated automatically at end of configure. '*'/ >>$tmp/pconfig.h + + sed -f _script $_INP >>$tmp/pconfig.h + printf '%s\n' ' ' >>$tmp/pconfig.h + printf '%s\n' '/* once:' $_DEF '*/' >>$tmp/pconfig.h + printf '%s\n' "@%:@endif" >>$tmp/pconfig.h + if cmp -s $_OUT $tmp/pconfig.h 2>/dev/null; then + AC_MSG_NOTICE([$_OUT is unchanged]) + else + ac_dir=`AS_DIRNAME(["$_OUT"])` + AS_MKDIR_P(["$ac_dir"]) + rm -f "$_OUT" + mv $tmp/pconfig.h "$_OUT" + fi + cp _script _configs.sed + else + AC_MSG_ERROR([input file $_INP does not exist - skip generating $_OUT]) + fi + rm -f conftest.* +fi +m4_popdef([_symbol])dnl +m4_popdef([_script])dnl +AS_VAR_POPDEF([_INP])dnl +AS_VAR_POPDEF([_UPP])dnl +AS_VAR_POPDEF([_LOW])dnl +AS_VAR_POPDEF([_PKG])dnl +AS_VAR_POPDEF([_DEF])dnl +AS_VAR_POPDEF([_OUT])dnl +],[PACKAGE="$PACKAGE"])]) --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/doc/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,3 @@ +Doxyfile +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/ClockerPlugIn/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/DumperPlugIn/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/cppunittest/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +cppunittestmain +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/hierarchy/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +hierarchy +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/money/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +MoneyApp +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/examples/simple/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,5 @@ +.deps +.libs +Makefile +simple +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,3 @@ +Makefile +config-auto.h +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/config/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/extensions/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/plugin/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/portability/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/tools/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/ui/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/ui/mfc/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/ui/qt/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/include/cppunit/ui/text/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/src/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,2 @@ +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/src/DllPlugInTester/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,6 @@ +.deps +.libs +DllPlugInTester +DllPlugInTesterTest +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/cppunit-1.10.0/src/cppunit/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,7 @@ +*.lo +*.la +.cvsignore +.deps +.libs +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/lib/tests/.cvsignore Wed Feb 14 13:38:02 2007 @@ -0,0 +1,4 @@ +.dirstamp +.libs +testAll +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ACLHTTPHeaderData.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,109 @@ +/* + * $Id: ACLHTTPHeaderData.cc,v 1.2.8.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * DEBUG: section 28 Access Control + * AUTHOR: Duane Wessels + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#include "squid.h" +#include "ACLHTTPHeaderData.h" +#include "authenticate.h" +#include "ACLChecklist.h" +#include "ACL.h" +#include "ACLRegexData.h" +#include "wordlist.h" +#include "ConfigParser.h" + +/* Construct an ACLHTTPHeaderData that uses an ACLRegex rule with the value of the + * selected header from a given request. + * + * TODO: This can be generalised by making the type of the regex_rule into a + * template parameter - so that we can use different rules types in future. + */ +ACLHTTPHeaderData::ACLHTTPHeaderData() : hdrId(HDR_BAD_HDR), regex_rule(new ACLRegexData) +{} + +ACLHTTPHeaderData::~ACLHTTPHeaderData() +{ + delete regex_rule; +} + +bool +ACLHTTPHeaderData::match(HttpHeader* hdr) +{ + if (hdr == NULL) + return false; + + debug(28, 3) ("aclHeaderData::match: checking '%s'\n", hdrName.buf()); + + String value = hdrId != HDR_BAD_HDR ? hdr->getStrOrList(hdrId) : hdr->getByName(hdrName.buf()); + + return regex_rule->match(value.buf()); +} + +wordlist * +ACLHTTPHeaderData::dump() +{ + wordlist *W = NULL; + wordlistAdd(&W, hdrName.buf()); + wordlist * regex_dump = regex_rule->dump(); + wordlistAddWl(&W, regex_dump); + wordlistDestroy(®ex_dump); + return W; +} + +void +ACLHTTPHeaderData::parse() +{ + char* t = strtokFile(); + assert (t != NULL); + hdrName = t; + hdrId = httpHeaderIdByNameDef(hdrName.buf(), strlen(hdrName.buf())); + regex_rule->parse(); +} + +bool +ACLHTTPHeaderData::empty() const +{ + return (hdrId == HDR_BAD_HDR && !hdrName.buf()) || regex_rule->empty(); +} + +ACLData * +ACLHTTPHeaderData::clone() const +{ + /* Header's don't clone yet. */ + ACLHTTPHeaderData * result = new ACLHTTPHeaderData; + result->regex_rule = regex_rule->clone(); + result->hdrId = hdrId; + result->hdrName = hdrName; + return result; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ACLHTTPHeaderData.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,62 @@ + +/* + * $Id: ACLHTTPHeaderData.h,v 1.2.8.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#ifndef SQUID_ACLHTTPHEADERDATA_H +#define SQUID_ACLHTTPHEADERDATA_H +#include "ACLData.h" + +class ACLHTTPHeaderData : public ACLData +{ + +public: + MEMPROXY_CLASS(ACLHTTPHeaderData); + + ACLHTTPHeaderData(); + virtual ~ACLHTTPHeaderData(); + virtual bool match(HttpHeader* hdr); + virtual wordlist *dump(); + virtual void parse(); + virtual bool empty() const; + virtual ACLData *clone() const; + +private: + http_hdr_type hdrId; // set if header is known + String hdrName; // always set + ACLData * regex_rule; +}; + +MEMPROXY_CLASS_INLINE(ACLHTTPHeaderData) + +#endif /* SQUID_ACLHTTPHEADERDATA_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ACLHTTPRepHeader.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,65 @@ + +/* + * $Id: ACLHTTPRepHeader.cc,v 1.1.10.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#include "squid.h" +#include "ACLHTTPRepHeader.h" +#include "ACLHTTPHeaderData.h" +#include "ACLChecklist.h" +#include "HttpReply.h" + +/* explicit template instantiation required for some systems */ + +template class ACLStrategised + +; + +ACL::Prototype ACLHTTPRepHeader::RegistryProtoype(&ACLHTTPRepHeader::RegistryEntry_, "rep_header"); + +ACLStrategised ACLHTTPRepHeader::RegistryEntry_(new ACLHTTPHeaderData, ACLHTTPRepHeaderStrategy::Instance(), "rep_header"); + +int +ACLHTTPRepHeaderStrategy::match (ACLData * &data, ACLChecklist *checklist) +{ + return data->match (&checklist->reply->header); +} + +ACLHTTPRepHeaderStrategy * +ACLHTTPRepHeaderStrategy::Instance() +{ + return &Instance_; +} + +ACLHTTPRepHeaderStrategy ACLHTTPRepHeaderStrategy::Instance_; + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ACLHTTPRepHeader.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,70 @@ + +/* + * $Id: ACLHTTPRepHeader.h,v 1.2.8.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#ifndef SQUID_ACLHTTPREPHEADER_H +#define SQUID_ACLHTTPREPHEADER_H +#include "ACLStrategy.h" +#include "ACLStrategised.h" +#include "HttpHeader.h" + +class ACLHTTPRepHeaderStrategy : public ACLStrategy +{ + +public: + virtual int match (ACLData * &, ACLChecklist *); + virtual bool requiresReply() const { return true; } + + static ACLHTTPRepHeaderStrategy *Instance(); + /* Not implemented to prevent copies of the instance. */ + /* Not private to prevent brain dead g+++ warnings about + * private constructors with no friends */ + ACLHTTPRepHeaderStrategy(ACLHTTPRepHeaderStrategy const &); + +private: + static ACLHTTPRepHeaderStrategy Instance_; + ACLHTTPRepHeaderStrategy() { } + + ACLHTTPRepHeaderStrategy&operator = (ACLHTTPRepHeaderStrategy const &); +}; + +class ACLHTTPRepHeader +{ + +private: + static ACL::Prototype RegistryProtoype; + static ACLStrategised RegistryEntry_; +}; + +#endif /* SQUID_ACLHTTPREPHEADER_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ACLHTTPReqHeader.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,65 @@ + +/* + * $Id: ACLHTTPReqHeader.cc,v 1.1.10.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#include "squid.h" +#include "ACLHTTPReqHeader.h" +#include "ACLHTTPHeaderData.h" +#include "ACLChecklist.h" +#include "HttpRequest.h" + +/* explicit template instantiation required for some systems */ + +template class ACLStrategised + +; + +ACL::Prototype ACLHTTPReqHeader::RegistryProtoype(&ACLHTTPReqHeader::RegistryEntry_, "req_header"); + +ACLStrategised ACLHTTPReqHeader::RegistryEntry_(new ACLHTTPHeaderData, ACLHTTPReqHeaderStrategy::Instance(), "req_header"); + +int +ACLHTTPReqHeaderStrategy::match (ACLData * &data, ACLChecklist *checklist) +{ + return data->match (&checklist->request->header); +} + +ACLHTTPReqHeaderStrategy * +ACLHTTPReqHeaderStrategy::Instance() +{ + return &Instance_; +} + +ACLHTTPReqHeaderStrategy ACLHTTPReqHeaderStrategy::Instance_; + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ACLHTTPReqHeader.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,70 @@ + +/* + * $Id: ACLHTTPReqHeader.h,v 1.2.8.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#ifndef SQUID_ACLHTTPREQHEADER_H +#define SQUID_ACLHTTPREQHEADER_H +#include "ACLStrategy.h" +#include "ACLStrategised.h" +#include "HttpHeader.h" + +class ACLHTTPReqHeaderStrategy : public ACLStrategy +{ + +public: + virtual int match (ACLData * &, ACLChecklist *); + virtual bool requiresRequest() const { return true; } + + static ACLHTTPReqHeaderStrategy *Instance(); + /* Not implemented to prevent copies of the instance. */ + /* Not private to prevent brain dead g+++ warnings about + * private constructors with no friends */ + ACLHTTPReqHeaderStrategy(ACLHTTPReqHeaderStrategy const &); + +private: + static ACLHTTPReqHeaderStrategy Instance_; + ACLHTTPReqHeaderStrategy() { } + + ACLHTTPReqHeaderStrategy&operator = (ACLHTTPReqHeaderStrategy const &); +}; + +class ACLHTTPReqHeader +{ + +private: + static ACL::Prototype RegistryProtoype; + static ACLStrategised RegistryEntry_; +}; + +#endif /* SQUID_ACLHTTPREQHEADER_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/AsyncEngine.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,34 @@ + +/* + * $Id: AsyncEngine.cc,v 1.1.10.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "AsyncEngine.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/AsyncEngine.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,86 @@ + +/* + * $Id: AsyncEngine.h,v 1.1.10.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_ASYNCENGINE_H +#define SQUID_ASYNCENGINE_H + +#include "squid.h" + + +/* Abstract interface for async engines which an event loop can utilise. + * + * Some implementations will be truely async, others like the event engine + * will be pseudo async. + */ + +class AsyncEngine +{ + +public: + /* error codes returned from checkEvents. If the return value is not + * negative, then it is the requested delay until the next call. If it is + * negative, it is one of the following codes: + */ + enum CheckError { + /* this engine is completely idle: it has no pending events, and nothing + * registered with it that can create events + */ + EVENT_IDLE = -1, + /* some error has occured in this engine */ + EVENT_ERROR = -2, + }; + + virtual ~AsyncEngine() {} + + /* Check the engine for events. If there are events that have completed, + * the engine should at this point hand them off to their dispatcher. + * Engines that operate asynchronously - i.e. the DiskThreads engine - + * should hand events off to their dispatcher as they arrive rather than + * waiting for checkEvents to be called. Engines like poll and select should + * use this call as the time to perform their checks with the OS for new + * events. + * + * The return value is the status code of the event checking. If its a + * non-negative value then it is used as hint for the minimum requested + * time before checkEvents is called again. I.e. the event engine knows + * how long it is until the next event will be scheduled - so it will + * return that time (in milliseconds). + * + * The timeout value is a requested timeout for this engine - the engine + * should not block for more than this period. (If it takes longer than the + * timeout to do actual checks thats fine though undesirable). + */ + virtual int checkEvents(int timeout) = 0; +}; + +#endif /* SQUID_ASYNCENGINE_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/BodyReader.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,159 @@ + + +#include "squid.h" +#include "MemBuf.h" +#include "BodyReader.h" + +BodyReader::BodyReader(size_t len, BodyReadFunc *r, BodyAbortFunc *a, BodyKickFunc *k, void *d) : + _remaining(len), _available(0), + read_func(r), abort_func(a), kick_func(k), read_func_data(d), + read_callback(NULL), read_callback_data(NULL) +{ + theBuf.init(4096, 65536); + debugs(32,3,HERE << this << " " << "created new BodyReader for content-length " << len); + bytes_read = 0; +} + +BodyReader::~BodyReader() +{ + if (_remaining && abort_func) + abort_func(read_func_data, _remaining); + + if (callbackPending()) + doCallback(); + +} + +void +BodyReader::read(CBCB *callback, void *cbdata) +{ + assert(_remaining || theBuf.contentSize()); + debugs(32,3,HERE << this << " " << "remaining = " << _remaining); + debugs(32,3,HERE << this << " " << "available = " << _available); + + if (read_callback == NULL) { + read_callback = callback; + read_callback_data = cbdataReference(cbdata); + } else { + assert(read_callback == callback); + assert(read_callback_data == cbdata); + } + + if ((_available == 0) && (theBuf.contentSize() == 0)) { + debugs(32,3,HERE << this << " " << "read: no body data available, saving callback pointers"); + + if (kick_func) + kick_func(read_func_data); + + return; + } + + debugs(32,3,HERE << this << " " << "read_func=" << read_func); + debugs(32,3,HERE << this << " " << "data=" << read_func_data); + size_t size = theBuf.potentialSpaceSize(); + + debugs(32, 3, "BodyReader::read: available: " << _available << ", size " << size << ", remaining: " << _remaining); + + if (size > _available) + size = _available; + + if (size > _remaining) + size = _remaining; + + if (size > 0) { + debugs(32,3,HERE << this << " " << "calling read_func for " << size << " bytes"); + + size_t nread = read_func(read_func_data, theBuf, size); + + if (nread > 0) { + _available -= nread; + reduce_remaining(nread); + } else { + debugs(32,3,HERE << this << " " << "Help, read_func() ret " << nread); + } + } + + if (theBuf.contentSize() > 0) { + debugs(32,3,HERE << this << " have " << theBuf.contentSize() << " bytes in theBuf, calling back"); + doCallback(); + } +} + +void +BodyReader::notify(size_t now_available) +{ + debugs(32,3,HERE << this << " " << "old available = " << _available); + debugs(32,3,HERE << this << " " << "now_available = " << now_available); + _available = now_available; + + if (!callbackPending()) { + debugs(32,3,HERE << this << " " << "no callback pending, nothing to do"); + return; + } + + debugs(32,3,HERE << this << " " << "have data and pending callback, calling read()"); + + read(read_callback, read_callback_data); +} + +bool +BodyReader::callbackPending() +{ + return read_callback ? true : false; +} + +/* + * doCallback + * + * Execute the read callback if there is a function registered + * and the read_callback_data is still valid. + */ +bool +BodyReader::doCallback() +{ + CBCB *t_callback = read_callback; + void *t_cbdata; + + if (t_callback == NULL) + return false; + + read_callback = NULL; + + if (!cbdataReferenceValidDone(read_callback_data, &t_cbdata)) + return false; + + debugs(32,3,HERE << this << " doing callback, theBuf size = " << theBuf.contentSize()); + + t_callback(theBuf, t_cbdata); + + return true; +} + +bool +BodyReader::consume(size_t size) +{ + debugs(32,3,HERE << this << " BodyReader::consume consuming " << size); + + if (theBuf.contentSize() < (mb_size_t) size) { + debugs(0,0,HERE << this << "BodyReader::consume failed"); + debugs(0,0,HERE << this << "BodyReader::consume size = " << size); + debugs(0,0,HERE << this << "BodyReader::consume contentSize() = " << theBuf.contentSize()); + return false; + } + + theBuf.consume(size); + + if (callbackPending() && _available > 0) { + debugs(32,3,HERE << this << " " << "data avail and pending callback, calling read()"); + read(read_callback, read_callback_data); + } + + return true; +} + +void +BodyReader::reduce_remaining(size_t size) +{ + assert(size <= _remaining); + _remaining -= size; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/BodyReader.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,56 @@ + +#ifndef SQUID_BODY_READER_H +#define SQUID_BODY_READER_H + +typedef void CBCB (MemBuf &mb, void *data); +typedef size_t BodyReadFunc (void *, MemBuf &mb, size_t size); +typedef void BodyAbortFunc (void *, size_t); +typedef void BodyKickFunc (void *); + +class BodyReader : public RefCountable +{ + +public: + typedef RefCount Pointer; + BodyReader(size_t len, BodyReadFunc *r, BodyAbortFunc *a, BodyKickFunc *k, void *d); + ~BodyReader(); + void read(CBCB *, void *); + void notify(size_t now_available); + size_t remaining() { return _remaining; } + + bool callbackPending(); + bool consume(size_t size); + + int bytes_read; + + /* reduce the number of bytes that the BodyReader is looking for. + * Will trigger an assertion if it tries to reduce below zero + */ + void reduce_remaining(size_t size); + +private: + size_t _remaining; + size_t _available; + MemBuf theBuf; + + /* + * These are for interacting with things that + * "provide" body content. ie, ConnStateData and + * ICAPReqMod after adapation. + */ + BodyReadFunc *read_func; + BodyAbortFunc *abort_func; + BodyKickFunc *kick_func; + void *read_func_data; + + /* + * These are for interacting with things that + * "consume" body content. ie, HttpStateData and + * ICAPReqMod before adaptation. + */ + CBCB *read_callback; + void *read_callback_data; + bool doCallback(); +}; + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/CacheManager.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,94 @@ + +/* + * $Id: CacheManager.h,v 1.1.10.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_CACHEMANAGER_H +#define SQUID_CACHEMANAGER_H + +#include "squid.h" + + +extern void cachemgrStart(int fd, HttpRequest * request, StoreEntry * entry); + +/* + * A single menu item in the cache manager - an 'action'. + */ + +class CacheManagerAction +{ + +public: + char *action; + char *desc; + OBJH *handler; + + struct + { + +unsigned int pw_req: + 1; + +unsigned int atomic: + 1; + } + + flags; + + CacheManagerAction *next; +}; + + +/* + * a CacheManager - the menu system for interacting with squid. + * This is currently just an adapter to the global cachemgr* routines to + * provide looser coupling between modules, but once fully transitioned, + * an instance of this class will represent a single independent manager. + */ + +class CacheManager +{ + +public: + CacheManager(); + /* the holy trinity - assignment, copy cons, destructor */ + /* unimplemented - prevents bugs from synthetic */ + CacheManager & operator = (CacheManager &); + /* unimplemented - prevents bugs from synthetic */ + CacheManager(CacheManager const &); + /* inline so that we dont need to link in cachemgr.cc at all in tests */ + virtual ~CacheManager() {} + + virtual void registerAction(char const * action, char const * desc, OBJH * handler, int pw_req_flag, int atomic); + virtual CacheManagerAction * findAction(char const * action); +}; + +#endif /* SQUID_CACHEMANAGER_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ClientBody.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,112 @@ +#include "squid.h" +#include "client_side.h" +#include "ClientBody.h" +#include "HttpRequest.h" + + +ClientBody::ClientBody(ConnStateData::Pointer & aConn, HttpRequest *Request) : conn(aConn), request(NULL), buf (NULL), bufsize(0), callback(NULL), cbdata(NULL) +{ + request = HTTPMSGLOCK(Request); +} + +ClientBody::~ClientBody() +{ + if (cbdata) + cbdataReferenceDone(cbdata); + + HTTPMSGUNLOCK(request); + + conn = NULL; // refcounted +} + +/* Called by clientReadRequest to process body content */ +void +ClientBody::process() +{ + + debug(33, 2) ("clientBody::process: start FD %d body_size=%lu in.notYetUsed=%lu cb=%p req=%p\n", + conn->fd, + (unsigned long int) conn->body_size_left, + (unsigned long int) conn->in.notYetUsed, + callback, + request); + + if (conn->in.notYetUsed) + processBuffer(); + else + conn->readSomeData(); +} + +void +ClientBody::processBuffer() +{ + /* Some sanity checks... */ + assert(conn->body_size_left > 0); + assert(conn->in.notYetUsed > 0); + assert(callback != NULL); + assert(buf != NULL); + /* How much do we have to process? */ + size_t size = conn->in.notYetUsed; + + if (size > conn->body_size_left) /* only process the body part */ + size = conn->body_size_left; + + if (size > bufsize) /* don't copy more than requested */ + size = bufsize; + + xmemcpy(buf, conn->in.buf, size); + + conn->body_size_left -= size; + + /* Move any remaining data */ + conn->in.notYetUsed -= size; + + if (conn->in.notYetUsed > 0) + xmemmove(conn->in.buf, conn->in.buf + size, conn->in.notYetUsed); + + /* Remove request link if this is the last part of the body, as + * clientReadRequest automatically continues to process next request */ + if (conn->body_size_left <= 0 && request != NULL) + request->body_connection = NULL; + + request->flags.body_sent = 1; + + doCallback(size); + + debug(33, 2) ("ClientBody::process: end FD %d size=%lu body_size=%lu in.notYetUsed=%lu cb=%p req=%p\n", + conn->fd, (unsigned long int)size, (unsigned long int) conn->body_size_left, + (unsigned long) conn->in.notYetUsed, callback, request); +} + +void +ClientBody::init(char *Buf, size_t Bufsize, CBCB *Callback, void *Cbdata) +{ + buf = Buf; + bufsize = Bufsize; + callback = Callback; + cbdata = cbdataReference(Cbdata); +} + +void +ClientBody::doCallback(size_t theSize) +{ + char *theBuf = buf; + CBCB *theCallback = callback; + void *theCbdata = cbdata; + + buf = NULL; + bufsize = 0; + callback = NULL; + cbdata = NULL; + + void *someCbdata; + + if (cbdataReferenceValidDone(theCbdata, &someCbdata)) + theCallback(theBuf, theSize, someCbdata); +} + +void +ClientBody::negativeCallback() +{ + doCallback((size_t)-1); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ClientBody.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,29 @@ +#ifndef SQUID_CLIENTBODY_H +#define SQUID_CLIENTBODY_H + +class ClientBody +{ + +public: + ClientBody (ConnStateData::Pointer &, HttpRequest *); + ~ClientBody(); + void process(); + void processBuffer(); + void init(char *, size_t, CBCB *, void *); +bool hasCallback() const { return callback ? true : false; }; + + void doCallback(size_t); + void negativeCallback(); + HttpRequest * getRequest() { return request; }; + +private: + ConnStateData::Pointer conn; + HttpRequest *request; + char *buf; + size_t bufsize; + CBCB *callback; + void *cbdata; +}; + + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/CompletionDispatcher.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,34 @@ + +/* + * $Id: CompletionDispatcher.cc,v 1.1.10.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "CompletionDispatcher.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/CompletionDispatcher.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,58 @@ + +/* + * $Id: CompletionDispatcher.h,v 1.2.8.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_COMPLETIONDISPATCHER_H +#define SQUID_COMPLETIONDISPATCHER_H + +#include "squid.h" + + +/* Dispatch code to handle events that have completed. Completed events are queued + * with a completion dispatcher by the OS Async engine - i.e. the poll or kqueue or + * select loop, or a signal reciever, or the diskd/diskthreads/etc modules. + */ + +class CompletionDispatcher +{ + +public: + + virtual ~CompletionDispatcher() {} + + /* dispatch events. This should return true if there were events dispatched + * between the last call to dispatch() returning and this call returning. + */ + virtual bool dispatch() = 0; +}; + +#endif /* SQUID_COMPLETIONDISPATCHER_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ConfigParser.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,121 @@ + +/* + * $Id: ConfigParser.cc,v 1.2.8.2 2006/09/29 23:15:58 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * + * Copyright (c) 2003, Robert Collins + */ + +#include "ConfigParser.h" +#include "globals.h" + +void +ConfigParser::destruct() +{ + shutting_down = 1; + fatalf("Bungled %s line %d: %s", + cfg_filename, config_lineno, config_input_line); +} + +char * +ConfigParser::strtokFile(void) +{ + static int fromFile = 0; + static FILE *wordFile = NULL; + + char *t, *fn; + LOCAL_ARRAY(char, buf, 256); + +strtok_again: + + if (!fromFile) { + t = (strtok(NULL, w_space)); + + if (!t || *t == '#') { + return NULL; + } else if (*t == '\"' || *t == '\'') { + /* quote found, start reading from file */ + fn = ++t; + + while (*t && *t != '\"' && *t != '\'') + t++; + + *t = '\0'; + + if ((wordFile = fopen(fn, "r")) == NULL) { + debug(28, 0) ("strtokFile: %s not found\n", fn); + return (NULL); + } + +#ifdef _SQUID_WIN32_ + setmode(fileno(wordFile), O_TEXT); + +#endif + + fromFile = 1; + } else { + return t; + } + } + + /* fromFile */ + if (fgets(buf, 256, wordFile) == NULL) { + /* stop reading from file */ + fclose(wordFile); + wordFile = NULL; + fromFile = 0; + goto strtok_again; + } else { + char *t2, *t3; + t = buf; + /* skip leading and trailing white space */ + t += strspn(buf, w_space); + t2 = t + strcspn(t, w_space); + t3 = t2 + strspn(t2, w_space); + + while (*t3 && *t3 != '#') { + t2 = t3 + strcspn(t3, w_space); + t3 = t2 + strspn(t2, w_space); + } + + *t2 = '\0'; + /* skip comments */ + + if (*t == '#') + goto strtok_again; + + /* skip blank lines */ + if (!*t) + goto strtok_again; + + return t; + } +} + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/EventLoop.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,172 @@ + +/* + * $Id: EventLoop.cc,v 1.3.8.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * DEBUG: section 1 Main Loop + * AUTHOR: Harvest Derived + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "EventLoop.h" + +EventLoop::EventLoop() : errcount(0), last_loop(false), timeService(NULL), + primaryEngine(NULL) +{} + +void +EventLoop::checkEngine(AsyncEngine * engine, bool const primary) +{ + int requested_delay; + + if (!primary) + requested_delay = engine->checkEvents(0); + else + requested_delay = engine->checkEvents(loop_delay); + + if (requested_delay < 0) + switch (requested_delay) { + + case AsyncEngine::EVENT_IDLE: + debugs(1, 9, "Engine " << engine << " is idle."); + break; + + case AsyncEngine::EVENT_ERROR: + runOnceResult = false; + error = true; + break; + + default: + fatal_dump("unknown AsyncEngine result"); + } + else { + /* not idle or error */ + runOnceResult = false; + + if (requested_delay < loop_delay) + loop_delay = requested_delay; + } +} + +void +EventLoop::prepareToRun() +{ + last_loop = false; + errcount = 0; +} + +void +EventLoop::registerDispatcher(CompletionDispatcher *dispatcher) +{ + dispatchers.push_back(dispatcher); +} + +void +EventLoop::registerEngine(AsyncEngine *engine) +{ + engines.push_back(engine); +} + +void +EventLoop::run() +{ + prepareToRun(); + + while (!runOnce()) + + ; +} + +bool +EventLoop::runOnce() +{ + runOnceResult = true; + error = false; + loop_delay = 10; /* 10 ms default delay */ + + for (engine_vector::iterator i = engines.begin(); + i != engines.end(); ++i) { + /* check the primary outside the loop */ + + if (*i == primaryEngine) + continue; + + /* special case the last engine to be primary */ + checkEngine(*i, primaryEngine == NULL && (i - engines.end() == -1)); + } + + if (primaryEngine != NULL) + checkEngine(primaryEngine, true); + + if (timeService != NULL) + timeService->tick(); + + for (dispatcher_vector::iterator i = dispatchers.begin(); + i != dispatchers.end(); ++i) + if ((*i)->dispatch()) + runOnceResult = false; + + if (error) { + ++errcount; + debugs(1, 0, "Select loop Error. Retry " << errcount); + } else + errcount = 0; + + if (errcount == 10) + return true; + + if (last_loop) + return true; + + return runOnceResult; +} + +void +EventLoop::setPrimaryEngine(AsyncEngine * engine) +{ + for (engine_vector::iterator i = engines.begin(); + i != engines.end(); ++i) + if (*i == engine) { + primaryEngine = engine; + return; + } + + fatal("EventLoop::setPrimaryEngine: No such engine!."); +} + +void +EventLoop::setTimeService(TimeEngine *engine) +{ + timeService = engine; +} + +void +EventLoop::stop() +{ + last_loop = true; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/EventLoop.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,109 @@ + +/* + * $Id: EventLoop.h,v 1.3.8.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_EVENTLOOP_H +#define SQUID_EVENTLOOP_H + +#include "squid.h" +#include "Array.h" +#include "AsyncEngine.h" +#include "CompletionDispatcher.h" +#include "SquidTime.h" + +/* An event loop. An event loop is the core inner loop of squid. + * The event loop can be run until exit, or once. After it finishes control + * returns to the caller. If desired it can be run again. + * + * The event loop cannot be run once it is running until it has finished. + */ + +class EventLoop +{ + +public: + EventLoop(); + /* register an event dispatcher to be invoked on each event loop. */ + void registerDispatcher(CompletionDispatcher *dispatcher); + /* register an async engine which will be given the opportunity to perform + * in-main-thread tasks each event loop. + */ + void registerEngine(AsyncEngine *engine); + /* start the event loop running. The loop will run until it is stopped by + * calling stop(), or when the loop is completely idle - nothing + * dispatched in a loop, and all engines idle. + */ + void run(); + /* run the loop once. This may not complete all events! It should therefor + * be used with care. + * TODO: signal in runOnce whether or not the loop is over - IDLE vs OK vs + * TIMEOUT? + */ + bool runOnce(); + /* set the primary async engine. The primary async engine recieves the + * lowest requested timeout gathered from the other engines each loop. + * (There is a default of 10ms if all engines are idle or request higher + * delays). + * If no primary has been nominated, the last async engine added is + * implicitly the default. + */ + void setPrimaryEngine(AsyncEngine * engine); + /* set the time service. There can be only one time service set at any + * time. The time service is invoked on each loop + */ + void setTimeService(TimeEngine *engine); + /* stop the event loop - it will finish the current loop and then return to the + * caller of run(). + */ + void stop(); + + int errcount; + +private: + /* setup state variables prior to running */ + void prepareToRun(); + /* check an individual engine */ + void checkEngine(AsyncEngine * engine, bool const primary); + bool last_loop; + typedef Vector dispatcher_vector; + dispatcher_vector dispatchers; + typedef Vector engine_vector; + engine_vector engines; + TimeEngine * timeService; + AsyncEngine * primaryEngine; + int loop_delay; /* the delay to be given to the primary engine */ + bool error; /* has an error occured in this loop */ + bool runOnceResult; /* the result from runOnce */ +}; + + +#endif /* SQUID_EVENTLOOP_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/HttpHdrSc.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,70 @@ + +/* + * $Id: HttpHdrSc.h,v 1.1.12.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_HTTPHDRSURROGATECONTROL_H +#define SQUID_HTTPHDRSURROGATECONTROL_H + +#include "dlink.h" +#include "HttpHdrScTarget.h" + +/* http surogate control header field */ + +class HttpHdrSc +{ + +public: + MEMPROXY_CLASS(HttpHdrSc); + dlink_list targets; +}; + +MEMPROXY_CLASS_INLINE(HttpHdrSc); + +/* Http Surrogate Control Header Field */ +extern void httpHdrScStatDumper(StoreEntry * sentry, int idx, double val, double size, int count); +extern void httpHdrScInitModule (void); +extern void httpHdrScCleanModule (void); +extern HttpHdrSc *httpHdrScCreate(void); +extern HttpHdrSc *httpHdrScParseCreate(String const *); +extern void httpHdrScDestroy(HttpHdrSc * sc); +extern HttpHdrSc *httpHdrScDup(const HttpHdrSc * sc); +extern void httpHdrScPackInto(const HttpHdrSc * sc, Packer * p); +extern void httpHdrScJoinWith(HttpHdrSc *, const HttpHdrSc *); +extern void httpHdrScSetMaxAge(HttpHdrSc *, char const *, int); +extern void httpHdrScUpdateStats(const HttpHdrSc *, StatHist *); +extern HttpHdrScTarget * httpHdrScFindTarget (HttpHdrSc *sc, const char *target); +extern HttpHdrScTarget * httpHdrScGetMergedTarget (HttpHdrSc *sc, const char *ourtarget); + +extern void httpHeaderPutSc(HttpHeader *hdr, const HttpHdrSc *sc); +extern HttpHdrSc *httpHeaderGetSc(const HttpHeader *hdr); + +#endif /* SQUID_HTTPHDRSURROGATECONTROL_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/HttpHdrScTarget.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,67 @@ + +/* + * $Id: HttpHdrScTarget.h,v 1.1.12.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_HTTPHDRSURROGATECONTROLTARGET_H +#define SQUID_HTTPHDRSURROGATECONTROLTARGET_H + +#include "dlink.h" + +/* http surogate control header field */ + +class HttpHdrScTarget +{ + +public: + MEMPROXY_CLASS(HttpHdrScTarget); + dlink_node node; + int mask; + int max_age; + int max_stale; + String content; + String target; +}; + +MEMPROXY_CLASS_INLINE(HttpHdrScTarget); + +/* Http Surrogate control header field 'targets' */ +extern HttpHdrScTarget * httpHdrScTargetCreate (const char *); +extern void httpHdrScTargetDestroy(HttpHdrScTarget *); +extern HttpHdrScTarget *httpHdrScTargetDup(const HttpHdrScTarget *); +extern void httpHdrScTargetPackInto(const HttpHdrScTarget *, Packer *); +extern void httpHdrScTargetSetMaxAge(HttpHdrScTarget *, int); +extern void httpHdrScTargetUpdateStats(const HttpHdrScTarget *, StatHist *); +extern void httpHdrScTargetJoinWith(HttpHdrScTarget *, const HttpHdrScTarget *); +extern void httpHdrScTargetMergeWith(HttpHdrScTarget *, const HttpHdrScTarget *); +extern void httpHdrScTargetStatDumper(StoreEntry * sentry, int idx, double val, double size, int count); + +#endif /* SQUID_HTTPHDRSURROGATECONTROLTARGET_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/HttpHeaderMask.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,41 @@ + +/* + * $Id: HttpHeaderMask.h,v 1.1.12.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_HTTPHEADERMASK_H +#define SQUID_HTTPHEADERMASK_H + +/* big mask for http headers */ +typedef char HttpHeaderMask[12]; + +SQUIDCEXTERN void httpHeaderMaskInit(HttpHeaderMask * mask, int value); +#endif /* SQUID_HTTPHEADERMASK_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/HttpRequestMethod.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,177 @@ + +/* + * $Id: HttpRequestMethod.cc,v 1.1.12.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * DEBUG: section 73 HTTP Request + * AUTHOR: Duane Wessels + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * Copyright (c) 2003, Robert Collins + */ + +#include "squid.h" +#include "HttpRequestMethod.h" +#include "wordlist.h" + +const char *RequestMethodStr[] = + { + "NONE", + "GET", + "POST", + "PUT", + "HEAD", + "CONNECT", + "TRACE", + "PURGE", + "OPTIONS", + "DELETE", + "PROPFIND", + "PROPPATCH", + "MKCOL", + "COPY", + "MOVE", + "LOCK", + "UNLOCK", + "BMOVE", + "BDELETE", + "BPROPFIND", + "BPROPPATCH", + "BCOPY", + "SEARCH", + "SUBSCRIBE", + "UNSUBSCRIBE", + "POLL", + "REPORT", + "%EXT00", + "%EXT01", + "%EXT02", + "%EXT03", + "%EXT04", + "%EXT05", + "%EXT06", + "%EXT07", + "%EXT08", + "%EXT09", + "%EXT10", + "%EXT11", + "%EXT12", + "%EXT13", + "%EXT14", + "%EXT15", + "%EXT16", + "%EXT17", + "%EXT18", + "%EXT19", + "ERROR" + }; + +static +method_t &operator++ (method_t &aMethod) +{ + int tmp = (int)aMethod; + aMethod = (method_t)(++tmp); + return aMethod; +} + +/* + * Construct a HttpRequestMethod from a NULL terminated string such as "GET" + * or from a range of chars, * such as "GET" from "GETFOOBARBAZ" + * (pass in pointer to G and pointer to F.) + */ +HttpRequestMethod::HttpRequestMethod(char const *begin, char const *end) : theMethod (METHOD_NONE) +{ + if (begin == NULL) + return; + + /* + * This check for '%' makes sure that we don't + * match one of the extension method placeholders, + * which have the form %EXT[0-9][0-9] + */ + + if (*begin == '%') + return; + + /* + * if e is NULL, b must be NULL terminated and we + * make e point to the first whitespace character + * after b. + */ + if (NULL == end) + end = begin + strcspn(begin, w_space); + + for (++theMethod; theMethod < METHOD_ENUM_END; ++theMethod) { + if (0 == strncasecmp(begin, RequestMethodStr[theMethod], end-begin)) + return; + } + + /* reset to none */ + theMethod = METHOD_NONE; +} + +void +HttpRequestMethod::AddExtension(const char *mstr) +{ + method_t method = METHOD_NONE; + + for (++method; method < METHOD_ENUM_END; ++method) { + if (0 == strcmp(mstr, RequestMethodStr[method])) { + debug(23, 2) ("Extension method '%s' already exists\n", mstr); + return; + } + + if (0 != strncmp("%EXT", RequestMethodStr[method], 4)) + continue; + + /* Don't free statically allocated "%EXTnn" string */ + RequestMethodStr[method] = xstrdup(mstr); + + debug(23, 1) ("Extension method '%s' added, enum=%d\n", mstr, (int) method); + + return; + } + + debug(23, 1) ("WARNING: Could not add new extension method '%s' due to lack of array space\n", mstr); +} + +void +HttpRequestMethod::Configure(SquidConfig &Config) +{ + wordlist *w = Config.ext_methods; + + while (w) { + char *s; + + for (s = w->key; *s; s++) + *s = xtoupper(*s); + + AddExtension(w->key); + + w = w->next; + } +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/HttpRequestMethod.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,144 @@ + +/* + * $Id: HttpRequestMethod.h,v 1.1.12.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_HTTPREQUESTMETHOD_H +#define SQUID_HTTPREQUESTMETHOD_H + +#include + +enum _method_t { + METHOD_NONE, /* 000 */ + METHOD_GET, /* 001 */ + METHOD_POST, /* 010 */ + METHOD_PUT, /* 011 */ + METHOD_HEAD, /* 100 */ + METHOD_CONNECT, /* 101 */ + METHOD_TRACE, /* 110 */ + METHOD_PURGE, /* 111 */ + METHOD_OPTIONS, + METHOD_DELETE, /* RFC2616 section 9.7 */ + METHOD_PROPFIND, + METHOD_PROPPATCH, + METHOD_MKCOL, + METHOD_COPY, + METHOD_MOVE, + METHOD_LOCK, + METHOD_UNLOCK, + METHOD_BMOVE, + METHOD_BDELETE, + METHOD_BPROPFIND, + METHOD_BPROPPATCH, + METHOD_BCOPY, + METHOD_SEARCH, + METHOD_SUBSCRIBE, + METHOD_UNSUBSCRIBE, + METHOD_POLL, + METHOD_REPORT, + METHOD_EXT00, + METHOD_EXT01, + METHOD_EXT02, + METHOD_EXT03, + METHOD_EXT04, + METHOD_EXT05, + METHOD_EXT06, + METHOD_EXT07, + METHOD_EXT08, + METHOD_EXT09, + METHOD_EXT10, + METHOD_EXT11, + METHOD_EXT12, + METHOD_EXT13, + METHOD_EXT14, + METHOD_EXT15, + METHOD_EXT16, + METHOD_EXT17, + METHOD_EXT18, + METHOD_EXT19, + METHOD_ENUM_END +}; + +typedef enum _method_t method_t; + +extern const char *RequestMethodStr[]; + +/* forward decls */ + +typedef struct _SquidConfig SquidConfig; + + +/* This class represents an HTTP Request METHOD - i.e. + * PUT, POST, GET etc. It has a runtime extensionf acility to allow it to + * efficiently support new methods + */ + +class HttpRequestMethod +{ + +public: + static void AddExtension(const char *methodString); + static void Configure(SquidConfig &Config); + + HttpRequestMethod() : theMethod(METHOD_NONE) {} + + HttpRequestMethod(method_t const aMethod) : theMethod(aMethod) {} + + HttpRequestMethod(char const * begin, char const * end=0); + + operator method_t() const {return theMethod; } + + HttpRequestMethod & operator = (method_t const aMethod) + { + theMethod = aMethod; + return *this; + } + + bool operator != (method_t const & aMethod) { return theMethod != aMethod;} + + /* Get a char string representation of the method. */ + char const *const_str() const { return RequestMethodStr[theMethod]; } + +private: + method_t theMethod; + +}; + +inline bool operator != (HttpRequestMethod const &left, method_t const &right) { return right != left; } + +inline std::ostream & +operator << (std::ostream &os, HttpRequestMethod const &method) +{ + os << method.const_str(); + return os; +} + +#endif /* SQUID_HTTPREQUESTMETHOD_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/Packer.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,75 @@ + +/* + * $Id: Packer.h,v 1.2.8.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_PACKER_H +#define SQUID_PACKER_H + +#include "config.h" + +/* see Packer.cc for description */ + +class Packer; + +/* a common objPackInto interface; used by debugObj */ +typedef void (*ObjPackMethod) (void *obj, Packer * p); + +/* append/vprintf's for Packer */ +typedef void (*append_f) (void *, const char *buf, int size); +#if STDC_HEADERS +typedef void (*vprintf_f) (void *, const char *fmt, va_list args); +#else +typedef void (*vprintf_f) (); +#endif + + +class Packer +{ + +public: + /* protected, use interface functions instead */ + append_f append; + vprintf_f packer_vprintf; + void *real_handler; /* first parameter to real append and vprintf */ +}; + +SQUIDCEXTERN void packerClean(Packer * p); +SQUIDCEXTERN void packerAppend(Packer * p, const char *buf, int size); +#if STDC_HEADERS +SQUIDCEXTERN void +packerPrintf(Packer * p, const char *fmt,...) PRINTF_FORMAT_ARG2; +#else +SQUIDCEXTERN void packerPrintf(); +#endif + + +#endif /* SQUID_PACKER_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/PeerDigest.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,156 @@ + +/* + * $Id: PeerDigest.h,v 1.1.10.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_PEERDIGEST_H +#define SQUID_PEERDIGEST_H + +#include "squid.h" + +#if USE_CACHE_DIGESTS + +#include "cbdata.h" + +struct _Version +{ + short int current; /* current version */ + short int required; /* minimal version that can safely handle current version */ +}; + +/* digest control block; used for transmission and storage */ + +class StoreDigestCBlock +{ + public: + Version ver; + int capacity; + int count; + int del_count; + int mask_size; + unsigned char bits_per_entry; + unsigned char hash_func_count; + short int reserved_short; + int reserved[32 - 6]; +}; + +struct _DigestFetchState +{ + PeerDigest *pd; + StoreEntry *entry; + StoreEntry *old_entry; + store_client *sc; + store_client *old_sc; + HttpRequest *request; + int offset; + int mask_offset; + time_t start_time; + time_t resp_time; + time_t expires; + + struct + { + int msg; + int bytes; + } + + sent, recv; + char buf[SM_PAGE_SIZE]; + ssize_t bufofs; + digest_read_state_t state; +}; + +class PeerDigest +{ + +public: + void *operator new (size_t); + void operator delete(void *); + + struct _peer *peer; /* pointer back to peer structure, argh */ + CacheDigest *cd; /* actual digest structure */ + String host; /* copy of peer->host */ + const char *req_result; /* text status of the last request */ + + struct + { + +unsigned int needed: + 1; /* there were requests for this digest */ + +unsigned int usable: + 1; /* can be used for lookups */ + +unsigned int requested: + 1; /* in process of receiving [fresh] digest */ + } + + flags; + + struct + { + /* all times are absolute unless augmented with _delay */ + time_t initialized; /* creation */ + time_t needed; /* first lookup/use by a peer */ + time_t next_check; /* next scheduled check/refresh event */ + time_t retry_delay; /* delay before re-checking _invalid_ digest */ + time_t requested; /* requested a fresh copy of a digest */ + time_t req_delay; /* last request response time */ + time_t received; /* received the current copy of a digest */ + time_t disabled; /* disabled for good */ + } + + times; + + struct + { + cd_guess_stats guess; + int used_count; + + struct + { + int msgs; + kb_t kbytes; + } + + sent, recv; + } + + stats; + +private: + CBDATA_CLASS(PeerDigest); +}; + +extern const Version CacheDigestVer; +#endif + +#endif /* SQUID_PEERDIGEST_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/RemovalPolicy.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,39 @@ + +/* + * $Id: RemovalPolicy.cc,v 1.1.10.2 2006/09/29 23:15:59 dwsquid Exp $ + * + * DEBUG: section ? Common Removal policy + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "RemovalPolicy.h" +CBDATA_CLASS_INIT(RemovalPolicy); +CBDATA_CLASS_INIT(RemovalPolicyWalker); +CBDATA_CLASS_INIT(RemovalPurgeWalker); --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/RemovalPolicy.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,108 @@ + +/* + * $Id: RemovalPolicy.h,v 1.1.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * Copyright (c) 2003, Robert Collins + */ + +#ifndef SQUID_REMOVALPOLICY_H +#define SQUID_REMOVALPOLICY_H + +#include "squid.h" +#include "cbdata.h" + +class RemovalPolicyWalker; +class RemovalPurgeWalker; + +class RemovalPolicySettings +{ + +public: + RemovalPolicySettings() : type(NULL), args(NULL) {}; + + char *type; + wordlist *args; +}; + +class RemovalPolicyNode +{ + +public: + RemovalPolicyNode() : data(NULL) {} + + void *data; +}; + +class RemovalPolicy +{ + public: + const char *_type; + void *_data; + void (*Free) (RemovalPolicy * policy); + void (*Add) (RemovalPolicy * policy, StoreEntry * entry, RemovalPolicyNode * node); + void (*Remove) (RemovalPolicy * policy, StoreEntry * entry, RemovalPolicyNode * node); + void (*Referenced) (RemovalPolicy * policy, const StoreEntry * entry, RemovalPolicyNode * node); + void (*Dereferenced) (RemovalPolicy * policy, const StoreEntry * entry, RemovalPolicyNode * node); + RemovalPolicyWalker *(*WalkInit) (RemovalPolicy * policy); + RemovalPurgeWalker *(*PurgeInit) (RemovalPolicy * policy, int max_scan); + void (*Stats) (RemovalPolicy * policy, StoreEntry * entry); + private: + CBDATA_CLASS2(RemovalPolicy); +}; + +class RemovalPolicyWalker +{ + public: + RemovalPolicy *_policy; + void *_data; + const StoreEntry *(*Next) (RemovalPolicyWalker * walker); + void (*Done) (RemovalPolicyWalker * walker); + private: + CBDATA_CLASS2(RemovalPolicyWalker); +}; + +class RemovalPurgeWalker +{ + public: + RemovalPolicy *_policy; + void *_data; + int scanned, max_scan, locked; + StoreEntry *(*Next) (RemovalPurgeWalker * walker); + void (*Done) (RemovalPurgeWalker * walker); + private: + CBDATA_CLASS2(RemovalPurgeWalker); +}; + +extern RemovalPolicy *createRemovalPolicy(RemovalPolicySettings * settings); + +typedef RemovalPolicy *REMOVALPOLICYCREATE(wordlist * args); + + +#endif /* SQUID_REMOVALPOLICY_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/Server.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,85 @@ +/* + * $Id: Server.cc,v 1.4.2.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * DEBUG: + * AUTHOR: Duane Wessels + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "Server.h" +#include "Store.h" +#include "HttpRequest.h" +#include "HttpReply.h" +#if ICAP_CLIENT +#include "ICAP/ICAPClientRespmodPrecache.h" +#endif + +ServerStateData::ServerStateData(FwdState *theFwdState) +{ + fwd = theFwdState; + entry = fwd->entry; + + entry->lock() + + ; + request = HTTPMSGLOCK(fwd->request); +} + +ServerStateData::~ServerStateData() +{ + entry->unlock(); + + HTTPMSGUNLOCK(request); + HTTPMSGUNLOCK(reply); + + fwd = NULL; // refcounted + +#if ICAP_CLIENT + if (icap) + delete icap; +#endif +} + +#if ICAP_CLIENT +/* + * Initiate an ICAP transaction. Return 0 if all is well, or -1 upon error. + * Caller will handle error condition by generating a Squid error message + * or take other action. + */ +int +ServerStateData::doIcap(ICAPServiceRep::Pointer service) +{ + debug(11,5)("ServerStateData::doIcap() called\n"); + assert(NULL == icap); + icap = new ICAPClientRespmodPrecache(service); + return 0; +} + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/Server.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,88 @@ + +/* + * $Id: Server.h,v 1.1.12.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * AUTHOR: Duane Wessels + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +/* + * ServerStateData is a class for common elements of Server-side modules + * such as http.cc and ftp.cc. It was invented to make ICAP code simpler. + */ + +#ifndef SQUID_SERVER_H +#define SQUID_SERVER_H + +#include "StoreIOBuffer.h" +#include "forward.h" + +#if ICAP_CLIENT +#include "ICAP/ICAPServiceRep.h" + +class ICAPClientRespmodPrecache; + +class ICAPAccessCheck; +#endif + +class ServerStateData +{ + +public: + ServerStateData(FwdState *); + virtual ~ServerStateData(); + +#if ICAP_CLIENT + + virtual void takeAdaptedHeaders(HttpReply *) = 0; + virtual void takeAdaptedBody(MemBuf *) = 0; + virtual void doneAdapting() = 0; + virtual void abortAdapting() = 0; + virtual void icapSpaceAvailable() = 0; + virtual void icapAclCheckDone(ICAPServiceRep::Pointer) = 0; +#endif + +public: + // should be protected + StoreEntry *entry; + FwdState::Pointer fwd; + HttpRequest *request; + HttpReply *reply; + +protected: +#if ICAP_CLIENT + + ICAPClientRespmodPrecache *icap; + bool icapAccessCheckPending; + int doIcap(ICAPServiceRep::Pointer); +#endif + +}; + +#endif /* SQUID_SERVER_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/SquidTime.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,57 @@ + +/* + * $Id: SquidTime.h,v 1.2.6.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * DEBUG: section 21 Time Functions + * AUTHOR: Harvest Derived + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_TIME_H +#define SQUID_TIME_H + +#include "squid.h" + +extern time_t squid_curtime; /* 0 */ + +time_t getCurrentTime(void); + +/* event class for doing synthetic time etc */ + +class TimeEngine +{ + +public: + virtual ~TimeEngine(); + /* tick the clock - update from the OS or other time source, */ + virtual void tick(); +}; + + +#endif /* SQUID_TIME_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/StoreEntryStream.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,130 @@ + +/* + * $Id: StoreEntryStream.h,v 1.2.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_STORE_ENTRY_STREAM_H +#define SQUID_STORE_ENTRY_STREAM_H + +#include "Store.h" + +#include + +/* + * This class provides a streambuf interface for writing + * to StoreEntries. Typical use is via a StoreEntryStream + * rather than direct manipulation + */ + +class StoreEntryStreamBuf : public std::streambuf +{ + +public: + StoreEntryStreamBuf(StoreEntry *anEntry) : anEntry(anEntry) + { + + anEntry->lock() + + ; + anEntry->buffer(); + } + + ~StoreEntryStreamBuf() + { + anEntry->unlock(); + } + +protected: + /* flush the current buffer and the character that is overflowing + * to the store entry. + */ + virtual char overflow(char aChar = traits_type::eof()) + { + std::streamsize pending(pptr() - pbase()); + + if (pending && sync ()) + return traits_type::eof(); + + if (aChar != traits_type::eof()) { + char chars[1] = {aChar}; + + if (aChar != traits_type::eof()) + anEntry->append(chars, 1); + } + + pbump (-pending); // Reset pptr(). + return aChar; + } + + /* push the buffer to the store */ + virtual int sync() + { + std::streamsize pending(pptr() - pbase()); + + if (pending) + anEntry->append(pbase(), pending); + + anEntry->flush(); + + return 0; + } + + /* write multiple characters to the store entry + * - this is an optimisation method. + */ + virtual std::streamsize xsputn(const char * chars, std::streamsize number) + { + if (number) + anEntry->append(chars, number); + + return number; + } + +private: + StoreEntry *anEntry; + +}; + +class StoreEntryStream : public std::ostream +{ + +public: + /* create a stream for writing text etc into anEntry */ + StoreEntryStream(StoreEntry *anEntry) : std::ostream(&_buffer), _buffer(anEntry) { this->init(&_buffer);} + +private: + StoreEntryStreamBuf _buffer; + +public: + StoreEntryStreamBuf * rdbuf() const { return const_cast(&_buffer); } +}; + +#endif /* SQUID_STORE_ENTRY_STREAM_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/URL.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,75 @@ + +/* + * $Id: URL.h,v 1.1.12.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_SRC_URL_H +#define SQUID_SRC_URL_H + +#include "squid.h" +#include "MemPool.h" +#include "URLScheme.h" + +/* The URL class represents a UniformResourceLocation */ + +class URL +{ + +public: + + MEMPROXY_CLASS(URL); + URL(); + URL(URLScheme const &); + URLScheme const & getScheme() const {return scheme; } + +private: + /* the scheme of this URL. This has the 'type code' smell about it. + * In future we may want to make the methods that dispatch based on + * the scheme virtual and have a class per protocol. + * on the other hand, having Protocol as an explicit concept is useful, + * see for instance the ACLProtocol acl type. One way to represent this + * is to have one prototype URL with no host etc for each scheme, + * another is to have an explicit scheme class, and then each URL class + * could be a subclass of the scheme. Another way is one instance of + * a URLScheme class instance for each URLScheme we support, and one URL + * class for each manner of treating the scheme : a Hierarchical URL, a + * non-hierarchical URL etc. + * Deferring the decision, its a type code for now. RBC 20060507. + * + * In order to make taking any of these routes easy, scheme is private + * and immutable, only settable at construction time, + */ + URLScheme const scheme; +}; + +MEMPROXY_CLASS_INLINE(URL); + +#endif /* SQUID_SRC_URL_H_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/URLScheme.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,58 @@ + +/* + * $Id: URLScheme.cc,v 1.1.12.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * DEBUG: section 23 URL Scheme parsing + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "URLScheme.h" +#include "wordlist.h" + +const char *ProtocolStr[] = + { + "NONE", + "http", + "ftp", + "gopher", + "wais", + "cache_object", + "icp", +#if USE_HTCP + "htcp", +#endif + "urn", + "whois", + "internal", + "https", + "TOTAL" + }; + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/URLScheme.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,80 @@ + +/* + * $Id: URLScheme.h,v 1.1.12.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_URLSCHEME_H +#define SQUID_URLSCHEME_H + +/* For the definition of NULL and protocol_t */ +#include "squid.h" + +#include + +extern const char *ProtocolStr[]; + +/* This class represents a URL Scheme such as HTTPS, HTTP, WAIS etc. + * It does not represent the PROTOCOL that such schemes refer to. + */ + +class URLScheme +{ + +public: + URLScheme() : theScheme(PROTO_NONE) {} + + URLScheme(protocol_t const aScheme) : theScheme(aScheme) {} + + operator protocol_t() const { return theScheme; } + + bool operator != (protocol_t const & aProtocol) const { return theScheme != aProtocol;} + + /* Get a char string representation of the scheme. */ + char const *const_str() const { return ProtocolStr[theScheme]; } + +private: + /* This is a typecode for now - TODO make the varying methods virtual + * Doing that without doubling the storage size will require having + * something like a flyweight. perhaps the strategy pattern is appropiate: + * one strategy per scheme, and an object that is nothing but a pointer + * into the registry of schemes. + */ + protocol_t theScheme; +}; + +inline std::ostream & +operator << (std::ostream &os, URLScheme const &scheme) +{ + os << scheme.const_str(); + return os; +} + +#endif /* SQUID_URLSCHEME_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/WinSvc.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,981 @@ + +/* + * $Id: WinSvc.cc,v 1.2.4.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * Windows support + * AUTHOR: Guido Serassio + * inspired by previous work by Romeo Anghelache & Eric Stern. + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "squid_windows.h" + +#ifdef _SQUID_MSWIN_ +#ifndef _MSWSOCK_ +#include +#endif +#include +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +#include +#endif +#endif + +static unsigned int GetOSVersion(); +void WIN32_svcstatusupdate(DWORD, DWORD); +void WINAPI WIN32_svcHandler(DWORD); +#if USE_WIN32_SERVICE +static int WIN32_StoreKey(const char *, DWORD, unsigned char *, int); +static int WIN32_create_key(void); +static void WIN32_build_argv (char *); +#endif +extern "C" void WINAPI SquidWinSvcMain(DWORD, char **); + +#if defined(_SQUID_MSWIN_) +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ +void Squid_Win32InvalidParameterHandler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t); +#endif +static int Win32SockInit(void); +static void Win32SockCleanup(void); +SQUIDCEXTERN LPCRITICAL_SECTION dbg_mutex; +void WIN32_ExceptionHandlerCleanup(void); +static int s_iInitCount = 0; +#endif + +static int Squid_Aborting = 0; + +#if USE_WIN32_SERVICE +static SERVICE_STATUS svcStatus; +static SERVICE_STATUS_HANDLE svcHandle; +static int WIN32_argc; +static char ** WIN32_argv; +static char * WIN32_module_name; + +#define VENDOR "GNU" +static char VENDORString[] = VENDOR; +#define SOFTWARENAME "Squid" +static char SOFTWARENAMEString[] = SOFTWARENAME; +#define WIN32_VERSION "3.0" +static char WIN32_VERSIONString[] = WIN32_VERSION; +#define SOFTWARE "SOFTWARE" +static char SOFTWAREString[] = SOFTWARE; +#define COMMANDLINE "CommandLine" +#define CONFIGFILE "ConfigFile" +#undef ChangeServiceConfig2 +typedef BOOL (WINAPI * PFChangeServiceConfig2) (SC_HANDLE, DWORD, LPVOID); +#ifdef UNICODE +#define CHANGESERVICECONFIG2 "ChangeServiceConfig2W" +#else +#define CHANGESERVICECONFIG2 "ChangeServiceConfig2A" +#endif +static SC_ACTION Squid_SCAction[] = { { SC_ACTION_RESTART, 60000 } }; +static char Squid_ServiceDescriptionString[] = SOFTWARENAME " " VERSION " WWW Proxy Server"; +static SERVICE_DESCRIPTION Squid_ServiceDescription = { Squid_ServiceDescriptionString }; +static SERVICE_FAILURE_ACTIONS Squid_ServiceFailureActions = { INFINITE, NULL, NULL, 1, Squid_SCAction }; +static char REGKEY[256]=SOFTWARE"\\"VENDOR"\\"SOFTWARENAME"\\"WIN32_VERSION"\\"; +static char *keys[] = { + SOFTWAREString, /* key[0] */ + VENDORString, /* key[1] */ + SOFTWARENAMEString, /* key[2] */ + WIN32_VERSIONString, /* key[3] */ + NULL, /* key[4] */ + NULL /* key[5] */ + }; +#endif + +/* ====================================================================== */ +/* LOCAL FUNCTIONS */ +/* ====================================================================== */ + +#if USE_WIN32_SERVICE +static int +WIN32_create_key(void) +{ + int index; + HKEY hKey; + HKEY hKeyNext; + int retval; + LONG rv; + + hKey = HKEY_LOCAL_MACHINE; + index = 0; + retval = 0; + + /* Walk the tree, creating at each stage if necessary */ + + while (keys[index]) { + unsigned long result; + rv = RegCreateKeyEx(hKey, keys[index], /* subkey */ + 0, /* reserved */ + NULL, /* class */ + REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKeyNext, &result); + + if (rv != ERROR_SUCCESS) { + fprintf(stderr, "RegCreateKeyEx(%s),%d\n", keys[index], (int) rv); + retval = -4; + } + + /* Close the old key */ + rv = RegCloseKey(hKey); + + if (rv != ERROR_SUCCESS) { + fprintf(stderr, "RegCloseKey %d\n", (int) rv); + + if (retval == 0) { + /* Keep error status from RegCreateKeyEx, if any */ + retval = -4; + } + } + + if (retval) { + break; + } + + hKey = hKeyNext; + index++; + } + + if (keys[index] == NULL) { + /* Close the final key we opened, if we walked the entire + * tree + */ + rv = RegCloseKey(hKey); + + if (rv != ERROR_SUCCESS) { + fprintf(stderr, "RegCloseKey %d\n", (int) rv); + + if (retval == 0) { + /* Keep error status from RegCreateKeyEx, if any */ + retval = -4; + } + } + } + + return retval; +} + +static int +WIN32_StoreKey(const char *key, DWORD type, unsigned char *value, + int value_size) +{ + LONG rv; + HKEY hKey; + int retval; + + rv = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY, 0, KEY_WRITE, &hKey); + + if (rv == ERROR_FILE_NOT_FOUND) { + /* Key could not be opened -- try to create it + */ + + if (WIN32_create_key() < 0) { + /* Creation failed (error already reported) */ + return -4; + } + + /* Now it has been created we should be able to open it + */ + rv = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY, 0, KEY_WRITE, &hKey); + + if (rv == ERROR_FILE_NOT_FOUND) { + fprintf(stderr, "Registry does not contain key %s after creation\n", + REGKEY); + return -1; + } + } + + if (rv != ERROR_SUCCESS) { + fprintf(stderr, "RegOpenKeyEx HKLM\\%s, %d\n", REGKEY, (int) rv); + return -4; + } + + /* Now set the value and data */ + rv = RegSetValueEx(hKey, key, /* value key name */ + 0, /* reserved */ + type, /* type */ + value, /* value data */ + (DWORD) value_size); /* for size of "value" */ + + retval = 0; /* Return value */ + + if (rv != ERROR_SUCCESS) { + fprintf(stderr, "RegQueryValueEx(key %s),%d\n", key, (int) rv); + retval = -4; + } else { + fprintf(stderr, "Registry stored HKLM\\%s\\%s value %s\n", + REGKEY, + key, + type == REG_SZ ? value : (unsigned char *) "(not displayable)"); + } + + /* Make sure we close the key even if there was an error storing + * the data + */ + rv = RegCloseKey(hKey); + + if (rv != ERROR_SUCCESS) { + fprintf(stderr, "RegCloseKey HKLM\\%s, %d\n", REGKEY, (int) rv); + + if (retval == 0) { + /* Keep error status from RegQueryValueEx, if any */ + retval = -4; + } + } + + return retval; +} + +/* Build argv, argc from string passed from Windows. */ +static void WIN32_build_argv(char *cmd) +{ + int argvlen = 0; + char *word; + + WIN32_argc = 1; + WIN32_argv = (char **) xmalloc ((WIN32_argc+1) * sizeof (char *)); + WIN32_argv[0]=xstrdup(WIN32_module_name); + /* Scan command line until there is nothing left. */ + + while (*cmd) { + /* Ignore spaces */ + + if (xisspace(*cmd)) { + cmd++; + continue; + } + + /* Found the beginning of an argument. */ + word = cmd; + + while (*cmd) { + cmd++; /* Skip over this character */ + + if (xisspace(*cmd)) /* End of argument if space */ + break; + } + + if (*cmd) + *cmd++ = '\0'; /* Terminate `word' */ + + /* See if we need to allocate more space for argv */ + if (WIN32_argc >= argvlen) { + argvlen = WIN32_argc + 1; + WIN32_argv = (char **) xrealloc (WIN32_argv, (1 + argvlen) * sizeof (char *)); + } + + /* Add word to argv file. */ + WIN32_argv[WIN32_argc++] = word; + } + + WIN32_argv[WIN32_argc] = NULL; +} + +#endif /* USE_WIN32_SERVICE */ + +static unsigned int +GetOSVersion() +{ + OSVERSIONINFO osvi; + + safe_free(WIN32_OS_string); + memset(&osvi, '\0', sizeof(OSVERSIONINFO)); + osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx((OSVERSIONINFO *) & osvi); + + switch (osvi.dwPlatformId) { + + case VER_PLATFORM_WIN32_NT: + + if (osvi.dwMajorVersion <= 4) { + WIN32_OS_string = xstrdup("Windows NT"); + return _WIN_OS_WINNT; + } + + if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 0)) { + WIN32_OS_string = xstrdup("Windows 2000"); + return _WIN_OS_WIN2K; + } + + if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1)) { + WIN32_OS_string = xstrdup("Windows XP"); + return _WIN_OS_WINXP; + } + + if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2)) { + WIN32_OS_string = xstrdup("Windows Server 2003"); + return _WIN_OS_WINNET; + } + + if ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0)) { + WIN32_OS_string = xstrdup("Windows code name \"Longhorn\""); + return _WIN_OS_WINLON; + } + + break; + + case VER_PLATFORM_WIN32_WINDOWS: + + if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 0)) { + WIN32_OS_string = xstrdup("Windows 95"); + return _WIN_OS_WIN95; + } + + if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 10)) { + WIN32_OS_string = xstrdup("Windows 98"); + return _WIN_OS_WIN98; + } + + if ((osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion == 90)) { + WIN32_OS_string = xstrdup("Windows Me"); + return _WIN_OS_WINME; + } + + break; + + case VER_PLATFORM_WIN32s: + WIN32_OS_string = xstrdup("Windows 3.1 with WIN32S"); + return _WIN_OS_WIN32S; + break; + + default: + break; + } + + WIN32_OS_string = xstrdup("Unknown Windows system"); + return _WIN_OS_UNKNOWN; +} + +/* ====================================================================== */ +/* PUBLIC FUNCTIONS */ +/* ====================================================================== */ + +void +WIN32_Abort(int sig) +{ +#if USE_WIN32_SERVICE + svcStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; + svcStatus.dwServiceSpecificExitCode = 1; +#endif + + Squid_Aborting = 1; + WIN32_Exit(); +} + +void +WIN32_Exit() +{ +#ifdef _SQUID_MSWIN_ + Win32SockCleanup(); +#endif +#if USE_WIN32_SERVICE + + if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) { + if (!Squid_Aborting) { + svcStatus.dwCurrentState = SERVICE_STOPPED; + SetServiceStatus(svcHandle, &svcStatus); + } + } + +#endif +#ifdef _SQUID_MSWIN_ + if (dbg_mutex) + DeleteCriticalSection(dbg_mutex); + + WIN32_ExceptionHandlerCleanup(); + +#endif + + _exit(0); +} + +int WIN32_Subsystem_Init(int * argc, char *** argv) +{ +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ + _invalid_parameter_handler oldHandler, newHandler; +#endif + + WIN32_OS_version = GetOSVersion(); + + if ((WIN32_OS_version == _WIN_OS_UNKNOWN) || (WIN32_OS_version == _WIN_OS_WIN32S)) + return 1; + + if (atexit(WIN32_Exit) != 0) + return 1; + +#if defined(_MSC_VER) /* Microsoft C Compiler ONLY */ + + newHandler = Squid_Win32InvalidParameterHandler; + + oldHandler = _set_invalid_parameter_handler(newHandler); + + _CrtSetReportMode(_CRT_ASSERT, 0); + +#endif +#if USE_WIN32_SERVICE + + if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) { + char path[512]; + HKEY hndKey; + + if (signal(SIGABRT, WIN32_Abort) == SIG_ERR) + return 1; + + /* Register the service Handler function */ + svcHandle = + RegisterServiceCtrlHandler(WIN32_Service_name, + WIN32_svcHandler); + + if (svcHandle == 0) + return 1; + + /* Set Process work dir to directory cointaining squid.exe */ + GetModuleFileName(NULL, path, 512); + + WIN32_module_name=xstrdup(path); + + path[strlen(path) - 10] = '\0'; + + if (SetCurrentDirectory(path) == 0) + return 1; + + safe_free(ConfigFile); + + /* get config file from Windows Registry */ + if (RegOpenKey(HKEY_LOCAL_MACHINE, REGKEY, &hndKey) == ERROR_SUCCESS) { + DWORD Type = 0; + DWORD Size = 0; + LONG Result; + Result = + RegQueryValueEx(hndKey, CONFIGFILE, NULL, &Type, NULL, &Size); + + if (Result == ERROR_SUCCESS && Size) { + ConfigFile = static_cast(xmalloc(Size)); + RegQueryValueEx(hndKey, CONFIGFILE, NULL, &Type, (unsigned char *)ConfigFile, + &Size); + } else + ConfigFile = xstrdup(DefaultConfigFile); + + Size = 0; + + Type = 0; + + Result = + RegQueryValueEx(hndKey, COMMANDLINE, NULL, &Type, NULL, &Size); + + if (Result == ERROR_SUCCESS && Size) { + WIN32_Service_Command_Line = static_cast(xmalloc(Size)); + RegQueryValueEx(hndKey, COMMANDLINE, NULL, &Type, (unsigned char *)WIN32_Service_Command_Line, + &Size); + } else + WIN32_Service_Command_Line = xstrdup(""); + + RegCloseKey(hndKey); + } else { + ConfigFile = xstrdup(DefaultConfigFile); + WIN32_Service_Command_Line = xstrdup(""); + } + + WIN32_build_argv(WIN32_Service_Command_Line); + *argc = WIN32_argc; + *argv = WIN32_argv; + /* Set Service Status to SERVICE_START_PENDING */ + svcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + svcStatus.dwCurrentState = SERVICE_START_PENDING; + svcStatus.dwControlsAccepted = + SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; + svcStatus.dwWin32ExitCode = 0; + svcStatus.dwServiceSpecificExitCode = 0; + svcStatus.dwCheckPoint = 0; + svcStatus.dwWaitHint = 10000; + SetServiceStatus(svcHandle, &svcStatus); +#ifdef _SQUID_MSWIN_ + + _setmaxstdio(Squid_MaxFD); +#endif + + } + +#endif /* USE_WIN32_SERVICE */ +#ifdef _SQUID_MSWIN_ + if (Win32SockInit() < 0) + return 1; + +#endif + + return 0; +} + +#if USE_WIN32_SERVICE +void +WIN32_svcstatusupdate(DWORD svcstate, DWORD WaitHint) +{ + if (WIN32_run_mode == _WIN_SQUID_RUN_MODE_SERVICE) { + svcStatus.dwCheckPoint++; + svcStatus.dwWaitHint = WaitHint; + svcStatus.dwCurrentState = svcstate; + SetServiceStatus(svcHandle, &svcStatus); + } +} + +VOID WINAPI +WIN32_svcHandler(DWORD Opcode) +{ + DWORD status; + + switch (Opcode) { + + case _WIN_SQUID_SERVICE_CONTROL_STOP: + + case _WIN_SQUID_SERVICE_CONTROL_SHUTDOWN: + /* Do whatever it takes to stop here. */ + svcStatus.dwWin32ExitCode = 0; + svcStatus.dwCurrentState = SERVICE_STOP_PENDING; + svcStatus.dwCheckPoint = 0; + svcStatus.dwWaitHint = 10000; + shut_down(SIGTERM); + + if (!SetServiceStatus(svcHandle, &svcStatus)) { + status = GetLastError(); + debug(1, 1) ("SetServiceStatus error %ld\n", status); + } + + debug(1, 1) ("Leaving Squid service\n"); + return; + + case _WIN_SQUID_SERVICE_CONTROL_INTERROGATE: + /* Fall through to send current status. */ + + if (!SetServiceStatus(svcHandle, &svcStatus)) { + status = GetLastError(); + debug(1, 1) ("SetServiceStatus error %ld\n", status); + } + + break; + + case _WIN_SQUID_SERVICE_CONTROL_ROTATE: + rotate_logs(SIGUSR1); + break; + + case _WIN_SQUID_SERVICE_CONTROL_RECONFIGURE: + reconfigure(SIGHUP); + break; + + case _WIN_SQUID_SERVICE_CONTROL_DEBUG: + sigusr2_handle(SIGUSR2); + break; + + case _WIN_SQUID_SERVICE_CONTROL_INTERRUPT: + /* Do whatever it takes to stop here. */ + svcStatus.dwWin32ExitCode = 0; + svcStatus.dwCurrentState = SERVICE_STOP_PENDING; + svcStatus.dwCheckPoint = 0; + svcStatus.dwWaitHint = 10000; + shut_down(SIGINT); + + if (!SetServiceStatus(svcHandle, &svcStatus)) { + status = GetLastError(); + debug(1, 1) ("SetServiceStatus error %ld\n", status); + } + + debug(1, 1) ("Leaving Squid service\n"); + break; + + default: + debug(1, 1) ("Unrecognized opcode %ld\n", Opcode); + } + + return; +} + +void +WIN32_RemoveService() +{ + SC_HANDLE schService; + SC_HANDLE schSCManager; + + if (!WIN32_Service_name) + WIN32_Service_name = xstrdup(_WIN_SQUID_DEFAULT_SERVICE_NAME); + + strcat(REGKEY, WIN32_Service_name); + + keys[4] = WIN32_Service_name; + + schSCManager = OpenSCManager(NULL, /* machine (NULL == local) */ + NULL, /* database (NULL == default) */ + SC_MANAGER_ALL_ACCESS /* access required */ + ); + + if (!schSCManager) + fprintf(stderr, "OpenSCManager failed\n"); + else { + schService = OpenService(schSCManager, WIN32_Service_name, SERVICE_ALL_ACCESS); + + if (schService == NULL) + fprintf(stderr, "OpenService failed\n"); + + /* Could not open the service */ + else { + /* try to stop the service */ + + if (ControlService(schService, _WIN_SQUID_SERVICE_CONTROL_STOP, + &svcStatus)) { + sleep(1); + + while (QueryServiceStatus(schService, &svcStatus)) { + if (svcStatus.dwCurrentState == SERVICE_STOP_PENDING) + sleep(1); + else + break; + } + } + + /* now remove the service */ + if (DeleteService(schService) == 0) + fprintf(stderr, "DeleteService failed.\n"); + else + printf("Service %s deleted successfully.\n", + WIN32_Service_name); + + CloseServiceHandle(schService); + } + + CloseServiceHandle(schSCManager); + } +} + +void +WIN32_SetServiceCommandLine() +{ + if (!WIN32_Service_name) + WIN32_Service_name = xstrdup(_WIN_SQUID_DEFAULT_SERVICE_NAME); + + strcat(REGKEY, WIN32_Service_name); + + keys[4] = WIN32_Service_name; + + /* Now store the Service Command Line in the registry */ + WIN32_StoreKey(COMMANDLINE, REG_SZ, (unsigned char *) WIN32_Command_Line, strlen(WIN32_Command_Line) + 1); +} + +void +WIN32_InstallService() +{ + SC_HANDLE schService; + SC_HANDLE schSCManager; + char ServicePath[512]; + char szPath[512]; + int lenpath; + + if (!WIN32_Service_name) + WIN32_Service_name = xstrdup(_WIN_SQUID_DEFAULT_SERVICE_NAME); + + strcat(REGKEY, WIN32_Service_name); + + keys[4] = WIN32_Service_name; + + if ((lenpath = GetModuleFileName(NULL, ServicePath, 512)) == 0) { + fprintf(stderr, "Can't get executable path\n"); + exit(1); + } + + snprintf(szPath, sizeof(szPath), "%s %s:%s", ServicePath, _WIN_SQUID_SERVICE_OPTION, WIN32_Service_name); + schSCManager = OpenSCManager(NULL, /* machine (NULL == local) */ + NULL, /* database (NULL == default) */ + SC_MANAGER_ALL_ACCESS /* access required */ + ); + + if (!schSCManager) { + fprintf(stderr, "OpenSCManager failed\n"); + exit(1); + } else { + schService = CreateService(schSCManager, /* SCManager database */ + WIN32_Service_name, /* name of service */ + WIN32_Service_name, /* name to display */ + SERVICE_ALL_ACCESS, /* desired access */ + SERVICE_WIN32_OWN_PROCESS, /* service type */ + SERVICE_AUTO_START, /* start type */ + SERVICE_ERROR_NORMAL, /* error control type */ + (const char *) szPath, /* service's binary */ + NULL, /* no load ordering group */ + NULL, /* no tag identifier */ + "Tcpip\0AFD\0", /* dependencies */ + NULL, /* LocalSystem account */ + NULL); /* no password */ + + if (schService) { + if (WIN32_OS_version > _WIN_OS_WINNT) { + HMODULE ADVAPI32Handle; + PFChangeServiceConfig2 ChangeServiceConfig2; + DWORD dwInfoLevel = SERVICE_CONFIG_DESCRIPTION; + + ADVAPI32Handle = GetModuleHandle("advapi32"); + ChangeServiceConfig2 = (PFChangeServiceConfig2) GetProcAddress(ADVAPI32Handle, CHANGESERVICECONFIG2); + ChangeServiceConfig2(schService, dwInfoLevel, &Squid_ServiceDescription); + dwInfoLevel = SERVICE_CONFIG_FAILURE_ACTIONS; + ChangeServiceConfig2(schService, dwInfoLevel, &Squid_ServiceFailureActions); + } + + CloseServiceHandle(schService); + /* Now store the config file location in the registry */ + + if (!ConfigFile) + ConfigFile = xstrdup(DefaultConfigFile); + + WIN32_StoreKey(CONFIGFILE, REG_SZ, (unsigned char *) ConfigFile, strlen(ConfigFile) + 1); + + printf("Squid Cache version %s for %s\n", version_string, + CONFIG_HOST_TYPE); + + printf("installed successfully as %s Windows System Service.\n", + WIN32_Service_name); + + printf + ("To run, start it from the Services Applet of Control Panel.\n"); + + printf("Don't forget to edit squid.conf before starting it.\n\n"); + } else { + fprintf(stderr, "CreateService failed\n"); + exit(1); + } + + CloseServiceHandle(schSCManager); + } +} + +void +WIN32_sendSignal(int WIN32_signal) +{ + SERVICE_STATUS ssStatus; + DWORD fdwAccess, fdwControl; + SC_HANDLE schService; + SC_HANDLE schSCManager; + + if (!WIN32_Service_name) + WIN32_Service_name = xstrdup(_WIN_SQUID_DEFAULT_SERVICE_NAME); + + schSCManager = OpenSCManager(NULL, /* machine (NULL == local) */ + NULL, /* database (NULL == default) */ + SC_MANAGER_ALL_ACCESS /* access required */ + ); + + if (!schSCManager) { + fprintf(stderr, "OpenSCManager failed\n"); + exit(1); + } + + /* The required service object access depends on the control. */ + switch (WIN32_signal) { + + case 0: /* SIGNULL */ + fdwAccess = SERVICE_INTERROGATE; + fdwControl = _WIN_SQUID_SERVICE_CONTROL_INTERROGATE; + break; + + case SIGUSR1: + fdwAccess = SERVICE_USER_DEFINED_CONTROL; + fdwControl = _WIN_SQUID_SERVICE_CONTROL_ROTATE; + break; + + case SIGUSR2: + fdwAccess = SERVICE_USER_DEFINED_CONTROL; + fdwControl = _WIN_SQUID_SERVICE_CONTROL_DEBUG; + break; + + case SIGHUP: + fdwAccess = SERVICE_USER_DEFINED_CONTROL; + fdwControl = _WIN_SQUID_SERVICE_CONTROL_RECONFIGURE; + break; + + case SIGTERM: + fdwAccess = SERVICE_STOP; + fdwControl = _WIN_SQUID_SERVICE_CONTROL_STOP; + break; + + case SIGINT: + + case SIGKILL: + fdwAccess = SERVICE_USER_DEFINED_CONTROL; + fdwControl = _WIN_SQUID_SERVICE_CONTROL_INTERRUPT; + break; + + default: + exit(1); + } + + /* Open a handle to the service. */ + schService = OpenService(schSCManager, /* SCManager database */ + WIN32_Service_name, /* name of service */ + fdwAccess); /* specify access */ + + if (schService == NULL) { + fprintf(stderr, "%s: ERROR: Could not open Service %s\n", appname, + WIN32_Service_name); + exit(1); + } else { + /* Send a control value to the service. */ + + if (!ControlService(schService, /* handle of service */ + fdwControl, /* control value to send */ + &ssStatus)) { /* address of status info */ + fprintf(stderr, "%s: ERROR: Could not Control Service %s\n", + appname, WIN32_Service_name); + exit(1); + } else { + /* Print the service status. */ + printf("\nStatus of %s Service:\n", WIN32_Service_name); + printf(" Service Type: 0x%lx\n", ssStatus.dwServiceType); + printf(" Current State: 0x%lx\n", ssStatus.dwCurrentState); + printf(" Controls Accepted: 0x%lx\n", ssStatus.dwControlsAccepted); + printf(" Exit Code: %ld\n", ssStatus.dwWin32ExitCode); + printf(" Service Specific Exit Code: %ld\n", + ssStatus.dwServiceSpecificExitCode); + printf(" Check Point: %ld\n", ssStatus.dwCheckPoint); + printf(" Wait Hint: %ld\n", ssStatus.dwWaitHint); + } + + CloseServiceHandle(schService); + } + + CloseServiceHandle(schSCManager); +} + +int main(int argc, char **argv) +{ + SERVICE_TABLE_ENTRY DispatchTable[] = { + {NULL, SquidWinSvcMain}, + {NULL, NULL} + }; + char *c; + char stderr_path[256]; + + if ((argc == 2) && strstr(argv[1], _WIN_SQUID_SERVICE_OPTION)) { + strcpy(stderr_path, argv[0]); + strcat(stderr_path,".log"); + freopen(stderr_path, "w", stderr); + setmode(fileno(stderr), O_TEXT); + WIN32_run_mode = _WIN_SQUID_RUN_MODE_SERVICE; + opt_no_daemon = 1; + + if (!(c=strchr(argv[1],':'))) { + fprintf(stderr, "Bad Service Parameter: %s\n", argv[1]); + return 1; + } + + WIN32_Service_name = xstrdup(c+1); + DispatchTable[0].lpServiceName=WIN32_Service_name; + strcat(REGKEY, WIN32_Service_name); + keys[4] = WIN32_Service_name; + + if (!StartServiceCtrlDispatcher(DispatchTable)) { + fprintf(stderr, "StartServiceCtrlDispatcher error = %ld\n", + GetLastError()); + return 1; + } + } else { + WIN32_run_mode = _WIN_SQUID_RUN_MODE_INTERACTIVE; +#ifdef _SQUID_MSWIN_ + + opt_no_daemon = 1; + +#endif + + return SquidMain(argc, argv); + } + + return 0; +} + +#endif /* USE_WIN32_SERVICE */ + +#if defined(_SQUID_MSWIN_) +static int Win32SockInit(void) +{ + int iVersionRequested; + WSADATA wsaData; + int err, opt; + int optlen = sizeof(opt); + + if (s_iInitCount > 0) { + s_iInitCount++; + return (0); + } else if (s_iInitCount < 0) + return (s_iInitCount); + + /* s_iInitCount == 0. Do the initailization */ + iVersionRequested = MAKEWORD(2, 0); + + err = WSAStartup((WORD) iVersionRequested, &wsaData); + + if (err) { + s_iInitCount = -1; + return (s_iInitCount); + } + + if (LOBYTE(wsaData.wVersion) != 2 || + HIBYTE(wsaData.wVersion) != 0) { + s_iInitCount = -2; + WSACleanup(); + return (s_iInitCount); + } + + if (WIN32_OS_version !=_WIN_OS_WINNT) { + if (::getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&opt, &optlen)) { + s_iInitCount = -3; + WSACleanup(); + return (s_iInitCount); + } else { + opt = opt | SO_SYNCHRONOUS_NONALERT; + + if (::setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *) &opt, optlen)) { + s_iInitCount = -3; + WSACleanup(); + return (s_iInitCount); + } + } + } + + WIN32_Socks_initialized = 1; + s_iInitCount++; + return (s_iInitCount); +} + +static void Win32SockCleanup(void) +{ + if (--s_iInitCount == 0) + WSACleanup(); + + return; +} + +void Squid_Win32InvalidParameterHandler(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved) +{ + return; +} + +#endif /* SQUID_MSWIN_ */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/acl_noncore.cc Wed Feb 14 13:38:02 2007 @@ -0,0 +1,341 @@ +/* + * $Id: acl_noncore.cc,v 1.3.6.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * DEBUG: section 28 Access Control + * AUTHOR: Duane Wessels + * + * This file contains ACL routines that are not part of the + * ACL class, nor any other class yet, and that need to be + * factored into appropriate places. They are here to reduce + * unneeded dependencies between the ACL class and the rest + * of squid. + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "ACL.h" +#include "ACLChecklist.h" +#include "ConfigParser.h" +#include "errorpage.h" +#include "HttpRequest.h" + + +/* does name lookup, returns page_id */ +err_type +aclGetDenyInfoPage(acl_deny_info_list ** head, const char *name) +{ + acl_deny_info_list *A = NULL; + acl_name_list *L = NULL; + + debug(28,9)("aclGetDenyInfoPage: got called for %s\n",name); + + A = *head; + + if (NULL == *head) { /* empty list */ + debug(28,9)("aclGetDenyInfoPage: called for an empty list\n"); + return ERR_NONE; + } + + while (A) { + L = A->acl_list; + + if (NULL == L) { /* empty list should never happen, but in case */ + debug(28,3)("aclGetDenyInfoPage: " + "WARNING, unexpected codepath taken\n"); + continue; + } + + while (L) { + if (!strcmp(name, L->name)) { + debug(28,8)("aclGetDenyInfoPage: match on %s\n",name); + return A->err_page_id; + } + + L = L->next; + } + + A = A->next; + } + + debug(28,8)("aclGetDenyInfoPage: no match\n"); + return ERR_NONE; +} + +/* does name lookup, returns if it is a proxy_auth acl */ +int +aclIsProxyAuth(const char *name) +{ + debug(28,5)("aclIsProxyAuth: called for %s\n",name); + + if (NULL == name) + return false; + + ACL *a; + + if ((a = ACL::FindByName(name))) { + debug(28,5)("aclIsProxyAuth: returning %d\n",a->isProxyAuth()); + return a->isProxyAuth(); + } + + debug(28,3)("aclIsProxyAuth: WARNING, called for nonexistent ACL\n"); + return false; +} + + +/* maex@space.net (05.09.96) + * get the info for redirecting "access denied" to info pages + * TODO (probably ;-) + * currently there is no optimization for + * - more than one deny_info line with the same url + * - a check, whether the given acl really is defined + * - a check, whether an acl is added more than once for the same url + */ + +void +aclParseDenyInfoLine(acl_deny_info_list ** head) +{ + char *t = NULL; + acl_deny_info_list *A = NULL; + acl_deny_info_list *B = NULL; + acl_deny_info_list **T = NULL; + acl_name_list *L = NULL; + acl_name_list **Tail = NULL; + + /* first expect a page name */ + + if ((t = strtok(NULL, w_space)) == NULL) { + debug(28, 0) ("aclParseDenyInfoLine: %s line %d: %s\n", + cfg_filename, config_lineno, config_input_line); + debug(28, 0) ("aclParseDenyInfoLine: missing 'error page' parameter.\n"); + return; + } + + A = (acl_deny_info_list *)memAllocate(MEM_ACL_DENY_INFO_LIST); + A->err_page_id = errorReservePageId(t); + A->err_page_name = xstrdup(t); + A->next = (acl_deny_info_list *) NULL; + /* next expect a list of ACL names */ + Tail = &A->acl_list; + + while ((t = strtok(NULL, w_space))) { + L = (acl_name_list *)memAllocate(MEM_ACL_NAME_LIST); + xstrncpy(L->name, t, ACL_NAME_SZ); + *Tail = L; + Tail = &L->next; + } + + if (A->acl_list == NULL) { + debug(28, 0) ("aclParseDenyInfoLine: %s line %d: %s\n", + cfg_filename, config_lineno, config_input_line); + debug(28, 0) ("aclParseDenyInfoLine: deny_info line contains no ACL's, skipping\n"); + memFree(A, MEM_ACL_DENY_INFO_LIST); + return; + } + + for (B = *head, T = head; B; T = &B->next, B = B->next) + + ; /* find the tail */ + *T = A; +} + +void +aclParseAccessLine(ConfigParser &parser, acl_access ** head) +{ + char *t = NULL; + acl_access *A = NULL; + acl_access *B = NULL; + acl_access **T = NULL; + + /* first expect either 'allow' or 'deny' */ + + if ((t = strtok(NULL, w_space)) == NULL) { + debug(28, 0) ("aclParseAccessLine: %s line %d: %s\n", + cfg_filename, config_lineno, config_input_line); + debug(28, 0) ("aclParseAccessLine: missing 'allow' or 'deny'.\n"); + return; + } + + A = new acl_access; + + if (!strcmp(t, "allow")) + A->allow = ACCESS_ALLOWED; + else if (!strcmp(t, "deny")) + A->allow = ACCESS_DENIED; + else { + debug(28, 0) ("aclParseAccessLine: %s line %d: %s\n", + cfg_filename, config_lineno, config_input_line); + debug(28, 0) ("aclParseAccessLine: expecting 'allow' or 'deny', got '%s'.\n", t); + delete A; + return; + } + + aclParseAclList(parser, &A->aclList); + + if (A->aclList == NULL) { + debug(28, 0) ("%s line %d: %s\n", + cfg_filename, config_lineno, config_input_line); + debug(28, 0) ("aclParseAccessLine: Access line contains no ACL's, skipping\n"); + delete A; + return; + } + + A->cfgline = xstrdup(config_input_line); + /* Append to the end of this list */ + + for (B = *head, T = head; B; T = &B->next, B = B->next) + + ; + *T = A; + + /* We lock _acl_access structures in ACLChecklist::check() */ +} + +void +aclParseAclList(ConfigParser &parser, acl_list ** head) +{ + acl_list **Tail = head; /* sane name in the use below */ + ACL *a = NULL; + char *t; + + /* next expect a list of ACL names, possibly preceeded + * by '!' for negation */ + + while ((t = strtok(NULL, w_space))) { + acl_list *L = new ACLList; + + if (*t == '!') { + L->negated (true); + t++; + } + + debug(28, 3) ("aclParseAccessLine: looking for ACL name '%s'\n", t); + a = ACL::FindByName(t); + + if (a == NULL) { + debug(28, 0) ("aclParseAccessLine: ACL name '%s' not found.\n", t); + delete L; + parser.destruct(); + continue; + } + + L->_acl = a; + *Tail = L; + Tail = &L->next; + } +} + + + +/*********************/ +/* Destroy functions */ +/*********************/ + +void +aclDestroyAcls(ACL ** head) +{ + ACL *next = NULL; + + debug(28,8)("aclDestroyACLs: invoked\n"); + + for (ACL *a = *head; a; a = next) { + next = a->next; + delete a; + } + + *head = NULL; +} + +void +aclDestroyAclList(acl_list ** head) +{ + acl_list *l; + debug(28,8)("aclDestroyAclList: invoked\n"); + + for (l = *head; l; l = *head) { + *head = l->next; + delete l; + } +} + +void +aclDestroyAccessList(acl_access ** list) +{ + acl_access *l = NULL; + acl_access *next = NULL; + + for (l = *list; l; l = next) { + debug(28, 3) ("aclDestroyAccessList: '%s'\n", l->cfgline); + next = l->next; + aclDestroyAclList(&l->aclList); + safe_free(l->cfgline); + cbdataFree(l); + } + + *list = NULL; +} + +/* maex@space.net (06.09.1996) + * destroy an _acl_deny_info_list */ + +void +aclDestroyDenyInfoList(acl_deny_info_list ** list) +{ + acl_deny_info_list *a = NULL; + acl_deny_info_list *a_next = NULL; + acl_name_list *l = NULL; + acl_name_list *l_next = NULL; + + debug(28,8)("aclDestroyDenyInfoList: invoked\n"); + + for (a = *list; a; a = a_next) { + for (l = a->acl_list; l; l = l_next) { + l_next = l->next; + safe_free(l); + } + + a_next = a->next; + xfree(a->err_page_name); + memFree(a, MEM_ACL_DENY_INFO_LIST); + } + + *list = NULL; +} + +/* + * This function traverses all ACL elements referenced + * by an access list (presumably 'http_access'). If + * it finds a PURGE method ACL, then it returns TRUE, + * otherwise FALSE. + */ +/* XXX: refactor this more sensibly. perhaps have the parser detect it ? */ +int +aclPurgeMethodInUse(acl_access * a) +{ + return a->containsPURGE(); +} --- squid3/src/cachemgr.cc Wed Feb 14 13:38:02 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,1212 +0,0 @@ - -/* - * $Id: cachemgr.cc,v 1.14.2.1 2005/08/26 19:09:54 dwsquid Exp $ - * - * DEBUG: section 0 CGI Cache Manager - * AUTHOR: Duane Wessels - * - * SQUID Web Proxy Cache http://www.squid-cache.org/ - * ---------------------------------------------------------- - * - * Squid is the result of efforts by numerous individuals from - * the Internet community; see the CONTRIBUTORS file for full - * details. Many organizations have provided support for Squid's - * development; see the SPONSORS file for full details. Squid is - * Copyrighted (C) 2001 by the Regents of the University of - * California; see the COPYRIGHT file for full details. Squid - * incorporates software developed and/or copyrighted by other - * sources; see the CREDITS file for full details. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. - * - */ - -#include "config.h" - -#if HAVE_UNISTD_H -#include -#endif -#if HAVE_STDLIB_H -#include -#endif -#if HAVE_STDIO_H -#include -#endif -#if HAVE_SYS_TYPES_H -#include -#endif -#if HAVE_CTYPE_H -#include -#endif -#if HAVE_ERRNO_H -#include -#endif -#if HAVE_FCNTL_H -#include -#endif -#if HAVE_GRP_H -#include -#endif -#if HAVE_GNUMALLOC_H -#include -#elif HAVE_MALLOC_H -#include -#endif -#if HAVE_MEMORY_H -#include -#endif -#if HAVE_NETDB_H && !defined(_SQUID_NETDB_H_) /* protect NEXTSTEP */ -#define _SQUID_NETDB_H_ -#include -#endif -#if HAVE_PWD_H -#include -#endif -#if HAVE_SIGNAL_H -#include -#endif -#if HAVE_TIME_H -#include -#endif -#if HAVE_SYS_PARAM_H -#include -#endif -#if HAVE_SYS_TIME_H -#include -#endif -#if HAVE_SYS_RESOURCE_H -#include /* needs sys/time.h above it */ -#endif -#if HAVE_SYS_SOCKET_H -#include -#endif -#if HAVE_NETINET_IN_H -#include -#endif -#if HAVE_ARPA_INET_H -#include -#endif -#if HAVE_SYS_STAT_H -#include -#endif -#if HAVE_SYS_UN_H -#include -#endif -#if HAVE_SYS_WAIT_H -#include -#endif -#if HAVE_LIBC_H -#include -#endif -#if HAVE_STRING_H -#include -#endif -#if HAVE_STRINGS_H -#include -#endif -#if HAVE_BSTRING_H -#include -#endif -#if HAVE_CRYPT_H -#include -#endif -#if HAVE_SYS_SELECT_H -#include -#endif -#if HAVE_FNMATCH_H -extern "C" -{ -#include -} - -#endif - -#include - -#include "util.h" -#include "snprintf.h" - -#ifndef DEFAULT_CACHEMGR_CONFIG -#define DEFAULT_CACHEMGR_CONFIG "/etc/squid/cachemgr.conf" -#endif - -typedef struct -{ - char *server; - char *hostname; - int port; - char *action; - char *user_name; - char *passwd; - char *pub_auth; -} - -cachemgr_request; - -/* - * Debugging macros (info goes to error_log on your web server) - * Note: do not run cache manager with non zero debugging level - * if you do not debug, it may write a lot of [sensitive] - * information to your error log. - */ - -/* debugging level 0 (disabled) - 3 (max) */ -#define DEBUG_LEVEL 0 -#define debug(level) if ((level) <= DEBUG_LEVEL && DEBUG_LEVEL > 0) - -/* - * Static variables and constants - */ -static const time_t passwd_ttl = 60 * 60 * 3; /* in sec */ -static const char *script_name = "/cgi-bin/cachemgr.cgi"; -static const char *progname = NULL; -static time_t now; - -static struct IN_ADDR no_addr; - -/* - * Function prototypes - */ -#define safe_free(str) { if (str) { xfree(str); (str) = NULL; } } -static const char *safe_str(const char *str); -static const char *xstrtok(char **str, char del); -static void print_trailer(void); -static void auth_html(const char *host, int port, const char *user_name); -static void error_html(const char *msg); -static char *menu_url(cachemgr_request * req, const char *action); -static int parse_status_line(const char *sline, const char **statusStr); -#ifdef _SQUID_MSWIN_ -static cachemgr_request *read_request(char *); -#else -static cachemgr_request *read_request(void); -#endif -static char *read_get_request(void); -static char *read_post_request(void); - -static void make_pub_auth(cachemgr_request * req); -static void decode_pub_auth(cachemgr_request * req); -static void reset_auth(cachemgr_request * req); -static const char *make_auth_header(const cachemgr_request * req); - -static int check_target_acl(const char *hostname, int port); - -#ifdef _SQUID_MSWIN_ -static int s_iInitCount = 0; -int Win32SockInit(void) -{ - int iVersionRequested; - WSADATA wsaData; - int err; - - if (s_iInitCount > 0) { - s_iInitCount++; - return (0); - } else if (s_iInitCount < 0) - return (s_iInitCount); - - /* s_iInitCount == 0. Do the initailization */ - iVersionRequested = MAKEWORD(2, 0); - - err = WSAStartup((WORD) iVersionRequested, &wsaData); - - if (err) { - s_iInitCount = -1; - return (s_iInitCount); - } - - if (LOBYTE(wsaData.wVersion) != 2 || - HIBYTE(wsaData.wVersion) != 0) { - s_iInitCount = -2; - WSACleanup(); - return (s_iInitCount); - } - - s_iInitCount++; - return (s_iInitCount); -} - -void Win32SockCleanup(void) -{ - if (--s_iInitCount == 0) - WSACleanup(); - - return; -} - -#endif /* ifdef _SQUID_MSWIN_ */ - -static const char * -safe_str(const char *str) -{ - return str ? str : ""; -} - -/* relaxed number format */ -static int -is_number(const char *str) -{ - return strspn(str, "\t -+01234567890./\n") == strlen(str); -} - -static const char * -xstrtok(char **str, char del) -{ - if (*str) { - char *p = strchr(*str, del); - char *tok = *str; - int len; - - if (p) { - *str = p + 1; - *p = '\0'; - } else - *str = NULL; - - /* trim */ - len = strlen(tok); - - while (len && xisspace(tok[len - 1])) - tok[--len] = '\0'; - - while (xisspace(*tok)) - tok++; - - return tok; - } else - return ""; -} - -static void -print_trailer(void) -{ - printf("
\n"); - printf("
\n"); - printf("Generated %s, by %s/%s@%s\n", - mkrfc1123(now), progname, VERSION, getfullhostname()); - printf("
\n"); -} - -static void -auth_html(const char *host, int port, const char *user_name) -{ - FILE *fp; - int need_host = 1; - - if (!user_name) - user_name = ""; - - if (!host || !strlen(host)) - host = ""; - - printf("Content-Type: text/html\r\n\r\n"); - - printf("\n"); - - printf("Cache Manager Interface\n"); - - printf("\n"); - - printf("

Cache Manager Interface

\n"); - - printf("

This is a WWW interface to the instrumentation interface\n"); - - printf("for the Squid object cache.

\n"); - - printf("
\n"); - - printf("
\n", script_name); - - printf("\n"); - - - fp = fopen("cachemgr.conf", "r"); - - if (fp == NULL) - fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r"); - - if (fp != NULL) { - int servers = 0; - char config_line[BUFSIZ]; - - while (fgets(config_line, BUFSIZ, fp)) { - char *server, *comment; - strtok(config_line, "\r\n"); - - if (config_line[0] == '#') - continue; - - if (config_line[0] == '\0') - continue; - - if ((server = strtok(config_line, " \t")) == NULL) - continue; - - if (strchr(server, '*') || strchr(server, '[') || strchr(server, '?')) { - need_host = -1; - continue; - } - - comment = strtok(NULL, ""); - - if (comment) - while (*comment == ' ' || *comment == '\t') - comment++; - - if (!comment || !*comment) - comment = server; - - if (!servers) { - printf("\n"); - } - - fclose(fp); - } - - if (need_host) { - if (need_host == 1 && !*host) - host = "localhost"; - - printf("\n", host); - - printf("\n", port); - } - - printf("\n", user_name); - - printf("\n"); - - printf("
Cache Server:
Cache Host:
Cache Port:
Manager name:
Password:

\n"); - - printf("\n"); - - printf("
\n"); - - print_trailer(); -} - -static void -error_html(const char *msg) -{ - printf("Content-Type: text/html\r\n\r\n"); - printf("\n"); - printf("Cache Manager Error\n"); - printf("\n"); - printf("

Cache Manager Error

\n"); - printf("

\n%s

\n", msg); - print_trailer(); -} - -/* returns http status extracted from status line or -1 on parsing failure */ -static int -parse_status_line(const char *sline, const char **statusStr) -{ - const char *sp = strchr(sline, ' '); - - if (statusStr) - *statusStr = NULL; - - if (strncasecmp(sline, "HTTP/", 5) || !sp) - return -1; - - while (xisspace(*++sp)) - - ; - if (!xisdigit(*sp)) - return -1; - - if (statusStr) - *statusStr = sp; - - return atoi(sp); -} - -static char * -menu_url(cachemgr_request * req, const char *action) -{ - static char url[1024]; - snprintf(url, sizeof(url), "%s?host=%s&port=%d&user_name=%s&operation=%s&auth=%s", - script_name, - req->hostname, - req->port, - safe_str(req->user_name), - action, - safe_str(req->pub_auth)); - return url; -} - -static const char * -munge_menu_line(const char *buf, cachemgr_request * req) -{ - char *x; - const char *a; - const char *d; - const char *p; - char *a_url; - char *buf_copy; - static char html[2 * 1024]; - - if (strlen(buf) < 1) - return buf; - - if (*buf != ' ') - return buf; - - buf_copy = x = xstrdup(buf); - - a = xstrtok(&x, '\t'); - - d = xstrtok(&x, '\t'); - - p = xstrtok(&x, '\t'); - - a_url = xstrdup(menu_url(req, a)); - - /* no reason to give a url for a disabled action */ - if (!strcmp(p, "disabled")) - snprintf(html, sizeof(html), "
  • %s (disabled).\n", d, a_url); - else - /* disable a hidden action (requires a password, but password is not in squid.conf) */ - if (!strcmp(p, "hidden")) - snprintf(html, sizeof(html), "
  • %s (hidden).\n", d, a_url); - else - /* disable link if authentication is required and we have no password */ - if (!strcmp(p, "protected") && !req->passwd) - snprintf(html, sizeof(html), "
  • %s (requires authentication).\n", - d, menu_url(req, "authenticate"), a_url); - else - /* highlight protected but probably available entries */ - if (!strcmp(p, "protected")) - snprintf(html, sizeof(html), "
  • %s\n", - a_url, d); - - /* public entry or unknown type of protection */ - else - snprintf(html, sizeof(html), "
  • %s\n", a_url, d); - - xfree(a_url); - - xfree(buf_copy); - - return html; -} - -static const char * -munge_other_line(const char *buf, cachemgr_request * req) -{ - static const char *ttags[] = {"td", "th"}; - - static char html[4096]; - static int table_line_num = 0; - static int next_is_header = 0; - int is_header = 0; - const char *ttag; - char *buf_copy; - char *x, *p; - int l = 0; - /* does it look like a table? */ - - if (!strchr(buf, '\t') || *buf == '\t') { - /* nope, just text */ - snprintf(html, sizeof(html), "%s%s", - table_line_num ? "\n
    " : "", buf);
    -        table_line_num = 0;
    -        return html;
    -    }
    -
    -    /* start html table */
    -    if (!table_line_num) {
    -        l += snprintf(html + l, sizeof(html) - l, "
    \n"); - next_is_header = 0; - } - - /* remove '\n' */ - is_header = (!table_line_num || next_is_header) && !strchr(buf, ':') && !is_number(buf); - - ttag = ttags[is_header]; - - /* record starts */ - l += snprintf(html + l, sizeof(html) - l, ""); - - /* substitute '\t' */ - buf_copy = x = xstrdup(buf); - - if ((p = strchr(x, '\n'))) - *p = '\0'; - - while (x && strlen(x)) { - int column_span = 1; - const char *cell = xstrtok(&x, '\t'); - - while (x && *x == '\t') { - column_span++; - x++; - } - - l += snprintf(html + l, sizeof(html) - l, "<%s colspan=\"%d\" align=\"%s\">%s", - ttag, column_span, - is_header ? "center" : is_number(cell) ? "right" : "left", - cell, ttag); - } - - xfree(buf_copy); - /* record ends */ - l += snprintf(html + l, sizeof(html) - l, "\n"); - next_is_header = is_header && strstr(buf, "\t\t"); - table_line_num++; - return html; -} - -static int -read_reply(int s, cachemgr_request * req) -{ - char buf[4 * 1024]; -#ifdef _SQUID_MSWIN_ - - int reply; - FILE *fp = tmpfile(); -#else - - FILE *fp = fdopen(s, "r"); -#endif - /* interpretation states */ - enum { - isStatusLine, isHeaders, isBodyStart, isBody, isForward, isEof, isForwardEof, isSuccess, isError - } istate = isStatusLine; - int parse_menu = 0; - const char *action = req->action; - const char *statusStr = NULL; - int status = -1; - - if (0 == strlen(req->action)) - parse_menu = 1; - else if (0 == strcasecmp(req->action, "menu")) - parse_menu = 1; - - if (fp == NULL) { - perror("fdopen"); - return 1; - } - -#ifdef _SQUID_MSWIN_ - - while ((reply=recv(s, buf , sizeof(buf), 0)) > 0) - fwrite(buf, 1, reply, fp); - - rewind(fp); - -#endif - - if (parse_menu) - action = "menu"; - - /* read reply interpreting one line at a time depending on state */ - while (istate < isEof) { - if (!fgets(buf, sizeof(buf), fp)) - istate = istate == isForward ? isForwardEof : isEof; - - switch (istate) { - - case isStatusLine: - /* get HTTP status */ - /* uncomment the following if you want to debug headers */ - /* fputs("\r\n\r\n", stdout); */ - status = parse_status_line(buf, &statusStr); - istate = status == 200 ? isHeaders : isForward; - /* if cache asks for authentication, we have to reset our info */ - - if (status == 401 || status == 407) { - reset_auth(req); - status = 403; /* Forbiden, see comments in case isForward: */ - } - - /* this is a way to pass HTTP status to the Web server */ - if (statusStr) - printf("Status: %d %s", status, statusStr); /* statusStr has '\n' */ - - break; - - case isHeaders: - /* forward header field */ - if (!strcmp(buf, "\r\n")) { /* end of headers */ - fputs("Content-Type: text/html\r\n", stdout); /* add our type */ - istate = isBodyStart; - } - - if (strncasecmp(buf, "Content-Type:", 13)) /* filter out their type */ - fputs(buf, stdout); - - break; - - case isBodyStart: - printf("\n"); - - printf("CacheMgr@%s: %s\n", - req->hostname, action); - - printf("\n"); - - printf("\n"); - - if (parse_menu) { - printf("

    Cache Manager menu for %s:

    ", - menu_url(req, "authenticate"), req->hostname); - printf("
      \n"); - } else { - printf("

      %s\n


      \n", - menu_url(req, "menu"), "Cache Manager menu"); - printf("
      \n");
      -            }
      -
      -            istate = isBody;
      -            /* yes, fall through, we do not want to loose the first line */
      -
      -        case isBody:
      -            /* interpret [and reformat] cache response */
      -
      -            if (parse_menu)
      -                fputs(munge_menu_line(buf, req), stdout);
      -            else
      -                fputs(munge_other_line(buf, req), stdout);
      -
      -            break;
      -
      -        case isForward:
      -            /* forward: no modifications allowed */
      -            /*
      -             * Note: we currently do not know any way to get browser.reply to
      -             * 401 to .cgi because web server filters out all auth info. Thus we
      -             * disable authentication headers for now.
      -             */
      -            if (!strncasecmp(buf, "WWW-Authenticate:", 17) || !strncasecmp(buf, "Proxy-Authenticate:", 19))
      -
      -                ;	/* skip */
      -            else
      -                fputs(buf, stdout);
      -
      -            break;
      -
      -        case isEof:
      -            /* print trailers */
      -            if (parse_menu)
      -                printf("
    \n"); - else - printf("
    \n"); - - print_trailer(); - - istate = isSuccess; - - break; - - case isForwardEof: - /* indicate that we finished processing an "error" sequence */ - istate = isError; - - break; - - default: - printf("%s: internal bug: invalid state reached: %d", script_name, istate); - - istate = isError; - } - } - - close(s); - return 0; -} - -static int -process_request(cachemgr_request * req) -{ - - const struct hostent *hp; - - static struct sockaddr_in S; - int s; - int l; -#ifdef _SQUID_MSWIN_ - - int answer; -#endif - - static char buf[2 * 1024]; - - if (req == NULL) { - auth_html(CACHEMGR_HOSTNAME, CACHE_HTTP_PORT, ""); - return 1; - } - - if (req->hostname == NULL) { - req->hostname = xstrdup(CACHEMGR_HOSTNAME); - } - - if (req->port == 0) { - req->port = CACHE_HTTP_PORT; - } - - if (req->action == NULL) { - req->action = xstrdup(""); - } - - if (strcmp(req->action, "authenticate") == 0) { - auth_html(req->hostname, req->port, req->user_name); - return 0; - } - - if (!check_target_acl(req->hostname, req->port)) { - snprintf(buf, 1024, "target %s:%d not allowed in cachemgr.conf\n", req->hostname, req->port); - error_html(buf); - return 1; - } - - if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { - snprintf(buf, 1024, "socket: %s\n", xstrerror()); - error_html(buf); - return 1; - } - - memset(&S, '\0', sizeof(S)); - S.sin_family = AF_INET; - - if ((hp = gethostbyname(req->hostname)) != NULL) { - assert(hp->h_length >= 0 && (size_t)hp->h_length <= sizeof(S.sin_addr.s_addr)); - xmemcpy(&S.sin_addr.s_addr, hp->h_addr, hp->h_length); - } else if (safe_inet_addr(req->hostname, &S.sin_addr)) - (void) 0; - else { - snprintf(buf, 1024, "Unknown host: %s\n", req->hostname); - error_html(buf); - return 1; - } - - S.sin_port = htons(req->port); - - if (connect(s, (struct sockaddr *) &S, sizeof(S)) < 0) { - snprintf(buf, 1024, "connect %s:%d: %s\n", - inet_ntoa(S.sin_addr), - ntohs(S.sin_port), - xstrerror()); - error_html(buf); - return 1; - } - - l = snprintf(buf, sizeof(buf), - "GET cache_object://%s/%s HTTP/1.0\r\n" - "Accept: */*\r\n" - "%s" /* Authentication info or nothing */ - "\r\n", - req->hostname, - req->action, - make_auth_header(req)); - write(s, buf, l); - debug(1) fprintf(stderr, "wrote request: '%s'\n", buf); -#ifdef _SQUID_MSWIN_ - - answer=read_reply(s, req); - close(s); - return answer; -#else - - return read_reply(s, req); -#endif -} - -int -main(int argc, char *argv[]) -{ - char *s; - cachemgr_request *req; -#ifdef _SQUID_MSWIN_ - - int answer; -#endif - - safe_inet_addr("255.255.255.255", &no_addr); - now = time(NULL); -#ifdef _SQUID_MSWIN_ - - Win32SockInit(); - - _setmode( _fileno( stdin ), _O_BINARY ); - _setmode( _fileno( stdout ), _O_BINARY ); - _fmode = _O_BINARY; - - if ((s = strrchr(argv[0], '\\'))) -#else - - if ((s = strrchr(argv[0], '/'))) -#endif - - progname = xstrdup(s + 1); - else - progname = xstrdup(argv[0]); - - if ((s = getenv("SCRIPT_NAME")) != NULL) - script_name = xstrdup(s); - -#ifdef _SQUID_MSWIN_ - - req = read_request(NULL); - - answer=process_request(req); - - Win32SockCleanup(); - - return answer; - -#else - - req = read_request(); - - return process_request(req); - -#endif -} - -static char * -read_post_request(void) -{ - char *s; - char *buf; - int len; - - if ((s = getenv("REQUEST_METHOD")) == NULL) - return NULL; - - if (0 != strcasecmp(s, "POST")) - return NULL; - - if ((s = getenv("CONTENT_LENGTH")) == NULL) - return NULL; - - if ((len = atoi(s)) <= 0) - return NULL; - - buf = (char *)xmalloc(len + 1); - - fread(buf, len, 1, stdin); - - buf[len] = '\0'; - - return buf; -} - -static char * -read_get_request(void) -{ - char *s; - - if ((s = getenv("QUERY_STRING")) == NULL) - return NULL; - - return xstrdup(s); -} - -#ifdef _SQUID_MSWIN_ -static cachemgr_request * -read_request(char* buf) -{ -#else -static cachemgr_request * -read_request(void) { - char *buf; -#endif - - cachemgr_request *req; - char *s; - char *t; - char *q; - - if ((buf = read_post_request()) != NULL) - (void) 0; - else if ((buf = read_get_request()) != NULL) - (void) 0; - else - return NULL; - -#ifdef _SQUID_MSWIN_ - - if (strlen(buf) == 0 || strlen(buf) == 4000) -#else - - if (strlen(buf) == 0) -#endif - - return NULL; - - req = (cachemgr_request *)xcalloc(1, sizeof(cachemgr_request)); - - for (s = strtok(buf, "&"); s != NULL; s = strtok(NULL, "&")) { - t = xstrdup(s); - - if ((q = strchr(t, '=')) == NULL) - continue; - - *q++ = '\0'; - - rfc1738_unescape(t); - - rfc1738_unescape(q); - - if (0 == strcasecmp(t, "server") && strlen(q)) - req->server = xstrdup(q); - else if (0 == strcasecmp(t, "host") && strlen(q)) - req->hostname = xstrdup(q); - else if (0 == strcasecmp(t, "port") && strlen(q)) - req->port = atoi(q); - else if (0 == strcasecmp(t, "user_name") && strlen(q)) - req->user_name = xstrdup(q); - else if (0 == strcasecmp(t, "passwd") && strlen(q)) - req->passwd = xstrdup(q); - else if (0 == strcasecmp(t, "auth") && strlen(q)) - req->pub_auth = xstrdup(q), decode_pub_auth(req); - else if (0 == strcasecmp(t, "operation")) - req->action = xstrdup(q); - } - - if (req->server && !req->hostname) { - char *p; - req->hostname = strtok(req->server, ":"); - - if ((p = strtok(NULL, ":"))) - req->port = atoi(p); - } - - make_pub_auth(req); - debug(1) fprintf(stderr, "cmgr: got req: host: '%s' port: %d uname: '%s' passwd: '%s' auth: '%s' oper: '%s'\n", - safe_str(req->hostname), req->port, safe_str(req->user_name), safe_str(req->passwd), safe_str(req->pub_auth), safe_str(req->action)); - return req; -} - - -/* Routines to support authentication */ - -/* - * Encodes auth info into a "public" form. - * Currently no powerful encryption is used. - */ -static void -make_pub_auth(cachemgr_request * req) { - static char buf[1024]; - safe_free(req->pub_auth); - debug(3) fprintf(stderr, "cmgr: encoding for pub...\n"); - - if (!req->passwd || !strlen(req->passwd)) - return; - - /* host | time | user | passwd */ - snprintf(buf, sizeof(buf), "%s|%d|%s|%s", - req->hostname, - (int) now, - req->user_name ? req->user_name : "", - req->passwd); - - debug(3) fprintf(stderr, "cmgr: pre-encoded for pub: %s\n", buf); - - debug(3) fprintf(stderr, "cmgr: encoded: '%s'\n", base64_encode(buf)); - - req->pub_auth = xstrdup(base64_encode(buf)); -} - -static void -decode_pub_auth(cachemgr_request * req) { - char *buf; - const char *host_name; - const char *time_str; - const char *user_name; - const char *passwd; - - debug(2) fprintf(stderr, "cmgr: decoding pub: '%s'\n", safe_str(req->pub_auth)); - safe_free(req->passwd); - - if (!req->pub_auth || strlen(req->pub_auth) < 4 + strlen(safe_str(req->hostname))) - return; - - buf = xstrdup(base64_decode(req->pub_auth)); - - debug(3) fprintf(stderr, "cmgr: length ok\n"); - - /* parse ( a lot of memory leaks, but that is cachemgr style :) */ - if ((host_name = strtok(buf, "|")) == NULL) - return; - - debug(3) fprintf(stderr, "cmgr: decoded host: '%s'\n", host_name); - - if ((time_str = strtok(NULL, "|")) == NULL) - return; - - debug(3) fprintf(stderr, "cmgr: decoded time: '%s' (now: %d)\n", time_str, (int) now); - - if ((user_name = strtok(NULL, "|")) == NULL) - return; - - debug(3) fprintf(stderr, "cmgr: decoded uname: '%s'\n", user_name); - - if ((passwd = strtok(NULL, "|")) == NULL) - return; - - debug(2) fprintf(stderr, "cmgr: decoded passwd: '%s'\n", passwd); - - /* verify freshness and validity */ - if (atoi(time_str) + passwd_ttl < now) - return; - - if (strcasecmp(host_name, req->hostname)) - return; - - debug(1) fprintf(stderr, "cmgr: verified auth. info.\n"); - - /* ok, accept */ - xfree(req->user_name); - - req->user_name = xstrdup(user_name); - - req->passwd = xstrdup(passwd); - - xfree(buf); -} - -static void -reset_auth(cachemgr_request * req) { - safe_free(req->passwd); - safe_free(req->pub_auth); -} - -static const char * -make_auth_header(const cachemgr_request * req) { - static char buf[1024]; - size_t stringLength = 0; - const char *str64; - - if (!req->passwd) - return ""; - - snprintf(buf, sizeof(buf), "%s:%s", - req->user_name ? req->user_name : "", - req->passwd); - - str64 = base64_encode(buf); - - stringLength += snprintf(buf, sizeof(buf), "Authorization: Basic %s\r\n", str64); - - assert(stringLength < sizeof(buf)); - - stringLength += snprintf(&buf[stringLength], sizeof(buf) - stringLength, - "Proxy-Authorization: Basic %s\r\n", str64); - - return buf; -} - -static int -check_target_acl(const char *hostname, int port) { - char config_line[BUFSIZ]; - FILE *fp = NULL; - int ret = 0; - fp = fopen("cachemgr.conf", "r"); - - if (fp == NULL) - fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r"); - - if (fp == NULL) { -#ifdef CACHEMGR_HOSTNAME_DEFINED - - if (strcmp(hostname, CACHEMGR_HOSTNAME) == 0 && port == CACHE_HTTP_PORT) - return 1; - -#else - - if (strcmp(hostname, "localhost") == 0) - return 1; - - if (strcmp(hostname, getfullhostname()) == 0) - return 1; - -#endif - - return 0; - } - - while (fgets(config_line, BUFSIZ, fp)) { - char *token = NULL; - strtok(config_line, " \r\n\t"); - - if (config_line[0] == '#') - continue; - - if (config_line[0] == '\0') - continue; - - if ((token = strtok(config_line, ":")) == NULL) - continue; - -#if HAVE_FNMATCH_H - - if (fnmatch(token, hostname, 0) != 0) - continue; - -#else - - if (strcmp(token, hostname) != 0) - continue; - -#endif - - if ((token = strtok(NULL, ":")) != NULL) { - int i; - - if (strcmp(token, "*") == 0) - - ; /* Wildcard port specification */ - else if (strcasecmp(token, "any") == 0) - - ; /* Wildcard port specification */ - else if (sscanf(token, "%d", &i) != 1) - continue; - - else if (i != port) - continue; - } else if (port != CACHE_HTTP_PORT) - continue; - - ret = 1; - - break; - } - - fclose(fp); - return ret; -} --- squid3/src/cachemgr.conf Wed Feb 14 13:38:02 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,13 +0,0 @@ -# This file controls which servers may be managed by -# the cachemgr.cgi script -# -# The file consists of one server per line on the format -# hostname:port description -# -# Specifying :port is optional. If not specified then -# the default proxy port is assumed. :* or :any matches -# any port on the target server. -# -# hostname is matched using shell filename matching, allowing -# * and other shell wildcards. -localhost --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/cbdata.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,139 @@ + +/* + * $Id: cbdata.h,v 1.1.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * Copyright (c) 2003, Robert Collins + */ + +#ifndef SQUID_CBDATA_H +#define SQUID_CBDATA_H + +#include "squid.h" + +/* + * cbdata types. similar to the MEM_* types above, but managed + * in cbdata.c. A big difference is that these types are dynamically + * allocated. This list is only a list of predefined types. Other types + * are added runtime + */ +typedef enum { + CBDATA_UNKNOWN = 0, +} cbdata_type; + +extern void cbdataRegisterWithCacheManager(CacheManager & manager); +#if CBDATA_DEBUG +extern void *cbdataInternalAllocDbg(cbdata_type type, const char *, int); +extern void *cbdataInternalFreeDbg(void *p, const char *, int); +extern void cbdataInternalLockDbg(const void *p, const char *, int); +extern void cbdataInternalUnlockDbg(const void *p, const char *, int); +extern int cbdataInternalReferenceDoneValidDbg(void **p, void **tp, const char *, int); +#else +extern void *cbdataInternalAlloc(cbdata_type type); +extern void *cbdataInternalFree(void *p); +extern void cbdataInternalLock(const void *p); +extern void cbdataInternalUnlock(const void *p); +extern int cbdataInternalReferenceDoneValid(void **p, void **tp); +#endif +extern int cbdataReferenceValid(const void *p); +extern cbdata_type cbdataInternalAddType(cbdata_type type, const char *label, int size, FREE * free_func); + + +/* cbdata macros */ +#if CBDATA_DEBUG +#define cbdataAlloc(type) ((type *)cbdataInternalAllocDbg(CBDATA_##type,__FILE__,__LINE__)) +#define cbdataFree(var) do {if (var) {cbdataInternalFreeDbg(var,__FILE__,__LINE__); var = NULL;}} while(0) +#define cbdataInternalLock(a) cbdataInternalLockDbg(a,__FILE__,__LINE__) +#define cbdataInternalUnlock(a) cbdataInternalUnlockDbg(a,__FILE__,__LINE__) +#define cbdataReferenceValidDone(var, ptr) cbdataInternalReferenceDoneValidDbg((void **)&(var), (ptr), __FILE__,__LINE__) +#define CBDATA_CLASS2(type) \ + static cbdata_type CBDATA_##type; \ + public: \ + void *operator new(size_t size) { \ + assert(size == sizeof(type)); \ + (CBDATA_##type ? CBDATA_UNKNOWN : (CBDATA_##type = cbdataInternalAddType(CBDATA_##type, #type, sizeof(type), NULL))); \ + return cbdataInternalAllocDbg(CBDATA_##type,__FILE__,__LINE__); \ + } \ + void operator delete (void *address) { \ + if (address) cbdataInternalFreeDbg(address,__FILE__,__LINE__); \ + } \ + private: +#else +#define cbdataAlloc(type) ((type *)cbdataInternalAlloc(CBDATA_##type)) +#define cbdataFree(var) do {if (var) {cbdataInternalFree(var); var = NULL;}} while(0) +#define cbdataReferenceValidDone(var, ptr) cbdataInternalReferenceDoneValid((void **)&(var), (ptr)) +#define CBDATA_CLASS2(type) \ + static cbdata_type CBDATA_##type; \ + public: \ + void *operator new(size_t size) { \ + assert(size == sizeof(type)); \ + (CBDATA_##type ? CBDATA_UNKNOWN : (CBDATA_##type = cbdataInternalAddType(CBDATA_##type, #type, sizeof(type), NULL))); \ + return (type *)cbdataInternalAlloc(CBDATA_##type); \ + } \ + void operator delete (void *address) { \ + if (address) cbdataInternalFree(address);\ + } \ + private: +#endif +#define cbdataReference(var) (cbdataInternalLock(var), var) +#define cbdataReferenceDone(var) do {if (var) {cbdataInternalUnlock(var); var = NULL;}} while(0) +#define CBDATA_CLASS(type) static cbdata_type CBDATA_##type +#define CBDATA_CLASS_INIT(type) cbdata_type type::CBDATA_##type = CBDATA_UNKNOWN +#define CBDATA_TYPE(type) static cbdata_type CBDATA_##type = CBDATA_UNKNOWN +#define CBDATA_GLOBAL_TYPE(type) cbdata_type CBDATA_##type +#define CBDATA_INIT_TYPE(type) (CBDATA_##type ? CBDATA_UNKNOWN : (CBDATA_##type = cbdataInternalAddType(CBDATA_##type, #type, sizeof(type), NULL))) +#define CBDATA_INIT_TYPE_FREECB(type, free_func) (CBDATA_##type ? CBDATA_UNKNOWN : (CBDATA_##type = cbdataInternalAddType(CBDATA_##type, #type, sizeof(type), free_func))) + +/* + * use this when you need to pass callback data to a blocking + * operation, but you don't want to/cannot have that pointer be cbdata itself. + */ + +class generic_cbdata +{ + public: + generic_cbdata(void * data) : data(data) {} + templatevoid unwrap(wrapped_type **output) + { + *output = static_cast(data); + delete this; + } + /* the wrapped data - only public to allow the mild abuse of this facility + * done by store_swapout - it gives a wrapped StoreEntry to StoreIO as the + * object to be given to the callbacks. That needs to be fully cleaned up! + * - RBC 20060820 + */ + void *data; /* the wrapped data */ + private: + CBDATA_CLASS2(generic_cbdata); +}; + + + +#endif /* SQUID_CBDATA_H */ --- squid3/src/client.cc Wed Feb 14 13:38:02 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,652 +0,0 @@ - -/* - * $Id: client.cc,v 1.11 2005/05/27 02:13:27 squidadm Exp $ - * - * DEBUG: section 0 WWW Client - * AUTHOR: Harvest Derived - * - * SQUID Web Proxy Cache http://www.squid-cache.org/ - * ---------------------------------------------------------- - * - * Squid is the result of efforts by numerous individuals from - * the Internet community; see the CONTRIBUTORS file for full - * details. Many organizations have provided support for Squid's - * development; see the SPONSORS file for full details. Squid is - * Copyrighted (C) 2001 by the Regents of the University of - * California; see the COPYRIGHT file for full details. Squid - * incorporates software developed and/or copyrighted by other - * sources; see the CREDITS file for full details. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. - * - */ - -#include "squid.h" - -#ifndef BUFSIZ -#define BUFSIZ 8192 -#endif - -/* Local functions */ -static int client_comm_bind(int, const char *); - -static int client_comm_connect(int, const char *, u_short, struct timeval *); -static void usage(const char *progname); - -static int Now(struct timeval *); -static SIGHDLR catchSignal; -static SIGHDLR pipe_handler; -static void set_our_signal(void); -#ifndef _SQUID_MSWIN_ -static ssize_t myread(int fd, void *buf, size_t len); -static ssize_t mywrite(int fd, void *buf, size_t len); -#endif -static int put_fd; -static char *put_file = NULL; - -static struct stat sb; -int total_bytes = 0; -int io_timeout = 120; - -static void -usage(const char *progname) -{ - fprintf(stderr, - "Usage: %s [-arsv] [-i IMS] [-h remote host] [-l local host] [-p port] [-m method] [-t count] [-I ping-interval] [-H 'strings'] [-T timeout] url\n" - "Options:\n" - " -P file PUT request.\n" - " -a Do NOT include Accept: header.\n" - " -r Force cache to reload URL.\n" - " -s Silent. Do not print data to stdout.\n" - " -v Verbose. Print outgoing message to stderr.\n" - " -i IMS If-Modified-Since time (in Epoch seconds).\n" - " -h host Retrieve URL from cache on hostname. Default is localhost.\n" - " -l host Specify a local IP address to bind to. Default is none.\n" - " -p port Port number of cache. Default is %d.\n" - " -m method Request method, default is GET.\n" - " -t count Trace count cache-hops\n" - " -g count Ping mode, \"count\" iterations (0 to loop until interrupted).\n" - " -I interval Ping interval in seconds (default 1 second).\n" - " -H 'string' Extra headers to send. Use '\\n' for new lines.\n" - " -T timeout Timeout value (seconds) for read/write operations.\n" - " -u user Proxy authentication username\n" - " -w password Proxy authentication password\n" - " -U user WWW authentication username\n" - " -W password WWW authentication password\n", - progname, CACHE_HTTP_PORT); - exit(1); -} - -static int interrupted = 0; -int -main(int argc, char *argv[]) -{ - int conn, c, len, bytesWritten; - int port, to_stdout, reload; - int ping, pcount; - int keep_alive = 0; - int opt_noaccept = 0; - int opt_verbose = 0; - const char *hostname, *localhost; - char url[BUFSIZ], msg[49152], buf[BUFSIZ]; - char extra_hdrs[32768]; - const char *method = "GET"; - extern char *optarg; - time_t ims = 0; - int max_forwards = -1; - - struct timeval tv1, tv2; - int i = 0, loops; - long ping_int; - long ping_min = 0, ping_max = 0, ping_sum = 0, ping_mean = 0; - char *proxy_user = NULL; - char *proxy_password = NULL; - char *www_user = NULL; - char *www_password = NULL; - - /* set the defaults */ - hostname = "localhost"; - localhost = NULL; - extra_hdrs[0] = '\0'; - port = CACHE_HTTP_PORT; - to_stdout = 1; - reload = 0; - ping = 0; - pcount = 0; - ping_int = 1 * 1000; - - if (argc < 2) { - usage(argv[0]); /* need URL */ - } else if (argc >= 2) { - strncpy(url, argv[argc - 1], BUFSIZ); - url[BUFSIZ - 1] = '\0'; - - if (url[0] == '-') - usage(argv[0]); - - while ((c = getopt(argc, argv, "ah:l:P:i:km:p:rsvt:g:p:I:H:T:u:U:w:W:?")) != -1) - switch (c) { - - case 'a': - opt_noaccept = 1; - break; - - case 'h': /* remote host */ - - if (optarg != NULL) - hostname = optarg; - - break; - - case 'l': /* local host */ - if (optarg != NULL) - localhost = optarg; - - break; - - case 's': /* silent */ - to_stdout = 0; - - break; - - case 'k': /* backward compat */ - keep_alive = 1; - - break; - - case 'r': /* reload */ - reload = 1; - - break; - - case 'p': /* port number */ - sscanf(optarg, "%d", &port); - - if (port < 1) - port = CACHE_HTTP_PORT; /* default */ - - break; - - case 'P': - put_file = xstrdup(optarg); - - break; - - case 'i': /* IMS */ - ims = (time_t) atoi(optarg); - - break; - - case 'm': - method = xstrdup(optarg); - - break; - - case 't': - method = xstrdup("TRACE"); - - max_forwards = atoi(optarg); - - break; - - case 'g': - ping = 1; - - pcount = atoi(optarg); - - to_stdout = 0; - - break; - - case 'I': - if ((ping_int = atoi(optarg) * 1000) <= 0) - usage(argv[0]); - - break; - - case 'H': - if (strlen(optarg)) { - char *t; - strncpy(extra_hdrs, optarg, sizeof(extra_hdrs)); - - while ((t = strstr(extra_hdrs, "\\n"))) - *t = '\r', *(t + 1) = '\n'; - } - - break; - - case 'T': - io_timeout = atoi(optarg); - break; - - case 'u': - proxy_user = optarg; - break; - - case 'w': - proxy_password = optarg; - break; - - case 'U': - www_user = optarg; - break; - - case 'W': - www_password = optarg; - break; - - case 'v': - /* undocumented: may increase verb-level by giving more -v's */ - opt_verbose++; - break; - - case '?': /* usage */ - - default: - usage(argv[0]); - break; - } - } - -#ifdef _SQUID_MSWIN_ - { - WSADATA wsaData; - WSAStartup(2, &wsaData); - } -#endif - /* Build the HTTP request */ - if (strncmp(url, "mgr:", 4) == 0) { - char *t = xstrdup(url + 4); - snprintf(url, BUFSIZ, "cache_object://%s/%s", hostname, t); - xfree(t); - } - - if (put_file) { - put_fd = open(put_file, O_RDONLY); - set_our_signal(); - - if (put_fd < 0) { - fprintf(stderr, "%s: can't open file (%s)\n", argv[0], - xstrerror()); - exit(-1); - } - -#ifdef _SQUID_WIN32_ - setmode(put_fd, O_BINARY); - -#endif - - fstat(put_fd, &sb); - } - - snprintf(msg, BUFSIZ, "%s %s HTTP/1.0\r\n", method, url); - - if (reload) { - snprintf(buf, BUFSIZ, "Pragma: no-cache\r\n"); - strcat(msg, buf); - } - - if (put_fd > 0) { - snprintf(buf, BUFSIZ, "Content-length: %d\r\n", (int) sb.st_size); - strcat(msg, buf); - } - - if (opt_noaccept == 0) { - snprintf(buf, BUFSIZ, "Accept: */*\r\n"); - strcat(msg, buf); - } - - if (ims) { - snprintf(buf, BUFSIZ, "If-Modified-Since: %s\r\n", mkrfc1123(ims)); - strcat(msg, buf); - } - - if (max_forwards > -1) { - snprintf(buf, BUFSIZ, "Max-Forwards: %d\r\n", max_forwards); - strcat(msg, buf); - } - - if (proxy_user) { - char *user = proxy_user; - char *password = proxy_password; -#if HAVE_GETPASS - - if (!password) - password = getpass("Proxy password: "); - -#endif - - if (!password) { - fprintf(stderr, "ERROR: Proxy password missing\n"); - exit(1); - } - - snprintf(buf, BUFSIZ, "%s:%s", user, password); - snprintf(buf, BUFSIZ, "Proxy-Authorization: Basic %s\r\n", base64_encode(buf)); - strcat(msg, buf); - } - - if (www_user) { - char *user = www_user; - char *password = www_password; -#if HAVE_GETPASS - - if (!password) - password = getpass("WWW password: "); - -#endif - - if (!password) { - fprintf(stderr, "ERROR: WWW password missing\n"); - exit(1); - } - - snprintf(buf, BUFSIZ, "%s:%s", user, password); - snprintf(buf, BUFSIZ, "Authorization: Basic %s\r\n", base64_encode(buf)); - strcat(msg, buf); - } - - if (keep_alive) { - if (port != 80) - snprintf(buf, BUFSIZ, "Proxy-Connection: keep-alive\r\n"); - else - snprintf(buf, BUFSIZ, "Connection: keep-alive\r\n"); - - strcat(msg, buf); - } - - strcat(msg, extra_hdrs); - snprintf(buf, BUFSIZ, "\r\n"); - strcat(msg, buf); - - if (opt_verbose) - fprintf(stderr, "headers: '%s'\n", msg); - - if (ping) { -#if HAVE_SIGACTION - - struct sigaction sa, osa; - - if (sigaction(SIGINT, NULL, &osa) == 0 && osa.sa_handler == SIG_DFL) { - sa.sa_handler = catchSignal; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - (void) sigaction(SIGINT, &sa, NULL); - } - -#else - void (*osig) (int); - - if ((osig = signal(SIGINT, catchSignal)) != SIG_DFL) - (void) signal(SIGINT, osig); - -#endif - - } - - loops = ping ? pcount : 1; - - for (i = 0; loops == 0 || i < loops; i++) { - int fsize = 0; - /* Connect to the server */ - - if ((conn = socket(PF_INET, SOCK_STREAM, 0)) < 0) { - perror("client: socket"); - exit(1); - } - - if (localhost && client_comm_bind(conn, localhost) < 0) { - perror("client: bind"); - exit(1); - } - - if (client_comm_connect(conn, hostname, port, ping ? &tv1 : NULL) < 0) { - if (errno == 0) { - fprintf(stderr, "client: ERROR: Cannot connect to %s:%d: Host unknown.\n", hostname, port); - } else { - char tbuf[BUFSIZ]; - snprintf(tbuf, BUFSIZ, "client: ERROR: Cannot connect to %s:%d", - hostname, port); - perror(tbuf); - } - - exit(1); - } - - /* Send the HTTP request */ -#ifdef _SQUID_MSWIN_ - bytesWritten = send(conn, (const void *) msg, strlen(msg), 0); - -#else - - bytesWritten = mywrite(conn, msg, strlen(msg)); - -#endif - - if (bytesWritten < 0) { - perror("client: ERROR: write"); - exit(1); - } else if ((unsigned) bytesWritten != strlen(msg)) { - fprintf(stderr, "client: ERROR: Cannot send request?: %s\n", msg); - exit(1); - } - - if (put_file) { - int x; - lseek(put_fd, 0, SEEK_SET); -#ifdef _SQUID_MSWIN_ - - while ((x = read(put_fd, buf, sizeof(buf))) > 0) { - x = write(conn, buf, x); -#else - - while ((x = myread(put_fd, buf, sizeof(buf))) > 0) { - x = mywrite(conn, buf, x); -#endif - - total_bytes += x; - - if (x <= 0) - break; - } - - if (x != 0) - fprintf(stderr, "client: ERROR: Cannot send file.\n"); - } - - /* Read the data */ - -#ifdef _SQUID_MSWIN_ - setmode(1, O_BINARY); - - while ((len = recv(conn, (void *) buf, sizeof(buf), 0)) > 0) { -#else - - while ((len = myread(conn, buf, sizeof(buf))) > 0) { -#endif - fsize += len; - - if (to_stdout) - fwrite(buf, len, 1, stdout); - } - -#ifdef _SQUID_MSWIN_ - setmode(1, O_TEXT); - -#endif - - (void) close(conn); /* done with socket */ - - if (interrupted) - break; - - if (ping) { - - struct tm *tmp; - time_t t2s; - long elapsed_msec; - - (void) Now(&tv2); - elapsed_msec = tvSubMsec(tv1, tv2); - t2s = tv2.tv_sec; - tmp = localtime(&t2s); - fprintf(stderr, "%d-%02d-%02d %02d:%02d:%02d [%d]: %ld.%03ld secs, %f KB/s\n", - tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, - tmp->tm_hour, tmp->tm_min, tmp->tm_sec, i + 1, - elapsed_msec / 1000, elapsed_msec % 1000, - elapsed_msec ? (double) fsize / elapsed_msec : -1.0); - - if (i == 0 || elapsed_msec < ping_min) - ping_min = elapsed_msec; - - if (i == 0 || elapsed_msec > ping_max) - ping_max = elapsed_msec; - - ping_sum += elapsed_msec; - - /* Delay until next "ping_int" boundary */ - if ((loops == 0 || i + 1 < loops) && elapsed_msec < ping_int) { - - struct timeval tvs; - long msec_left = ping_int - elapsed_msec; - - tvs.tv_sec = msec_left / 1000; - tvs.tv_usec = (msec_left % 1000) * 1000; - select(0, NULL, NULL, NULL, &tvs); - } - } - } - - if (ping && i) { - ping_mean = ping_sum / i; - fprintf(stderr, "%d requests, round-trip (secs) min/avg/max = " - "%ld.%03ld/%ld.%03ld/%ld.%03ld\n", i, - ping_min / 1000, ping_min % 1000, ping_mean / 1000, ping_mean % 1000, - ping_max / 1000, ping_max % 1000); - } - - exit(0); - /*NOTREACHED */ - return 0; -} - -static int -client_comm_bind(int sock, const char *local_host) { - - static const struct hostent *hp = NULL; - - static struct sockaddr_in from_addr; - - /* Set up the source socket address from which to send. */ - - if (hp == NULL) { - from_addr.sin_family = AF_INET; - - if ((hp = gethostbyname(local_host)) == 0) { - return (-1); - } - - xmemcpy(&from_addr.sin_addr, hp->h_addr, hp->h_length); - from_addr.sin_port = 0; - } - - return bind(sock, (struct sockaddr *) &from_addr, sizeof(struct sockaddr_in)); -} - -static int - -client_comm_connect(int sock, const char *dest_host, u_short dest_port, struct timeval *tvp) { - - static const struct hostent *hp = NULL; - - static struct sockaddr_in to_addr; - - /* Set up the destination socket address for message to send to. */ - - if (hp == NULL) - { - to_addr.sin_family = AF_INET; - - if ((hp = gethostbyname(dest_host)) == 0) { - return (-1); - } - - xmemcpy(&to_addr.sin_addr, hp->h_addr, hp->h_length); - to_addr.sin_port = htons(dest_port); - } - - if (tvp) - (void) Now(tvp); - - return connect(sock, (struct sockaddr *) &to_addr, sizeof(struct sockaddr_in)); -} - -static int - -Now(struct timeval *tp) { -#if GETTIMEOFDAY_NO_TZP - return gettimeofday(tp); -#else - - return gettimeofday(tp, NULL); -#endif -} /* ARGSUSED */ - -static void -catchSignal(int sig) { - interrupted = 1; - fprintf(stderr, "Interrupted.\n"); -} - -static void -pipe_handler(int sig) { - fprintf(stderr, "SIGPIPE received.\n"); -} - -static void -set_our_signal(void) { -#if HAVE_SIGACTION - - struct sigaction sa; - sa.sa_handler = pipe_handler; - sa.sa_flags = SA_RESTART; - sigemptyset(&sa.sa_mask); - - if (sigaction(SIGPIPE, &sa, NULL) < 0) { - fprintf(stderr, "Cannot set PIPE signal.\n"); - exit(-1); - } - -#else - signal(SIGPIPE, pipe_handler); - -#endif - -} - -#ifndef _SQUID_MSWIN_ -static ssize_t -myread(int fd, void *buf, size_t len) { - alarm(io_timeout); - return read(fd, buf, len); -} - -static ssize_t -mywrite(int fd, void *buf, size_t len) { - alarm(io_timeout); - return write(fd, buf, len); -} - -#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/comm_epoll.h Wed Feb 14 13:38:02 2007 @@ -0,0 +1,43 @@ + +/* + * $Id: comm_epoll.h,v 1.1.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_COMM_EPOLL_H +#define SQUID_COMM_EPOLL_H + +/* forward decls */ + +class CacheManager; + +extern void commEPollRegisterWithCacheManager(CacheManager & manager); + +#endif /* SQUID_COMM_EPOLL_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/comm_kqueue.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,43 @@ + +/* + * $Id: comm_kqueue.h,v 1.1.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_COMM_KQUEUE_H +#define SQUID_COMM_KQUEUE_H + +/* forward decls */ + +class CacheManager; + +extern void commKQueueRegisterWithCacheManager(CacheManager & manager); + +#endif /* SQUID_COMM_KQUEUE_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/comm_poll.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,43 @@ + +/* + * $Id: comm_poll.h,v 1.1.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_COMM_POLL_H +#define SQUID_COMM_POLL_H + +/* forward decls */ + +class CacheManager; + +extern void commPollRegisterWithCacheManager(CacheManager & manager); + +#endif /* SQUID_COMM_POLL_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/comm_select.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,43 @@ + +/* + * $Id: comm_select.h,v 1.1.10.2 2006/09/29 23:16:00 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_COMM_SELECT_H +#define SQUID_COMM_SELECT_H + +/* forward decls */ + +class CacheManager; + +extern void commSelectRegisterWithCacheManager(CacheManager & manager); + +#endif /* SQUID_COMM_SELECT_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/comm_select_win32.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,905 @@ + +/* + * $Id: comm_select_win32.cc,v 1.3.2.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * DEBUG: section 5 Socket Functions + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "comm_select.h" +#include "CacheManager.h" +#include "SquidTime.h" + +#ifdef USE_SELECT_WIN32 +#include "Store.h" +#include "fde.h" + +static int MAX_POLL_TIME = 1000; /* see also comm_quick_poll_required() */ + +#ifndef howmany +#define howmany(x, y) (((x)+((y)-1))/(y)) +#endif +#ifndef NBBY +#define NBBY 8 +#endif +#define FD_MASK_BYTES sizeof(fd_mask) +#define FD_MASK_BITS (FD_MASK_BYTES*NBBY) + +/* STATIC */ +static int examine_select(fd_set *, fd_set *); +static int fdIsHttp(int fd); +static int fdIsIcp(int fd); +static int fdIsDns(int fd); +static OBJH commIncomingStats; +static int comm_check_incoming_select_handlers(int nfds, int *fds); +static void comm_select_dns_incoming(void); +static void commUpdateReadBits(int fd, PF * handler); +static void commUpdateWriteBits(int fd, PF * handler); + + +static struct timeval zero_tv; +static fd_set global_readfds; +static fd_set global_writefds; +static int nreadfds; +static int nwritefds; + +/* + * Automatic tuning for incoming requests: + * + * INCOMING sockets are the ICP and HTTP ports. We need to check these + * fairly regularly, but how often? When the load increases, we + * want to check the incoming sockets more often. If we have a lot + * of incoming ICP, then we need to check these sockets more than + * if we just have HTTP. + * + * The variables 'incoming_icp_interval' and 'incoming_http_interval' + * determine how many normal I/O events to process before checking + * incoming sockets again. Note we store the incoming_interval + * multipled by a factor of (2^INCOMING_FACTOR) to have some + * pseudo-floating point precision. + * + * The variable 'icp_io_events' and 'http_io_events' counts how many normal + * I/O events have been processed since the last check on the incoming + * sockets. When io_events > incoming_interval, its time to check incoming + * sockets. + * + * Every time we check incoming sockets, we count how many new messages + * or connections were processed. This is used to adjust the + * incoming_interval for the next iteration. The new incoming_interval + * is calculated as the current incoming_interval plus what we would + * like to see as an average number of events minus the number of + * events just processed. + * + * incoming_interval = incoming_interval + target_average - number_of_events_processed + * + * There are separate incoming_interval counters for both HTTP and ICP events + * + * You can see the current values of the incoming_interval's, as well as + * a histogram of 'incoming_events' by asking the cache manager + * for 'comm_incoming', e.g.: + * + * % ./client mgr:comm_incoming + * + * Caveats: + * + * - We have MAX_INCOMING_INTEGER as a magic upper limit on + * incoming_interval for both types of sockets. At the + * largest value the cache will effectively be idling. + * + * - The higher the INCOMING_FACTOR, the slower the algorithm will + * respond to load spikes/increases/decreases in demand. A value + * between 3 and 8 is recommended. + */ + +#define MAX_INCOMING_INTEGER 256 +#define INCOMING_FACTOR 5 +#define MAX_INCOMING_INTERVAL (MAX_INCOMING_INTEGER << INCOMING_FACTOR) +static int icp_io_events = 0; +static int dns_io_events = 0; +static int http_io_events = 0; +static int incoming_icp_interval = 16 << INCOMING_FACTOR; +static int incoming_dns_interval = 16 << INCOMING_FACTOR; +static int incoming_http_interval = 16 << INCOMING_FACTOR; +#define commCheckICPIncoming (++icp_io_events > (incoming_icp_interval>> INCOMING_FACTOR)) +#define commCheckDNSIncoming (++dns_io_events > (incoming_dns_interval>> INCOMING_FACTOR)) +#define commCheckHTTPIncoming (++http_io_events > (incoming_http_interval>> INCOMING_FACTOR)) + +void +commSetSelect(int fd, unsigned int type, PF * handler, void *client_data, + time_t timeout) +{ + fde *F = &fd_table[fd]; + assert(fd >= 0); + assert(F->flags.open); + debug(5, 5) ("commSetSelect: FD %d type %d\n", fd, type); + + if (type & COMM_SELECT_READ) { + F->read_handler = handler; + F->read_data = client_data; + commUpdateReadBits(fd, handler); + } + + if (type & COMM_SELECT_WRITE) { + F->write_handler = handler; + F->write_data = client_data; + commUpdateWriteBits(fd, handler); + } + + if (timeout) + F->timeout = squid_curtime + timeout; +} + + +static int +fdIsIcp(int fd) +{ + if (fd == theInIcpConnection) + return 1; + + if (fd == theOutIcpConnection) + return 1; + + return 0; +} + +static int +fdIsDns(int fd) +{ + if (fd == DnsSocket) + return 1; + + return 0; +} + +static int +fdIsHttp(int fd) +{ + int j; + + for (j = 0; j < NHttpSockets; j++) { + if (fd == HttpSockets[j]) + return 1; + } + + return 0; +} + +#if DELAY_POOLS +static int slowfdcnt = 0; +static int slowfdarr[SQUID_MAXFD]; + +static void +commAddSlowFd(int fd) +{ + assert(slowfdcnt < SQUID_MAXFD); + slowfdarr[slowfdcnt++] = fd; +} + +static int +commGetSlowFd(void) +{ + int whichfd, retfd; + + if (!slowfdcnt) + return -1; + + whichfd = squid_random() % slowfdcnt; + + retfd = slowfdarr[whichfd]; + + slowfdarr[whichfd] = slowfdarr[--slowfdcnt]; + + return retfd; +} + +#endif + +static int +comm_check_incoming_select_handlers(int nfds, int *fds) +{ + int i; + int fd; + int maxfd = 0; + PF *hdl = NULL; + fd_set read_mask; + fd_set write_mask; + fd_set errfds; + FD_ZERO(&errfds); + FD_ZERO(&read_mask); + FD_ZERO(&write_mask); + incoming_sockets_accepted = 0; + + for (i = 0; i < nfds; i++) { + fd = fds[i]; + + if (fd_table[fd].read_handler) { + FD_SET(fd, &read_mask); + + if (fd > maxfd) + maxfd = fd; + } + + if (fd_table[fd].write_handler) { + FD_SET(fd, &write_mask); + + if (fd > maxfd) + maxfd = fd; + } + } + + if (maxfd++ == 0) + return -1; + + getCurrentTime(); + + statCounter.syscalls.selects++; + + if (select(maxfd, &read_mask, &write_mask, &errfds, &zero_tv) < 1) + + return incoming_sockets_accepted; + + for (i = 0; i < nfds; i++) { + fd = fds[i]; + + if (FD_ISSET(fd, &read_mask)) { + if ((hdl = fd_table[fd].read_handler) != NULL) { + fd_table[fd].read_handler = NULL; + commUpdateReadBits(fd, NULL); + hdl(fd, fd_table[fd].read_data); + } else { + debug(5, 1) ("comm_select_incoming: FD %d NULL read handler\n", + fd); + } + } + + if (FD_ISSET(fd, &write_mask)) { + if ((hdl = fd_table[fd].write_handler) != NULL) { + fd_table[fd].write_handler = NULL; + commUpdateWriteBits(fd, NULL); + hdl(fd, fd_table[fd].write_data); + } else { + debug(5, 1) ("comm_select_incoming: FD %d NULL write handler\n", + fd); + } + } + } + + return incoming_sockets_accepted; +} + +static void +comm_select_icp_incoming(void) +{ + int nfds = 0; + int fds[2]; + int nevents; + icp_io_events = 0; + + if (theInIcpConnection >= 0) + fds[nfds++] = theInIcpConnection; + + if (theInIcpConnection != theOutIcpConnection) + if (theOutIcpConnection >= 0) + fds[nfds++] = theOutIcpConnection; + + if (nfds == 0) + return; + + nevents = comm_check_incoming_select_handlers(nfds, fds); + + incoming_icp_interval += Config.comm_incoming.icp_average - nevents; + + if (incoming_icp_interval < 0) + incoming_icp_interval = 0; + + if (incoming_icp_interval > MAX_INCOMING_INTERVAL) + incoming_icp_interval = MAX_INCOMING_INTERVAL; + + if (nevents > INCOMING_ICP_MAX) + nevents = INCOMING_ICP_MAX; + + statHistCount(&statCounter.comm_icp_incoming, nevents); +} + +static void +comm_select_http_incoming(void) +{ + int nfds = 0; + int fds[MAXHTTPPORTS]; + int j; + int nevents; + http_io_events = 0; + + for (j = 0; j < NHttpSockets; j++) { + if (HttpSockets[j] < 0) + continue; + + fds[nfds++] = HttpSockets[j]; + } + + nevents = comm_check_incoming_select_handlers(nfds, fds); + incoming_http_interval += Config.comm_incoming.http_average - nevents; + + if (incoming_http_interval < 0) + incoming_http_interval = 0; + + if (incoming_http_interval > MAX_INCOMING_INTERVAL) + incoming_http_interval = MAX_INCOMING_INTERVAL; + + if (nevents > INCOMING_HTTP_MAX) + nevents = INCOMING_HTTP_MAX; + + statHistCount(&statCounter.comm_http_incoming, nevents); +} + +#define DEBUG_FDBITS 0 +/* Select on all sockets; call handlers for those that are ready. */ +comm_err_t +comm_select(int msec) +{ + fd_set readfds; + fd_set pendingfds; + fd_set writefds; +#if DELAY_POOLS + + fd_set slowfds; +#endif + + PF *hdl = NULL; + int fd; + int maxfd; + int num; + int pending; + int callicp = 0, callhttp = 0; + int calldns = 0; + int j; +#if DEBUG_FDBITS + + int i; +#endif + struct timeval poll_time; + double timeout = current_dtime + (msec / 1000.0); + fde *F; + + int no_bits; + fd_set errfds; + FD_ZERO(&errfds); + + do { + double start; + getCurrentTime(); + start = current_dtime; +#if DELAY_POOLS + + FD_ZERO(&slowfds); +#endif + + if (commCheckICPIncoming) + comm_select_icp_incoming(); + + if (commCheckDNSIncoming) + comm_select_dns_incoming(); + + if (commCheckHTTPIncoming) + comm_select_http_incoming(); + + callicp = calldns = callhttp = 0; + + maxfd = Biggest_FD + 1; + + xmemcpy(&readfds, &global_readfds, sizeof(global_readfds)); + + xmemcpy(&writefds, &global_writefds, sizeof(global_writefds)); + + xmemcpy(&errfds, &global_writefds, sizeof(global_writefds)); + + /* remove stalled FDs, and deal with pending descriptors */ + pending = 0; + + FD_ZERO(&pendingfds); + + for (j = 0; j < (int) readfds.fd_count; j++) { + register int readfds_handle = readfds.fd_array[j]; + no_bits = 1; + + for ( fd = Biggest_FD; fd; fd-- ) { + if ( fd_table[fd].win32.handle == readfds_handle ) { + if (fd_table[fd].flags.open) { + no_bits = 0; + break; + } + } + } + + if (no_bits) + continue; + + if (FD_ISSET(fd, &readfds) && fd_table[fd].flags.read_pending) { + FD_SET(fd, &pendingfds); + pending++; + } + } + +#if DEBUG_FDBITS + for (i = 0; i < maxfd; i++) { + /* Check each open socket for a handler. */ + + if (fd_table[i].read_handler) { + assert(FD_ISSET(i, &readfds)); + } + + if (fd_table[i].write_handler) { + assert(FD_ISSET(i, &writefds)); + } + } + +#endif + if (nreadfds + nwritefds == 0) { + assert(shutting_down); + return COMM_SHUTDOWN; + } + + if (msec > MAX_POLL_TIME) + msec = MAX_POLL_TIME; + + if (comm_iocallbackpending()) + pending++; + + if (pending) + msec = 0; + + for (;;) { + poll_time.tv_sec = msec / 1000; + poll_time.tv_usec = (msec % 1000) * 1000; + statCounter.syscalls.selects++; + num = select(maxfd, &readfds, &writefds, &errfds, &poll_time); + statCounter.select_loops++; + + if (num >= 0 || pending > 0) + break; + + if (ignoreErrno(errno)) + break; + + debug(5, 0) ("comm_select: select failure: %s\n", + xstrerror()); + + examine_select(&readfds, &writefds); + + return COMM_ERROR; + + /* NOTREACHED */ + } + + if (num < 0 && !pending) + continue; + + getCurrentTime(); + + debug(5, num ? 5 : 8) ("comm_select: %d+%d FDs ready\n", + num, pending); + + statHistCount(&statCounter.select_fds_hist, num); + + if (num == 0 && pending == 0) + continue; + + /* Scan return fd masks for ready descriptors */ + + assert(readfds.fd_count <= (unsigned int) Biggest_FD); + + assert(pendingfds.fd_count <= (unsigned int) Biggest_FD); + + for (j = 0; j < (int) readfds.fd_count; j++) { + register int readfds_handle = readfds.fd_array[j]; + register int pendingfds_handle = pendingfds.fd_array[j]; + register int osfhandle; + no_bits = 1; + + for ( fd = Biggest_FD; fd; fd-- ) { + osfhandle = fd_table[fd].win32.handle; + + if (( osfhandle == readfds_handle ) || + ( osfhandle == pendingfds_handle )) { + if (fd_table[fd].flags.open) { + no_bits = 0; + break; + } + } + } + + if (no_bits) + continue; + +#if DEBUG_FDBITS + + debug(5, 9) ("FD %d bit set for reading\n", fd); + + assert(FD_ISSET(fd, &readfds)); + +#endif + + if (fdIsIcp(fd)) { + callicp = 1; + continue; + } + + if (fdIsDns(fd)) { + calldns = 1; + continue; + } + + if (fdIsHttp(fd)) { + callhttp = 1; + continue; + } + + F = &fd_table[fd]; + debug(5, 6) ("comm_select: FD %d ready for reading\n", fd); + + if (NULL == (hdl = F->read_handler)) + (void) 0; + +#if DELAY_POOLS + + else if (FD_ISSET(fd, &slowfds)) + commAddSlowFd(fd); + +#endif + + else { + F->read_handler = NULL; + commUpdateReadBits(fd, NULL); + hdl(fd, F->read_data); + statCounter.select_fds++; + + if (commCheckICPIncoming) + comm_select_icp_incoming(); + + if (commCheckDNSIncoming) + comm_select_dns_incoming(); + + if (commCheckHTTPIncoming) + comm_select_http_incoming(); + } + } + + assert(errfds.fd_count <= (unsigned int) Biggest_FD); + + for (j = 0; j < (int) errfds.fd_count; j++) { + register int errfds_handle = errfds.fd_array[j]; + + for ( fd = Biggest_FD; fd; fd-- ) { + if ( fd_table[fd].win32.handle == errfds_handle ) + break; + } + + if (fd_table[fd].flags.open) { + F = &fd_table[fd]; + + if ((hdl = F->write_handler)) { + F->write_handler = NULL; + commUpdateWriteBits(fd, NULL); + hdl(fd, F->write_data); + statCounter.select_fds++; + } + } + } + + assert(writefds.fd_count <= (unsigned int) Biggest_FD); + + for (j = 0; j < (int) writefds.fd_count; j++) { + register int writefds_handle = writefds.fd_array[j]; + no_bits = 1; + + for ( fd = Biggest_FD; fd; fd-- ) { + if ( fd_table[fd].win32.handle == writefds_handle ) { + if (fd_table[fd].flags.open) { + no_bits = 0; + break; + } + } + } + + if (no_bits) + continue; + +#if DEBUG_FDBITS + + debug(5, 9) ("FD %d bit set for writing\n", fd); + + assert(FD_ISSET(fd, &writefds)); + +#endif + + if (fdIsIcp(fd)) { + callicp = 1; + continue; + } + + if (fdIsDns(fd)) { + calldns = 1; + continue; + } + + if (fdIsHttp(fd)) { + callhttp = 1; + continue; + } + + F = &fd_table[fd]; + debug(5, 5) ("comm_select: FD %d ready for writing\n", fd); + + if ((hdl = F->write_handler)) { + F->write_handler = NULL; + commUpdateWriteBits(fd, NULL); + hdl(fd, F->write_data); + statCounter.select_fds++; + + if (commCheckICPIncoming) + comm_select_icp_incoming(); + + if (commCheckDNSIncoming) + comm_select_dns_incoming(); + + if (commCheckHTTPIncoming) + comm_select_http_incoming(); + + + } + } + + if (callicp) + comm_select_icp_incoming(); + + if (calldns) + comm_select_dns_incoming(); + + if (callhttp) + comm_select_http_incoming(); + +#if DELAY_POOLS + + while ((fd = commGetSlowFd()) != -1) { + F = &fd_table[fd]; + debug(5, 6) ("comm_select: slow FD %d selected for reading\n", fd); + + if ((hdl = F->read_handler)) { + F->read_handler = NULL; + commUpdateReadBits(fd, NULL); + hdl(fd, F->read_data); + statCounter.select_fds++; + + if (commCheckICPIncoming) + comm_select_icp_incoming(); + + if (commCheckDNSIncoming) + comm_select_dns_incoming(); + + if (commCheckHTTPIncoming) + comm_select_http_incoming(); + } + } + +#endif + getCurrentTime(); + + statCounter.select_time += (current_dtime - start); + + return COMM_OK; + } while (timeout > current_dtime) + + ; + debug(5, 8) ("comm_select: time out: %d\n", (int) squid_curtime); + + return COMM_TIMEOUT; +} + +static void +comm_select_dns_incoming(void) +{ + int nfds = 0; + int fds[2]; + int nevents; + dns_io_events = 0; + + if (DnsSocket < 0) + return; + + fds[nfds++] = DnsSocket; + + nevents = comm_check_incoming_select_handlers(nfds, fds); + + if (nevents < 0) + return; + + incoming_dns_interval += Config.comm_incoming.dns_average - nevents; + + if (incoming_dns_interval < Config.comm_incoming.dns_min_poll) + incoming_dns_interval = Config.comm_incoming.dns_min_poll; + + if (incoming_dns_interval > MAX_INCOMING_INTERVAL) + incoming_dns_interval = MAX_INCOMING_INTERVAL; + + if (nevents > INCOMING_DNS_MAX) + nevents = INCOMING_DNS_MAX; + + statHistCount(&statCounter.comm_dns_incoming, nevents); +} + +void +comm_select_init(void) +{ + zero_tv.tv_sec = 0; + zero_tv.tv_usec = 0; + FD_ZERO(&global_readfds); + FD_ZERO(&global_writefds); + nreadfds = nwritefds = 0; +} + +void +commSelectRegisterWithCacheManager(CacheManager & manager) +{ + manager.registerAction("comm_select_incoming", + "comm_incoming() stats", + commIncomingStats, 0, 1); +} + +/* + * examine_select - debug routine. + * + * I spend the day chasing this core dump that occurs when both the client + * and the server side of a cache fetch simultaneoulsy abort the + * connection. While I haven't really studied the code to figure out how + * it happens, the snippet below may prevent the cache from exitting: + * + * Call this from where the select loop fails. + */ +static int +examine_select(fd_set * readfds, fd_set * writefds) +{ + int fd = 0; + fd_set read_x; + fd_set write_x; + + struct timeval tv; + close_handler *ch = NULL; + fde *F = NULL; + + struct stat sb; + debug(5, 0) ("examine_select: Examining open file descriptors...\n"); + + for (fd = 0; fd < Squid_MaxFD; fd++) { + FD_ZERO(&read_x); + FD_ZERO(&write_x); + tv.tv_sec = tv.tv_usec = 0; + + if (FD_ISSET(fd, readfds)) + FD_SET(fd, &read_x); + else if (FD_ISSET(fd, writefds)) + FD_SET(fd, &write_x); + else + continue; + + statCounter.syscalls.selects++; + + errno = 0; + + if (!fstat(fd, &sb)) { + debug(5, 5) ("FD %d is valid.\n", fd); + continue; + } + + F = &fd_table[fd]; + debug(5, 0) ("FD %d: %s\n", fd, xstrerror()); + debug(5, 0) ("WARNING: FD %d has handlers, but it's invalid.\n", fd); + debug(5, 0) ("FD %d is a %s called '%s'\n", + fd, + fdTypeStr[F->type], + F->desc); + debug(5, 0) ("tmout:%p read:%p write:%p\n", + F->timeout_handler, + F->read_handler, + F->write_handler); + + for (ch = F->closeHandler; ch; ch = ch->next) + debug(5, 0) (" close handler: %p\n", ch->handler); + + if (F->closeHandler) { + commCallCloseHandlers(fd); + } else if (F->timeout_handler) { + debug(5, 0) ("examine_select: Calling Timeout Handler\n"); + F->timeout_handler(fd, F->timeout_data); + } + + F->closeHandler = NULL; + F->timeout_handler = NULL; + F->read_handler = NULL; + F->write_handler = NULL; + FD_CLR(fd, readfds); + FD_CLR(fd, writefds); + } + + return 0; +} + + +static void +commIncomingStats(StoreEntry * sentry) +{ + StatCounters *f = &statCounter; + storeAppendPrintf(sentry, "Current incoming_icp_interval: %d\n", + incoming_icp_interval >> INCOMING_FACTOR); + storeAppendPrintf(sentry, "Current incoming_dns_interval: %d\n", + incoming_dns_interval >> INCOMING_FACTOR); + storeAppendPrintf(sentry, "Current incoming_http_interval: %d\n", + incoming_http_interval >> INCOMING_FACTOR); + storeAppendPrintf(sentry, "\n"); + storeAppendPrintf(sentry, "Histogram of events per incoming socket type\n"); + storeAppendPrintf(sentry, "ICP Messages handled per comm_select_icp_incoming() call:\n"); + statHistDump(&f->comm_icp_incoming, sentry, statHistIntDumper); + storeAppendPrintf(sentry, "DNS Messages handled per comm_select_dns_incoming() call:\n"); + statHistDump(&f->comm_dns_incoming, sentry, statHistIntDumper); + storeAppendPrintf(sentry, "HTTP Messages handled per comm_select_http_incoming() call:\n"); + statHistDump(&f->comm_http_incoming, sentry, statHistIntDumper); +} + +void +commUpdateReadBits(int fd, PF * handler) +{ + if (handler && !FD_ISSET(fd, &global_readfds)) { + FD_SET(fd, &global_readfds); + nreadfds++; + } else if (!handler && FD_ISSET(fd, &global_readfds)) { + FD_CLR(fd, &global_readfds); + nreadfds--; + } +} + +void +commUpdateWriteBits(int fd, PF * handler) +{ + if (handler && !FD_ISSET(fd, &global_writefds)) { + FD_SET(fd, &global_writefds); + nwritefds++; + } else if (!handler && FD_ISSET(fd, &global_writefds)) { + FD_CLR(fd, &global_writefds); + nwritefds--; + } +} + +/* Called by async-io or diskd to speed up the polling */ +void +comm_quick_poll_required(void) +{ + MAX_POLL_TIME = 10; +} + +#endif /* USE_SELECT_WIN32 */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/dlink.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,60 @@ + +/* + * $Id: dlink.h,v 1.1.12.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_DLINK_H +#define SQUID_DLINK_H + +#include "config.h" + +class dlink_node +{ + +public: + dlink_node() : data(NULL), prev(NULL), next(NULL){} + + void *data; + dlink_node *prev; + dlink_node *next; +}; + +struct _dlink_list +{ + dlink_node *head; + dlink_node *tail; +}; + +class dlink_node; + +typedef struct _dlink_list dlink_list; + +#endif /* SQUID_DLINK_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/errorpage.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,95 @@ + +/* + * $Id: errorpage.h,v 1.2.8.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + * Copyright (c) 2003, Robert Collins + */ + +#ifndef SQUID_ERRORPAGE_H +#define SQUID_ERRORPAGE_H + +#include "squid.h" +#include "cbdata.h" + +class ErrorState +{ + +public: + err_type type; + int page_id; + http_status httpStatus; + auth_user_request_t *auth_user_request; + HttpRequest *request; + char *url; + int xerrno; + u_short port; + char *dnsserver_msg; + time_t ttl; + + struct IN_ADDR src_addr; + char *redirect_url; + ERCB *callback; + void *callback_data; + + struct + { + +unsigned int flag_cbdata: + 1; + } + + flags; + + struct + { + wordlist *server_msg; + char *request; + char *reply; + } + + ftp; + char *request_hdrs; + char *err_msg; /* Preformatted error message from the cache */ + +private: + CBDATA_CLASS2(ErrorState); +}; + +SQUIDCEXTERN void errorInitialize(void); +SQUIDCEXTERN void errorClean(void); +SQUIDCEXTERN HttpReply *errorBuildReply(ErrorState * err); +SQUIDCEXTERN void errorSend(int fd, ErrorState *); +SQUIDCEXTERN void errorAppendEntry(StoreEntry *, ErrorState *); +SQUIDCEXTERN void errorStateFree(ErrorState * err); +SQUIDCEXTERN err_type errorReservePageId(const char *page_name); +SQUIDCEXTERN ErrorState *errorCon(err_type type, http_status, HttpRequest * request); + + +#endif /* SQUID_ERRORPAGE_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/event.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,133 @@ + +/* + * $Id: event.h,v 1.3.2.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_EVENT_H +#define SQUID_EVENT_H + +#include "squid.h" +#include "Array.h" +#include "AsyncEngine.h" +#include "CompletionDispatcher.h" + +/* forward decls */ + +class StoreEntry; + +/* event scheduling facilities - run a callback after a given time period. */ + +typedef void EVH(void *); + +extern void eventAdd(const char *name, EVH * func, void *arg, double when, int, bool cbdata=true); +SQUIDCEXTERN void eventAddIsh(const char *name, EVH * func, void *arg, double delta_ish, int); +SQUIDCEXTERN void eventDelete(EVH * func, void *arg); +SQUIDCEXTERN void eventInit(CacheManager &); +SQUIDCEXTERN void eventFreeMemory(void); +SQUIDCEXTERN int eventFind(EVH *, void *); + +class ev_entry +{ + +public: + ev_entry(char const * name, EVH * func, void *arg, double when, int weight, bool cbdata=true); + MEMPROXY_CLASS(ev_entry); + const char *name; + EVH *func; + void *arg; + double when; + + int weight; + bool cbdata; + + ev_entry *next; +}; + +MEMPROXY_CLASS_INLINE(ev_entry); + +class EventDispatcher : public CompletionDispatcher +{ + +public: + EventDispatcher(); + /* add an event to dequeue when dispatch is called */ + + void add + (ev_entry *); + + /* add an event to be dispatched in the future */ + void add + (const char *name, EVH * func, void *arg, double when, int, bool cbdata=true); + + bool dispatch(); + + static EventDispatcher *GetInstance(); + +private: + Vector queue; + + static EventDispatcher _instance; +}; + +class EventScheduler : public AsyncEngine +{ + +public: + /* Create an event scheduler that will hand its ready to run callbacks to + * an EventDispatcher + * + * TODO: add should include a dispatcher to use perhaps? then it would be + * more decoupled.. + */ + EventScheduler(EventDispatcher *); + ~EventScheduler(); + /* cancel a scheduled but not dispatched event */ + void cancel(EVH * func, void * arg); + /* clean up the used memory in the scheduler */ + void clean(); + /* how long until the next event ? */ + int checkDelay(); + /* cache manager output for the event queue */ + void dump(StoreEntry *); + /* find a scheduled event */ + bool find(EVH * func, void * arg); + /* schedule a callback function to run in when seconds */ + void schedule(const char *name, EVH * func, void *arg, double when, int weight, bool cbdata=true); + int checkEvents(int timeout); + static EventScheduler *GetInstance(); + +private: + static EventScheduler _instance; + EventDispatcher * dispatcher; + ev_entry * tasks; +}; + +#endif /* SQUID_EVENT_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/forward.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,106 @@ +#ifndef SQUID_FORWARD_H +#define SQUID_FORWARD_H + +/* forward decls */ + +class CacheManager; +class ErrorState; + +#include "comm.h" + +class FwdServer +{ + +public: + peer *_peer; /* NULL --> origin server */ + hier_code code; + FwdServer *next; +}; + +class FwdState : public RefCountable +{ + +public: + typedef RefCount Pointer; + FwdState(int fd, StoreEntry *, HttpRequest *); + ~FwdState(); + static void initModule(); + static void RegisterWithCacheManager(CacheManager & manager); + + static void fwdStart(int fd, StoreEntry *, HttpRequest *); + void startComplete(FwdServer *); + void startFail(); + void fail(ErrorState *err); + void unregister(int fd); + void complete(); + int reforward(); + bool reforwardableStatus(http_status s); + void serverClosed(int fd); + void connectStart(); + void connectDone(int server_fd, comm_err_t status, int xerrno); + void connectTimeout(int fd); + void initiateSSL(); + void negotiateSSL(int fd); + bool checkRetry(); + bool checkRetriable(); + void dispatch(); + void pconnPush(int fd, const char *host, int port, const char *domain); + + bool dontRetry() { return flags.dont_retry; } + + void dontRetry(bool val) { flags.dont_retry = val; } + + bool ftpPasvFailed() { return flags.ftp_pasv_failed; } + + void ftpPasvFailed(bool val) { flags.ftp_pasv_failed = val; } + + static void serversFree(FwdServer **); + +private: + static void logReplyStatus(int tries, http_status status); + void completed(); + +#if WIP_FWD_LOG + + void uninit + static void logRotate + void status() +#endif + +public: + StoreEntry *entry; + HttpRequest *request; + int server_fd; + FwdServer *servers; + static void abort(void*); + +private: + CBDATA_CLASS2(FwdState); + Pointer self; + ErrorState *err; + int client_fd; + time_t start_t; + int n_tries; + int origin_tries; +#if WIP_FWD_LOG + + http_status last_status; +#endif + + struct + { + +unsigned int dont_retry: + 1; + +unsigned int ftp_pasv_failed: + 1; + +unsigned int forward_completed:1; + } + + flags; + +}; + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ipc_win32.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,864 @@ + +/* + * $Id: ipc_win32.cc,v 1.3.4.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * DEBUG: section 54 Windows Interprocess Communication + * AUTHOR: Andrey Shorin + * AUTHOR: Guido Serassio + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "comm.h" +#include "fde.h" +#include "SquidTime.h" + +#ifndef _MSWSOCK_ +#include +#endif +#include + +struct ipc_params +{ + int type; + int crfd; + int cwfd; + + struct sockaddr_in PS; + const char *prog; + char **args; +}; + +struct thread_params +{ + int type; + int rfd; + int send_fd; + const char *prog; + pid_t pid; +}; + +static unsigned int __stdcall ipc_thread_1(void *params); +static unsigned int __stdcall ipc_thread_2(void *params); + +static const char *ok_string = "OK\n"; +static const char *err_string = "ERR\n"; +static const char *shutdown_string = "$shutdown\n"; + +static const char *hello_string = "hi there\n"; +#define HELLO_BUF_SZ 32 +static char hello_buf[HELLO_BUF_SZ]; + +static int +ipcCloseAllFD(int prfd, int pwfd, int crfd, int cwfd) +{ + if (prfd >= 0) + comm_close(prfd); + + if (prfd != pwfd) + if (pwfd >= 0) + comm_close(pwfd); + + if (crfd >= 0) + comm_close(crfd); + + if (crfd != cwfd) + if (cwfd >= 0) + comm_close(cwfd); + + return -1; +} + +static void +PutEnvironment() +{ +#if HAVE_PUTENV + char *env_str; + int tmp_s; + env_str = (char *)xcalloc((tmp_s = strlen(Config.debugOptions) + 32), 1); + snprintf(env_str, tmp_s, "SQUID_DEBUG=%s", Config.debugOptions); + putenv(env_str); +#endif +} + +pid_t +ipcCreate(int type, const char *prog, const char *const args[], const char *name, int *rfd, int *wfd, void **hIpc) +{ + unsigned long thread; + + struct ipc_params params; + int opt; + int optlen = sizeof(opt); + DWORD ecode = 0; + pid_t pid; + + struct sockaddr_in CS; + + struct sockaddr_in PS; + int crfd = -1; + int prfd = -1; + int cwfd = -1; + int pwfd = -1; + socklen_t len; + int x; + + requirePathnameExists(name, prog); + + if (rfd) + *rfd = -1; + + if (wfd) + *wfd = -1; + + if (hIpc) + *hIpc = NULL; + + if (WIN32_OS_version != _WIN_OS_WINNT) { + getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *) &opt, &optlen); + opt = opt & ~(SO_SYNCHRONOUS_NONALERT | SO_SYNCHRONOUS_ALERT); + setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *) &opt, sizeof(opt)); + } + + if (type == IPC_TCP_SOCKET) { + crfd = cwfd = comm_open(SOCK_STREAM, + IPPROTO_TCP, + local_addr, + 0, + COMM_NOCLOEXEC, + name); + prfd = pwfd = comm_open(SOCK_STREAM, + IPPROTO_TCP, /* protocol */ + local_addr, + 0, /* port */ + 0, /* blocking */ + name); + } else if (type == IPC_UDP_SOCKET) { + crfd = cwfd = comm_open(SOCK_DGRAM, + IPPROTO_UDP, + local_addr, + 0, + COMM_NOCLOEXEC, + name); + prfd = pwfd = comm_open(SOCK_DGRAM, + IPPROTO_UDP, + local_addr, + 0, + 0, + name); + } else if (type == IPC_FIFO) { + debug(54, 0) + ("ipcCreate: %s: use IPC_TCP_SOCKET instead of IP_FIFO on Windows\n", + prog); + assert(0); + } else { + assert(IPC_NONE); + } + + debug(54, 3) ("ipcCreate: prfd FD %d\n", prfd); + debug(54, 3) ("ipcCreate: pwfd FD %d\n", pwfd); + debug(54, 3) ("ipcCreate: crfd FD %d\n", crfd); + debug(54, 3) ("ipcCreate: cwfd FD %d\n", cwfd); + + if (WIN32_OS_version != _WIN_OS_WINNT) { + getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *) &opt, &optlen); + opt = opt | SO_SYNCHRONOUS_NONALERT; + setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *) &opt, optlen); + } + + if (crfd < 0) { + debug(54, 0) ("ipcCreate: Failed to create child FD.\n"); + return ipcCloseAllFD(prfd, pwfd, crfd, cwfd); + } + + if (pwfd < 0) { + debug(54, 0) ("ipcCreate: Failed to create server FD.\n"); + return ipcCloseAllFD(prfd, pwfd, crfd, cwfd); + } + + if (type == IPC_TCP_SOCKET || type == IPC_UDP_SOCKET) { + len = sizeof(PS); + memset(&PS, '\0', len); + + if (getsockname(pwfd, (struct sockaddr *) &PS, &len) < 0) { + debug(54, 0) ("ipcCreate: getsockname: %s\n", xstrerror()); + return ipcCloseAllFD(prfd, pwfd, crfd, cwfd); + } + + debug(54, 3) ("ipcCreate: FD %d sockaddr %s:%d\n", + pwfd, inet_ntoa(PS.sin_addr), ntohs(PS.sin_port)); + len = sizeof(CS); + memset(&CS, '\0', len); + + if (getsockname(crfd, (struct sockaddr *) &CS, &len) < 0) { + debug(54, 0) ("ipcCreate: getsockname: %s\n", xstrerror()); + return ipcCloseAllFD(prfd, pwfd, crfd, cwfd); + } + + debug(54, 3) ("ipcCreate: FD %d sockaddr %s:%d\n", + crfd, inet_ntoa(CS.sin_addr), ntohs(CS.sin_port)); + } + + if (type == IPC_TCP_SOCKET) { + if (listen(crfd, 1) < 0) { + debug(54, 1) ("ipcCreate: listen FD %d: %s\n", crfd, xstrerror()); + return ipcCloseAllFD(prfd, pwfd, crfd, cwfd); + } + + debug(54, 3) ("ipcCreate: FD %d listening...\n", crfd); + } + + /* flush or else we get dup data if unbuffered_logs is set */ + logsFlush(); + + params.type = type; + + params.crfd = crfd; + + params.cwfd = cwfd; + + params.PS = PS; + + params.prog = prog; + + params.args = (char **) args; + + thread = _beginthreadex(NULL, 0, ipc_thread_1, ¶ms, 0, NULL); + + if (thread == 0) { + debug(54, 1) ("ipcCreate: _beginthread: %s\n", xstrerror()); + return ipcCloseAllFD(prfd, pwfd, crfd, cwfd); + } + + if (comm_connect_addr(pwfd, &CS) == COMM_ERROR) { + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } + + memset(hello_buf, '\0', HELLO_BUF_SZ); + x = recv(prfd, (void *)hello_buf, HELLO_BUF_SZ - 1, 0); + + if (x < 0) { + debug(54, 0) ("ipcCreate: PARENT: hello read test failed\n"); + debug(54, 0) ("--> read: %s\n", xstrerror()); + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } else if (strcmp(hello_buf, hello_string)) { + debug(54, 0) ("ipcCreate: PARENT: hello read test failed\n"); + debug(54, 0) ("--> read returned %d\n", x); + debug(54, 0) ("--> got '%s'\n", rfc1738_escape(hello_buf)); + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } + + x = send(pwfd, (const void *)ok_string, strlen(ok_string), 0); + + if (x < 0) { + debug(54, 0) ("ipcCreate: PARENT: OK write test failed\n"); + debug(54, 0) ("--> read: %s\n", xstrerror()); + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } + + memset(hello_buf, '\0', HELLO_BUF_SZ); + x = recv(prfd, (void *)hello_buf, HELLO_BUF_SZ - 1, 0); + + if (x < 0) { + debug(54, 0) ("ipcCreate: PARENT: OK read test failed\n"); + debug(54, 0) ("--> read: %s\n", xstrerror()); + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } else if (!strcmp(hello_buf, err_string)) { + debug(54, 0) ("ipcCreate: PARENT: OK read test failed\n"); + debug(54, 0) ("--> read returned %d\n", x); + debug(54, 0) ("--> got '%s'\n", rfc1738_escape(hello_buf)); + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } + + hello_buf[x] = '\0'; + pid = atol(hello_buf); + commSetTimeout(prfd, -1, NULL, NULL); + commSetNonBlocking(prfd); + commSetNonBlocking(pwfd); + commSetCloseOnExec(prfd); + commSetCloseOnExec(pwfd); + + if (rfd) + *rfd = prfd; + + if (wfd) + *wfd = pwfd; + + fd_table[prfd].flags.ipc = 1; + + fd_table[pwfd].flags.ipc = 1; + + fd_table[crfd].flags.ipc = 1; + + fd_table[cwfd].flags.ipc = 1; + + if (Config.sleep_after_fork) { + /* XXX emulation of usleep() */ + DWORD sl; + sl = Config.sleep_after_fork / 1000; + + if (sl == 0) + sl = 1; + + Sleep(sl); + } + + if (GetExitCodeThread((HANDLE) thread, &ecode) && ecode == STILL_ACTIVE) { + if (hIpc) + *hIpc = (HANDLE) thread; + + return pid; + } else { + CloseHandle((HANDLE) thread); + return ipcCloseAllFD(prfd, pwfd, -1, -1); + } +} + +static int +ipcSend(int cwfd, const char *buf, int len) +{ + int x; + + x = send(cwfd, (const void *)buf, len, 0); + + if (x < 0) { + debug(54, 0) ("sendto FD %d: %s\n", cwfd, xstrerror()); + debug(54, 0) ("ipcCreate: CHILD: hello write test failed\n"); + } + + return x; +} + +static unsigned int __stdcall +ipc_thread_1(void *in_params) +{ + int t1, t2, t3, retval = -1; + int p2c[2] = + {-1, -1}; + int c2p[2] = + {-1, -1}; + HANDLE hProcess = NULL, thread = NULL; + pid_t pid = -1; + + struct thread_params thread_params; + ssize_t x; + int tmp_s, fd = -1; + char *str; + STARTUPINFO si; + PROCESS_INFORMATION pi; + long F; + int prfd_ipc = -1, pwfd_ipc = -1, crfd_ipc = -1, cwfd_ipc = -1; + char *prog = NULL, *buf1 = NULL; + + struct sockaddr_in CS_ipc, PS_ipc; + + struct ipc_params *params = (struct ipc_params *) in_params; + int type = params->type; + int crfd = params->crfd; + int cwfd = params->cwfd; + char **args = params->args; + + struct sockaddr_in PS = params->PS; + + + buf1 = (char *)xcalloc(1, 8192); + strcpy(buf1, params->prog); + prog = strtok(buf1, w_space); + + if ((str = strrchr(prog, '/'))) + prog = ++str; + + if ((str = strrchr(prog, '\\'))) + prog = ++str; + + prog = xstrdup(prog); + + if (type == IPC_TCP_SOCKET) { + debug(54, 3) ("ipcCreate: calling accept on FD %d\n", crfd); + + if ((fd = accept(crfd, NULL, NULL)) < 0) { + debug(54, 0) ("ipcCreate: FD %d accept: %s\n", crfd, xstrerror()); + goto cleanup; + } + + debug(54, 3) ("ipcCreate: CHILD accepted new FD %d\n", fd); + comm_close(crfd); + snprintf(buf1, 8191, "%s CHILD socket", prog); + fd_open(fd, FD_SOCKET, buf1); + fd_table[fd].flags.ipc = 1; + cwfd = crfd = fd; + } else if (type == IPC_UDP_SOCKET) { + if (comm_connect_addr(crfd, &PS) == COMM_ERROR) + goto cleanup; + } + + x = send(cwfd, (const void *)hello_string, strlen(hello_string) + 1, 0); + + if (x < 0) { + debug(54, 0) ("sendto FD %d: %s\n", cwfd, xstrerror()); + debug(54, 0) ("ipcCreate: CHILD: hello write test failed\n"); + goto cleanup; + } + + PutEnvironment(); + memset(buf1, '\0', sizeof(buf1)); + x = recv(crfd, (void *)buf1, 8191, 0); + + if (x < 0) { + debug(54, 0) ("ipcCreate: CHILD: OK read test failed\n"); + debug(54, 0) ("--> read: %s\n", xstrerror()); + goto cleanup; + } else if (strcmp(buf1, ok_string)) { + debug(54, 0) ("ipcCreate: CHILD: OK read test failed\n"); + debug(54, 0) ("--> read returned %d\n", x); + debug(54, 0) ("--> got '%s'\n", rfc1738_escape(hello_buf)); + goto cleanup; + } + + /* assign file descriptors to child process */ + if (_pipe(p2c, 1024, _O_BINARY | _O_NOINHERIT) < 0) { + debug(54, 0) ("ipcCreate: CHILD: pipe: %s\n", xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + if (_pipe(c2p, 1024, _O_BINARY | _O_NOINHERIT) < 0) { + debug(54, 0) ("ipcCreate: CHILD: pipe: %s\n", xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + if (type == IPC_UDP_SOCKET) { + snprintf(buf1, 8192, "%s(%ld) <-> ipc CHILD socket", prog, -1L); + crfd_ipc = cwfd_ipc = comm_open(SOCK_DGRAM, IPPROTO_UDP, local_addr, 0, 0, buf1); + + if (crfd_ipc < 0) { + debug(54, 0) ("ipcCreate: CHILD: Failed to create child FD for %s.\n", + prog); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + snprintf(buf1, 8192, "%s(%ld) <-> ipc PARENT socket", prog, -1L); + prfd_ipc = pwfd_ipc = comm_open(SOCK_DGRAM, IPPROTO_UDP, local_addr, 0, 0, buf1); + + if (pwfd_ipc < 0) { + debug(54, 0) ("ipcCreate: CHILD: Failed to create server FD for %s.\n", + prog); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + tmp_s = sizeof(PS_ipc); + memset(&PS_ipc, '\0', tmp_s); + + if (getsockname(pwfd_ipc, (struct sockaddr *) &PS_ipc, &tmp_s) < 0) { + debug(54, 0) ("ipcCreate: getsockname: %s\n", xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + debug(54, 3) ("ipcCreate: FD %d sockaddr %s:%d\n", + pwfd_ipc, inet_ntoa(PS_ipc.sin_addr), ntohs(PS_ipc.sin_port)); + tmp_s = sizeof(CS_ipc); + memset(&CS_ipc, '\0', tmp_s); + + if (getsockname(crfd_ipc, (struct sockaddr *) &CS_ipc, &tmp_s) < 0) { + debug(54, 0) ("ipcCreate: getsockname: %s\n", xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + debug(54, 3) ("ipcCreate: FD %d sockaddr %s:%d\n", + crfd_ipc, inet_ntoa(CS_ipc.sin_addr), ntohs(CS_ipc.sin_port)); + + if (comm_connect_addr(pwfd_ipc, &CS_ipc) == COMM_ERROR) { + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + fd = crfd; + + if (comm_connect_addr(crfd_ipc, &PS_ipc) == COMM_ERROR) { + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + } /* IPC_UDP_SOCKET */ + + t1 = dup(0); + + t2 = dup(1); + + t3 = dup(2); + + dup2(c2p[0], 0); + + dup2(p2c[1], 1); + + dup2(fileno(debug_log), 2); + + close(c2p[0]); + + close(p2c[1]); + + commUnsetNonBlocking(fd); + + memset(&si, 0, sizeof(STARTUPINFO)); + + si.cb = sizeof(STARTUPINFO); + + si.hStdInput = (HANDLE) _get_osfhandle(0); + + si.hStdOutput = (HANDLE) _get_osfhandle(1); + + si.hStdError = (HANDLE) _get_osfhandle(2); + + si.dwFlags = STARTF_USESTDHANDLES; + + /* Make sure all other valid handles are not inerithable */ + for (x = 3; x < Squid_MaxFD; x++) { + if ((F = _get_osfhandle(x)) == -1) + continue; + + SetHandleInformation((HANDLE) F, HANDLE_FLAG_INHERIT, 0); + } + + *buf1 = '\0'; + strcpy(buf1 + 4096, params->prog); + str = strtok(buf1 + 4096, w_space); + + do { + strcat(buf1, str); + strcat(buf1, " "); + } while ((str = strtok(NULL, w_space))); + + x = 1; + + while (args[x]) { + strcat(buf1, args[x++]); + strcat(buf1, " "); + } + + if (CreateProcess(buf1 + 4096, buf1, NULL, NULL, TRUE, CREATE_NO_WINDOW, + NULL, NULL, &si, &pi)) { + pid = pi.dwProcessId; + hProcess = pi.hProcess; + } else { + pid = -1; + WIN32_maperror(GetLastError()); + x = errno; + } + + dup2(t1, 0); + dup2(t2, 1); + dup2(t3, 2); + close(t1); + close(t2); + close(t3); + + if (pid == -1) { + errno = x; + debug(54, 0) ("ipcCreate: CHILD: %s: %s\n", params->prog, xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + if (type == IPC_UDP_SOCKET) { + WSAPROTOCOL_INFO wpi; + + memset(&wpi, 0, sizeof(wpi)); + + if (SOCKET_ERROR == WSADuplicateSocket(crfd_ipc, pid, &wpi)) { + debug(54, 0) ("ipcCreate: CHILD: WSADuplicateSocket: %s\n", + xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + x = write(c2p[1], (const char *) &wpi, sizeof(wpi)); + + if (x < (ssize_t)sizeof(wpi)) { + debug(54, 0) ("ipcCreate: CHILD: write FD %d: %s\n", c2p[1], + xstrerror()); + debug(54, 0) ("ipcCreate: CHILD: %s: socket exchange failed\n", + prog); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + x = read(p2c[0], buf1, 8192); + + if (x < 0) { + debug(54, 0) ("ipcCreate: CHILD: read FD %d: %s\n", p2c[0], + xstrerror()); + debug(54, 0) ("ipcCreate: CHILD: %s: socket exchange failed\n", + prog); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } else if (strncmp(buf1, ok_string, strlen(ok_string))) { + debug(54, 0) ("ipcCreate: CHILD: %s: socket exchange failed\n", + prog); + debug(54, 0) ("--> read returned %d\n", x); + buf1[x] = '\0'; + debug(54, 0) ("--> got '%s'\n", rfc1738_escape(buf1)); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + x = write(c2p[1], (const char *) &PS_ipc, sizeof(PS_ipc)); + + if (x < (ssize_t)sizeof(PS_ipc)) { + debug(54, 0) ("ipcCreate: CHILD: write FD %d: %s\n", c2p[1], + xstrerror()); + debug(54, 0) ("ipcCreate: CHILD: %s: socket exchange failed\n", + prog); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + x = read(p2c[0], buf1, 8192); + + if (x < 0) { + debug(54, 0) ("ipcCreate: CHILD: read FD %d: %s\n", p2c[0], + xstrerror()); + debug(54, 0) ("ipcCreate: CHILD: %s: socket exchange failed\n", + prog); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } else if (strncmp(buf1, ok_string, strlen(ok_string))) { + debug(54, 0) ("ipcCreate: CHILD: %s: socket exchange failed\n", + prog); + debug(54, 0) ("--> read returned %d\n", x); + buf1[x] = '\0'; + debug(54, 0) ("--> got '%s'\n", rfc1738_escape(buf1)); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + x = send(pwfd_ipc, (const void *)ok_string, strlen(ok_string), 0); + x = recv(prfd_ipc, (void *)(buf1 + 200), 8191 - 200, 0); + assert((size_t) x == strlen(ok_string) + && !strncmp(ok_string, buf1 + 200, strlen(ok_string))); + } /* IPC_UDP_SOCKET */ + + snprintf(buf1, 8191, "%s(%ld) CHILD socket", prog, (long int) pid); + + fd_note(fd, buf1); + + if (prfd_ipc != -1) { + snprintf(buf1, 8191, "%s(%ld) <-> ipc CHILD socket", prog, (long int) pid); + fd_note(crfd_ipc, buf1); + snprintf(buf1, 8191, "%s(%ld) <-> ipc PARENT socket", prog, (long int) pid); + fd_note(prfd_ipc, buf1); + } + + /* else { IPC_TCP_SOCKET */ + /* commSetNoLinger(fd); */ + /* } */ + thread_params.prog = prog; + + thread_params.send_fd = cwfd; + + thread_params.pid = pid; + + if ((thread_params.type = type) == IPC_TCP_SOCKET) + thread_params.rfd = p2c[0]; + else + thread_params.rfd = prfd_ipc; + + thread = + (HANDLE) _beginthreadex(NULL, 0, ipc_thread_2, &thread_params, 0, NULL); + + if (!thread) { + debug(54, 0) ("ipcCreate: CHILD: _beginthreadex: %s\n", xstrerror()); + ipcSend(cwfd, err_string, strlen(err_string)); + goto cleanup; + } + + snprintf(buf1, 8191, "%ld\n", (long int) pid); + + if (-1 == ipcSend(cwfd, buf1, strlen(buf1))) + goto cleanup; + + debug(54, 2) ("ipc(%s,%ld): started successfully\n", prog, (long int) pid); + + /* cycle */ + for (;;) { + x = recv(crfd, (void *)buf1, 8192, 0); + + if (x <= 0) { + debug(54, 3) ("ipc(%s,%d): %d bytes received from parent. Exiting...\n", + prog, pid, x); + break; + } + + buf1[x] = '\0'; + + if (type == IPC_UDP_SOCKET && !strcmp(buf1, shutdown_string)) { + debug(54, 3) + ("ipc(%s,%d): request for shutdown received from parent. Exiting...\n", + prog, pid); + TerminateProcess(hProcess, 0); + break; + } + + debug(54, 5) ("ipc(%s,%d): received from parent: %s\n", prog, pid, + rfc1738_escape_unescaped(buf1)); + + if (type == IPC_TCP_SOCKET) + x = write(c2p[1], buf1, x); + else + x = send(pwfd_ipc, (const void *)buf1, x, 0); + + if (x <= 0) { + debug(54, 3) ("ipc(%s,%d): %d bytes written to %s. Exiting...\n", + prog, pid, x, prog); + break; + } + } + + retval = 0; + +cleanup: + + if (c2p[1] != -1) + close(c2p[1]); + + if (fd_table[crfd].flags.open) + ipcCloseAllFD(-1, -1, crfd, cwfd); + + if (prfd_ipc != -1) { + send(crfd_ipc, (const void *)shutdown_string, strlen(shutdown_string), 0); + shutdown(crfd_ipc, SD_BOTH); + shutdown(prfd_ipc, SD_BOTH); + } + + ipcCloseAllFD(prfd_ipc, pwfd_ipc, crfd_ipc, cwfd_ipc); + + if (hProcess && WAIT_OBJECT_0 != + WaitForSingleObject(hProcess, type == IPC_UDP_SOCKET ? 12000 : 5000)) { + + getCurrentTime(); + debug(54, 0) ("ipc(%s,%d): WARNING: %s didn't exit in %d seconds.\n", + prog, pid, prog, type == IPC_UDP_SOCKET ? 12 : 5); + } + + if (thread && WAIT_OBJECT_0 != WaitForSingleObject(thread, 3000)) { + getCurrentTime(); + debug(54, 0) + ("ipc(%s,%d): WARNING: ipc_thread_2 didn't exit in 3 seconds.\n", + prog, pid); + } + + getCurrentTime(); + + if (!retval) + debug(54, 2) ("ipc(%s,%d): normal exit\n", prog, pid); + + if (buf1) + xfree(buf1); + + if (prog) + xfree(prog); + + if (thread) + CloseHandle(thread); + + if (hProcess) + CloseHandle(hProcess); + + if (p2c[0] != -1) + close(p2c[0]); + + return retval; +} + +static unsigned int __stdcall +ipc_thread_2(void *in_params) +{ + int x; + + struct thread_params *params = (struct thread_params *) in_params; + int type = params->type; + int rfd = params->rfd; + int send_fd = params->send_fd; + char *prog = xstrdup(params->prog); + pid_t pid = params->pid; + char *buf2 = (char *)xcalloc(1, 8192); + + for (;;) { + if (type == IPC_TCP_SOCKET) + x = read(rfd, buf2, 8192); + else + x = recv(rfd, (void *)buf2, 8192, 0); + + if ((x <= 0 && type == IPC_TCP_SOCKET) || + (x < 0 && type == IPC_UDP_SOCKET)) { + debug(54, 3) ("ipc(%s,%d): %d bytes read from %s. Exiting...\n", + prog, pid, x, prog); + break; + } + + buf2[x] = '\0'; + + if (type == IPC_UDP_SOCKET && !strcmp(buf2, shutdown_string)) { + debug(54, 3) ("ipc(%s,%d): request for shutdown received. Exiting...\n", + prog, pid); + break; + } + + if (x >= 2) { + if ((buf2[x - 1] == '\n') && (buf2[x - 2] == '\r')) { + buf2[x - 2] = '\n'; + buf2[x - 1] = '\0'; + x--; + } + } + + debug(54, 5) ("ipc(%s,%d): received from child : %s\n", prog, pid, + rfc1738_escape_unescaped(buf2)); + x = send(send_fd, (const void *)buf2, x, 0); + + if ((x <= 0 && type == IPC_TCP_SOCKET) || + (x < 0 && type == IPC_UDP_SOCKET)) { + debug(54, 3) ("ipc(%s,%d): %d bytes sent to parent. Exiting...\n", + prog, pid, x); + break; + } + } + + xfree(prog); + xfree(buf2); + return 0; +} --- squid3/src/leakfinder.cc Wed Feb 14 13:38:03 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,146 +0,0 @@ - -/* - * $Id: leakfinder.cc,v 1.2 2003/02/22 03:14:34 squidadm Exp $ - * - * DEBUG: section 45 Callback Data Registry - * AUTHOR: Duane Wessels - * - * SQUID Web Proxy Cache http://www.squid-cache.org/ - * ---------------------------------------------------------- - * - * Squid is the result of efforts by numerous individuals from - * the Internet community; see the CONTRIBUTORS file for full - * details. Many organizations have provided support for Squid's - * development; see the SPONSORS file for full details. Squid is - * Copyrighted (C) 2001 by the Regents of the University of - * California; see the COPYRIGHT file for full details. Squid - * incorporates software developed and/or copyrighted by other - * sources; see the CREDITS file for full details. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. - * - */ - -/* - * Use these to find memory leaks - */ - -#include "squid.h" -#include "Store.h" - -static hash_table *htable = NULL; - -static int leakCount = 0; - -typedef struct _ptr -{ - hash_link hash; /* must be first */ - void *key; - - struct _ptr *next; - const char *file; - int line; - time_t when; -} - -ptr; - -static HASHCMP ptr_cmp; -static HASHHASH ptr_hash; -static OBJH ptrDump; - -/* ========================================================================= */ - -void -leakInit(void) -{ - debug(45, 3) ("ptrInit\n"); - htable = hash_create(ptr_cmp, 1 << 8, ptr_hash); - cachemgrRegister("leaks", - "Memory Leak Tracking", - ptrDump, 0, 1); -} - -void * -leakAddFL(void *p, const char *file, int line) -{ - ptr *c; - assert(p); - assert(htable != NULL); - assert(hash_lookup(htable, p) == NULL); - c = (ptr *)xcalloc(1, sizeof(*c)); - c->key = p; - c->file = file; - c->line = line; - c->when = squid_curtime; - hash_join(htable, &c->hash); - leakCount++; - return p; -} - -void * -leakTouchFL(void *p, const char *file, int line) -{ - ptr *c = (ptr *) hash_lookup(htable, p); - assert(p); - assert(htable != NULL); - assert(c); - c->file = file; - c->line = line; - c->when = squid_curtime; - return p; -} - -void * -leakFreeFL(void *p, const char *file, int line) -{ - ptr *c = (ptr *) hash_lookup(htable, p); - assert(p); - assert(c != NULL); - hash_remove_link(htable, (hash_link *) c); - leakCount--; - xfree(c); - return p; -} - -/* ========================================================================= */ - -static int -ptr_cmp(const void *p1, const void *p2) -{ - return (char *) p1 - (char *) p2; -} - -static unsigned int -ptr_hash(const void *p, unsigned int mod) -{ - return ((unsigned long) p >> 8) % mod; -} - - -static void -ptrDump(StoreEntry * sentry) -{ - hash_link *hptr; - ptr *c; - storeAppendPrintf(sentry, "Tracking %d pointers\n", leakCount); - hash_first(htable); - - while ((hptr = (hash_link *)hash_next(htable))) { - c = (ptr *) hptr; - storeAppendPrintf(sentry, "%20p last used %9d seconds ago by %s:%d\n", - c->key, (int)(squid_curtime - c->when), c->file, c->line); - } -} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/mk-globals-c.awk Wed Feb 14 13:38:03 2007 @@ -0,0 +1,43 @@ +# tested with gawk, mawk, and nawk. +# drop-in replacement for mk-globals-c.pl. +# modified to work with Solaris awk (junk). +# creates "globals.c" (on stdout) from "globals.h". +# invoke similarly: perl mk-globals-c.pl globals.h +# --> awk -f mk-globals-c.awk globals.h +# +# 2006 by Christopher Kerr. + +BEGIN { Copyright = 0 + print "#include \"squid.h\"" } + +Copyright != 1 && /^ \*\/$/ { Copyright = 1; print; next } +Copyright != 1 { print; next } +/SQUID_GLOBALS_H/ { next } + +# arrays defined elsewhere +/\[\];/ { next } +/^extern \"C\"/ { print; next } + +# +# Check exactly for lines beginning with " extern", generated +# from astyle (grrrrr ...) +# +/^ extern / { # process "^extern " input lines. + # 0 1 2 ####### + # extern int variable; /* val */ --> int variable; /* val */ ####### + ########################################################################## + len = length($0) - 11 # sub(/extern /, "") + str = substr($0, 12, len) # strip "^extern ". + + pos0 = index(str, ";") # position of ";". + pos1 = index(str, "/*") # position of "/*". + pos2 = index(str, "*/") # position of "*/". + + if ( pos1 != 0 ) { # make assignment. + + val = substr(str, pos1+3, pos2-pos1-4) # get comment value. + str = substr(str, 1, pos0-1) " = " val ";" # string to semi-colon. + } + print str; next # get next input line. +} +{ print } # C preprocessor lines. --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/mk-string-arrays.awk Wed Feb 14 13:38:03 2007 @@ -0,0 +1,38 @@ +# tested with gawk, mawk, and nawk. +# drop-in replacement for mk-string-arrays.pl. +# creates "enum.c" (on stdout) from "enum.h". +# invoke similarly: perl -f mk-string-arrays.pl enum.h +# --> awk -f mk-string-arrays.awk enum.h +# +# 2006 by Christopher Kerr. + +BEGIN { # converted to "const char *"TypedefEnum[?]"_str[]" + TypedefEnum["err_type"] = 1 + TypedefEnum["lookup_t"] = 1 + TypedefEnum["icp_opcode"] = 1 + TypedefEnum["swap_log_op"] = 1 +} + +/^ \*\/$/ && Copyright != 1 { Copyright = 1; print; next } +Copyright != 1 { print; next } +/^typedef/ { e = 0; next } + +/^[ \t]*[A-Z]/ { + split($1, t, ",") # remove , + Element[++e] = t[1] + next +} + +/^} / { + split($2, t, ";") # remove ; + type = t[1] + if (TypedefEnum[type]) { + print "\nconst char *" type "_str[] = {" + for ( i = 1; i < e; ++i) + print "\t\"" Element[i] "\"," + print "\t\"" Element[i] "\"" + print "};" + } + next +} + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/pconn.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,94 @@ + +#ifndef SQUID_PCONN_H +#define SQUID_PCONN_H + +/* forward decls */ + +class CacheManager; + +class PconnPool; + +#define MAX_NUM_PCONN_POOLS 10 +#define PCONN_HIST_SZ (1<<16) + +class IdleConnList +{ + +public: + IdleConnList(const char *key, PconnPool *parent); + ~IdleConnList(); + int numIdle() { return nfds; } + + int findFDIndex(int fd); + void removeFD(int fd); + void push(int fd); + int findUseableFD(); + void clearHandlers(int fd); + +private: + static IOCB read; + static PF timeout; + +public: + hash_link hash; /* must be first */ + +private: + int *fds; + int nfds_alloc; + int nfds; + PconnPool *parent; + char fakeReadBuf[4096]; + CBDATA_CLASS2(IdleConnList); +}; + +class PconnPool +{ + +public: + PconnPool(const char *); + + void moduleInit(); + void push(int fd, const char *host, u_short port, const char *domain); + int pop(const char *host, u_short port, const char *domain); + void count(int uses); + void dumpHist(StoreEntry *e); + void unlinkList(IdleConnList *list) const; + +private: + + static const char *key(const char *host, u_short port, const char *domain); + + int hist[PCONN_HIST_SZ]; + hash_table *table; + const char *descr; + +}; + +class PconnModule +{ + +public: + /* the module is a singleton until we have instance based cachemanager + * management + */ + static PconnModule * GetInstance(); + /* A thunk to the still C like CacheManager callback api. */ + static void DumpWrapper(StoreEntry *e); + + PconnModule(); + void registerWithCacheManager(CacheManager & manager); + + void add + (PconnPool *); + + OBJH dump; + +private: + PconnPool **pools; + + static PconnModule * instance; + + int poolCount; +}; + +#endif /* SQUID_PCONN_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/time.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,62 @@ + +/* + * $Id: time.cc,v 1.3.6.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * DEBUG: section 21 Time Functions + * AUTHOR: Harvest Derived + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "SquidTime.h" + +time_t squid_curtime = 0; + +time_t +getCurrentTime(void) +{ +#if GETTIMEOFDAY_NO_TZP + gettimeofday(¤t_time); +#else + + gettimeofday(¤t_time, NULL); +#endif + + current_dtime = (double) current_time.tv_sec + + (double) current_time.tv_usec / 1000000.0; + return squid_curtime = current_time.tv_sec; +} + +TimeEngine::~TimeEngine() +{} + +void +TimeEngine::tick() +{ + getCurrentTime(); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/wccp2.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,2052 @@ + +/* + * $Id: wccp2.cc,v 1.9.2.2 2006/09/29 23:16:01 dwsquid Exp $ + * + * DEBUG: section 80 WCCP Support + * AUTHOR: Steven Wilton + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ +#include "squid.h" +#include "comm.h" +#include "event.h" +#include "Parsing.h" +#include "Store.h" +#include "SwapDir.h" + +#if USE_WCCPv2 +#include + +#define WCCP_PORT 2048 +#define WCCP_RESPONSE_SIZE 12448 +#define WCCP_BUCKETS 256 + +static int theWccp2Connection = -1; +static int wccp2_connected = 0; + +static PF wccp2HandleUdp; +static EVH wccp2HereIam; +static EVH wccp2AssignBuckets; + +/* KDW WCCP V2 */ +#define WCCP2_HERE_I_AM 10 +#define WCCP2_I_SEE_YOU 11 +#define WCCP2_REDIRECT_ASSIGN 12 +#define WCCP2_REMOVAL_QUERY 13 + +#define WCCP2_VERSION 0x200 + +#define WCCP2_SECURITY_INFO 0 +#define WCCP2_NO_SECURITY 0 +#define WCCP2_MD5_SECURITY 1 + +#define WCCP2_SERVICE_INFO 1 +#define WCCP2_SERVICE_STANDARD 0 +#define WCCP2_SERVICE_DYNAMIC 1 +#define WCCP2_SERVICE_ID_HTTP 0x00 + +#define WCCP2_SERVICE_SRC_IP_HASH 0x1 +#define WCCP2_SERVICE_DST_IP_HASH 0x2 +#define WCCP2_SERVICE_SOURCE_PORT_HASH 0x4 +#define WCCP2_SERVICE_DST_PORT_HASH 0x8 +#define WCCP2_SERVICE_PORTS_DEFINED 0x10 +#define WCCP2_SERVICE_PORTS_SOURCE 0x20 +#define WCCP2_SERVICE_SRC_IP_ALT_HASH 0x100 +#define WCCP2_SERVICE_DST_IP_ALT_HASH 0x200 +#define WCCP2_SERVICE_SRC_PORT_ALT_HASH 0x400 +#define WCCP2_SERVICE_DST_PORT_ALT_HASH 0x800 + +#define WCCP2_ROUTER_ID_INFO 2 + +#define WCCP2_WC_ID_INFO 3 + +#define WCCP2_RTR_VIEW_INFO 4 + +#define WCCP2_WC_VIEW_INFO 5 + +#define WCCP2_REDIRECT_ASSIGNMENT 6 + +#define WCCP2_QUERY_INFO 7 + +#define WCCP2_CAPABILITY_INFO 8 + +#define WCCP2_CAPABILITY_FORWARDING_METHOD 0x01 +#define WCCP2_CAPABILITY_ASSIGNMENT_METHOD 0x02 +#define WCCP2_CAPABILITY_RETURN_METHOD 0x03 + +#define WCCP2_FORWARDING_METHOD_GRE 0x00000001 +#define WCCP2_FORWARDING_METHOD_L2 0x00000002 + +#define WCCP2_ASSIGNMENT_METHOD_HASH 0x00000001 +#define WCCP2_ASSIGNMENT_METHOD_MASK 0x00000002 + +#define WCCP2_PACKET_RETURN_METHOD_GRE 0x00000001 +#define WCCP2_PACKET_RETURN_METHOD_L2 0x00000002 + +#define WCCP2_NONE_SECURITY_LEN 0 +#define WCCP2_MD5_SECURITY_LEN 16 + +/* Useful defines */ +#define WCCP2_NUMPORTS 8 +#define WCCP2_PASSWORD_LEN 8 + +/* WCCP v2 packet header */ + +struct wccp2_here_i_am_header_t +{ + uint32_t type; + uint16_t version; + uint16_t length; +}; + +static struct wccp2_here_i_am_header_t wccp2_here_i_am_header; + +/* Security struct for the "no security" option */ + +struct wccp2_security_none_t +{ + uint16_t security_type; + uint16_t security_length; + uint32_t security_option; +}; + +struct wccp2_security_md5_t +{ + uint16_t security_type; + uint16_t security_length; + uint32_t security_option; + uint8_t security_implementation[WCCP2_MD5_SECURITY_LEN]; +}; + +/* Service info struct */ + +struct wccp2_service_info_t +{ + uint16_t service_type; + uint16_t service_length; + uint8_t service; + uint8_t service_id; + uint8_t service_priority; + uint8_t service_protocol; + uint32_t service_flags; + uint16_t port0; + uint16_t port1; + uint16_t port2; + uint16_t port3; + uint16_t port4; + uint16_t port5; + uint16_t port6; + uint16_t port7; +}; + +struct wccp2_cache_identity_info_t +{ + + struct IN_ADDR addr; + uint16_t hash_revision; + char bits[2]; + char buckets[32]; + uint16_t weight; + uint16_t status; +}; + +/* Web Cache identity info */ + +struct wccp2_identity_info_t +{ + uint16_t cache_identity_type; + uint16_t cache_identity_length; + + struct wccp2_cache_identity_info_t cache_identity; +}; + +static struct wccp2_identity_info_t wccp2_identity_info; + +/* View header */ + +struct wccp2_cache_view_header_t +{ + uint16_t cache_view_type; + uint16_t cache_view_length; + uint32_t cache_view_version; +}; + +static struct wccp2_cache_view_header_t wccp2_cache_view_header; + +/* View info */ + +struct wccp2_cache_view_info_t +{ + uint32_t num_routers; + uint32_t num_caches; +}; + +static struct wccp2_cache_view_info_t wccp2_cache_view_info; + +/* Router ID element */ + +struct wccp2_router_id_element_t +{ + + struct IN_ADDR router_address; + uint32_t received_id; +}; + +static struct wccp2_router_id_element_t wccp2_router_id_element; + +/* Capability info header */ + +struct wccp2_capability_info_header_t +{ + uint16_t capability_info_type; + uint16_t capability_info_length; +}; + +static struct wccp2_capability_info_header_t wccp2_capability_info_header; + +/* Capability element header */ + +struct wccp2_capability_element_header_t +{ + uint16_t capability_type; + uint16_t capability_length; +}; + +/* Capability element */ + +struct wccp2_capability_element_t +{ + uint16_t capability_type; + uint16_t capability_length; + uint32_t capability_value; +}; + +static struct wccp2_capability_element_t wccp2_capability_element; + + +/* RECEIVED PACKET STRUCTURE */ + +struct wccp2_i_see_you_t +{ + uint32_t type; + uint16_t version; + uint16_t length; + char data[WCCP_RESPONSE_SIZE]; +}; + +static struct wccp2_i_see_you_t wccp2_i_see_you; + +/* Router ID element */ + +struct wccp2_router_assign_element_t +{ + + struct IN_ADDR router_address; + uint32_t received_id; + uint32_t change_number; +}; + +/* Generic header struct */ + +struct wccp2_item_header_t +{ + uint16_t type; + uint16_t length; +}; + +/* Router identity struct */ + +struct router_identity_info_t +{ + + struct wccp2_item_header_t header; + + struct wccp2_router_id_element_t router_id_element; + + struct IN_ADDR router_address; + uint32_t number_caches; +}; + +/* assigment key */ + +struct assignment_key_t +{ + + struct IN_ADDR master_ip; + uint32_t master_number; +}; + +/* Router view of WCCP */ + +struct router_view_t +{ + + struct wccp2_item_header_t header; + uint32_t change_number; + + struct assignment_key_t assignment_key; +}; + + +/* Lists used to keep track of caches, routers and services */ + +struct wccp2_cache_list_t +{ + + struct IN_ADDR cache_ip; + + int weight; + + struct wccp2_cache_list_t *next; +}; + +struct wccp2_router_list_t +{ + + struct wccp2_router_id_element_t *info; + + struct IN_ADDR local_ip; + + struct IN_ADDR router_sendto_address; + uint32_t member_change; + uint32_t num_caches; + + struct wccp2_cache_list_t cache_list_head; + + struct wccp2_router_list_t *next; +}; + +static int wccp2_numrouters; + +struct wccp2_service_list_t +{ + + struct wccp2_service_info_t info; + uint32_t num_routers; + + struct wccp2_router_list_t router_list_head; + int lowest_ip; + uint32_t change_num; + + struct wccp2_identity_info_t *wccp2_identity_info_ptr; + + struct wccp2_security_md5_t *security_info; + + struct wccp2_service_info_t *service_info; + char wccp_packet[WCCP_RESPONSE_SIZE]; + size_t wccp_packet_size; + + struct wccp2_service_list_t *next; + char wccp_password[WCCP2_PASSWORD_LEN + 1]; /* hold the trailing C-string NUL */ + uint32_t wccp2_security_type; +}; + +static struct wccp2_service_list_t *wccp2_service_list_head = NULL; + +int empty_portlist[WCCP2_NUMPORTS] = + {0, 0, 0, 0, 0, 0, 0, 0}; + +/* END WCCP V2 */ +void wccp2_add_service_list(int service, int service_id, int service_priority, + int service_proto, int service_flags, int ports[], int security_type, char *password); + +/* + * The functions used during startup: + * wccp2Init + * wccp2ConnectionOpen + * wccp2ConnectionClose + */ + +static void +wccp2InitServices(void) +{ + debug(80, 5) ("wccp2InitServices: called\n"); +} + +static void + +wccp2_update_service(struct wccp2_service_list_t *srv, int service, + int service_id, int service_priority, int service_proto, int service_flags, + int ports[]) +{ + /* XXX check what needs to be wrapped in htons()! */ + srv->info.service = service; + srv->info.service_id = service_id; + srv->info.service_priority = service_priority; + srv->info.service_protocol = service_proto; + srv->info.service_flags = htonl(service_flags); + srv->info.port0 = htons(ports[0]); + srv->info.port1 = htons(ports[1]); + srv->info.port2 = htons(ports[2]); + srv->info.port3 = htons(ports[3]); + srv->info.port4 = htons(ports[4]); + srv->info.port5 = htons(ports[5]); + srv->info.port6 = htons(ports[6]); + srv->info.port7 = htons(ports[7]); +} + +void +wccp2_add_service_list(int service, int service_id, int service_priority, + int service_proto, int service_flags, int ports[], int security_type, + char *password) +{ + + struct wccp2_service_list_t *wccp2_service_list_ptr; + + wccp2_service_list_ptr = (wccp2_service_list_t *) xcalloc(1, sizeof(struct wccp2_service_list_t)); + + debug(80, 5) ("wccp2_add_service_list: added service id %d\n", service_id); + + /* XXX check what needs to be wrapped in htons()! */ + wccp2_service_list_ptr->info.service_type = htons(WCCP2_SERVICE_INFO); + + wccp2_service_list_ptr->info.service_length = htons(sizeof(struct wccp2_service_info_t) - 4); + wccp2_service_list_ptr->change_num = 0; + wccp2_update_service(wccp2_service_list_ptr, service, service_id, + service_priority, service_proto, service_flags, ports); + wccp2_service_list_ptr->wccp2_security_type = security_type; + memset(wccp2_service_list_ptr->wccp_password, 0, WCCP2_PASSWORD_LEN + 1); + strncpy(wccp2_service_list_ptr->wccp_password, password, WCCP2_PASSWORD_LEN); + /* add to linked list - XXX this should use the Squid dlink* routines! */ + wccp2_service_list_ptr->next = wccp2_service_list_head; + wccp2_service_list_head = wccp2_service_list_ptr; +} + +static struct wccp2_service_list_t * + wccp2_get_service_by_id(int service, int service_id) +{ + + struct wccp2_service_list_t *p; + + p = wccp2_service_list_head; + + while (p != NULL) + { + if (p->info.service == service && p->info.service_id == service_id) { + return p; + } + + p = p->next; + } + + return NULL; +} + +/* + * Update the md5 security header, if possible + * + * Returns: 1 if we set it, 0 if not (eg, no security section, or non-md5) + */ +static char +wccp2_update_md5_security(char *password, char *ptr, char *packet, int len) +{ + u_int8_t md5_digest[16]; + char pwd[WCCP2_PASSWORD_LEN]; + MD5_CTX M; + + struct wccp2_security_md5_t *ws; + + debug(80, 5) ("wccp2_update_md5_security: called\n"); + + /* The password field, for the MD5 hash, needs to be 8 bytes and NUL padded. */ + memset(pwd, 0, sizeof(pwd)); + strncpy(pwd, password, sizeof(pwd)); + + ws = (struct wccp2_security_md5_t *) ptr; + assert(ntohs(ws->security_type) == WCCP2_SECURITY_INFO); + /* Its the security part */ + + if (ntohl(ws->security_option) != WCCP2_MD5_SECURITY) { + debug(80, 5) ("wccp2_update_md5_security: this service ain't md5'ing, abort\n"); + return 0; + } + + /* And now its the MD5 section! */ + /* According to the draft, the MD5 security hash is the combination of + * the 8-octet password (padded w/ NUL bytes) and the entire WCCP packet, + * including the WCCP message header. The WCCP security implementation + * area should be zero'ed before calculating the MD5 hash. + */ + /* XXX eventually we should be able to kill md5_digest and blit it directly in */ + memset(ws->security_implementation, 0, sizeof(ws->security_implementation)); + + MD5Init(&M); + + MD5Update(&M, pwd, 8); + + MD5Update(&M, packet, len); + + MD5Final(md5_digest, &M); + + memcpy(ws->security_implementation, md5_digest, sizeof(md5_digest)); + + /* Finished! */ + return 1; +} + + +/* + * Check the given WCCP2 packet against the given password. + */ +static char + +wccp2_check_security(struct wccp2_service_list_t *srv, char *security, char *packet, int len) +{ + + struct wccp2_security_md5_t *ws = (struct wccp2_security_md5_t *) security; + u_int8_t md5_digest[16], md5_challenge[16]; + char pwd[WCCP2_PASSWORD_LEN]; + MD5_CTX M; + + /* Make sure the security type matches what we expect */ + + if (ntohl(ws->security_option) != srv->wccp2_security_type) + { + debug(80, 1) ("wccp2_check_security: received packet has the wrong security option\n"); + return 0; + } + + if (srv->wccp2_security_type == WCCP2_NO_SECURITY) + { + return 1; + } + + if (srv->wccp2_security_type != WCCP2_MD5_SECURITY) + { + debug(80, 1) ("wccp2_check_security: invalid security option\n"); + return 0; + } + + /* If execution makes it here then we have an MD5 security */ + + /* The password field, for the MD5 hash, needs to be 8 bytes and NUL padded. */ + memset(pwd, 0, sizeof(pwd)); + + strncpy(pwd, srv->wccp_password, sizeof(pwd)); + + /* Take a copy of the challenge: we need to NUL it before comparing */ + memcpy(md5_challenge, ws->security_implementation, 16); + + memset(ws->security_implementation, 0, sizeof(ws->security_implementation)); + + MD5Init(&M); + + MD5Update(&M, pwd, 8); + + MD5Update(&M, packet, len); + + MD5Final(md5_digest, &M); + + return (memcmp(md5_digest, md5_challenge, 16) == 0); +} + + +void +wccp2Init(void) +{ + sockaddr_in_list *s; + char *ptr; + + struct wccp2_service_list_t *service_list_ptr; + + struct wccp2_router_list_t *router_list_ptr; + + struct wccp2_security_md5_t wccp2_security_md5; + + debug(80, 5) ("wccp2Init: Called\n"); + + if (wccp2_connected == 1) + return; + + wccp2_numrouters = 0; + + /* Calculate the number of routers configured in the config file */ + for (s = Config.Wccp2.router; s; s = s->next) { + if (s->s.sin_addr.s_addr != any_addr.s_addr) { + /* Increment the counter */ + wccp2_numrouters++; + } + } + + if (wccp2_numrouters == 0) { + return; + } + + /* Initialise the list of services */ + wccp2InitServices(); + + service_list_ptr = wccp2_service_list_head; + + while (service_list_ptr != NULL) { + /* Set up our list pointers */ + router_list_ptr = &service_list_ptr->router_list_head; + + /* start the wccp header */ + wccp2_here_i_am_header.type = htonl(WCCP2_HERE_I_AM); + wccp2_here_i_am_header.version = htons(WCCP2_VERSION); + wccp2_here_i_am_header.length = 0; + ptr = service_list_ptr->wccp_packet + sizeof(wccp2_here_i_am_header); + + /* add the security section */ + /* XXX this is ugly */ + + if (service_list_ptr->wccp2_security_type == WCCP2_MD5_SECURITY) { + wccp2_security_md5.security_option = htonl(WCCP2_MD5_SECURITY); + + wccp2_security_md5.security_length = htons(sizeof(struct wccp2_security_md5_t) - 4); + } else if (service_list_ptr->wccp2_security_type == WCCP2_NO_SECURITY) { + wccp2_security_md5.security_option = htonl(WCCP2_NO_SECURITY); + /* XXX I hate magic length numbers! */ + wccp2_security_md5.security_length = htons(4); + } else { + fatalf("Bad WCCP2 security type\n"); + } + + wccp2_here_i_am_header.length += ntohs(wccp2_security_md5.security_length) + 4; + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + wccp2_security_md5.security_type = htons(WCCP2_SECURITY_INFO); + + service_list_ptr->security_info = (struct wccp2_security_md5_t *) ptr; + + if (service_list_ptr->wccp2_security_type == WCCP2_MD5_SECURITY) { + + xmemcpy(ptr, &wccp2_security_md5, sizeof(struct wccp2_security_md5_t)); + + ptr += sizeof(struct wccp2_security_md5_t); + } else { + /* assume NONE, and XXX I hate magic length numbers */ + xmemcpy(ptr, &wccp2_security_md5, 8); + ptr += 8; + } + + /* Add the service info section */ + + wccp2_here_i_am_header.length += sizeof(struct wccp2_service_info_t); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + xmemcpy(ptr, &service_list_ptr->info, sizeof(struct wccp2_service_info_t)); + + service_list_ptr->service_info = (struct wccp2_service_info_t *) ptr; + + ptr += sizeof(struct wccp2_service_info_t); + + /* Add the cache identity section */ + + wccp2_here_i_am_header.length += sizeof(struct wccp2_identity_info_t); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_identity_info.cache_identity_type = htons(WCCP2_WC_ID_INFO); + + wccp2_identity_info.cache_identity_length = htons(sizeof(wccp2_identity_info.cache_identity)); + + memset(&wccp2_identity_info.cache_identity.addr, '\0', sizeof(wccp2_identity_info.cache_identity.addr)); + + memset(&wccp2_identity_info.cache_identity.hash_revision, '\0', sizeof(wccp2_identity_info.cache_identity.hash_revision)); + + memset(&wccp2_identity_info.cache_identity.bits, '\0', sizeof(wccp2_identity_info.cache_identity.bits)); + + memset(&wccp2_identity_info.cache_identity.buckets, '\0', sizeof(wccp2_identity_info.cache_identity.buckets)); + + wccp2_identity_info.cache_identity.weight = htons(Config.Wccp2.weight); + + memset(&wccp2_identity_info.cache_identity.status, '\0', sizeof(wccp2_identity_info.cache_identity.status)); + + xmemcpy(ptr, &wccp2_identity_info, sizeof(struct wccp2_identity_info_t)); + + service_list_ptr->wccp2_identity_info_ptr = (struct wccp2_identity_info_t *) ptr; + + ptr += sizeof(struct wccp2_identity_info_t); + + /* Add the cache view section */ + wccp2_here_i_am_header.length += sizeof(wccp2_cache_view_header); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_cache_view_header.cache_view_type = htons(WCCP2_WC_VIEW_INFO); + + wccp2_cache_view_header.cache_view_length = htons(sizeof(wccp2_cache_view_header) - 4 + + sizeof(wccp2_cache_view_info) + (wccp2_numrouters * sizeof(wccp2_router_id_element))); + + wccp2_cache_view_header.cache_view_version = htonl(1); + + xmemcpy(ptr, &wccp2_cache_view_header, sizeof(wccp2_cache_view_header)); + + ptr += sizeof(wccp2_cache_view_header); + + /* Add the number of routers to the packet */ + wccp2_here_i_am_header.length += sizeof(service_list_ptr->num_routers); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + service_list_ptr->num_routers = htonl(wccp2_numrouters); + + xmemcpy(ptr, &service_list_ptr->num_routers, sizeof(service_list_ptr->num_routers)); + + ptr += sizeof(service_list_ptr->num_routers); + + /* Add each router. Keep this functionality here to make sure the received_id can be updated in the packet */ + for (s = Config.Wccp2.router; s; s = s->next) { + if (s->s.sin_addr.s_addr != any_addr.s_addr) { + + wccp2_here_i_am_header.length += sizeof(struct wccp2_router_id_element_t); + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + /* Add a pointer to the router list for this router */ + + router_list_ptr->info = (struct wccp2_router_id_element_t *) ptr; + router_list_ptr->info->router_address = s->s.sin_addr; + router_list_ptr->info->received_id = htonl(0); + router_list_ptr->router_sendto_address = s->s.sin_addr; + router_list_ptr->member_change = htonl(0); + + /* Build the next struct */ + + router_list_ptr->next = (wccp2_router_list_t*) xcalloc(1, sizeof(struct wccp2_router_list_t)); + + /* update the pointer */ + router_list_ptr = router_list_ptr->next; + router_list_ptr->next = NULL; + + /* no need to copy memory - we've just set the values directly in the packet above */ + + ptr += sizeof(struct wccp2_router_id_element_t); + } + } + + /* Add the number of caches (0) */ + wccp2_here_i_am_header.length += sizeof(wccp2_cache_view_info.num_caches); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_cache_view_info.num_caches = htonl(0); + + xmemcpy(ptr, &wccp2_cache_view_info.num_caches, sizeof(wccp2_cache_view_info.num_caches)); + + ptr += sizeof(wccp2_cache_view_info.num_caches); + + /* Add the extra capability header */ + wccp2_here_i_am_header.length += sizeof(wccp2_capability_info_header); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_capability_info_header.capability_info_type = htons(WCCP2_CAPABILITY_INFO); + + wccp2_capability_info_header.capability_info_length = htons(3 * sizeof(wccp2_capability_element)); + + xmemcpy(ptr, &wccp2_capability_info_header, sizeof(wccp2_capability_info_header)); + + ptr += sizeof(wccp2_capability_info_header); + + /* Add the forwarding method */ + wccp2_here_i_am_header.length += sizeof(wccp2_capability_element); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_capability_element.capability_type = htons(WCCP2_CAPABILITY_FORWARDING_METHOD); + + wccp2_capability_element.capability_length = htons(sizeof(wccp2_capability_element.capability_value)); + + wccp2_capability_element.capability_value = htonl(Config.Wccp2.forwarding_method); + + xmemcpy(ptr, &wccp2_capability_element, sizeof(wccp2_capability_element)); + + ptr += sizeof(wccp2_capability_element); + + /* Add the assignment method */ + wccp2_here_i_am_header.length += sizeof(wccp2_capability_element); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_capability_element.capability_type = htons(WCCP2_CAPABILITY_ASSIGNMENT_METHOD); + + wccp2_capability_element.capability_length = htons(sizeof(wccp2_capability_element.capability_value)); + + wccp2_capability_element.capability_value = htonl(WCCP2_ASSIGNMENT_METHOD_HASH); + + xmemcpy(ptr, &wccp2_capability_element, sizeof(wccp2_capability_element)); + + ptr += sizeof(wccp2_capability_element); + + /* Add the return method */ + wccp2_here_i_am_header.length += sizeof(wccp2_capability_element); + + assert(wccp2_here_i_am_header.length <= WCCP_RESPONSE_SIZE); + + wccp2_capability_element.capability_type = htons(WCCP2_CAPABILITY_RETURN_METHOD); + + wccp2_capability_element.capability_length = htons(sizeof(wccp2_capability_element.capability_value)); + + wccp2_capability_element.capability_value = htonl(Config.Wccp2.return_method); + + xmemcpy(ptr, &wccp2_capability_element, sizeof(wccp2_capability_element)); + + ptr += sizeof(wccp2_capability_element); + + /* Finally, fix the total length to network order, and copy to the appropriate memory blob */ + wccp2_here_i_am_header.length = htons(wccp2_here_i_am_header.length); + + memcpy(&service_list_ptr->wccp_packet, &wccp2_here_i_am_header, sizeof(wccp2_here_i_am_header)); + + service_list_ptr->wccp_packet_size = ntohs(wccp2_here_i_am_header.length) + sizeof(wccp2_here_i_am_header); + + /* Add the event if everything initialised correctly */ + if (wccp2_numrouters) { + if (!eventFind(wccp2HereIam, NULL)) { + eventAdd("wccp2HereIam", wccp2HereIam, NULL, 1, 1); + } + } + + service_list_ptr = service_list_ptr->next; + } +} + +void +wccp2ConnectionOpen(void) +{ + u_short port = WCCP_PORT; + + struct sockaddr_in router, local, null; + socklen_t local_len, router_len; + + struct wccp2_service_list_t *service_list_ptr; + + struct wccp2_router_list_t *router_list_ptr; + + debug(80, 5) ("wccp2ConnectionOpen: Called\n"); + + if (wccp2_numrouters == 0 || !wccp2_service_list_head) { + debug(80, 2) ("WCCPv2 Disabled.\n"); + return; + } + + theWccp2Connection = comm_open(SOCK_DGRAM, + 0, + Config.Wccp2.address, + port, + COMM_NONBLOCKING, + "WCCPv2 Socket"); + + if (theWccp2Connection < 0) + fatal("Cannot open WCCP Port"); + + commSetSelect(theWccp2Connection, + COMM_SELECT_READ, + wccp2HandleUdp, + NULL, + 0); + + debug(80, 1) ("Accepting WCCPv2 messages on port %d, FD %d.\n", + (int) port, theWccp2Connection); + + debug(80, 1) ("Initialising all WCCPv2 lists\n"); + + /* Initialise all routers on all services */ + memset(&null, 0, sizeof(null)); + + null.sin_family = AF_UNSPEC; + + service_list_ptr = wccp2_service_list_head; + + while (service_list_ptr != NULL) { + for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) { + router_len = sizeof(router); + memset(&router, '\0', router_len); + router.sin_family = AF_INET; + router.sin_port = htons(port); + router.sin_addr = router_list_ptr->router_sendto_address; + + if (connect(theWccp2Connection, (struct sockaddr *) &router, router_len)) + fatal("Unable to connect WCCP out socket"); + + local_len = sizeof(local); + + memset(&local, '\0', local_len); + + if (getsockname(theWccp2Connection, (struct sockaddr *) &local, &local_len)) + fatal("Unable to getsockname on WCCP out socket"); + + router_list_ptr->local_ip = local.sin_addr; + + /* Disconnect the sending socket. Note: FreeBSD returns error + * but disconnects anyway so we have to just assume it worked + */ + if (wccp2_numrouters > 1) + + connect(theWccp2Connection, (struct sockaddr *) &null, router_len); + } + + service_list_ptr = service_list_ptr->next; + } + + wccp2_connected = 1; +} + +void +wccp2ConnectionClose(void) +{ + + struct wccp2_service_list_t *service_list_ptr; + + struct wccp2_service_list_t *service_list_ptr_next; + + struct wccp2_router_list_t *router_list_ptr; + + struct wccp2_router_list_t *router_list_next; + + struct wccp2_cache_list_t *cache_list_ptr; + + struct wccp2_cache_list_t *cache_list_ptr_next; + + if (wccp2_connected == 0) { + return; + } + + if (theWccp2Connection > -1) { + debug(80, 1) ("FD %d Closing WCCP socket\n", theWccp2Connection); + comm_close(theWccp2Connection); + theWccp2Connection = -1; + } + + /* for each router on each service send a packet */ + service_list_ptr = wccp2_service_list_head; + + while (service_list_ptr != NULL) { + for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr != NULL; router_list_ptr = router_list_next) { + for (cache_list_ptr = &router_list_ptr->cache_list_head; cache_list_ptr; cache_list_ptr = cache_list_ptr_next) { + cache_list_ptr_next = cache_list_ptr->next; + + if (cache_list_ptr != &router_list_ptr->cache_list_head) { + xfree(cache_list_ptr); + } else { + + memset(cache_list_ptr, '\0', sizeof(struct wccp2_cache_list_t)); + } + } + + router_list_next = router_list_ptr->next; + + if (router_list_ptr != &service_list_ptr->router_list_head) { + xfree(router_list_ptr); + } else { + + memset(router_list_ptr, '\0', sizeof(struct wccp2_router_list_t)); + } + } + + service_list_ptr_next = service_list_ptr->next; + xfree(service_list_ptr); + service_list_ptr = service_list_ptr_next; + } + + wccp2_service_list_head = NULL; + eventDelete(wccp2HereIam, NULL); + eventDelete(wccp2AssignBuckets, NULL); + eventDelete(wccp2HereIam, NULL); + wccp2_connected = 0; +} + +/* + * Functions for handling the requests. + */ + +/* + * Accept the UDP packet + */ +static void +wccp2HandleUdp(int sock, void *not_used) +{ + + struct wccp2_service_list_t *service_list_ptr; + + struct wccp2_router_list_t *router_list_ptr; + + struct wccp2_cache_list_t *cache_list_ptr; + + struct wccp2_cache_list_t *cache_list_ptr_next; + + /* These structs form the parts of the packet */ + + struct wccp2_item_header_t *header = NULL; + + struct wccp2_security_none_t *security_info = NULL; + + struct wccp2_service_info_t *service_info = NULL; + + struct router_identity_info_t *router_identity_info = NULL; + + struct router_view_t *router_view_header = NULL; + + struct wccp2_cache_identity_info_t *cache_identity = NULL; + + struct wccp2_capability_info_header_t *router_capability_header = NULL; + + struct wccp2_capability_element_t *router_capability_element; + + struct sockaddr_in from; + + struct IN_ADDR cache_address; + socklen_t from_len; + int len, found; + short int data_length, offset; + uint32_t tmp; + char *ptr; + int num_caches; + + debug(80, 6) ("wccp2HandleUdp: Called.\n"); + + commSetSelect(sock, COMM_SELECT_READ, wccp2HandleUdp, NULL, 0); + + from_len = sizeof(struct sockaddr_in); + memset(&from, '\0', from_len); + + len = comm_udp_recvfrom(sock, + &wccp2_i_see_you, + WCCP_RESPONSE_SIZE, + 0, + + (struct sockaddr *) &from, + &from_len); + + if (len < 0) + return; + + if (ntohs(wccp2_i_see_you.version) != WCCP2_VERSION) + return; + + if (ntohl(wccp2_i_see_you.type) != WCCP2_I_SEE_YOU) + return; + + debug(80, 3) ("Incoming WCCPv2 I_SEE_YOU length %d.\n", ntohs(wccp2_i_see_you.length)); + + /* Record the total data length */ + data_length = ntohs(wccp2_i_see_you.length); + + offset = 0; + + if (data_length > len) { + debug(80, 1) ("ERROR: Malformed WCCPv2 packet claiming it's bigger than received data\n"); + return; + } + + /* Go through the data structure */ + while (data_length > offset) { + + header = (struct wccp2_item_header_t *) &wccp2_i_see_you.data[offset]; + + switch (ntohs(header->type)) { + + case WCCP2_SECURITY_INFO: + + if (security_info != NULL) { + debug(80, 1) ("Duplicate security definition\n"); + return; + } + + security_info = (struct wccp2_security_none_t *) &wccp2_i_see_you.data[offset]; + break; + + case WCCP2_SERVICE_INFO: + + if (service_info != NULL) { + debug(80, 1) ("Duplicate service_info definition\n"); + return; + } + + service_info = (struct wccp2_service_info_t *) &wccp2_i_see_you.data[offset]; + break; + + case WCCP2_ROUTER_ID_INFO: + + if (router_identity_info != NULL) { + debug(80, 1) ("Duplicate router_identity_info definition\n"); + return; + } + + router_identity_info = (struct router_identity_info_t *) &wccp2_i_see_you.data[offset]; + break; + + case WCCP2_RTR_VIEW_INFO: + + if (router_view_header != NULL) { + debug(80, 1) ("Duplicate router_view definition\n"); + return; + } + + router_view_header = (struct router_view_t *) &wccp2_i_see_you.data[offset]; + break; + + case WCCP2_CAPABILITY_INFO: + + if (router_capability_header != NULL) { + debug(80, 1) ("Duplicate router_capability definition\n"); + return; + } + + router_capability_header = (struct wccp2_capability_info_header_t *) &wccp2_i_see_you.data[offset]; + break; + + default: + debug(80, 1) ("Unknown record type in WCCPv2 Packet (%d).\n", + ntohs(header->type)); + } + + offset += sizeof(struct wccp2_item_header_t); + offset += ntohs(header->length); + + if (offset > data_length) { + debug(80, 1) ("Error: WCCPv2 packet tried to tell us there is data beyond the end of the packet\n"); + return; + } + } + + if ((security_info == NULL) || (service_info == NULL) || (router_identity_info == NULL) || (router_view_header == NULL)) { + debug(80, 1) ("Incomplete WCCPv2 Packet\n"); + return; + } + + debug(80, 5) ("Complete packet received\n"); + + /* Check that the service in the packet is configured on this router */ + service_list_ptr = wccp2_service_list_head; + + while (service_list_ptr != NULL) { + if (service_info->service_id == service_list_ptr->service_info->service_id) { + break; + } + + service_list_ptr = service_list_ptr->next; + } + + if (service_list_ptr == NULL) { + debug(80, 1) ("WCCPv2 Unknown service received from router (%d)\n", service_info->service_id); + return; + } + + if (ntohl(security_info->security_option) != ntohl(service_list_ptr->security_info->security_option)) { + debugs(80, 1, "Invalid security option in WCCPv2 Packet (" << ntohl(security_info->security_option) << " vs " << ntohl(service_list_ptr->security_info->security_option) << ")."); + return; + } + + if (!wccp2_check_security(service_list_ptr, (char *) security_info, (char *) &wccp2_i_see_you, len)) { + debug(80, 1) ("Received WCCPv2 Packet failed authentication\n"); + return; + } + + /* Check that the router address is configured on this router */ + for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) { + if (router_list_ptr->router_sendto_address.s_addr == from.sin_addr.s_addr) + break; + } + + if (router_list_ptr->next == NULL) { + debug(80, 1) ("WCCPv2 Packet received from unknown router\n"); + return; + } + + /* Set the router id */ + router_list_ptr->info->router_address = router_identity_info->router_id_element.router_address; + + /* Increment the received id in the packet */ + if (ntohl(router_list_ptr->info->received_id) != ntohl(router_identity_info->router_id_element.received_id)) { + debugs(80, 3, "Incoming WCCP2_I_SEE_YOU Received ID old=" << ntohl(router_list_ptr->info->received_id) << " new=" << ntohl(router_identity_info->router_id_element.received_id) << "."); + router_list_ptr->info->received_id = router_identity_info->router_id_element.received_id; + } + + /* TODO: check return/forwarding methods */ + if (router_capability_header == NULL) { + if ((Config.Wccp2.return_method != WCCP2_PACKET_RETURN_METHOD_GRE) || (Config.Wccp2.forwarding_method != WCCP2_FORWARDING_METHOD_GRE)) { + debug(80, 1) ("wccp2HandleUdp: fatal error - A WCCP router does not support the forwarding method specified, only GRE supported\n"); + wccp2ConnectionClose(); + return; + } + } else { + + char *end = ((char *) router_capability_header) + sizeof(*router_capability_header) + ntohs(router_capability_header->capability_info_length) - sizeof(struct wccp2_capability_info_header_t); + + router_capability_element = (struct wccp2_capability_element_t *) (((char *) router_capability_header) + sizeof(*router_capability_header)); + + while ((char *) router_capability_element <= end) { + + switch (ntohs(router_capability_element->capability_type)) { + + case WCCP2_CAPABILITY_FORWARDING_METHOD: + + if (!(ntohl(router_capability_element->capability_value) & Config.Wccp2.forwarding_method)) { + debugs(80, 1, "wccp2HandleUdp: fatal error - A WCCP router has specified a different forwarding method " << ntohl(router_capability_element->capability_value) << ", expected " << Config.Wccp2.forwarding_method); + wccp2ConnectionClose(); + return; + } + + break; + + case WCCP2_CAPABILITY_ASSIGNMENT_METHOD: + + if (!(ntohl(router_capability_element->capability_value) & WCCP2_ASSIGNMENT_METHOD_HASH)) { + debugs(80, 1, "wccp2HandleUdp: fatal error - A WCCP router has specified a different assignment method " << ntohl(router_capability_element->capability_value) << ", expected "<< WCCP2_ASSIGNMENT_METHOD_HASH); + wccp2ConnectionClose(); + return; + } + + break; + + case WCCP2_CAPABILITY_RETURN_METHOD: + + if (!(ntohl(router_capability_element->capability_value) & Config.Wccp2.return_method)) { + debugs(80, 1, "wccp2HandleUdp: fatal error - A WCCP router has specified a different return method " << ntohl(router_capability_element->capability_value) << ", expected " << Config.Wccp2.return_method); + wccp2ConnectionClose(); + return; + } + + break; + + default: + debug(80, 1) ("Unknown capability type in WCCPv2 Packet (%d).\n", + ntohs(router_capability_element->capability_type)); + } + + router_capability_element = (struct wccp2_capability_element_t *) (((char *) router_capability_element) + sizeof(struct wccp2_capability_element_header_t) + ntohs(router_capability_element->capability_length)); + } + } + + debug(80, 5) ("Cleaning out cache list\n"); + /* clean out the old cache list */ + + for (cache_list_ptr = &router_list_ptr->cache_list_head; cache_list_ptr; cache_list_ptr = cache_list_ptr_next) { + cache_list_ptr_next = cache_list_ptr->next; + + if (cache_list_ptr != &router_list_ptr->cache_list_head) { + xfree(cache_list_ptr); + } + } + + router_list_ptr->num_caches = htonl(0); + num_caches = 0; + + /* Check to see if we're the master cache and update the cache list */ + found = 0; + service_list_ptr->lowest_ip = 1; + cache_list_ptr = &router_list_ptr->cache_list_head; + + /* to find the list of caches, we start at the end of the router view header */ + + ptr = (char *) (router_view_header) + sizeof(struct router_view_t); + + /* Then we read the number of routers */ + memcpy(&tmp, ptr, sizeof(tmp)); + + /* skip the number plus all the ip's */ + + ptr += sizeof(tmp) + (ntohl(tmp) * sizeof(struct IN_ADDR)); + + /* Then read the number of caches */ + memcpy(&tmp, ptr, sizeof(tmp)); + ptr += sizeof(tmp); + + if (ntohl(tmp) != 0) { + /* search through the list of received-from ip addresses */ + + for (num_caches = 0; num_caches < (int) ntohl(tmp); num_caches++) { + /* Get a copy of the ip */ + + cache_identity = (struct wccp2_cache_identity_info_t *) ptr; + + ptr += sizeof(struct wccp2_cache_identity_info_t); + + memcpy(&cache_address, &cache_identity->addr, sizeof(struct IN_ADDR)); + + /* Update the cache list */ + cache_list_ptr->cache_ip = cache_address; + cache_list_ptr->weight = ntohs(cache_identity->weight); + cache_list_ptr->next = (wccp2_cache_list_t*) xcalloc(1, sizeof(struct wccp2_cache_list_t)); + cache_list_ptr = cache_list_ptr->next; + cache_list_ptr->next = NULL; + + debug(80, 5) ("checking cache list: (%x:%x)\n", cache_address.s_addr, router_list_ptr->local_ip.s_addr); + /* Check to see if it's the master, or us */ + + if (cache_address.s_addr == router_list_ptr->local_ip.s_addr) { + found = 1; + } + + if (cache_address.s_addr < router_list_ptr->local_ip.s_addr) { + service_list_ptr->lowest_ip = 0; + } + } + } else { + + /* Update the cache list */ + cache_list_ptr->cache_ip = router_list_ptr->local_ip; + + cache_list_ptr->next = (wccp2_cache_list_t*) xcalloc(1, sizeof(struct wccp2_cache_list_t)); + cache_list_ptr = cache_list_ptr->next; + cache_list_ptr->next = NULL; + + service_list_ptr->lowest_ip = 0; + found = 1; + num_caches = 1; + } + + router_list_ptr->num_caches = htonl(num_caches); + + if ((found == 1) && (service_list_ptr->lowest_ip == 1)) { + if (ntohl(router_view_header->change_number) != router_list_ptr->member_change) { + debug(80, 4) ("Change detected - queueing up new assignment\n"); + router_list_ptr->member_change = ntohl(router_view_header->change_number); + eventDelete(wccp2AssignBuckets, NULL); + eventAdd("wccp2AssignBuckets", wccp2AssignBuckets, NULL, 15.0, 1); + } + } else { + debug(80, 5) ("I am not the lowest ip cache - not assigning buckets\n"); + } +} + +static void +wccp2HereIam(void *voidnotused) +{ + + struct wccp2_service_list_t *service_list_ptr; + + struct wccp2_router_list_t *router_list_ptr; + + struct sockaddr_in router; + int router_len; + u_short port = WCCP_PORT; + + debug(80, 6) ("wccp2HereIam: Called\n"); + + if (wccp2_connected == 0) { + debug(80, 1) ("wccp2HereIam: wccp2 socket closed. Shutting down WCCP2\n"); + return; + } + + /* Wait if store dirs are rebuilding */ + if (StoreController::store_dirs_rebuilding && Config.Wccp2.rebuildwait) { + eventAdd("wccp2HereIam", wccp2HereIam, NULL, 1.0, 1); + return; + } + + router_len = sizeof(router); + memset(&router, '\0', router_len); + router.sin_family = AF_INET; + router.sin_port = htons(port); + + /* for each router on each service send a packet */ + service_list_ptr = wccp2_service_list_head; + + while (service_list_ptr != NULL) { + debug(80, 5) ("wccp2HereIam: sending to service id %d\n", service_list_ptr->info.service_id); + + for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) { + router.sin_addr = router_list_ptr->router_sendto_address; + + /* Set the cache id (ip) */ + service_list_ptr->wccp2_identity_info_ptr->cache_identity.addr = router_list_ptr->local_ip; + /* Security update, if needed */ + + if (service_list_ptr->wccp2_security_type == WCCP2_MD5_SECURITY) { + wccp2_update_md5_security(service_list_ptr->wccp_password, (char *) service_list_ptr->security_info, service_list_ptr->wccp_packet, service_list_ptr->wccp_packet_size); + } + + debug(80, 3) ("Sending HereIam packet size %d\n", (int) service_list_ptr->wccp_packet_size); + /* Send the packet */ + + if (wccp2_numrouters > 1) { + comm_udp_sendto(theWccp2Connection, + &router, + router_len, + &service_list_ptr->wccp_packet, + service_list_ptr->wccp_packet_size); + } else { + send(theWccp2Connection, + &service_list_ptr->wccp_packet, + service_list_ptr->wccp_packet_size, + 0); + } + } + + service_list_ptr = service_list_ptr->next; + } + + eventAdd("wccp2HereIam", wccp2HereIam, NULL, 10.0, 1); +} + +static void +wccp2AssignBuckets(void *voidnotused) +{ + + struct wccp2_service_list_t *service_list_ptr; + + struct wccp2_router_list_t *router_list_ptr; + + struct wccp2_cache_list_t *cache_list_ptr; + char wccp_packet[WCCP_RESPONSE_SIZE]; + short int offset, saved_offset; + + struct sockaddr_in router; + int router_len; + int bucket_counter; + u_short port = WCCP_PORT; + + /* Packet segments */ + + struct wccp2_here_i_am_header_t *main_header; + + struct wccp2_security_md5_t *security = NULL; + /* service from service struct */ + + struct wccp2_item_header_t *assignment_header; + + struct assignment_key_t *assignment_key; + /* number of routers */ + + struct wccp2_router_assign_element_t *router_assign; + /* number of caches */ + + struct IN_ADDR *cache_address; + char *buckets; + + router_len = sizeof(router); + memset(&router, '\0', router_len); + router.sin_family = AF_INET; + router.sin_port = htons(port); + + /* Start main header - fill in length later */ + offset = 0; + + main_header = (struct wccp2_here_i_am_header_t *) &wccp_packet[offset]; + main_header->type = htonl(WCCP2_REDIRECT_ASSIGN); + main_header->version = htons(WCCP2_VERSION); + + debug(80, 2) ("Running wccp2AssignBuckets\n"); + service_list_ptr = wccp2_service_list_head; + + while (service_list_ptr != NULL) { + /* If we're not the lowest, we don't need to worry */ + + if (service_list_ptr->lowest_ip == 0) { + /* XXX eww */ + service_list_ptr = service_list_ptr->next; + continue; + } + + /* reset the offset */ + + offset = sizeof(struct wccp2_here_i_am_header_t); + + /* build packet header from hereIam packet */ + /* Security info */ + /* XXX this should be made more generic! */ + /* XXX and I hate magic numbers! */ + switch (service_list_ptr->wccp2_security_type) { + + case WCCP2_NO_SECURITY: + + security = (struct wccp2_security_md5_t *) &wccp_packet[offset]; + memcpy(security, service_list_ptr->security_info, 8); + offset += 8; + break; + + case WCCP2_MD5_SECURITY: + + security = (struct wccp2_security_md5_t *) &wccp_packet[offset]; + + memcpy(security, service_list_ptr->security_info, sizeof(struct wccp2_security_md5_t)); + + offset += sizeof(struct wccp2_security_md5_t); + break; + + default: + fatalf("Unknown Wccp2 security type\n"); + } + + /* Service info */ + + memcpy(&wccp_packet[offset], service_list_ptr->service_info, sizeof(struct wccp2_service_info_t)); + + offset += sizeof(struct wccp2_service_info_t); + + /* assignment header - fill in length later */ + + assignment_header = (struct wccp2_item_header_t *) &wccp_packet[offset]; + + assignment_header->type = htons(WCCP2_REDIRECT_ASSIGNMENT); + + offset += sizeof(struct wccp2_item_header_t); + + /* Assignment key - fill in master ip later */ + + assignment_key = (struct assignment_key_t *) &wccp_packet[offset]; + + assignment_key->master_number = htonl(++service_list_ptr->change_num); + + offset += sizeof(struct assignment_key_t); + + /* Number of routers */ + xmemcpy(&wccp_packet[offset], &service_list_ptr->num_routers, sizeof(service_list_ptr->num_routers)); + + offset += sizeof(service_list_ptr->num_routers); + + for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) { + + /* Add routers */ + + router_assign = (struct wccp2_router_assign_element_t *) &wccp_packet[offset]; + router_assign->router_address = router_list_ptr->info->router_address; + router_assign->received_id = router_list_ptr->info->received_id; + router_assign->change_number = htonl(router_list_ptr->member_change); + + offset += sizeof(struct wccp2_router_assign_element_t); + } + + saved_offset = offset; + + for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) { + unsigned long *weight = (unsigned long *)xcalloc(sizeof(*weight), ntohl(router_list_ptr->num_caches)); + unsigned long total_weight = 0; + int num_caches = ntohl(router_list_ptr->num_caches); + + offset = saved_offset; + + /* Number of caches */ + xmemcpy(&wccp_packet[offset], &router_list_ptr->num_caches, sizeof(router_list_ptr->num_caches)); + offset += sizeof(router_list_ptr->num_caches); + + if (num_caches) { + int cache; + for (cache = 0, cache_list_ptr = &router_list_ptr->cache_list_head; cache_list_ptr->next; cache_list_ptr = cache_list_ptr->next, cache++) { + /* add caches */ + + cache_address = (struct IN_ADDR *) &wccp_packet[offset]; + + xmemcpy(cache_address, &cache_list_ptr->cache_ip, sizeof(struct IN_ADDR)); + total_weight += cache_list_ptr->weight << 12; + weight[cache] = cache_list_ptr->weight << 12; + offset += sizeof(struct IN_ADDR); + } + } + + /* Add buckets */ + buckets = (char *) &wccp_packet[offset]; + + memset(buckets, '\0', WCCP_BUCKETS); + + if (num_caches != 0) { + if (total_weight == 0) { + for (bucket_counter = 0; bucket_counter < WCCP_BUCKETS; bucket_counter++) { + buckets[bucket_counter] = (char) (bucket_counter % num_caches); + } + } else { + unsigned long *assigned = (unsigned long *)xcalloc(sizeof(*assigned), num_caches); + unsigned long done = 0; + int cache = -1; + unsigned long per_bucket = total_weight / WCCP_BUCKETS; + for (bucket_counter = 0; bucket_counter < WCCP_BUCKETS; bucket_counter++) { + int n; + unsigned long step; + for (n = num_caches; n; n--) { + cache++; + if (cache >= num_caches) + cache = 0; + if (!weight[cache]) { + n++; + continue; + } + if (assigned[cache] <= done) + break; + } + buckets[bucket_counter] = (char)cache; + step = per_bucket * total_weight / weight[cache]; + assigned[cache] += step; + done += per_bucket; + } + safe_free(assigned); + } + } + offset += (WCCP_BUCKETS * sizeof(char)); + safe_free(weight); + + /* Fill in length */ + + assignment_header->length = htons(sizeof(struct assignment_key_t) + sizeof(service_list_ptr->num_routers) + + + (ntohl(service_list_ptr->num_routers) * sizeof(struct wccp2_router_assign_element_t)) + + + sizeof (router_list_ptr->num_caches) + (ntohl(router_list_ptr->num_caches) * sizeof(struct IN_ADDR)) + + (WCCP_BUCKETS * sizeof(char))); + + /* Fill in assignment key */ + assignment_key->master_ip = router_list_ptr->local_ip; + + /* finish length */ + + main_header->length = htons(offset - sizeof(struct wccp2_here_i_am_header_t)); + + /* set the destination address */ + router.sin_addr = router_list_ptr->router_sendto_address; + + /* Security update, if needed */ + + if (service_list_ptr->wccp2_security_type == WCCP2_MD5_SECURITY) { + wccp2_update_md5_security(service_list_ptr->wccp_password, (char *) security, wccp_packet, offset); + } + + if (ntohl(router_list_ptr->num_caches)) { + /* send packet */ + + if (wccp2_numrouters > 1) { + comm_udp_sendto(theWccp2Connection, + &router, + router_len, + &wccp_packet, + offset); + } else { + send(theWccp2Connection, + &wccp_packet, + offset, + 0); + } + } + } + + service_list_ptr = service_list_ptr->next; + } +} + + +/* + * Configuration option parsing code + */ + +/* + * Format: + * + * wccp2_service {standard|dynamic} {id} (password=password) + */ +void +parse_wccp2_service(void *v) +{ + char *t; + int service = 0; + int service_id = 0; + int security_type = WCCP2_NO_SECURITY; + char wccp_password[WCCP2_PASSWORD_LEN + 1]; + + if (wccp2_connected == 1) { + debug(80, 1) ("WCCPv2: Somehow reparsing the configuration " + "without having shut down WCCP! Try reloading squid again.\n"); + return; + } + + /* Snarf the type */ + if ((t = strtok(NULL, w_space)) == NULL) { + debug(80, 0) ("wccp2ParseServiceInfo: missing service info type (standard|dynamic)\n"); + self_destruct(); + } + + if (strcmp(t, "standard") == 0) { + service = WCCP2_SERVICE_STANDARD; + } else if (strcmp(t, "dynamic") == 0) { + service = WCCP2_SERVICE_DYNAMIC; + } else { + debug(80, 0) ("wccp2ParseServiceInfo: bad service info type (expected standard|dynamic, got %s)\n", t); + self_destruct(); + } + + /* Snarf the ID */ + service_id = GetInteger(); + + if (service_id < 0 || service_id > 255) { + debug(80, 0) ("wccp2ParseServiceInfo: service info id %d is out of range (0..255)\n", service_id); + self_destruct(); + } + + memset(wccp_password, 0, sizeof(wccp_password)); + /* Handle password, if any */ + + if ((t = strtok(NULL, w_space)) != NULL) { + if (strncmp(t, "password=", 9) == 0) { + security_type = WCCP2_MD5_SECURITY; + strncpy(wccp_password, t + 9, WCCP2_PASSWORD_LEN); + } + } + + /* Create a placeholder service record */ + wccp2_add_service_list(service, service_id, 0, 0, 0, empty_portlist, security_type, wccp_password); +} + +void +dump_wccp2_service(StoreEntry * e, const char *label, void *v) +{ + + struct wccp2_service_list_t *srv; + srv = wccp2_service_list_head; + + while (srv != NULL) { + debug(80, 3) ("dump_wccp2_service: id %d, type %d\n", srv->info.service_id, srv->info.service); + storeAppendPrintf(e, "%s %s %d", label, + (srv->info.service == WCCP2_SERVICE_DYNAMIC) ? "dynamic" : "standard", + srv->info.service_id); + + if (srv->wccp2_security_type == WCCP2_MD5_SECURITY) { + storeAppendPrintf(e, " %s", srv->wccp_password); + } + + srv = srv->next; + } +} + +void +free_wccp2_service(void *v) +{} + +int +check_null_wccp2_service(void *v) +{ + return !wccp2_service_list_head; +} + +/* + * Format: + * + * wccp2_service_info {id} stuff.. + * + * Where stuff is: + * + * + flags=flag,flag,flag.. + * + proto=protocol (tcp|udp) + * + ports=port,port,port (up to a max of 8) + * + priority=priority (0->255) + * + * The flags here are: + * src_ip_hash, dst_ip_hash, source_port_hash, dst_port_hash, ports_defined, + * ports_source, src_ip_alt_hash, dst_ip_alt_hash, src_port_alt_hash, dst_port_alt_hash + */ +static int +parse_wccp2_service_flags(char *flags) +{ + char *tmp, *tmp2; + char *flag; + int retflag = 0; + + if (!flags) { + return 0; + } + + tmp = xstrdup(flags); + tmp2 = tmp; + + flag = strsep(&tmp2, ","); + + while (flag) { + if (strcmp(flag, "src_ip_hash") == 0) { + retflag |= WCCP2_SERVICE_SRC_IP_HASH; + } else if (strcmp(flag, "dst_ip_hash") == 0) { + retflag |= WCCP2_SERVICE_DST_IP_HASH; + } else if (strcmp(flag, "source_port_hash") == 0) { + retflag |= WCCP2_SERVICE_SOURCE_PORT_HASH; + } else if (strcmp(flag, "dst_port_hash") == 0) { + retflag |= WCCP2_SERVICE_DST_PORT_HASH; + } else if (strcmp(flag, "ports_source") == 0) { + retflag |= WCCP2_SERVICE_PORTS_SOURCE; + } else if (strcmp(flag, "src_ip_alt_hash") == 0) { + retflag |= WCCP2_SERVICE_SRC_IP_ALT_HASH; + } else if (strcmp(flag, "dst_ip_alt_hash") == 0) { + retflag |= WCCP2_SERVICE_DST_IP_ALT_HASH; + } else if (strcmp(flag, "src_port_alt_hash") == 0) { + retflag |= WCCP2_SERVICE_SRC_PORT_ALT_HASH; + } else if (strcmp(flag, "dst_port_alt_hash") == 0) { + retflag |= WCCP2_SERVICE_DST_PORT_ALT_HASH; + } else { + fatalf("Unknown wccp2 service flag: %s\n", flag); + } + + flag = strsep(&tmp2, ","); + } + + xfree(tmp); + return retflag; +} + +static void +parse_wccp2_service_ports(char *options, int portlist[]) +{ + int i = 0; + int p; + char *tmp, *tmp2, *port, *end; + + if (!options) { + return; + } + + tmp = xstrdup(options); + tmp2 = tmp; + + port = strsep(&tmp2, ","); + + while (port && i < WCCP2_NUMPORTS) { + p = strtol(port, &end, 0); + + if (p < 1 || p > 65535) { + fatalf("parse_wccp2_service_ports: port value '%s' isn't valid (1..65535)\n", port); + } + + portlist[i] = p; + i++; + port = strsep(&tmp2, ","); + } + + if (i == 8) { + fatalf("parse_wccp2_service_ports: too many ports (maximum: 8) in list '%s'\n", options); + } + + xfree(tmp); +} + +void +parse_wccp2_service_info(void *v) +{ + char *t, *end; + int service_id = 0; + int flags = 0; + int portlist[WCCP2_NUMPORTS]; + int protocol = -1; /* IPPROTO_TCP | IPPROTO_UDP */ + + struct wccp2_service_list_t *srv; + int priority = -1; + + if (wccp2_connected == 1) { + debug(80, 1) ("WCCPv2: Somehow reparsing the configuration " + "without having shut down WCCP! Try reloading squid again.\n"); + return; + } + + debug(80, 5) ("parse_wccp2_service_info: called\n"); + memset(portlist, 0, sizeof(portlist)); + /* First argument: id */ + service_id = GetInteger(); + + if (service_id < 0 || service_id > 255) { + debug(80, 1) ("parse_wccp2_service_info: invalid service id %d (must be between 0 .. 255)\n", service_id); + self_destruct(); + } + + /* Next: find the (hopefully!) existing service */ + srv = wccp2_get_service_by_id(WCCP2_SERVICE_DYNAMIC, service_id); + + if (srv == NULL) { + fatalf("parse_wccp2_service_info: unknown dynamic service id %d: you need to define it using wccp2_service (and make sure you wish to configure it as a dynamic service.)\n", service_id); + } + + /* Next: loop until we don't have any more tokens */ + while ((t = strtok(NULL, w_space)) != NULL) { + if (strncmp(t, "flags=", 6) == 0) { + /* XXX eww, string pointer math */ + flags = parse_wccp2_service_flags(t + 6); + } else if (strncmp(t, "ports=", 6) == 0) { + parse_wccp2_service_ports(t + 6, portlist); + flags |= WCCP2_SERVICE_PORTS_DEFINED; + } else if (strncmp(t, "protocol=tcp", 12) == 0) { + protocol = IPPROTO_TCP; + } else if (strncmp(t, "protocol=udp", 12) == 0) { + protocol = IPPROTO_UDP; + } else if (strncmp(t, "protocol=", 9) == 0) { + fatalf("parse_wccp2_service_info: id %d: unknown protocol (%s) - must be tcp or udp!\n", service_id, t); + } else if (strncmp(t, "priority=", 9) == 0) { + priority = strtol(t + 9, &end, 0); + + if (priority < 0 || priority > 255) { + fatalf("parse_wccp2_service_info: id %d: %s out of range (0..255)!\n", service_id, t); + } + } else { + fatalf("parse_wccp2_service_info: id %d: unknown option '%s'\n", service_id, t); + } + } + + /* Check everything is set */ + if (priority == -1) { + fatalf("parse_wccp2_service_info: service %d: no priority defined (valid: 0..255)!\n", service_id); + } + + if (protocol == -1) { + fatalf("parse_wccp2_service_info: service %d: no protocol defined (valid: tcp or udp)!\n", service_id); + } + + if (!(flags & WCCP2_SERVICE_PORTS_DEFINED)) { + fatalf("parse_wccp2_service_info: service %d: no ports defined!\n", service_id); + } + + /* rightio! now we can update */ + wccp2_update_service(srv, WCCP2_SERVICE_DYNAMIC, service_id, priority, + protocol, flags, portlist); + + /* Done! */ +} + +void +dump_wccp2_service_info(StoreEntry * e, const char *label, void *v) +{ + char comma; + + struct wccp2_service_list_t *srv; + int flags; + srv = wccp2_service_list_head; + + while (srv != NULL) { + debug(80, 3) ("dump_wccp2_service_info: id %d (type %d)\n", srv->info.service_id, srv->info.service); + + /* We don't need to spit out information for standard services */ + + if (srv->info.service == WCCP2_SERVICE_STANDARD) { + debug(80, 3) ("dump_wccp2_service_info: id %d: standard service, not dumping info\n", srv->info.service_id); + /* XXX eww */ + srv = srv->next; + continue; + } + + storeAppendPrintf(e, "%s %d", label, srv->info.service_id); + + /* priority */ + storeAppendPrintf(e, " priority=%d", srv->info.service_priority); + + /* flags */ + flags = ntohl(srv->info.service_flags); + + if (flags != 0) { + comma = 0; + storeAppendPrintf(e, " flags="); + + if (flags & WCCP2_SERVICE_SRC_IP_HASH) { + storeAppendPrintf(e, "%ssrc_ip_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_DST_IP_HASH) { + storeAppendPrintf(e, "%sdst_ip_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_SOURCE_PORT_HASH) { + storeAppendPrintf(e, "%ssource_port_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_DST_PORT_HASH) { + storeAppendPrintf(e, "%sdst_port_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_PORTS_DEFINED) { + storeAppendPrintf(e, "%sports_defined", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_PORTS_SOURCE) { + storeAppendPrintf(e, "%sports_source", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_SRC_IP_ALT_HASH) { + storeAppendPrintf(e, "%ssrc_ip_alt_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_DST_IP_ALT_HASH) { + storeAppendPrintf(e, "%ssrc_ip_alt_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_SRC_PORT_ALT_HASH) { + storeAppendPrintf(e, "%ssrc_port_alt_hash", comma ? "," : ""); + comma = 1; + } + + if (flags & WCCP2_SERVICE_DST_PORT_ALT_HASH) { + storeAppendPrintf(e, "%sdst_port_alt_hash", comma ? "," : ""); + comma = 1; + } + } + + /* ports */ + comma = 0; + + if (srv->info.port0 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : " ports=", ntohs(srv->info.port0)); + comma = 1; + } + + if (srv->info.port1 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port1)); + comma = 1; + } + + if (srv->info.port2 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port2)); + comma = 1; + } + + if (srv->info.port3 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port3)); + comma = 1; + } + + if (srv->info.port4 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port4)); + comma = 1; + } + + if (srv->info.port5 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port5)); + comma = 1; + } + + if (srv->info.port6 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port6)); + comma = 1; + } + + if (srv->info.port7 != 0) { + storeAppendPrintf(e, "%s%d", comma ? "," : "ports=", ntohs(srv->info.port7)); + comma = 1; + } + + /* protocol */ + storeAppendPrintf(e, " protocol=%s", (srv->info.service_protocol == IPPROTO_TCP) ? "tcp" : "udp"); + + storeAppendPrintf(e, "\n"); + + srv = srv->next; + } +} + +void +free_wccp2_service_info(void *v) +{} + +#endif /* USE_WCCPv2 */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/wordlist.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,112 @@ + +/* + * $Id: wordlist.cc,v 1.1.12.2 2006/09/29 23:16:02 dwsquid Exp $ + * + * DEBUG: section 3 Configuration File Parsing + * AUTHOR: Harvest Derived + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "wordlist.h" +#include "MemBuf.h" + +void +wordlistDestroy(wordlist ** list) +{ + wordlist *w = NULL; + + while ((w = *list) != NULL) { + *list = w->next; + safe_free(w->key); + delete w; + } + + *list = NULL; +} + +const char * +wordlistAdd(wordlist ** list, const char *key) +{ + while (*list) + list = &(*list)->next; + + *list = new wordlist; + + (*list)->key = xstrdup(key); + + (*list)->next = NULL; + + return (*list)->key; +} + +void +wordlistJoin(wordlist ** list, wordlist ** wl) +{ + while (*list) + list = &(*list)->next; + + *list = *wl; + + *wl = NULL; +} + +void +wordlistAddWl(wordlist ** list, wordlist * wl) +{ + while (*list) + list = &(*list)->next; + + for (; wl; wl = wl->next, list = &(*list)->next) { + *list = new wordlist(); + (*list)->key = xstrdup(wl->key); + (*list)->next = NULL; + } +} + +void +wordlistCat(const wordlist * w, MemBuf * mb) +{ + while (NULL != w) { + mb->Printf("%s\n", w->key); + w = w->next; + } +} + +wordlist * +wordlistDup(const wordlist * w) +{ + wordlist *D = NULL; + + while (NULL != w) { + wordlistAdd(&D, w->key); + w = w->next; + } + + return D; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/wordlist.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,57 @@ + +/* + * $Id: wordlist.h,v 1.1.12.2 2006/09/29 23:16:02 dwsquid Exp $ + * + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_WORDLIST_H +#define SQUID_WORDLIST_H + +#include "squid.h" +#include "MemPool.h" + +class wordlist +{ + +public: + MEMPROXY_CLASS(wordlist); + char *key; + wordlist *next; +}; + +MEMPROXY_CLASS_INLINE(wordlist); + +SQUIDCEXTERN const char *wordlistAdd(wordlist **, const char *); +SQUIDCEXTERN void wordlistAddWl(wordlist **, wordlist *); +SQUIDCEXTERN void wordlistJoin(wordlist **, wordlist **); +SQUIDCEXTERN wordlist *wordlistDup(const wordlist *); +SQUIDCEXTERN void wordlistDestroy(wordlist **); + +#endif /* SQUID_WORDLIST_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,3 @@ +.deps +.dirstamp +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/AIO/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,3 @@ +.deps +.dirstamp +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/AIO/aio_win32.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,362 @@ + +/* + * $Id: aio_win32.cc,v 1.3.4.2 2006/09/29 23:16:03 dwsquid Exp $ + * + * DEBUG: section 81 aio_xxx() POSIX emulation on Windows + * AUTHOR: Guido Serassio + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "comm.h" +#include "aio_win32.h" + +#ifdef _SQUID_WIN32_ +VOID CALLBACK IoCompletionRoutine(DWORD dwErrorCode, + DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) +{ + + struct aiocb *aiocbp = (struct aiocb *) lpOverlapped->hEvent; + + aiocbp->aio_sigevent.sigev_notify = dwErrorCode; + aiocbp->aio_sigevent.sigev_signo = dwNumberOfBytesTransfered; + debug(81,7) ("AIO operation complete: errorcode=%ld nbytes=%ld\n", dwErrorCode, dwNumberOfBytesTransfered); + xfree(lpOverlapped); +} + + +int aio_read(struct aiocb *aiocbp) +{ + LPOVERLAPPED Overlapped; + BOOL IoOperationStatus; + + /* Allocate an overlapped structure. */ + Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); + + if (!Overlapped) + { + errno = ENOMEM; + return -1; + } + +#if _FILE_OFFSET_BITS==64 +#ifdef __GNUC__ + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000LL); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000LL); + +#else + + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000); + +#endif +#else + + Overlapped->Offset = aiocbp->aio_offset; + + Overlapped->OffsetHigh = 0; + +#endif + + Overlapped->hEvent = aiocbp; + + aiocbp->aio_sigevent.sigev_notify = EINPROGRESS; + + aiocbp->aio_sigevent.sigev_signo = -1; + + IoOperationStatus = ReadFileEx((HANDLE)_get_osfhandle(aiocbp->aio_fildes), + aiocbp->aio_buf, + aiocbp->aio_nbytes, + Overlapped, + IoCompletionRoutine); + + /* Test to see if the I/O was queued successfully. */ + if (!IoOperationStatus) + { + errno = GetLastError(); + debug(81,1) ("aio_read: GetLastError=%i\n", errno); + return -1; + } + + /* The I/O queued successfully. Go back into the + alertable wait for I/O completion or for + more I/O requests. */ + return 0; +} + + +int aio_read64(struct aiocb64 *aiocbp) +{ + LPOVERLAPPED Overlapped; + BOOL IoOperationStatus; + + /* Allocate an overlapped structure. */ + Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); + + if (!Overlapped) + { + errno = ENOMEM; + return -1; + } + +#ifdef __GNUC__ + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000LL); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000LL); + +#else + + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000); + +#endif + + Overlapped->hEvent = aiocbp; + + aiocbp->aio_sigevent.sigev_notify = EINPROGRESS; + + aiocbp->aio_sigevent.sigev_signo = -1; + + IoOperationStatus = ReadFileEx((HANDLE)_get_osfhandle(aiocbp->aio_fildes), + aiocbp->aio_buf, + aiocbp->aio_nbytes, + Overlapped, + IoCompletionRoutine); + + /* Test to see if the I/O was queued successfully. */ + if (!IoOperationStatus) + { + errno = GetLastError(); + debug(81,1) ("aio_read: GetLastError=%i\n", errno); + return -1; + } + + /* The I/O queued successfully. Go back into the + alertable wait for I/O completion or for + more I/O requests. */ + return 0; +} + + +int aio_write(struct aiocb *aiocbp) +{ + LPOVERLAPPED Overlapped; + BOOL IoOperationStatus; + + /* Allocate an overlapped structure. */ + Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); + + if (!Overlapped) + { + errno = ENOMEM; + return -1; + } + +#if _FILE_OFFSET_BITS==64 +#ifdef __GNUC__ + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000LL); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000LL); + +#else + + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000); + +#endif +#else + + Overlapped->Offset = aiocbp->aio_offset; + + Overlapped->OffsetHigh = 0; + +#endif + + Overlapped->hEvent = aiocbp; + + aiocbp->aio_sigevent.sigev_notify = EINPROGRESS; + + aiocbp->aio_sigevent.sigev_signo = -1; + + IoOperationStatus = WriteFileEx((HANDLE)_get_osfhandle(aiocbp->aio_fildes), + aiocbp->aio_buf, + aiocbp->aio_nbytes, + Overlapped, + IoCompletionRoutine); + + /* Test to see if the I/O was queued successfully. */ + if (!IoOperationStatus) + { + errno = GetLastError(); + debug(81,1) ("aio_write: GetLastError=%i\n", errno); + return -1; + } + + /* The I/O queued successfully. Go back into the + alertable wait for I/O completion or for + more I/O requests. */ + return 0; +} + + +int aio_write64(struct aiocb64 *aiocbp) +{ + LPOVERLAPPED Overlapped; + BOOL IoOperationStatus; + + /* Allocate an overlapped structure. */ + Overlapped = (LPOVERLAPPED) xcalloc(1, sizeof(OVERLAPPED)); + + if (!Overlapped) + { + errno = ENOMEM; + return -1; + } + +#ifdef __GNUC__ + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000LL); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000LL); + +#else + + Overlapped->Offset = (DWORD) (aiocbp->aio_offset % 0x100000000); + + Overlapped->OffsetHigh = (DWORD) (aiocbp->aio_offset / 0x100000000); + +#endif + + Overlapped->hEvent = aiocbp; + + aiocbp->aio_sigevent.sigev_notify = EINPROGRESS; + + aiocbp->aio_sigevent.sigev_signo = -1; + + IoOperationStatus = WriteFileEx((HANDLE)_get_osfhandle(aiocbp->aio_fildes), + aiocbp->aio_buf, + aiocbp->aio_nbytes, + Overlapped, + IoCompletionRoutine); + + /* Test to see if the I/O was queued successfully. */ + if (!IoOperationStatus) + { + errno = GetLastError(); + debug(81,1) ("aio_write: GetLastError=%i\n", errno); + return -1; + } + + /* The I/O queued successfully. Go back into the + alertable wait for I/O completion or for + more I/O requests. */ + return 0; +} + + +int aio_error(const struct aiocb * aiocbp) +{ + return aiocbp->aio_sigevent.sigev_notify; +} + + +int aio_error64(const struct aiocb64 * aiocbp) +{ + return aiocbp->aio_sigevent.sigev_notify; +} + + +int aio_open(const char *path, int mode) +{ + HANDLE hndl; + DWORD dwCreationDisposition; + DWORD dwDesiredAccess; + int fd; + + if (mode & O_WRONLY) + mode |= O_APPEND; + + mode |= O_BINARY; + + errno = 0; + + if (mode & O_WRONLY) + dwDesiredAccess = GENERIC_WRITE; + else + dwDesiredAccess = (mode & O_RDONLY) ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE; + + if (mode & O_TRUNC) + dwCreationDisposition = CREATE_ALWAYS; + else + dwCreationDisposition = (mode & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING; + + if ((hndl = CreateFile(path, /* file name */ + dwDesiredAccess, /* access mode */ + 0, /* share mode */ + NULL, /* SD */ + dwCreationDisposition, /* how to create */ + FILE_FLAG_OVERLAPPED, /* file attributes */ + NULL /* handle to template file */ + )) != INVALID_HANDLE_VALUE) { + statCounter.syscalls.disk.opens++; + fd = _open_osfhandle((long) hndl, 0); + commSetCloseOnExec(fd); + fd_open(fd, FD_FILE, path); + } else { + errno = GetLastError(); + fd = DISK_ERROR; + } + + return fd; +} + + +void aio_close(int fd) +{ + CloseHandle((HANDLE)_get_osfhandle(fd)); + fd_close(fd); + statCounter.syscalls.disk.closes++; +} + + +ssize_t aio_return(struct aiocb * aiocbp) +{ + return aiocbp->aio_sigevent.sigev_signo; +} + + +ssize_t aio_return64(struct aiocb64 * aiocbp) + +{ + return aiocbp->aio_sigevent.sigev_signo; +} +#endif /* _SQUID_WIN32_ */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/AIO/aio_win32.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,110 @@ + +/* + * $Id: aio_win32.h,v 1.3.4.2 2006/09/29 23:16:03 dwsquid Exp $ + * + * AUTHOR: Guido Serassio + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef __WIN32_AIO_H__ +#define __WIN32_AIO_H__ + +#ifdef _SQUID_CYGWIN_ +#include "squid_windows.h" +#endif + +#ifndef off64_t +typedef int64_t off64_t; +#endif + +#ifdef _SQUID_MSWIN_ +union sigval { + int sival_int; /* integer value */ + void *sival_ptr; /* pointer value */ +}; + +struct sigevent +{ + int sigev_notify; /* notification mode */ + int sigev_signo; /* signal number */ + union sigval sigev_value; /* signal value */ +}; + +#endif + +struct aiocb64 +{ + int aio_fildes; /* file descriptor */ + void *aio_buf; /* buffer location */ + size_t aio_nbytes; /* length of transfer */ + off64_t aio_offset; /* file offset */ + int aio_reqprio; /* request priority offset */ + + struct sigevent aio_sigevent; /* signal number and offset */ + int aio_lio_opcode; /* listio operation */ +}; + +struct aiocb +{ + int aio_fildes; /* file descriptor */ + void *aio_buf; /* buffer location */ + size_t aio_nbytes; /* length of transfer */ +#if (_FILE_OFFSET_BITS == 64) + + off64_t aio_offset; /* file offset */ +#else + + off_t aio_offset; /* file offset */ +#endif + + int aio_reqprio; /* request priority offset */ + + struct sigevent aio_sigevent; /* signal number and offset */ + int aio_lio_opcode; /* listio operation */ +}; + +int aio_read(struct aiocb *); + +int aio_write(struct aiocb *); + +ssize_t aio_return(struct aiocb *); + +int aio_error(const struct aiocb *); + +int aio_read64(struct aiocb64 *); + +int aio_write64(struct aiocb64 *); + +ssize_t aio_return64(struct aiocb64 *); + +int aio_error64(const struct aiocb64 *); +int aio_open(const char *, int); +void aio_close(int); + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/Blocking/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,3 @@ +.deps +.dirstamp +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/DiskDaemon/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,5 @@ +.deps +.dirstamp +.libs +diskd +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/DiskThreads/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,3 @@ +.deps +.dirstamp +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/DiskIO/DiskThreads/aiops_win32.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,1228 @@ +/* + * $Id: aiops_win32.cc,v 1.3.4.2 2006/09/29 23:16:04 dwsquid Exp $ + * + * DEBUG: section 43 Windows AIOPS + * AUTHOR: Stewart Forster + * AUTHOR: Robert Collins + * AUTHOR: Guido Serassio + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "squid_windows.h" +#include "DiskThreads.h" + +#include +#include +#include +#include +#include +#include +#include +#include "CommIO.h" +#include "SquidTime.h" +#include "Store.h" + +#define RIDICULOUS_LENGTH 4096 + +enum _squidaio_thread_status { + _THREAD_STARTING = 0, + _THREAD_WAITING, + _THREAD_BUSY, + _THREAD_FAILED, + _THREAD_DONE +}; +typedef enum _squidaio_thread_status squidaio_thread_status; + +typedef struct squidaio_request_t +{ + + struct squidaio_request_t *next; + squidaio_request_type request_type; + int cancelled; + char *path; + int oflag; + mode_t mode; + int fd; + char *bufferp; + char *tmpbufp; + int buflen; + off_t offset; + int whence; + int ret; + int err; + + struct stat *tmpstatp; + + struct stat *statp; + squidaio_result_t *resultp; +} + +squidaio_request_t; + +typedef struct squidaio_request_queue_t +{ + HANDLE mutex; + HANDLE cond; /* See Event objects */ + squidaio_request_t *volatile head; + squidaio_request_t *volatile *volatile tailp; + unsigned long requests; + unsigned long blocked; /* main failed to lock the queue */ +} + +squidaio_request_queue_t; + +typedef struct squidaio_thread_t squidaio_thread_t; + +struct squidaio_thread_t +{ + squidaio_thread_t *next; + HANDLE thread; + DWORD dwThreadId; /* thread ID */ + squidaio_thread_status status; + + struct squidaio_request_t *current_req; + unsigned long requests; + int volatile exit; +}; + +static void squidaio_queue_request(squidaio_request_t *); +static void squidaio_cleanup_request(squidaio_request_t *); +static DWORD WINAPI squidaio_thread_loop( LPVOID lpParam ); +static void squidaio_do_open(squidaio_request_t *); +static void squidaio_do_read(squidaio_request_t *); +static void squidaio_do_write(squidaio_request_t *); +static void squidaio_do_close(squidaio_request_t *); +static void squidaio_do_stat(squidaio_request_t *); +#if USE_TRUNCATE +static void squidaio_do_truncate(squidaio_request_t *); +#else +static void squidaio_do_unlink(squidaio_request_t *); +#endif +#if AIO_OPENDIR +static void *squidaio_do_opendir(squidaio_request_t *); +#endif +static void squidaio_debug(squidaio_request_t *); +static void squidaio_poll_queues(void); + +static squidaio_thread_t *threads = NULL; +static int squidaio_initialised = 0; + + +#define AIO_LARGE_BUFS 16384 +#define AIO_MEDIUM_BUFS AIO_LARGE_BUFS >> 1 +#define AIO_SMALL_BUFS AIO_LARGE_BUFS >> 2 +#define AIO_TINY_BUFS AIO_LARGE_BUFS >> 3 +#define AIO_MICRO_BUFS 128 + +static MemAllocator *squidaio_large_bufs = NULL; /* 16K */ +static MemAllocator *squidaio_medium_bufs = NULL; /* 8K */ +static MemAllocator *squidaio_small_bufs = NULL; /* 4K */ +static MemAllocator *squidaio_tiny_bufs = NULL; /* 2K */ +static MemAllocator *squidaio_micro_bufs = NULL; /* 128K */ + +static int request_queue_len = 0; +static MemAllocator *squidaio_request_pool = NULL; +static MemAllocator *squidaio_thread_pool = NULL; +static squidaio_request_queue_t request_queue; + +static struct +{ + squidaio_request_t *head, **tailp; +} + +request_queue2 = { + + NULL, &request_queue2.head + }; +static squidaio_request_queue_t done_queue; + +static struct +{ + squidaio_request_t *head, **tailp; +} + +done_requests = { + + NULL, &done_requests.head + }; + +static HANDLE main_thread; + +static MemAllocator * +squidaio_get_pool(int size) +{ + if (size <= AIO_LARGE_BUFS) { + if (size <= AIO_MICRO_BUFS) + return squidaio_micro_bufs; + else if (size <= AIO_TINY_BUFS) + return squidaio_tiny_bufs; + else if (size <= AIO_SMALL_BUFS) + return squidaio_small_bufs; + else if (size <= AIO_MEDIUM_BUFS) + return squidaio_medium_bufs; + else + return squidaio_large_bufs; + } + + return NULL; +} + +void * +squidaio_xmalloc(int size) +{ + void *p; + MemAllocator *pool; + + if ((pool = squidaio_get_pool(size)) != NULL) { + p = pool->alloc(); + } else + p = xmalloc(size); + + return p; +} + +static char * +squidaio_xstrdup(const char *str) +{ + char *p; + int len = strlen(str) + 1; + + p = (char *)squidaio_xmalloc(len); + strncpy(p, str, len); + + return p; +} + +void +squidaio_xfree(void *p, int size) +{ + MemAllocator *pool; + + if ((pool = squidaio_get_pool(size)) != NULL) { + pool->free(p); + } else + xfree(p); +} + +static void +squidaio_xstrfree(char *str) +{ + MemAllocator *pool; + int len = strlen(str) + 1; + + if ((pool = squidaio_get_pool(len)) != NULL) { + pool->free(str); + } else + xfree(str); +} + +void +squidaio_init(void) +{ + int i; + squidaio_thread_t *threadp; + + if (squidaio_initialised) + return; + + if (!DuplicateHandle(GetCurrentProcess(), /* pseudo handle, don't close */ + GetCurrentThread(), /* pseudo handle to copy */ + GetCurrentProcess(), /* pseudo handle, don't close */ + &main_thread, + 0, /* required access */ + FALSE, /* child process's don't inherit the handle */ + DUPLICATE_SAME_ACCESS)) { + /* spit errors */ + fatal("Couldn't get current thread handle"); + } + + /* Initialize request queue */ + if ((request_queue.mutex = CreateMutex(NULL, /* no inheritance */ + FALSE, /* start unowned (as per mutex_init) */ + NULL) /* no name */ + ) == NULL) { + fatal("Failed to create mutex"); + } + + if ((request_queue.cond = CreateEvent(NULL, /* no inheritance */ + FALSE, /* auto signal reset - which I think is pthreads like ? */ + FALSE, /* start non signaled */ + NULL) /* no name */ + ) == NULL) { + fatal("Failed to create condition variable"); + } + + request_queue.head = NULL; + + request_queue.tailp = &request_queue.head; + + request_queue.requests = 0; + + request_queue.blocked = 0; + + /* Initialize done queue */ + + if ((done_queue.mutex = CreateMutex(NULL, /* no inheritance */ + FALSE, /* start unowned (as per mutex_init) */ + NULL) /* no name */ + ) == NULL) { + fatal("Failed to create mutex"); + } + + if ((done_queue.cond = CreateEvent(NULL, /* no inheritance */ + TRUE, /* manually signaled - which I think is pthreads like ? */ + FALSE, /* start non signaled */ + NULL) /* no name */ + ) == NULL) { + fatal("Failed to create condition variable"); + } + + done_queue.head = NULL; + + done_queue.tailp = &done_queue.head; + + done_queue.requests = 0; + + done_queue.blocked = 0; + + CommIO::NotifyIOCompleted(); + + /* Create threads and get them to sit in their wait loop */ + squidaio_thread_pool = memPoolCreate("aio_thread", sizeof(squidaio_thread_t)); + + assert(NUMTHREADS); + + for (i = 0; i < NUMTHREADS; i++) { + threadp = (squidaio_thread_t *)squidaio_thread_pool->alloc(); + threadp->status = _THREAD_STARTING; + threadp->current_req = NULL; + threadp->requests = 0; + threadp->next = threads; + threads = threadp; + + if ((threadp->thread = CreateThread(NULL, /* no security attributes */ + 0, /* use default stack size */ + squidaio_thread_loop, /* thread function */ + threadp, /* argument to thread function */ + 0, /* use default creation flags */ + &(threadp->dwThreadId)) /* returns the thread identifier */ + ) == NULL) { + fprintf(stderr, "Thread creation failed\n"); + threadp->status = _THREAD_FAILED; + continue; + } + + /* Set the new thread priority above parent process */ + SetThreadPriority(threadp->thread,THREAD_PRIORITY_ABOVE_NORMAL); + } + + /* Create request pool */ + squidaio_request_pool = memPoolCreate("aio_request", sizeof(squidaio_request_t)); + + squidaio_large_bufs = memPoolCreate("squidaio_large_bufs", AIO_LARGE_BUFS); + + squidaio_medium_bufs = memPoolCreate("squidaio_medium_bufs", AIO_MEDIUM_BUFS); + + squidaio_small_bufs = memPoolCreate("squidaio_small_bufs", AIO_SMALL_BUFS); + + squidaio_tiny_bufs = memPoolCreate("squidaio_tiny_bufs", AIO_TINY_BUFS); + + squidaio_micro_bufs = memPoolCreate("squidaio_micro_bufs", AIO_MICRO_BUFS); + + squidaio_initialised = 1; +} + +void +squidaio_shutdown(void) +{ + squidaio_thread_t *threadp; + int i; + HANDLE * hthreads; + + if (!squidaio_initialised) + return; + + /* This is the same as in squidaio_sync */ + do { + squidaio_poll_queues(); + } while (request_queue_len > 0); + + hthreads = (HANDLE *) xcalloc (NUMTHREADS, sizeof (HANDLE)); + + threadp = threads; + + for (i = 0; i < NUMTHREADS; i++) { + threadp->exit = 1; + hthreads[i] = threadp->thread; + threadp = threadp->next; + } + + ReleaseMutex(request_queue.mutex); + ResetEvent(request_queue.cond); + ReleaseMutex(done_queue.mutex); + ResetEvent(done_queue.cond); + Sleep(0); + + WaitForMultipleObjects(NUMTHREADS, hthreads, TRUE, 2000); + + for (i = 0; i < NUMTHREADS; i++) { + CloseHandle(hthreads[i]); + } + + CloseHandle(main_thread); + CommIO::NotifyIOClose(); + + squidaio_initialised = 0; + xfree(hthreads); +} + +static DWORD WINAPI +squidaio_thread_loop(LPVOID lpParam) +{ + squidaio_thread_t *threadp = (squidaio_thread_t *)lpParam; + squidaio_request_t *request; + HANDLE cond; /* local copy of the event queue because win32 event handles + * don't atomically release the mutex as cond variables do. */ + + /* lock the thread info */ + + if (WAIT_FAILED == WaitForSingleObject(request_queue.mutex, INFINITE)) { + fatal("Can't get ownership of mutex\n"); + } + + /* duplicate the handle */ + if (!DuplicateHandle(GetCurrentProcess(), /* pseudo handle, don't close */ + request_queue.cond, /* handle to copy */ + GetCurrentProcess(), /* pseudo handle, don't close */ + &cond, + 0, /* required access */ + FALSE, /* child process's don't inherit the handle */ + DUPLICATE_SAME_ACCESS)) + fatal("Can't duplicate mutex handle\n"); + + if (!ReleaseMutex(request_queue.mutex)) { + CloseHandle(cond); + fatal("Can't release mutex\n"); + } + + Sleep(0); + + while (1) { + DWORD rv; + threadp->current_req = request = NULL; + request = NULL; + /* Get a request to process */ + threadp->status = _THREAD_WAITING; + + if (threadp->exit) { + CloseHandle(request_queue.mutex); + CloseHandle(cond); + return 0; + } + + rv = WaitForSingleObject(request_queue.mutex, INFINITE); + + if (rv == WAIT_FAILED) { + CloseHandle(cond); + return 1; + } + + while (!request_queue.head) { + if (!ReleaseMutex(request_queue.mutex)) { + CloseHandle(cond); + threadp->status = _THREAD_FAILED; + return 1; + } + + Sleep(0); + rv = WaitForSingleObject(cond, INFINITE); + + if (rv == WAIT_FAILED) { + CloseHandle(cond); + return 1; + } + + rv = WaitForSingleObject(request_queue.mutex, INFINITE); + + if (rv == WAIT_FAILED) { + CloseHandle(cond); + return 1; + } + } + + request = request_queue.head; + + if (request) + request_queue.head = request->next; + + if (!request_queue.head) + request_queue.tailp = &request_queue.head; + + if (!ReleaseMutex(request_queue.mutex)) { + CloseHandle(cond); + return 1; + } + + Sleep(0); + + /* process the request */ + threadp->status = _THREAD_BUSY; + + request->next = NULL; + + threadp->current_req = request; + + errno = 0; + + if (!request->cancelled) { + switch (request->request_type) { + + case _AIO_OP_OPEN: + squidaio_do_open(request); + break; + + case _AIO_OP_READ: + squidaio_do_read(request); + break; + + case _AIO_OP_WRITE: + squidaio_do_write(request); + break; + + case _AIO_OP_CLOSE: + squidaio_do_close(request); + break; + +#if USE_TRUNCATE + + case _AIO_OP_TRUNCATE: + squidaio_do_truncate(request); + break; +#else + + case _AIO_OP_UNLINK: + squidaio_do_unlink(request); + break; + +#endif +#if AIO_OPENDIR /* Opendir not implemented yet */ + + case _AIO_OP_OPENDIR: + squidaio_do_opendir(request); + break; +#endif + + case _AIO_OP_STAT: + squidaio_do_stat(request); + break; + + default: + request->ret = -1; + request->err = EINVAL; + break; + } + } else { /* cancelled */ + request->ret = -1; + request->err = EINTR; + } + + threadp->status = _THREAD_DONE; + /* put the request in the done queue */ + rv = WaitForSingleObject(done_queue.mutex, INFINITE); + + if (rv == WAIT_FAILED) { + CloseHandle(cond); + return 1; + } + + *done_queue.tailp = request; + done_queue.tailp = &request->next; + + if (!ReleaseMutex(done_queue.mutex)) { + CloseHandle(cond); + return 1; + } + + CommIO::NotifyIOCompleted(); + Sleep(0); + threadp->requests++; + } /* while forever */ + + CloseHandle(cond); + + return 0; +} /* squidaio_thread_loop */ + +static void +squidaio_queue_request(squidaio_request_t * request) +{ + static int high_start = 0; + debug(43, 9) ("squidaio_queue_request: %p type=%d result=%p\n", + request, request->request_type, request->resultp); + /* Mark it as not executed (failing result, no error) */ + request->ret = -1; + request->err = 0; + /* Internal housekeeping */ + request_queue_len += 1; + request->resultp->_data = request; + /* Play some tricks with the request_queue2 queue */ + request->next = NULL; + + if (WaitForSingleObject(request_queue.mutex, 0) == WAIT_OBJECT_0) { + if (request_queue2.head) { + /* Grab blocked requests */ + *request_queue.tailp = request_queue2.head; + request_queue.tailp = request_queue2.tailp; + } + + /* Enqueue request */ + *request_queue.tailp = request; + + request_queue.tailp = &request->next; + + if (!SetEvent(request_queue.cond)) + fatal("Couldn't push queue"); + + if (!ReleaseMutex(request_queue.mutex)) { + /* unexpected error */ + fatal("Couldn't push queue"); + } + + Sleep(0); + + if (request_queue2.head) { + /* Clear queue of blocked requests */ + request_queue2.head = NULL; + request_queue2.tailp = &request_queue2.head; + } + } else { + /* Oops, the request queue is blocked, use request_queue2 */ + *request_queue2.tailp = request; + request_queue2.tailp = &request->next; + } + + if (request_queue2.head) { + static int filter = 0; + static int filter_limit = 8; + + if (++filter >= filter_limit) { + filter_limit += filter; + filter = 0; + debug(43, 1) ("squidaio_queue_request: WARNING - Queue congestion\n"); + } + } + + /* Warn if out of threads */ + if (request_queue_len > MAGIC1) { + static int last_warn = 0; + static int queue_high, queue_low; + + if (high_start == 0) { + high_start = (int)squid_curtime; + queue_high = request_queue_len; + queue_low = request_queue_len; + } + + if (request_queue_len > queue_high) + queue_high = request_queue_len; + + if (request_queue_len < queue_low) + queue_low = request_queue_len; + + if (squid_curtime >= (last_warn + 15) && + squid_curtime >= (high_start + 5)) { + debug(43, 1) ("squidaio_queue_request: WARNING - Disk I/O overloading\n"); + + if (squid_curtime >= (high_start + 15)) + debug(43, 1) ("squidaio_queue_request: Queue Length: current=%d, high=%d, low=%d, duration=%ld\n", + request_queue_len, queue_high, queue_low, (long int) (squid_curtime - high_start)); + + last_warn = (int)squid_curtime; + } + } else { + high_start = 0; + } + + /* Warn if seriously overloaded */ + if (request_queue_len > RIDICULOUS_LENGTH) { + debug(43, 0) ("squidaio_queue_request: Async request queue growing uncontrollably!\n"); + debug(43, 0) ("squidaio_queue_request: Syncing pending I/O operations.. (blocking)\n"); + squidaio_sync(); + debug(43, 0) ("squidaio_queue_request: Synced\n"); + } +} /* squidaio_queue_request */ + +static void +squidaio_cleanup_request(squidaio_request_t * requestp) +{ + squidaio_result_t *resultp = requestp->resultp; + int cancelled = requestp->cancelled; + + /* Free allocated structures and copy data back to user space if the */ + /* request hasn't been cancelled */ + + switch (requestp->request_type) { + + case _AIO_OP_STAT: + + if (!cancelled && requestp->ret == 0) + + xmemcpy(requestp->statp, requestp->tmpstatp, sizeof(struct stat)); + + squidaio_xfree(requestp->tmpstatp, sizeof(struct stat)); + + squidaio_xstrfree(requestp->path); + + break; + + case _AIO_OP_OPEN: + if (cancelled && requestp->ret >= 0) + /* The open() was cancelled but completed */ + close(requestp->ret); + + squidaio_xstrfree(requestp->path); + + break; + + case _AIO_OP_CLOSE: + if (cancelled && requestp->ret < 0) + /* The close() was cancelled and never got executed */ + close(requestp->fd); + + break; + + case _AIO_OP_UNLINK: + + case _AIO_OP_TRUNCATE: + + case _AIO_OP_OPENDIR: + squidaio_xstrfree(requestp->path); + + break; + + case _AIO_OP_READ: + break; + + case _AIO_OP_WRITE: + break; + + default: + break; + } + + if (resultp != NULL && !cancelled) { + resultp->aio_return = requestp->ret; + resultp->aio_errno = requestp->err; + } + + squidaio_request_pool->free(requestp); +} /* squidaio_cleanup_request */ + + +int +squidaio_cancel(squidaio_result_t * resultp) +{ + squidaio_request_t *request = (squidaio_request_t *)resultp->_data; + + if (request && request->resultp == resultp) { + debug(43, 9) ("squidaio_cancel: %p type=%d result=%p\n", + request, request->request_type, request->resultp); + request->cancelled = 1; + request->resultp = NULL; + resultp->_data = NULL; + resultp->result_type = _AIO_OP_NONE; + return 0; + } + + return 1; +} /* squidaio_cancel */ + + +int +squidaio_open(const char *path, int oflag, mode_t mode, squidaio_result_t * resultp) +{ + squidaio_init(); + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->path = (char *) squidaio_xstrdup(path); + + requestp->oflag = oflag; + + requestp->mode = mode; + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_OPEN; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_OPEN; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_open(squidaio_request_t * requestp) +{ + requestp->ret = open(requestp->path, requestp->oflag, requestp->mode); + requestp->err = errno; +} + + +int +squidaio_read(int fd, char *bufp, int bufs, off_t offset, int whence, squidaio_result_t * resultp) +{ + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->fd = fd; + + requestp->bufferp = bufp; + + requestp->buflen = bufs; + + requestp->offset = offset; + + requestp->whence = whence; + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_READ; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_READ; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_read(squidaio_request_t * requestp) +{ + lseek(requestp->fd, requestp->offset, requestp->whence); + + if (!ReadFile((HANDLE)_get_osfhandle(requestp->fd), requestp->bufferp, + requestp->buflen, (LPDWORD)&requestp->ret, NULL)) { + WIN32_maperror(GetLastError()); + requestp->ret = -1; + } + + requestp->err = errno; +} + + +int +squidaio_write(int fd, char *bufp, int bufs, off_t offset, int whence, squidaio_result_t * resultp) +{ + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->fd = fd; + + requestp->bufferp = bufp; + + requestp->buflen = bufs; + + requestp->offset = offset; + + requestp->whence = whence; + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_WRITE; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_WRITE; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_write(squidaio_request_t * requestp) +{ + if (!WriteFile((HANDLE)_get_osfhandle(requestp->fd), requestp->bufferp, + requestp->buflen, (LPDWORD)&requestp->ret, NULL)) { + WIN32_maperror(GetLastError()); + requestp->ret = -1; + } + + requestp->err = errno; +} + + +int +squidaio_close(int fd, squidaio_result_t * resultp) +{ + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->fd = fd; + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_CLOSE; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_CLOSE; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_close(squidaio_request_t * requestp) +{ + if((requestp->ret = close(requestp->fd)) < 0) { + debug(43, 0) ("squidaio_do_close: FD %d, errno %d\n", requestp->fd, errno); + close(requestp->fd); + } + + requestp->err = errno; +} + + +int + +squidaio_stat(const char *path, struct stat *sb, squidaio_result_t * resultp) +{ + squidaio_init(); + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->path = (char *) squidaio_xstrdup(path); + + requestp->statp = sb; + + requestp->tmpstatp = (struct stat *) squidaio_xmalloc(sizeof(struct stat)); + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_STAT; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_STAT; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_stat(squidaio_request_t * requestp) +{ + requestp->ret = stat(requestp->path, requestp->tmpstatp); + requestp->err = errno; +} + + +#if USE_TRUNCATE +int +squidaio_truncate(const char *path, off_t length, squidaio_result_t * resultp) +{ + squidaio_init(); + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->path = (char *) squidaio_xstrdup(path); + + requestp->offset = length; + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_TRUNCATE; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_TRUNCATE; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_truncate(squidaio_request_t * requestp) +{ + requestp->ret = truncate(requestp->path, requestp->offset); + requestp->err = errno; +} + + +#else +int +squidaio_unlink(const char *path, squidaio_result_t * resultp) +{ + squidaio_init(); + squidaio_request_t *requestp; + + requestp = (squidaio_request_t *)squidaio_request_pool->alloc(); + + requestp->path = squidaio_xstrdup(path); + + requestp->resultp = resultp; + + requestp->request_type = _AIO_OP_UNLINK; + + requestp->cancelled = 0; + + resultp->result_type = _AIO_OP_UNLINK; + + squidaio_queue_request(requestp); + + return 0; +} + + +static void +squidaio_do_unlink(squidaio_request_t * requestp) +{ + requestp->ret = unlink(requestp->path); + requestp->err = errno; +} + +#endif + +#if AIO_OPENDIR +/* XXX squidaio_opendir NOT implemented yet.. */ + +int +squidaio_opendir(const char *path, squidaio_result_t * resultp) +{ + squidaio_request_t *requestp; + int len; + + requestp = squidaio_request_pool->alloc(); + + resultp->result_type = _AIO_OP_OPENDIR; + + return -1; +} + +static void +squidaio_do_opendir(squidaio_request_t * requestp) +{ + /* NOT IMPLEMENTED */ +} + +#endif + +static void +squidaio_poll_queues(void) +{ + /* kick "overflow" request queue */ + + if (request_queue2.head && + (WaitForSingleObject(request_queue.mutex, 0 )== WAIT_OBJECT_0)) { + *request_queue.tailp = request_queue2.head; + request_queue.tailp = request_queue2.tailp; + + if (!SetEvent(request_queue.cond)) + fatal("couldn't push queue\n"); + + if (!ReleaseMutex(request_queue.mutex)) { + /* unexpected error */ + } + + Sleep(0); + request_queue2.head = NULL; + request_queue2.tailp = &request_queue2.head; + } + + /* poll done queue */ + if (done_queue.head && + (WaitForSingleObject(done_queue.mutex, 0)==WAIT_OBJECT_0)) { + + struct squidaio_request_t *requests = done_queue.head; + done_queue.head = NULL; + done_queue.tailp = &done_queue.head; + + if (!ReleaseMutex(done_queue.mutex)) { + /* unexpected error */ + } + + Sleep(0); + *done_requests.tailp = requests; + request_queue_len -= 1; + + while (requests->next) { + requests = requests->next; + request_queue_len -= 1; + } + + done_requests.tailp = &requests->next; + } +} + +squidaio_result_t * +squidaio_poll_done(void) +{ + squidaio_request_t *request; + squidaio_result_t *resultp; + int cancelled; + int polled = 0; + +AIO_REPOLL: + request = done_requests.head; + + if (request == NULL && !polled) { + CommIO::ResetNotifications(); + squidaio_poll_queues(); + polled = 1; + request = done_requests.head; + } + + if (!request) { + return NULL; + } + + debug(43, 9) ("squidaio_poll_done: %p type=%d result=%p\n", + request, request->request_type, request->resultp); + done_requests.head = request->next; + + if (!done_requests.head) + done_requests.tailp = &done_requests.head; + + resultp = request->resultp; + + cancelled = request->cancelled; + + squidaio_debug(request); + + debug(43, 5) ("DONE: %d -> %d\n", request->ret, request->err); + + squidaio_cleanup_request(request); + + if (cancelled) + goto AIO_REPOLL; + + return resultp; +} /* squidaio_poll_done */ + +int +squidaio_operations_pending(void) +{ + return request_queue_len + (done_requests.head ? 1 : 0); +} + +int +squidaio_sync(void) +{ + /* XXX This might take a while if the queue is large.. */ + + do { + squidaio_poll_queues(); + } while (request_queue_len > 0); + + return squidaio_operations_pending(); +} + +int +squidaio_get_queue_len(void) +{ + return request_queue_len; +} + +static void +squidaio_debug(squidaio_request_t * request) +{ + switch (request->request_type) { + + case _AIO_OP_OPEN: + debug(43, 5) ("OPEN of %s to FD %d\n", request->path, request->ret); + break; + + case _AIO_OP_READ: + debug(43, 5) ("READ on fd: %d\n", request->fd); + break; + + case _AIO_OP_WRITE: + debug(43, 5) ("WRITE on fd: %d\n", request->fd); + break; + + case _AIO_OP_CLOSE: + debug(43, 5) ("CLOSE of fd: %d\n", request->fd); + break; + + case _AIO_OP_UNLINK: + debug(43, 5) ("UNLINK of %s\n", request->path); + break; + + case _AIO_OP_TRUNCATE: + debug(43, 5) ("UNLINK of %s\n", request->path); + break; + + default: + break; + } +} + +void +squidaio_stats(StoreEntry * sentry) +{ + squidaio_thread_t *threadp; + int i; + + if (!squidaio_initialised) + return; + + storeAppendPrintf(sentry, "\n\nThreads Status:\n"); + + storeAppendPrintf(sentry, "#\tID\t# Requests\n"); + + threadp = threads; + + for (i = 0; i < NUMTHREADS; i++) { + storeAppendPrintf(sentry, "%i\t0x%lx\t%ld\n", i + 1, threadp->dwThreadId, threadp->requests); + threadp = threadp->next; + } +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/ICAP/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +.deps +.dirstamp +Makefile +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/auth/negotiate/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,3 @@ +.deps +.dirstamp +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/.cvsignore Wed Feb 14 13:38:03 2007 @@ -0,0 +1,17 @@ +.deps +.dirstamp +.libs +testAuth +testACLMaxUserIP +testBoilerplate +testCacheManager +testCoss +testHeaders +testHttpRequest +testNull +testStore +testString +testUfs +testURL +test_http_range +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/CapturingStoreEntry.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,39 @@ +#ifndef SQUID_TESTS_CAPTURINGSTORE_ENTRY_H +#define SQUID_TESTS_CAPTURINGSTORE_ENTRY_H + +#include "Mem.h" +#include "Store.h" + +/* class that captures various call data for test analysis */ + +class CapturingStoreEntry : public StoreEntry +{ + +public: + MEMPROXY_CLASS(CapturingStoreEntry); + + CapturingStoreEntry() : _buffer_calls(0), _flush_calls(0) {} + + String _appended_text; + int _buffer_calls; + int _flush_calls; + + virtual void buffer() + { + _buffer_calls += 1; + } + + virtual void flush() + { + _flush_calls += 1; + } + + virtual void append(char const * buf, int len) + { + _appended_text.append(buf, len); + } +}; + +MEMPROXY_CLASS_INLINE(CapturingStoreEntry); + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/stub_DelayId.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,51 @@ +/* + * $Id: stub_DelayId.cc,v 1.1.12.2 2006/09/29 23:16:05 dwsquid Exp $ + * + * DEBUG: section 20 Storage Manager + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "config.h" + + +#if DELAY_POOLS + +#include "squid.h" +#include "DelayId.h" + +DelayId::DelayId() {} + +void +DelayId::delayRead(DeferredRead const&) +{} + +DelayId::~DelayId() {} + +#endif --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/stub_access_log.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,57 @@ +/* + * $Id: stub_access_log.cc,v 1.1.12.2 2006/09/29 23:16:05 dwsquid Exp $ + * + * DEBUG: section 28 Access Control + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "HierarchyLogEntry.h" + + +HierarchyLogEntry::HierarchyLogEntry() +{ + fatal("Not implemented."); +} + +ping_data::ping_data() : + n_sent(0), + n_recv(0), + n_replies_expected(0), + timeout(0), + timedout(0), + w_rtt(0), + p_rtt(0) +{ + start.tv_sec = 0; + start.tv_usec = 0; + stop.tv_sec = 0; + stop.tv_usec = 0; +} --- squid3/src/tests/stub_cache_manager.cc Wed Feb 14 13:38:03 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,44 +0,0 @@ -/* - * $Id: stub_cache_manager.cc,v 1.1 2004/08/31 02:14:30 squidadm Exp $ - * - * DEBUG: section 16 Cache Manager Objects - * AUTHOR: Robert Collins - * - * SQUID Web Proxy Cache http://www.squid-cache.org/ - * ---------------------------------------------------------- - * - * Squid is the result of efforts by numerous individuals from - * the Internet community; see the CONTRIBUTORS file for full - * details. Many organizations have provided support for Squid's - * development; see the SPONSORS file for full details. Squid is - * Copyrighted (C) 2001 by the Regents of the University of - * California; see the COPYRIGHT file for full details. Squid - * incorporates software developed and/or copyrighted by other - * sources; see the CREDITS file for full details. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. - * - */ - -#include "squid.h" - -void -cachemgrRegister(const char *action, const char *desc, OBJH * handler, int pw_req_flag, int atomic) -{} - -/* - * DO NOT MODIFY: - * arch-tag: 4b6d624e-0e69-415f-bb92-f5991db65dd3 - */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/stub_client_side_request.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,40 @@ +/* + * $Id: stub_client_side_request.cc,v 1.1.12.2 2006/09/29 23:16:05 dwsquid Exp $ + * + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "client_side_request.h" +#include "Store.h" + +#ifndef _USE_INLINE_ +#include "client_side_request.cci" +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/stub_mime.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,42 @@ +/* + * $Id: stub_mime.cc,v 1.1.12.2 2006/09/29 23:16:05 dwsquid Exp $ + * + * DEBUG: section 28 Access Control + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" + +size_t +headersEnd(const char *mime, size_t l) +{ + fatal("Not implemented"); + return 0; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testACLMaxUserIP.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,38 @@ +#include "squid.h" +#include + +#include "testACLMaxUserIP.h" +#include "ACLMaxUserIP.h" + +CPPUNIT_TEST_SUITE_REGISTRATION( testACLMaxUserIP ); + + +void +testACLMaxUserIP::testDefaults() +{ + ACLMaxUserIP anACL("max_user_ip"); + /* 0 is not a valid maximum, so we start at 0 */ + CPPUNIT_ASSERT(anACL.getMaximum() == 0); + /* and we have no option to turn strict OFF, so start ON. */ + CPPUNIT_ASSERT(anACL.getStrict() == false); + /* an unparsed acl must not be valid - there is no sane default */ + CPPUNIT_ASSERT(!anACL.valid()); +} + + +void +testACLMaxUserIP::testParseLine() +{ + /* a config line to pass with a lead-in token to seed the parser. */ + char * line = xstrdup("token -s 1"); + /* seed the parser */ + strtok(line, w_space); + ACLMaxUserIP anACL("max_user_ip"); + anACL.parse(); + /* we want a maximum of one, and strict to be true */ + CPPUNIT_ASSERT(anACL.getMaximum() == 1); + CPPUNIT_ASSERT(anACL.getStrict() == true); + /* the acl must be vaid */ + CPPUNIT_ASSERT(anACL.valid()); + xfree(line); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testACLMaxUserIP.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,28 @@ + +#ifndef SQUID_SRC_TEST_ACLMAXUSERIP_H +#define SQUID_SRC_TEST_ACLMAXUSERIP_H + +#include + +/* + * demonstration test file, as new idioms are made they will + * be shown in the testBoilerplate source. + */ + +class testACLMaxUserIP : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testACLMaxUserIP ); + /* note the statement here and then the actual prototype below */ + CPPUNIT_TEST( testDefaults ); + CPPUNIT_TEST( testParseLine ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testDefaults(); + void testParseLine(); +}; + +#endif /* SQUID_SRC_TEST_ACLMAXUSERIP_H */ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testBoilerplate.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,13 @@ +#include "squid.h" +#include + +#include "testBoilerplate.h" + +CPPUNIT_TEST_SUITE_REGISTRATION( testBoilerplate ); + + +void +testBoilerplate::testDemonstration() +{ + CPPUNIT_ASSERT(0 == 0); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testBoilerplate.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,26 @@ + +#ifndef SQUID_SRC_TEST_BOILDERPLATE_H +#define SQUID_SRC_TEST_BOILDERPLATE_H + +#include + +/* + * demonstration test file, as new idioms are made they will + * be shown in the testBoilerplate source. + */ + +class testBoilerplate : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testBoilerplate ); + /* note the statement here and then the actual prototype below */ + CPPUNIT_TEST( testDemonstration ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testDemonstration(); +}; + +#endif /* SQUID_SRC_TEST_BOILDERPLATE_H */ + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testCacheManager.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,55 @@ +#include "squid.h" +#include + +#include "Mem.h" +#include "testCacheManager.h" +#include "CacheManager.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testCacheManager ); + +/* stub functions to link successfully */ +void +shut_down(int) +{} + +/* end stubs */ + +/* init memory pools */ + +struct Initer +{ + Initer() {Mem::Init();} +}; + +static Initer ensure_mempools; + +/* + * Test creating a CacheManager + */ +void +testCacheManager::testCreate() +{ + CacheManager(); +} + +/* an action to register */ +static void +dummy_action(StoreEntry * sentry) +{} + +/* + * registering an action makes it findable. + */ +void +testCacheManager::testRegister() +{ + CacheManager manager; + manager.registerAction("sample", "my sample", &dummy_action, false, false); + CacheManagerAction *anAction = manager.findAction("sample"); + CPPUNIT_ASSERT_EQUAL(String("sample"), String(anAction->action)); + CPPUNIT_ASSERT_EQUAL(String("my sample"), String(anAction->desc)); + CPPUNIT_ASSERT_EQUAL(&dummy_action, anAction->handler); + CPPUNIT_ASSERT_EQUAL(0, (int)anAction->flags.pw_req); + CPPUNIT_ASSERT_EQUAL(0, (int)anAction->flags.atomic); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testCacheManager.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,26 @@ + +#ifndef SQUID_SRC_TEST_CACHEMANAGER_H +#define SQUID_SRC_TEST_CACHEMANAGER_H + +#include + +/* + * test the CacheManager implementation + */ + +class testCacheManager : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testCacheManager ); + CPPUNIT_TEST( testCreate ); + CPPUNIT_TEST( testRegister ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testCreate(); + void testRegister(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testDiskIO.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,33 @@ +#include "squid.h" +#include + +#include "testDiskIO.h" +#include "Store.h" +#include "SwapDir.h" +#include "DiskIO/DiskIOModule.h" +#include "fs/ufs/ufscommon.h" +#include "fs/coss/CossSwapDir.h" +#include "Mem.h" +#include "MemObject.h" +#include "HttpHeader.h" +#include "HttpReply.h" +#include "StoreFileSystem.h" +#include "testStoreSupport.h" + +CPPUNIT_TEST_SUITE_REGISTRATION( testDiskIO ); + +struct Initer { + Initer() { + Mem::Init(); + DiskIOModule::SetupAllModules(); + }; +}; + +Initer ensure_inited; + +void +testDiskIO::testFindDefault() +{ + DiskIOModule * module = DiskIOModule::FindDefault(); + CPPUNIT_ASSERT(module != NULL); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testDiskIO.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,24 @@ + +#ifndef SQUID_SRC_TEST_DISKIO_H +#define SQUID_SRC_TEST_DISKIO_H + +#include + +/* + * test the DiskIO framework + */ + +class testDiskIO : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testDiskIO ); + CPPUNIT_TEST( testFindDefault ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testFindDefault(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testEvent.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,161 @@ +#include "squid.h" +#include + +#include "CapturingStoreEntry.h" +#include "CompletionDispatcher.h" +#include "Mem.h" +#include "testEvent.h" +#include "event.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testEvent ); + +/* stub functions to link successfully */ +void +shut_down(int) +{} + +/* end stubs */ + +/* init legacy static-initialized modules */ + +struct Initer +{ + Initer() + { + Mem::Init(); + statInit(); + } +}; + +static Initer ensure_mempools; + +/* + * Test creating a EventDispatcher and Scheduler + */ +void +testEvent::testCreate() +{ + EventDispatcher dispatcher = EventDispatcher(); + EventScheduler scheduler = EventScheduler(&dispatcher); +} + + +/* Helper for tests - an event which records the number of calls it recieved. */ + +struct CalledEvent +{ + CalledEvent() : calls(0) {} + + static void Handler(void *data) + { + static_cast(data)->calls++; + } + + int calls; +}; + +/* do a trivial test of invoking callbacks */ +void +testEvent::testDispatch() +{ + EventDispatcher dispatcher; + CalledEvent event; + dispatcher.add(new ev_entry("test event", CalledEvent::Handler, &event, 0, 0, false)); + /* return true when an event is dispatched */ + CPPUNIT_ASSERT_EQUAL(true, dispatcher.dispatch()); + /* return false when none were dispatched */ + CPPUNIT_ASSERT_EQUAL(false, dispatcher.dispatch()); + CPPUNIT_ASSERT_EQUAL(1, event.calls); +} + +/* submit two callbacks, and cancel one, then dispatch and only the other should run. + */ +void +testEvent::testCancel() +{ + EventDispatcher dispatcher; + EventScheduler scheduler(&dispatcher); + CalledEvent event; + CalledEvent event_to_cancel; + scheduler.schedule("test event", CalledEvent::Handler, &event, 0, 0, false); + scheduler.schedule("test event2", CalledEvent::Handler, &event_to_cancel, 0, 0, false); + scheduler.cancel(CalledEvent::Handler, &event_to_cancel); + scheduler.checkEvents(0); + dispatcher.dispatch(); + CPPUNIT_ASSERT_EQUAL(1, event.calls); + CPPUNIT_ASSERT_EQUAL(0, event_to_cancel.calls); +} + +/* submit two callbacks, and then dump the queue. + */ +void +testEvent::testDump() +{ + EventDispatcher dispatcher; + EventScheduler scheduler(&dispatcher); + CalledEvent event; + CalledEvent event2; + CapturingStoreEntry * anEntry = new CapturingStoreEntry(); + scheduler.schedule("last event", CalledEvent::Handler, &event, 0, 0, false); + /* schedule and dispatch to set the last run event */ + scheduler.checkEvents(0); + dispatcher.dispatch(); + scheduler.schedule("test event", CalledEvent::Handler, &event, 0, 0, false); + scheduler.schedule("test event2", CalledEvent::Handler, &event2, 0, 0, false); + scheduler.dump(anEntry); + CPPUNIT_ASSERT_EQUAL(String( + "Last event to run: last event\n" + "\n" + "Operation\tNext Execution\tWeight\tCallback Valid?\n" + "test event\t0.000000 seconds\t0\tN/A\n" + "test event2\t0.000000 seconds\t0\tN/A\n" + ), anEntry->_appended_text); + delete anEntry; +} + +/* submit two callbacks, and find the right one. + */ +void +testEvent::testFind() +{ + EventDispatcher dispatcher; + EventScheduler scheduler(&dispatcher); + CalledEvent event; + CalledEvent event_to_find; + scheduler.schedule("test event", CalledEvent::Handler, &event, 0, 0, false); + scheduler.schedule("test event2", CalledEvent::Handler, &event_to_find, 0, 0, false); + CPPUNIT_ASSERT_EQUAL(true, scheduler.find(CalledEvent::Handler, &event_to_find)); +} + +/* do a trivial test of invoking callbacks */ +void +testEvent::testCheckEvents() +{ + EventDispatcher dispatcher; + EventScheduler scheduler(&dispatcher); + CalledEvent event; + /* with no events, its an idle engine */ + CPPUNIT_ASSERT_EQUAL(int(AsyncEngine::EVENT_IDLE), scheduler.checkEvents(0)); + /* event running now gets will get sent to the dispatcher and the + * engine becomes idle. + */ + scheduler.schedule("test event", CalledEvent::Handler, &event, 0, 0, false); + CPPUNIT_ASSERT_EQUAL(int(AsyncEngine::EVENT_IDLE), scheduler.checkEvents(0)); + dispatcher.dispatch(); + /* event running later results in a delay of the time till it runs */ + scheduler.schedule("test event", CalledEvent::Handler, &event, 2, 0, false); + CPPUNIT_ASSERT_EQUAL(2000, scheduler.checkEvents(0)); + dispatcher.dispatch(); + CPPUNIT_ASSERT_EQUAL(1, event.calls); +} + +/* for convenience we have a singleton scheduler and dispatcher*/ +void +testEvent::testSingleton() +{ + EventScheduler *scheduler = dynamic_cast(EventScheduler::GetInstance()); + CPPUNIT_ASSERT(NULL != scheduler); + EventDispatcher *dispatcher = dynamic_cast(EventDispatcher::GetInstance()); + CPPUNIT_ASSERT(NULL != dispatcher); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testEvent.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,36 @@ + +#ifndef SQUID_SRC_TEST_EVENT_H +#define SQUID_SRC_TEST_EVENT_H + +#include + +/* + * test the event module. + */ + +class testEvent : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testEvent ); + CPPUNIT_TEST( testCreate ); + CPPUNIT_TEST( testDispatch ); + CPPUNIT_TEST( testDump ); + CPPUNIT_TEST( testFind ); + CPPUNIT_TEST( testCheckEvents ); + CPPUNIT_TEST( testSingleton ); + CPPUNIT_TEST( testCancel ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testCreate(); + void testDispatch(); + void testDump(); + void testFind(); + void testCheckEvents(); + void testSingleton(); + void testCancel(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testEventLoop.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,285 @@ +#include "squid.h" +#include + +#include "AsyncEngine.h" +#include "CompletionDispatcher.h" +#include "Mem.h" +#include "testEventLoop.h" +#include "EventLoop.h" +#include "event.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testEventLoop ); + +/* stub functions to link successfully */ +void +shut_down(int) +{} + +/* end stubs */ + +/* init legacy static-initialized modules */ + +struct Initer +{ + Initer() + { + Mem::Init(); + statInit(); + } +}; + +static Initer ensure_mempools; + +/* + * Test creating a EventLoop + */ +void +testEventLoop::testCreate() +{ + EventLoop(); +} + + +/* + * Running the loop once is useful for integration with other loops, such as + * migrating to it in incrementally. + * + * This test works by having a custom dispatcher and engine which record how + * many times they are called. + */ + +class RecordDispatcher : public CompletionDispatcher +{ + +public: + int calls; + RecordDispatcher(): calls(0) + {} + + bool dispatch() + { + ++calls; + /* claim we dispatched calls to be useful for the testStopOnIdle test. + */ + return true; + } +}; + +class RecordingEngine : public AsyncEngine +{ + +public: + int calls; + int lasttimeout; + int return_timeout; + RecordingEngine(int return_timeout=0): calls(0), lasttimeout(0), + return_timeout(return_timeout) + {} + + virtual int checkEvents(int timeout) + { + ++calls; + lasttimeout = timeout; + return return_timeout; + } + }; + +void +testEventLoop::testRunOnce() +{ + EventLoop theLoop; + RecordDispatcher dispatcher; + theLoop.registerDispatcher(&dispatcher); + RecordingEngine engine; + theLoop.registerEngine(&engine); + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(1, dispatcher.calls); + CPPUNIT_ASSERT_EQUAL(1, engine.calls); +} + +/* + * completion dispatchers registered with the event loop are invoked by the + * event loop. + * + * This test works by having a customer dispatcher which shuts the loop down + * once its been invoked twice. + * + * It also tests that loop.run() and loop.stop() work, because if they dont + * work, this test will either hang, or fail. + */ + +class ShutdownDispatcher : public CompletionDispatcher +{ + +public: + EventLoop &theLoop; + int calls; + ShutdownDispatcher(EventLoop & theLoop):theLoop(theLoop), calls(0) + {} + + bool dispatch() + { + if (++calls == 2) + theLoop.stop(); + + return true; + } +}; + +void +testEventLoop::testRegisterDispatcher() +{ + EventLoop theLoop; + ShutdownDispatcher testDispatcher(theLoop); + theLoop.registerDispatcher(&testDispatcher); + theLoop.run(); + /* we should get two calls because the test dispatched returns true from + * dispatch(), and calls stop on the second call. + */ + CPPUNIT_ASSERT_EQUAL(2, testDispatcher.calls); +} + +/* test that a registered async engine is invoked on each loop run + * we do this with an intstrumented async engine. + */ +void +testEventLoop::testRegisterEngine() +{ + EventLoop theLoop; + ShutdownDispatcher testDispatcher(theLoop); + theLoop.registerDispatcher(&testDispatcher); + RecordingEngine testEngine; + theLoop.registerEngine(&testEngine); + theLoop.run(); + CPPUNIT_ASSERT_EQUAL(2, testEngine.calls); +} + +/* each AsyncEngine needs to be given a timeout. We want one engine in each + * loop to be given the timeout value - and the rest to have a timeout of 0. + * The last registered engine should be given this timeout, which will mean + * that we dont block in the loop until the last engine. This will allow for + * dynamic introduction and removal of engines, as long as the last engine + * is one which can do a os call rather than busy waiting. + * + * So - we want the timeout hints returned from the earlier engines to be + * tracked, and the lowest non-negative value given to the last engine. + */ +void +testEventLoop::testEngineTimeout() +{ + EventLoop theLoop; + RecordingEngine engineOne(5); + RecordingEngine engineTwo; + theLoop.registerEngine(&engineOne); + theLoop.registerEngine(&engineTwo); + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(0, engineOne.lasttimeout); + CPPUNIT_ASSERT_EQUAL(5, engineTwo.lasttimeout); +} + +/* An event loop with all idle engines, and nothing dispatched in a run should + * automatically quit. The runOnce call should return True when the loop is + * entirely idle to make it easy for people running the loop by hand. + */ +void +testEventLoop::testStopOnIdle() +{ + EventLoop theLoop; + /* trivial case - no dispatchers or engines, should quit immediately */ + CPPUNIT_ASSERT_EQUAL(true, theLoop.runOnce()); + theLoop.run(); + /* add a dispatcher with nothing to dispatch - use an EventDispatcher as its + * sufficient and handy + */ + EventDispatcher dispatcher; + theLoop.registerDispatcher(&dispatcher); + CPPUNIT_ASSERT_EQUAL(true, theLoop.runOnce()); + theLoop.run(); + /* add an engine which is idle. + */ + RecordingEngine engine(AsyncEngine::EVENT_IDLE); + theLoop.registerEngine(&engine); + CPPUNIT_ASSERT_EQUAL(true, theLoop.runOnce()); + CPPUNIT_ASSERT_EQUAL(1, engine.calls); + theLoop.run(); + CPPUNIT_ASSERT_EQUAL(2, engine.calls); + /* add an engine which is suffering errors. This should result in 10 + * loops until the loop stops - because thats the error retry amount + */ + RecordingEngine failing_engine(AsyncEngine::EVENT_ERROR); + theLoop.registerEngine(&failing_engine); + CPPUNIT_ASSERT_EQUAL(false, theLoop.runOnce()); + CPPUNIT_ASSERT_EQUAL(1, failing_engine.calls); + theLoop.run(); + /* run resets the error count ... */ + CPPUNIT_ASSERT_EQUAL(11, failing_engine.calls); + + /* an engine that asks for a timeout should not be detected as idle: + * use runOnce which should return false + */ + theLoop = EventLoop(); + RecordingEngine non_idle_engine(1000); + theLoop.registerEngine(&non_idle_engine); + CPPUNIT_ASSERT_EQUAL(false, theLoop.runOnce()); +} + +/* An event loop has a time service which is like an async engine but never + * generates events and there can only be one such service. + */ + +class StubTime : public TimeEngine +{ + +public: + StubTime() : calls(0) {} + + int calls; + void tick() + { + ++calls; + } +}; + +void +testEventLoop::testSetTimeService() +{ + EventLoop theLoop; + StubTime myTime; + /* the loop will not error without a time service */ + theLoop.runOnce(); + /* we can set the time service */ + theLoop.setTimeService(&myTime); + /* it invokes our tick() call */ + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(1, myTime.calls); + /* it invokes our tick() call again */ + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(2, myTime.calls); +} + +/* one async engine is the primary engine - the engine that is allowed to block. + * this defaults to the last added one, but can be explicitly nominated + */ +void +testEventLoop::testSetPrimaryEngine() +{ + EventLoop theLoop; + RecordingEngine first_engine(10); + RecordingEngine second_engine(10); + /* one engine - gets a timeout */ + theLoop.registerEngine(&first_engine); + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(10, first_engine.lasttimeout); + /* two engines - the second gets the timeout */ + theLoop.registerEngine(&second_engine); + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(0, first_engine.lasttimeout); + CPPUNIT_ASSERT_EQUAL(10, second_engine.lasttimeout); + /* set the first engine to be primary explicitly and now gets the timeout */ + theLoop.setPrimaryEngine(&first_engine); + theLoop.runOnce(); + CPPUNIT_ASSERT_EQUAL(10, first_engine.lasttimeout); + CPPUNIT_ASSERT_EQUAL(0, second_engine.lasttimeout); + +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testEventLoop.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,42 @@ + +#ifndef SQUID_SRC_TEST_EVENTLOOP_H +#define SQUID_SRC_TEST_EVENTLOOP_H + +#include + +/* + * test the EventLoop implementation + */ + +class testEventLoop : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testEventLoop ); + CPPUNIT_TEST( testCreate ); + CPPUNIT_TEST( testRunOnce ); + CPPUNIT_TEST( testRegisterDispatcher ); + CPPUNIT_TEST( testRegisterEngine ); + CPPUNIT_TEST( testEngineTimeout ); + CPPUNIT_TEST( testSetTimeService ); + CPPUNIT_TEST( testSetPrimaryEngine ); + CPPUNIT_TEST( testStopOnIdle ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testCreate(); + void testEngineTimeout(); + void testRunOnce(); + void testRegisterDispatcher(); + void testRegisterEngine(); + void testSetTimeService(); + void testSetPrimaryEngine(); + void testStopOnIdle(); + /* TODO: + * test that engine which errors a couple of times, then returns 0, then + * errors 10 times in a row triggers a fail on the 10th time around + */ +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_ACL.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "ACL.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_AsyncEngine.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "AsyncEngine.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_CompletionDispatcher.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "CompletionDispatcher.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_ConfigParser.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "ConfigParser.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_EventLoop.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "EventLoop.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_HttpHeader.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "HttpHeader.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_HttpHeaderRange.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "HttpHeaderRange.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_HttpReply.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "HttpReply.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_HttpRequestMethod.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "HttpRequestMethod.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_RemovalPolicy.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "RemovalPolicy.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_SquidTime.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "SquidTime.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_Store.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "Store.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_StoreEntryStream.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "StoreEntryStream.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_URL.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "URL.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_URLScheme.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "URLScheme.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_cbdata.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "cbdata.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_client_side_request.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "client_side_request.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_comm.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "comm.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_dlink.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "dlink.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_errorpage.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "errorpage.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_event.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "event.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHeader_wordlist.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,4 @@ +/* This test tests that the header below can be processed on its own with + * no other #includes. Dont add any! + */ +#include "wordlist.h" --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHttpRequest.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,92 @@ +#include "squid.h" +#include + +#include "Mem.h" +#include "testHttpRequest.h" +#include "HttpRequest.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testHttpRequest ); + +/* stub functions to link successfully */ +void +shut_down(int) +{} + +/* end stubs */ + +/* init memory pools */ + +struct Initer +{ + Initer() {Mem::Init();} +}; + +static Initer ensure_mempools; + +/* + * Test creating an HttpRequest object from a Url and method + */ +void +testHttpRequest::testCreateFromUrlAndMethod() +{ + /* vanilla url */ + ushort expected_port; + char * url = xstrdup("http://foo:90/bar"); + HttpRequest *aRequest = HttpRequest::CreateFromUrlAndMethod(url, METHOD_GET); + expected_port = 90; + HttpRequest *nullRequest = NULL; + CPPUNIT_ASSERT_EQUAL(expected_port, aRequest->port); + CPPUNIT_ASSERT_EQUAL(METHOD_GET, aRequest->method); + CPPUNIT_ASSERT_EQUAL(String("foo"), String(aRequest->host)); + CPPUNIT_ASSERT_EQUAL(String("/bar"), aRequest->urlpath); + CPPUNIT_ASSERT_EQUAL(PROTO_HTTP, aRequest->protocol); + CPPUNIT_ASSERT_EQUAL(String("http://foo:90/bar"), String(url)); + xfree(url); + /* vanilla url, different method */ + url = xstrdup("http://foo/bar"); + aRequest = HttpRequest::CreateFromUrlAndMethod(url, METHOD_PUT); + expected_port = 80; + CPPUNIT_ASSERT_EQUAL(expected_port, aRequest->port); + CPPUNIT_ASSERT_EQUAL(METHOD_PUT, aRequest->method); + CPPUNIT_ASSERT_EQUAL(String("foo"), String(aRequest->host)); + CPPUNIT_ASSERT_EQUAL(String("/bar"), aRequest->urlpath); + CPPUNIT_ASSERT_EQUAL(PROTO_HTTP, aRequest->protocol); + CPPUNIT_ASSERT_EQUAL(String("http://foo/bar"), String(url)); + /* a connect url with non-CONNECT data */ + url = xstrdup(":foo/bar"); + aRequest = HttpRequest::CreateFromUrlAndMethod(url, METHOD_CONNECT); + xfree(url); + CPPUNIT_ASSERT_EQUAL(nullRequest, aRequest); + /* a CONNECT url with CONNECT data */ + url = xstrdup("foo:45"); + aRequest = HttpRequest::CreateFromUrlAndMethod(url, METHOD_CONNECT); + expected_port = 45; + CPPUNIT_ASSERT_EQUAL(expected_port, aRequest->port); + CPPUNIT_ASSERT_EQUAL(METHOD_CONNECT, aRequest->method); + CPPUNIT_ASSERT_EQUAL(String("foo"), String(aRequest->host)); + CPPUNIT_ASSERT_EQUAL(String(""), aRequest->urlpath); + CPPUNIT_ASSERT_EQUAL(PROTO_NONE, aRequest->protocol); + CPPUNIT_ASSERT_EQUAL(String("foo:45"), String(url)); + xfree(url); +} + +/* + * Test creating an HttpRequest object from a Url alone. + */ +void +testHttpRequest::testCreateFromUrl() +{ + /* vanilla url */ + ushort expected_port; + char * url = xstrdup("http://foo:90/bar"); + HttpRequest *aRequest = HttpRequest::CreateFromUrl(url); + expected_port = 90; + CPPUNIT_ASSERT_EQUAL(expected_port, aRequest->port); + CPPUNIT_ASSERT_EQUAL(METHOD_GET, aRequest->method); + CPPUNIT_ASSERT_EQUAL(String("foo"), String(aRequest->host)); + CPPUNIT_ASSERT_EQUAL(String("/bar"), aRequest->urlpath); + CPPUNIT_ASSERT_EQUAL(PROTO_HTTP, aRequest->protocol); + CPPUNIT_ASSERT_EQUAL(String("http://foo:90/bar"), String(url)); + xfree(url); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHttpRequest.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,26 @@ + +#ifndef SQUID_SRC_TEST_HTTP_REQUEST_H +#define SQUID_SRC_TEST_HTTP_REQUEST_H + +#include + +/* + * test HttpRequest + */ + +class testHttpRequest : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testHttpRequest ); + CPPUNIT_TEST( testCreateFromUrlAndMethod ); + CPPUNIT_TEST( testCreateFromUrl ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testCreateFromUrlAndMethod(); + void testCreateFromUrl(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHttpRequestMethod.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,119 @@ +#include "squid.h" +#include +#include + +#include "Mem.h" +#include "testHttpRequestMethod.h" +#include "HttpRequestMethod.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testHttpRequestMethod ); + + +/* + * We should be able to make an HttpRequestMethod straight from a string. + */ +void +testHttpRequestMethod::testConstructCharStart() +{ + /* parse an empty string -> METHOD_NONE */ + CPPUNIT_ASSERT(METHOD_NONE == HttpRequestMethod(NULL)); + /* parsing a literal should work */ + CPPUNIT_ASSERT(METHOD_GET == HttpRequestMethod("GET", NULL)); +} + +/* + * We can also parse precise ranges of characters + */ +void +testHttpRequestMethod::testConstructCharStartEnd() +{ + char const * buffer; + /* parse an empty string -> METHOD_NONE */ + CPPUNIT_ASSERT(METHOD_NONE == HttpRequestMethod(NULL, NULL)); + /* parsing a literal should work */ + CPPUNIT_ASSERT(METHOD_GET == HttpRequestMethod("GET", NULL)); + /* parsing with an explicit end should work */ + buffer = "POSTPLUS"; + CPPUNIT_ASSERT(METHOD_POST == HttpRequestMethod(buffer, buffer + 4)); +} + +/* + * we should be able to assign a method_t to a HttpRequestMethod + */ +void +testHttpRequestMethod::testAssignFrommethod_t() +{ + HttpRequestMethod method; + method = METHOD_NONE; + CPPUNIT_ASSERT_EQUAL(HttpRequestMethod(METHOD_NONE), method); + method = METHOD_POST; + CPPUNIT_ASSERT_EQUAL(HttpRequestMethod(METHOD_POST), method); +} + +/* + * a default constructed HttpRequestMethod is == METHOD_NONE + */ +void +testHttpRequestMethod::testDefaultConstructor() +{ + HttpRequestMethod lhs; + HttpRequestMethod rhs(METHOD_NONE); + CPPUNIT_ASSERT_EQUAL(lhs, rhs); +} + +/* + * we should be able to construct a HttpRequestMethod from a method_t + */ +void +testHttpRequestMethod::testConstructmethod_t() +{ + CPPUNIT_ASSERT_EQUAL(HttpRequestMethod(METHOD_NONE), HttpRequestMethod(METHOD_NONE)); + CPPUNIT_ASSERT_EQUAL(HttpRequestMethod(METHOD_POST), HttpRequestMethod(METHOD_POST)); + CPPUNIT_ASSERT(HttpRequestMethod(METHOD_NONE) != HttpRequestMethod(METHOD_POST)); +} + +/* + * we should be able to get a char const * version of the method. + */ +void +testHttpRequestMethod::testConst_str() +{ + CPPUNIT_ASSERT_EQUAL(String("POST"), String(HttpRequestMethod("post").const_str())); +} + +/* + * an HttpRequestMethod should be comparable to a method_t without false + * matches + */ +void +testHttpRequestMethod::testEqualmethod_t() +{ + CPPUNIT_ASSERT(HttpRequestMethod(METHOD_NONE) == METHOD_NONE); + CPPUNIT_ASSERT(not (HttpRequestMethod(METHOD_POST) == METHOD_GET)); + CPPUNIT_ASSERT(METHOD_GET == HttpRequestMethod(METHOD_GET)); + CPPUNIT_ASSERT(not (METHOD_SEARCH == HttpRequestMethod(METHOD_TRACE))); +} + +/* + * an HttpRequestMethod should testable for inequality without fail maatches + */ +void +testHttpRequestMethod::testNotEqualmethod_t() +{ + CPPUNIT_ASSERT(HttpRequestMethod(METHOD_NONE) != METHOD_GET); + CPPUNIT_ASSERT(not (HttpRequestMethod(METHOD_POST) != METHOD_POST)); + CPPUNIT_ASSERT(METHOD_NONE != HttpRequestMethod(METHOD_GET)); + CPPUNIT_ASSERT(not (METHOD_SEARCH != HttpRequestMethod(METHOD_SEARCH))); +} + +/* + * we should be able to send it to a stream and get the normalised version + */ +void +testHttpRequestMethod::testStream() +{ + std::ostringstream buffer; + buffer << HttpRequestMethod("get"); + CPPUNIT_ASSERT_EQUAL(String("GET"), String(buffer.str().c_str())); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testHttpRequestMethod.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,40 @@ + +#ifndef SQUID_SRC_TEST_HTTP_REQUEST_METHOD_H +#define SQUID_SRC_TEST_HTTP_REQUEST_METHOD_H + +#include + +/* + * test HttpRequestMethod + */ + +class testHttpRequestMethod : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testHttpRequestMethod ); + CPPUNIT_TEST( testAssignFrommethod_t ); + CPPUNIT_TEST( testConstructmethod_t ); + CPPUNIT_TEST( testConstructCharStart ); + CPPUNIT_TEST( testConstructCharStartEnd ); + CPPUNIT_TEST( testDefaultConstructor ); + CPPUNIT_TEST( testEqualmethod_t ); + CPPUNIT_TEST( testNotEqualmethod_t ); + CPPUNIT_TEST( testConst_str ); + CPPUNIT_TEST( testStream ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testAssignFrommethod_t(); + void testConstructmethod_t(); + void testConstructCharStart(); + void testConstructCharStartEnd(); + void testConst_str(); + void testDefaultConstructor(); + void testEqualmethod_t(); + void testNotEqualmethod_t(); + void testStream(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testStoreEntryStream.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,48 @@ +#include "squid.h" +#include "Mem.h" +#include "testStore.h" +#include "testStoreEntryStream.h" +#include "CapturingStoreEntry.h" +#include "Store.h" +#include "StoreEntryStream.h" + +#include + +#include + +CPPUNIT_TEST_SUITE_REGISTRATION( testStoreEntryStream ); + +/* init memory pools */ + +struct Initer +{ + Initer() {Mem::Init();} +}; + +static Initer ensure_mempools; + +void +testStoreEntryStream::testGetStream() +{ + /* Setup a store root so we can create a StoreEntry */ + StorePointer aStore (new TestStore); + Store::Root(aStore); + + CapturingStoreEntry * anEntry = new CapturingStoreEntry(); + { + StoreEntryStream stream(anEntry); + CPPUNIT_ASSERT_EQUAL(1, anEntry->_buffer_calls); + CPPUNIT_ASSERT_EQUAL(0, anEntry->_flush_calls); + stream << "some text" << std::setw(4) << "!"; + CPPUNIT_ASSERT_EQUAL(1, anEntry->_buffer_calls); + CPPUNIT_ASSERT_EQUAL(0, anEntry->_flush_calls); + stream.flush(); + CPPUNIT_ASSERT_EQUAL(1, anEntry->_buffer_calls); + CPPUNIT_ASSERT_EQUAL(1, anEntry->_flush_calls); + CPPUNIT_ASSERT_EQUAL(String("some text !"), anEntry->_appended_text); + } + + delete anEntry; + + Store::Root(NULL); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testStoreEntryStream.h Wed Feb 14 13:38:03 2007 @@ -0,0 +1,24 @@ + +#ifndef SQUID_SRC_TEST_STORE_ENTRY_STREAM_H +#define SQUID_SRC_TEST_STORE_ENTRY_STREAM_H + +#include + +/* + * test StoreEntryStream + */ + +class testStoreEntryStream : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testStoreEntryStream ); + CPPUNIT_TEST( testGetStream ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testGetStream(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testStoreSupport.cc Wed Feb 14 13:38:03 2007 @@ -0,0 +1,47 @@ + +/* + * DEBUG: + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "testStoreSupport.h" +#include "event.h" +#include "EventLoop.h" +#include "SquidTime.h" + +/* construct a stock loop with event dispatching, a time service that advances + * 1 second a tick + */ +StockEventLoop::StockEventLoop() : default_time_engine(TimeEngine()) +{ + registerDispatcher(EventDispatcher::GetInstance()); + registerEngine(EventScheduler::GetInstance()); + setTimeService(&default_time_engine); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testStoreSupport.h Wed Feb 14 13:38:04 2007 @@ -0,0 +1,51 @@ + +/* + * DEBUG: + * AUTHOR: Robert Collins + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#ifndef SQUID_TESTSTORESUPPORT_H +#define SQUID_TESTSTORESUPPORT_H + +#include "EventLoop.h" + +/* construct a stock loop with event dispatching, a time service that advances + * 1 second a tick + */ + +class StockEventLoop : public EventLoop +{ + +public: + StockEventLoop(); + TimeEngine default_time_engine; +}; + +#endif /* SQUID_TESTSTORESUPPORT_H */ --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testString.cc Wed Feb 14 13:38:04 2007 @@ -0,0 +1,61 @@ +#include "squid.h" +#include "event.h" +#include "Mem.h" +#include "SquidString.h" +#include "testString.h" + +CPPUNIT_TEST_SUITE_REGISTRATION( testString ); + +/* let this test link sanely */ +void +eventAdd(const char *name, EVH * func, void *arg, double when, int, bool cbdata) +{} + +/* init memory pools */ + +struct Initer +{ + Initer() {Mem::Init();} +}; + +static Initer ensure_mempools; + +void +testString::testCmpDefault() +{ + String left, right; + /* two default strings are equal */ + CPPUNIT_ASSERT(!left.cmp(right)); + CPPUNIT_ASSERT(!left.cmp(NULL)); + CPPUNIT_ASSERT(!left.cmp(NULL, 1)); +} + +void +testString::testCmpEmptyString() +{ + String left(""); + String right; + /* an empty string ("") is equal to a default string */ + CPPUNIT_ASSERT(!left.cmp(right)); + CPPUNIT_ASSERT(!left.cmp(NULL)); + CPPUNIT_ASSERT(!left.cmp(NULL, 1)); + /* reverse the order to catch corners */ + CPPUNIT_ASSERT(!right.cmp(left)); + CPPUNIT_ASSERT(!right.cmp("")); + CPPUNIT_ASSERT(!right.cmp("", 1)); +} + +void +testString::testCmpNotEmptyDefault() +{ + String left("foo"); + String right; + /* empty string sorts before everything */ + CPPUNIT_ASSERT(left.cmp(right) > 0); + CPPUNIT_ASSERT(left.cmp(NULL) > 0); + CPPUNIT_ASSERT(left.cmp(NULL, 1) > 0); + /* reverse for symmetry tests */ + CPPUNIT_ASSERT(right.cmp(left) < 0); + CPPUNIT_ASSERT(right.cmp("foo") < 0); + CPPUNIT_ASSERT(right.cmp("foo", 1) < 0); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testString.h Wed Feb 14 13:38:04 2007 @@ -0,0 +1,28 @@ + +#ifndef SQUID_SRC_TEST_STRING_H +#define SQUID_SRC_TEST_STRING_H + +#include + +/* + * test the store framework + */ + +class testString : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testString ); + CPPUNIT_TEST( testCmpDefault ); + CPPUNIT_TEST( testCmpEmptyString ); + CPPUNIT_TEST( testCmpNotEmptyDefault ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testCmpDefault(); + void testCmpEmptyString(); + void testCmpNotEmptyDefault(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testURL.cc Wed Feb 14 13:38:04 2007 @@ -0,0 +1,59 @@ +#include "squid.h" +#include +#include + +#include "Mem.h" +#include "testURL.h" +#include "URL.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testURL ); + +/* stub functions to link successfully */ +void +shut_down(int) +{} + +/* end stubs */ + +/* init memory pools */ + +struct Initer +{ + Initer() {Mem::Init();} +}; + +static Initer ensure_mempools; + +/* + * we can construct a URL with a URLScheme. + * This creates a URL for that scheme. + */ +void +testURL::testConstructScheme() +{ + URLScheme empty_scheme; + URL protoless_url(PROTO_NONE); + CPPUNIT_ASSERT_EQUAL(empty_scheme, protoless_url.getScheme()); + + URLScheme ftp_scheme(PROTO_FTP); + URL ftp_url(PROTO_FTP); + CPPUNIT_ASSERT_EQUAL(ftp_scheme, ftp_url.getScheme()); +} + +/* + * a default constructed URL has scheme "NONE". + * Also, we should be able to use new and delete on + * scheme instances. + */ +void +testURL::testDefaultConstructor() +{ + URLScheme aScheme; + URL aUrl; + CPPUNIT_ASSERT_EQUAL(aScheme, aUrl.getScheme()); + + URL *urlPointer = new URL; + CPPUNIT_ASSERT(urlPointer != NULL); + delete urlPointer; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testURL.h Wed Feb 14 13:38:04 2007 @@ -0,0 +1,27 @@ + +#ifndef SQUID_SRC_TEST_URL_H +#define SQUID_SRC_TEST_URL_H + +#include + +/* + * test the URL class. + */ + +class testURL : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testURL ); + CPPUNIT_TEST( testConstructScheme ); + CPPUNIT_TEST( testDefaultConstructor ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + + void testConstructScheme(); + void testDefaultConstructor(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testURLScheme.cc Wed Feb 14 13:38:04 2007 @@ -0,0 +1,149 @@ +#include "squid.h" +#include +#include + +#include "Mem.h" +#include "testURLScheme.h" +#include "URLScheme.h" + + +CPPUNIT_TEST_SUITE_REGISTRATION( testURLScheme ); + + +#if 0 +/* + * We should be able to make an HttpRequestMethod straight from a string. + */ +void +testHttpRequestMethod::testConstructCharStart() +{ + /* parse an empty string -> METHOD_NONE */ + CPPUNIT_ASSERT(METHOD_NONE == HttpRequestMethod(NULL)); + /* parsing a literal should work */ + CPPUNIT_ASSERT(METHOD_GET == HttpRequestMethod("GET", NULL)); +} + +/* + * We can also parse precise ranges of characters + */ +void +testHttpRequestMethod::testConstructCharStartEnd() +{ + char const * buffer; + /* parse an empty string -> METHOD_NONE */ + CPPUNIT_ASSERT(METHOD_NONE == HttpRequestMethod(NULL, NULL)); + /* parsing a literal should work */ + CPPUNIT_ASSERT(METHOD_GET == HttpRequestMethod("GET", NULL)); + /* parsing with an explicit end should work */ + buffer = "POSTPLUS"; + CPPUNIT_ASSERT(METHOD_POST == HttpRequestMethod(buffer, buffer + 4)); +} + +#endif + +/* + * we should be able to assign a protocol_t to a URLScheme for ease + * of code conversion + */ +void +testURLScheme::testAssignFromprotocol_t() +{ + URLScheme empty_scheme; + URLScheme scheme; + scheme = PROTO_NONE; + CPPUNIT_ASSERT_EQUAL(empty_scheme, scheme); + + URLScheme https_scheme(PROTO_HTTPS); + scheme = PROTO_HTTPS; + CPPUNIT_ASSERT_EQUAL(https_scheme, scheme); +} + +/* + * We should be able to get a protocol_t from a URLScheme for ease + * of migration + */ +void +testURLScheme::testCastToprotocol_t() +{ + /* explicit cast */ + protocol_t protocol = (protocol_t) URLScheme(); + CPPUNIT_ASSERT_EQUAL(PROTO_NONE, protocol); + /* and implicit */ + protocol = URLScheme(PROTO_HTTP); + CPPUNIT_ASSERT_EQUAL(PROTO_HTTP, protocol); +} + +/* + * a default constructed URLScheme is == PROTO_NONE + */ +void +testURLScheme::testDefaultConstructor() +{ + URLScheme lhs; + URLScheme rhs(PROTO_NONE); + CPPUNIT_ASSERT_EQUAL(lhs, rhs); +} + +/* + * we should be able to construct a URLScheme from the old 'protocol_t' enum. + */ +void +testURLScheme::testConstructprotocol_t() +{ + URLScheme lhs_none(PROTO_NONE), rhs_none(PROTO_NONE); + CPPUNIT_ASSERT_EQUAL(lhs_none, rhs_none); + + URLScheme lhs_cacheobj(PROTO_CACHEOBJ), rhs_cacheobj(PROTO_CACHEOBJ); + CPPUNIT_ASSERT_EQUAL(lhs_cacheobj, rhs_cacheobj); + CPPUNIT_ASSERT(lhs_none != rhs_cacheobj); +} + +/* + * we should be able to get a char const * version of the method. + */ +void +testURLScheme::testConst_str() +{ + String lhs("wais"); + URLScheme wais(PROTO_WAIS); + String rhs(wais.const_str()); + CPPUNIT_ASSERT_EQUAL(lhs, rhs); +} + +/* + * a URLScheme replaces protocol_t, so we should be able to test for equality on + * either the left or right hand side seamlessly. + */ +void +testURLScheme::testEqualprotocol_t() +{ + CPPUNIT_ASSERT(URLScheme() == PROTO_NONE); + CPPUNIT_ASSERT(not (URLScheme(PROTO_WAIS) == PROTO_HTTP)); + CPPUNIT_ASSERT(PROTO_HTTP == URLScheme(PROTO_HTTP)); + CPPUNIT_ASSERT(not (PROTO_CACHEOBJ == URLScheme(PROTO_HTTP))); +} + +/* + * a URLScheme should testable for inequality with a protocol_t. + */ +void +testURLScheme::testNotEqualprotocol_t() +{ + CPPUNIT_ASSERT(URLScheme(PROTO_NONE) != PROTO_HTTP); + CPPUNIT_ASSERT(not (URLScheme(PROTO_HTTP) != PROTO_HTTP)); + CPPUNIT_ASSERT(PROTO_NONE != URLScheme(PROTO_HTTP)); + CPPUNIT_ASSERT(not (PROTO_WAIS != URLScheme(PROTO_WAIS))); +} + +/* + * we should be able to send it to a stream and get the normalised version + */ +void +testURLScheme::testStream() +{ + std::ostringstream buffer; + buffer << URLScheme(PROTO_HTTP); + String http_str("http"); + String from_buf(buffer.str().c_str()); + CPPUNIT_ASSERT_EQUAL(http_str, from_buf); +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/testURLScheme.h Wed Feb 14 13:38:04 2007 @@ -0,0 +1,50 @@ + +#ifndef SQUID_SRC_TEST_URL_SCHEME_H +#define SQUID_SRC_TEST_URL_SCHEME_H + +#include + +/* + * test URLScheme + */ + +class testURLScheme : public CPPUNIT_NS::TestFixture +{ + CPPUNIT_TEST_SUITE( testURLScheme ); + CPPUNIT_TEST( testAssignFromprotocol_t ); + CPPUNIT_TEST( testCastToprotocol_t ); + CPPUNIT_TEST( testConstructprotocol_t ); +#if 0 + + CPPUNIT_TEST( testConstructCharStart ); + CPPUNIT_TEST( testConstructCharStartEnd ); +#endif + + CPPUNIT_TEST( testDefaultConstructor ); + CPPUNIT_TEST( testEqualprotocol_t ); + CPPUNIT_TEST( testNotEqualprotocol_t ); + CPPUNIT_TEST( testConst_str ); + CPPUNIT_TEST( testStream ); + CPPUNIT_TEST_SUITE_END(); + +public: + +protected: + void testAssignFromprotocol_t(); + void testCastToprotocol_t(); + void testConstructprotocol_t(); +#if 0 + + void testConstructCharStart(); + void testConstructCharStartEnd(); +#endif + + void testConst_str(); + void testDefaultConstructor(); + void testEqualprotocol_t(); + void testNotEqualprotocol_t(); + void testStream(); +}; + +#endif + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/src/tests/test_http_range.cc Wed Feb 14 13:38:04 2007 @@ -0,0 +1,201 @@ + +/* + * $Id: test_http_range.cc,v 1.1.10.2 2006/09/29 23:16:07 dwsquid Exp $ + * + * DEBUG: section 64 HTTP Range Header + * AUTHOR: Alex Rousskov + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "squid.h" +#include "Mem.h" +//#include "Store.h" +#include "HttpHeaderRange.h" +//#include "client_side_request.h" +#include "ACLChecklist.h" + +/* Stub routines */ +void +shut_down(int) +{} + +SQUIDCEXTERN void httpHeaderPutStr(HttpHeader * hdr, http_hdr_type type, const char *str) +{ + fatal ("dummy function\n"); +} + +SQUIDCEXTERN HttpHeaderEntry *httpHeaderGetEntry(const HttpHeader * hdr, HttpHeaderPos * pos) +{ + fatal ("dummy function\n"); + return NULL; +} + +extern String httpHeaderGetList(const HttpHeader * hdr, http_hdr_type id) +{ + fatal ("dummy function\n"); + return String(); +} + +SQUIDCEXTERN int httpHeaderHas(const HttpHeader * hdr, http_hdr_type type) +{ + fatal ("dummy function\n"); + return 0; +} + +SQUIDCEXTERN void httpHeaderPutContRange(HttpHeader * hdr, const HttpHdrContRange * cr) +{ + fatal ("dummy function\n"); +} + +void +testRangeParser(char const *rangestring) +{ + String aString (rangestring); + HttpHdrRange *range = HttpHdrRange::ParseCreate (&aString); + + if (!range) + exit (1); + + HttpHdrRange copy(*range); + + assert (copy.specs.count == range->specs.count); + + HttpHdrRange::iterator pos = range->begin(); + + assert (*pos); + + delete range; +} + +HttpHdrRange * +rangeFromString(char const *rangestring) +{ + String aString (rangestring); + HttpHdrRange *range = HttpHdrRange::ParseCreate (&aString); + + if (!range) + exit (1); + + return range; +} + +void +testRangeIter () +{ + HttpHdrRange *range=rangeFromString("bytes=0-3, 1-, -2"); + assert (range->specs.count == 3); + size_t counter = 0; + HttpHdrRange::iterator i = range->begin(); + + while (i != range->end()) { + ++counter; + ++i; + } + + assert (counter == 3); + i = range->begin(); + assert (i - range->begin() == 0); + ++i; + assert (i - range->begin() == 1); + assert (i - range->end() == -2); +} + +void +testRangeCanonization() +{ + HttpHdrRange *range=rangeFromString("bytes=0-3, 1-, -2"); + assert (range->specs.count == 3); + + /* 0-3 needs a content length of 4 */ + /* This passes in the extant code - but should it? */ + + if (!range->canonize(3)) + exit(1); + + assert (range->specs.count == 3); + + delete range; + + range=rangeFromString("bytes=0-3, 1-, -2"); + + assert (range->specs.count == 3); + + /* 0-3 needs a content length of 4 */ + if (!range->canonize(4)) + exit(1); + + delete range; + + range=rangeFromString("bytes=3-6"); + + assert (range->specs.count == 1); + + /* 3-6 needs a content length of 4 or more */ + if (range->canonize(3)) + exit(1); + + delete range; + + range=rangeFromString("bytes=3-6"); + + assert (range->specs.count == 1); + + /* 3-6 needs a content length of 4 or more */ + if (!range->canonize(4)) + exit(1); + + delete range; + + range=rangeFromString("bytes=1-1,2-3"); + + assert (range->specs.count == 2); + + if (!range->canonize(4)) + exit(1); + + assert (range->specs.count == 2); + + delete range; +} + +int +main (int argc, char **argv) +{ + Mem::Init(); + /* enable for debugging to console */ + // _db_init (NULL, NULL); + // Debug::Levels[64] = 9; + testRangeParser ("bytes=0-3"); + testRangeParser ("bytes=-3"); + testRangeParser ("bytes=1-"); + testRangeParser ("bytes=0-3, 1-, -2"); + testRangeIter (); + testRangeCanonization(); + return 0; +} --- squid3/test-suite/http_range_test.cc Wed Feb 14 13:38:04 2007 +++ /dev/null Wed Feb 14 13:37:19 2007 @@ -1,283 +0,0 @@ - -/* - * $Id: http_range_test.cc,v 1.12 2003/09/23 02:12:33 squidadm Exp $ - * - * DEBUG: section 64 HTTP Range Header - * AUTHOR: Alex Rousskov - * - * SQUID Web Proxy Cache http://www.squid-cache.org/ - * ---------------------------------------------------------- - * - * Squid is the result of efforts by numerous individuals from - * the Internet community; see the CONTRIBUTORS file for full - * details. Many organizations have provided support for Squid's - * development; see the SPONSORS file for full details. Squid is - * Copyrighted (C) 2001 by the Regents of the University of - * California; see the COPYRIGHT file for full details. Squid - * incorporates software developed and/or copyrighted by other - * sources; see the CREDITS file for full details. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. - * - */ - -#include "squid.h" -#include "Mem.h" -//#include "Store.h" -#include "HttpHeaderRange.h" -//#include "client_side_request.h" -#include "ACLChecklist.h" - -/* Stub routines */ -SQUIDCEXTERN void -cachemgrRegister(const char *, const char *, OBJH *, int, int) -{} - -SQUIDCEXTERN void httpHeaderPutStr(HttpHeader * hdr, http_hdr_type type, const char *str) -{ - fatal ("dummy function\n"); -} - -#if STDC_HEADERS -SQUIDCEXTERN void -storeAppendPrintf(StoreEntry *, const char *,...) -#else -SQUIDCEXTERN void storeAppendPrintf() -#endif -{ - fatal ("dummy function\n"); -} - -extern -void eventAdd(const char *name, EVH * func, void *arg, double when, int, bool) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void -storeBuffer(StoreEntry * e) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void -storeBufferFlush(StoreEntry * e) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void storeAppend(StoreEntry *, const char *, int) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void storeAppendVPrintf(StoreEntry *, const char *, va_list ap) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void httpHeaderDelAt(HttpHeader * hdr, HttpHeaderPos pos) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN HttpHeaderEntry *httpHeaderGetEntry(const HttpHeader * hdr, HttpHeaderPos * pos) -{ - fatal ("dummy function\n"); - return NULL; -} - -int -ACLChecklist::fastCheck() -{ - fatal ("dummy function\n"); - return 0; -} - -void -ACLChecklist::operator delete (void *address) -{ - safe_free( address); -} - -ACLChecklist::~ACLChecklist(){} - -SQUIDCEXTERN ACLChecklist *aclChecklistCreate(const acl_access *, - HttpRequest *, - const char *ident) -{ - fatal ("dummy function\n"); - return NULL; -} - -extern String httpHeaderGetList(const HttpHeader * hdr, http_hdr_type id) -{ - fatal ("dummy function\n"); - return String(); -} - -SQUIDCEXTERN int httpHeaderHas(const HttpHeader * hdr, http_hdr_type type) -{ - fatal ("dummy function\n"); - return 0; -} - -SQUIDCEXTERN void httpHdrContRangeDestroy(HttpHdrContRange * crange) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void httpHdrContRangeSet(HttpHdrContRange *, HttpHdrRangeSpec, ssize_t) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN void httpHeaderPutContRange(HttpHeader * hdr, const HttpHdrContRange * cr) -{ - fatal ("dummy function\n"); -} - -SQUIDCEXTERN HttpHdrContRange *httpHdrContRangeCreate(void) -{ - fatal ("dummy function\n"); - return NULL; -} - -void -testRangeParser(char const *rangestring) -{ - String aString (rangestring); - HttpHdrRange *range = HttpHdrRange::ParseCreate (&aString); - - if (!range) - exit (1); - - HttpHdrRange copy(*range); - - assert (copy.specs.count == range->specs.count); - - HttpHdrRange::iterator pos = range->begin(); - - assert (*pos); - - delete range; -} - -HttpHdrRange * -rangeFromString(char const *rangestring) -{ - String aString (rangestring); - HttpHdrRange *range = HttpHdrRange::ParseCreate (&aString); - - if (!range) - exit (1); - - return range; -} - -void -testRangeIter () -{ - HttpHdrRange *range=rangeFromString("bytes=0-3, 1-, -2"); - assert (range->specs.count == 3); - size_t counter = 0; - HttpHdrRange::iterator i = range->begin(); - - while (i != range->end()) { - ++counter; - ++i; - } - - assert (counter == 3); - i = range->begin(); - assert (i - range->begin() == 0); - ++i; - assert (i - range->begin() == 1); - assert (i - range->end() == -2); -} - -void -testRangeCanonization() -{ - HttpHdrRange *range=rangeFromString("bytes=0-3, 1-, -2"); - assert (range->specs.count == 3); - - /* 0-3 needs a content length of 4 */ - /* This passes in the extant code - but should it? */ - - if (!range->canonize(3)) - exit(1); - - assert (range->specs.count == 3); - - delete range; - - range=rangeFromString("bytes=0-3, 1-, -2"); - - assert (range->specs.count == 3); - - /* 0-3 needs a content length of 4 */ - if (!range->canonize(4)) - exit(1); - - delete range; - - range=rangeFromString("bytes=3-6"); - - assert (range->specs.count == 1); - - /* 3-6 needs a content length of 4 or more */ - if (range->canonize(3)) - exit(1); - - delete range; - - range=rangeFromString("bytes=3-6"); - - assert (range->specs.count == 1); - - /* 3-6 needs a content length of 4 or more */ - if (!range->canonize(4)) - exit(1); - - delete range; - - range=rangeFromString("bytes=1-1,2-3"); - - assert (range->specs.count == 2); - - if (!range->canonize(4)) - exit(1); - - assert (range->specs.count == 2); - - delete range; -} - -int -main (int argc, char **argv) -{ - Mem::Init(); - /* enable for debugging to console */ - // _db_init (NULL, NULL); - // Debug::Levels[64] = 9; - testRangeParser ("bytes=0-3"); - testRangeParser ("bytes=-3"); - testRangeParser ("bytes=1-"); - testRangeParser ("bytes=0-3, 1-, -2"); - testRangeIter (); - testRangeCanonization(); - return 0; -} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/tools/.cvsignore Wed Feb 14 13:38:04 2007 @@ -0,0 +1,6 @@ +.deps +.libs +Makefile +cachemgr.cgi +squidclient +Makefile.in --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/tools/Makefile.am Wed Feb 14 13:38:04 2007 @@ -0,0 +1,56 @@ +# +# Makefile for the Squid Object Cache server +# +# $Id: Makefile.am,v 1.1.12.2 2006/09/29 23:16:07 dwsquid Exp $ +# +# Uncomment and customize the following to suit your needs: +# + + +AUTOMAKE_OPTIONS = subdir-objects + +INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_srcdir)/include -I$(top_srcdir)/lib/libTrie/include +INCLUDES += @SQUID_CPPUNIT_INC@ + +TESTS=$(check_PROGRAMS) +check_PROGRAMS= + +SUBDIRS = + +bin_PROGRAMS = \ + squidclient + +libexec_PROGRAMS = \ + cachemgr$(CGIEXT) + +squidclient_SOURCES = squidclient.cc +cachemgr__CGIEXT__SOURCES = cachemgr.cc +cachemgr__CGIEXT__CFLAGS = -DDEFAULT_CACHEMGR_CONFIG=\"$(DEFAULT_CACHEMGR_CONFIG)\" $(AM_CFLAGS) + +LDADD = -L../lib -lmiscutil $(XTRA_LIBS) + +EXTRA_DIST = \ + cachemgr.conf + +DEFAULT_CACHEMGR_CONFIG = $(sysconfdir)/cachemgr.conf + +$(OBJS): $(top_srcdir)/include/version.h ../include/autoconf.h + +install-data-local: + @if test -f $(DESTDIR)$(DEFAULT_CACHEMGR_CONFIG) ; then \ + echo "$@ will not overwrite existing $(DESTDIR)$(DEFAULT_CACHEMGR_CONFIG)" ; \ + else \ + echo "$(INSTALL_DATA) $(srcdir)/cachemgr.conf $(DESTDIR)$(DEFAULT_CACHEMGR_CONFIG)"; \ + $(INSTALL_DATA) $(srcdir)/cachemgr.conf $(DESTDIR)$(DEFAULT_CACHEMGR_CONFIG); \ + fi + +uninstall-local: + +# Don't automatically uninstall config files +# @if test -f $(DESTDIR)$(DEFAULT_CONFIG_FILE) ; then \ +# echo "rm -f $(DESTDIR)$(DEFAULT_CONFIG_FILE)"; \ +# $(RM) -f $(DESTDIR)$(DEFAULT_CONFIG_FILE); \ +# fi + +DISTCLEANFILES = + --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/tools/cachemgr.cc Wed Feb 14 13:38:04 2007 @@ -0,0 +1,1196 @@ + +/* + * $Id: cachemgr.cc,v 1.3.2.2 2006/09/29 23:16:07 dwsquid Exp $ + * + * DEBUG: section 0 CGI Cache Manager + * AUTHOR: Duane Wessels + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "config.h" + +#if HAVE_UNISTD_H +#include +#endif +#if HAVE_STDLIB_H +#include +#endif +#if HAVE_STDIO_H +#include +#endif +#if HAVE_SYS_TYPES_H +#include +#endif +#if HAVE_CTYPE_H +#include +#endif +#if HAVE_ERRNO_H +#include +#endif +#if HAVE_FCNTL_H +#include +#endif +#if HAVE_GRP_H +#include +#endif +#if HAVE_GNUMALLOC_H +#include +#elif HAVE_MALLOC_H +#include +#endif +#if HAVE_MEMORY_H +#include +#endif +#if HAVE_NETDB_H && !defined(_SQUID_NETDB_H_) /* protect NEXTSTEP */ +#define _SQUID_NETDB_H_ +#include +#endif +#if HAVE_PWD_H +#include +#endif +#if HAVE_SIGNAL_H +#include +#endif +#if HAVE_TIME_H +#include +#endif +#if HAVE_SYS_PARAM_H +#include +#endif +#if HAVE_SYS_TIME_H +#include +#endif +#if HAVE_SYS_RESOURCE_H +#include /* needs sys/time.h above it */ +#endif +#if HAVE_SYS_SOCKET_H +#include +#endif +#if HAVE_NETINET_IN_H +#include +#endif +#if HAVE_ARPA_INET_H +#include +#endif +#if HAVE_SYS_STAT_H +#include +#endif +#if HAVE_SYS_UN_H +#include +#endif +#if HAVE_SYS_WAIT_H +#include +#endif +#if HAVE_LIBC_H +#include +#endif +#if HAVE_STRING_H +#include +#endif +#if HAVE_STRINGS_H +#include +#endif +#if HAVE_BSTRING_H +#include +#endif +#if HAVE_CRYPT_H +#include +#endif +#if HAVE_SYS_SELECT_H +#include +#endif +#if HAVE_FNMATCH_H +extern "C" +{ +#include +} + +#endif + +#include "assert.h" + +#include "util.h" +#include "snprintf.h" + +#ifndef DEFAULT_CACHEMGR_CONFIG +#define DEFAULT_CACHEMGR_CONFIG "/etc/squid/cachemgr.conf" +#endif + +typedef struct +{ + char *server; + char *hostname; + int port; + char *action; + char *user_name; + char *passwd; + char *pub_auth; +} + +cachemgr_request; + +/* + * Debugging macros (info goes to error_log on your web server) + * Note: do not run cache manager with non zero debugging level + * if you do not debug, it may write a lot of [sensitive] + * information to your error log. + */ + +/* debugging level 0 (disabled) - 3 (max) */ +#define DEBUG_LEVEL 0 +#define debug(level) if ((level) <= DEBUG_LEVEL && DEBUG_LEVEL > 0) + +/* + * Static variables and constants + */ +static const time_t passwd_ttl = 60 * 60 * 3; /* in sec */ +static const char *script_name = "/cgi-bin/cachemgr.cgi"; +static const char *progname = NULL; +static time_t now; + +static struct IN_ADDR no_addr; + +/* + * Function prototypes + */ +#define safe_free(str) { if (str) { xfree(str); (str) = NULL; } } +static const char *safe_str(const char *str); +static const char *xstrtok(char **str, char del); +static void print_trailer(void); +static void auth_html(const char *host, int port, const char *user_name); +static void error_html(const char *msg); +static char *menu_url(cachemgr_request * req, const char *action); +static int parse_status_line(const char *sline, const char **statusStr); +static cachemgr_request *read_request(void); +static char *read_get_request(void); +static char *read_post_request(void); + +static void make_pub_auth(cachemgr_request * req); +static void decode_pub_auth(cachemgr_request * req); +static void reset_auth(cachemgr_request * req); +static const char *make_auth_header(const cachemgr_request * req); + +static int check_target_acl(const char *hostname, int port); + +#ifdef _SQUID_MSWIN_ +static int s_iInitCount = 0; + +int Win32SockInit(void) +{ + int iVersionRequested; + WSADATA wsaData; + int err; + + if (s_iInitCount > 0) { + s_iInitCount++; + return (0); + } else if (s_iInitCount < 0) + return (s_iInitCount); + + /* s_iInitCount == 0. Do the initailization */ + iVersionRequested = MAKEWORD(2, 0); + + err = WSAStartup((WORD) iVersionRequested, &wsaData); + + if (err) { + s_iInitCount = -1; + return (s_iInitCount); + } + + if (LOBYTE(wsaData.wVersion) != 2 || + HIBYTE(wsaData.wVersion) != 0) { + s_iInitCount = -2; + WSACleanup(); + return (s_iInitCount); + } + + s_iInitCount++; + return (s_iInitCount); +} + +void Win32SockCleanup(void) +{ + if (--s_iInitCount == 0) + WSACleanup(); + + return; +} + +#endif /* ifdef _SQUID_MSWIN_ */ + +static const char * +safe_str(const char *str) +{ + return str ? str : ""; +} + +/* relaxed number format */ +static int +is_number(const char *str) +{ + return strspn(str, "\t -+01234567890./\n") == strlen(str); +} + +static const char * +xstrtok(char **str, char del) +{ + if (*str) { + char *p = strchr(*str, del); + char *tok = *str; + int len; + + if (p) { + *str = p + 1; + *p = '\0'; + } else + *str = NULL; + + /* trim */ + len = strlen(tok); + + while (len && xisspace(tok[len - 1])) + tok[--len] = '\0'; + + while (xisspace(*tok)) + tok++; + + return tok; + } else + return ""; +} + +static void +print_trailer(void) +{ + printf("
    \n"); + printf("
    \n"); + printf("Generated %s, by %s/%s@%s\n", + mkrfc1123(now), progname, VERSION, getfullhostname()); + printf("
    \n"); +} + +static void +auth_html(const char *host, int port, const char *user_name) +{ + FILE *fp; + int need_host = 1; + + if (!user_name) + user_name = ""; + + if (!host || !strlen(host)) + host = ""; + + printf("Content-Type: text/html\r\n\r\n"); + + printf("\n"); + + printf("Cache Manager Interface\n"); + + printf("\n"); + + printf("

    Cache Manager Interface

    \n"); + + printf("

    This is a WWW interface to the instrumentation interface\n"); + + printf("for the Squid object cache.

    \n"); + + printf("
    \n"); + + printf("
    \n", script_name); + + printf("\n"); + + + fp = fopen("cachemgr.conf", "r"); + + if (fp == NULL) + fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r"); + + if (fp != NULL) { + int servers = 0; + char config_line[BUFSIZ]; + + while (fgets(config_line, BUFSIZ, fp)) { + char *server, *comment; + strtok(config_line, "\r\n"); + + if (config_line[0] == '#') + continue; + + if (config_line[0] == '\0') + continue; + + if ((server = strtok(config_line, " \t")) == NULL) + continue; + + if (strchr(server, '*') || strchr(server, '[') || strchr(server, '?')) { + need_host = -1; + continue; + } + + comment = strtok(NULL, ""); + + if (comment) + while (*comment == ' ' || *comment == '\t') + comment++; + + if (!comment || !*comment) + comment = server; + + if (!servers) { + printf("\n"); + } + + fclose(fp); + } + + if (need_host) { + if (need_host == 1 && !*host) + host = "localhost"; + + printf("\n", host); + + printf("\n", port); + } + + printf("\n", user_name); + + printf("\n"); + + printf("
    Cache Server:
    Cache Host:
    Cache Port:
    Manager name:
    Password:

    \n"); + + printf("\n"); + + printf("
    \n"); + + print_trailer(); +} + +static void +error_html(const char *msg) +{ + printf("Content-Type: text/html\r\n\r\n"); + printf("\n"); + printf("Cache Manager Error\n"); + printf("\n"); + printf("

    Cache Manager Error

    \n"); + printf("

    \n%s

    \n", msg); + print_trailer(); +} + +/* returns http status extracted from status line or -1 on parsing failure */ +static int +parse_status_line(const char *sline, const char **statusStr) +{ + const char *sp = strchr(sline, ' '); + + if (statusStr) + *statusStr = NULL; + + if (strncasecmp(sline, "HTTP/", 5) || !sp) + return -1; + + while (xisspace(*++sp)) + + ; + if (!xisdigit(*sp)) + return -1; + + if (statusStr) + *statusStr = sp; + + return atoi(sp); +} + +static char * +menu_url(cachemgr_request * req, const char *action) +{ + static char url[1024]; + snprintf(url, sizeof(url), "%s?host=%s&port=%d&user_name=%s&operation=%s&auth=%s", + script_name, + req->hostname, + req->port, + safe_str(req->user_name), + action, + safe_str(req->pub_auth)); + return url; +} + +static const char * +munge_menu_line(const char *buf, cachemgr_request * req) +{ + char *x; + const char *a; + const char *d; + const char *p; + char *a_url; + char *buf_copy; + static char html[2 * 1024]; + + if (strlen(buf) < 1) + return buf; + + if (*buf != ' ') + return buf; + + buf_copy = x = xstrdup(buf); + + a = xstrtok(&x, '\t'); + + d = xstrtok(&x, '\t'); + + p = xstrtok(&x, '\t'); + + a_url = xstrdup(menu_url(req, a)); + + /* no reason to give a url for a disabled action */ + if (!strcmp(p, "disabled")) + snprintf(html, sizeof(html), "
  • %s (disabled).\n", d, a_url); + else + /* disable a hidden action (requires a password, but password is not in squid.conf) */ + if (!strcmp(p, "hidden")) + snprintf(html, sizeof(html), "
  • %s (hidden).\n", d, a_url); + else + /* disable link if authentication is required and we have no password */ + if (!strcmp(p, "protected") && !req->passwd) + snprintf(html, sizeof(html), "
  • %s (requires authentication).\n", + d, menu_url(req, "authenticate"), a_url); + else + /* highlight protected but probably available entries */ + if (!strcmp(p, "protected")) + snprintf(html, sizeof(html), "
  • %s\n", + a_url, d); + + /* public entry or unknown type of protection */ + else + snprintf(html, sizeof(html), "
  • %s\n", a_url, d); + + xfree(a_url); + + xfree(buf_copy); + + return html; +} + +static const char * +munge_other_line(const char *buf, cachemgr_request * req) +{ + static const char *ttags[] = {"td", "th"}; + + static char html[4096]; + static int table_line_num = 0; + static int next_is_header = 0; + int is_header = 0; + const char *ttag; + char *buf_copy; + char *x, *p; + int l = 0; + /* does it look like a table? */ + + if (!strchr(buf, '\t') || *buf == '\t') { + /* nope, just text */ + snprintf(html, sizeof(html), "%s%s", + table_line_num ? "\n
    " : "", buf);
    +        table_line_num = 0;
    +        return html;
    +    }
    +
    +    /* start html table */
    +    if (!table_line_num) {
    +        l += snprintf(html + l, sizeof(html) - l, "
    \n"); + next_is_header = 0; + } + + /* remove '\n' */ + is_header = (!table_line_num || next_is_header) && !strchr(buf, ':') && !is_number(buf); + + ttag = ttags[is_header]; + + /* record starts */ + l += snprintf(html + l, sizeof(html) - l, ""); + + /* substitute '\t' */ + buf_copy = x = xstrdup(buf); + + if ((p = strchr(x, '\n'))) + *p = '\0'; + + while (x && strlen(x)) { + int column_span = 1; + const char *cell = xstrtok(&x, '\t'); + + while (x && *x == '\t') { + column_span++; + x++; + } + + l += snprintf(html + l, sizeof(html) - l, "<%s colspan=\"%d\" align=\"%s\">%s", + ttag, column_span, + is_header ? "center" : is_number(cell) ? "right" : "left", + cell, ttag); + } + + xfree(buf_copy); + /* record ends */ + l += snprintf(html + l, sizeof(html) - l, "\n"); + next_is_header = is_header && strstr(buf, "\t\t"); + table_line_num++; + return html; +} + +static int +read_reply(int s, cachemgr_request * req) +{ + char buf[4 * 1024]; +#ifdef _SQUID_MSWIN_ + + int reply; + char *tmpfile = tempnam(NULL, "tmp0000"); + FILE *fp = fopen(tmpfile, "w+"); +#else + + FILE *fp = fdopen(s, "r"); +#endif + /* interpretation states */ + enum { + isStatusLine, isHeaders, isBodyStart, isBody, isForward, isEof, isForwardEof, isSuccess, isError + } istate = isStatusLine; + int parse_menu = 0; + const char *action = req->action; + const char *statusStr = NULL; + int status = -1; + + if (0 == strlen(req->action)) + parse_menu = 1; + else if (0 == strcasecmp(req->action, "menu")) + parse_menu = 1; + + if (fp == NULL) { +#ifdef _SQUID_MSWIN_ + perror(tmpfile); + xfree(tmpfile); +#else + + perror("fdopen"); +#endif + + close(s); + return 1; + } + +#ifdef _SQUID_MSWIN_ + + while ((reply=recv(s, buf , sizeof(buf), 0)) > 0) + fwrite(buf, 1, reply, fp); + + rewind(fp); + +#endif + + if (parse_menu) + action = "menu"; + + /* read reply interpreting one line at a time depending on state */ + while (istate < isEof) { + if (!fgets(buf, sizeof(buf), fp)) + istate = istate == isForward ? isForwardEof : isEof; + + switch (istate) { + + case isStatusLine: + /* get HTTP status */ + /* uncomment the following if you want to debug headers */ + /* fputs("\r\n\r\n", stdout); */ + status = parse_status_line(buf, &statusStr); + istate = status == 200 ? isHeaders : isForward; + /* if cache asks for authentication, we have to reset our info */ + + if (status == 401 || status == 407) { + reset_auth(req); + status = 403; /* Forbiden, see comments in case isForward: */ + } + + /* this is a way to pass HTTP status to the Web server */ + if (statusStr) + printf("Status: %d %s", status, statusStr); /* statusStr has '\n' */ + + break; + + case isHeaders: + /* forward header field */ + if (!strcmp(buf, "\r\n")) { /* end of headers */ + fputs("Content-Type: text/html\r\n", stdout); /* add our type */ + istate = isBodyStart; + } + + if (strncasecmp(buf, "Content-Type:", 13)) /* filter out their type */ + fputs(buf, stdout); + + break; + + case isBodyStart: + printf("\n"); + + printf("CacheMgr@%s: %s\n", + req->hostname, action); + + printf("\n"); + + printf("\n"); + + if (parse_menu) { + printf("

    Cache Manager menu for %s:

    ", + menu_url(req, "authenticate"), req->hostname); + printf("
      \n"); + } else { + printf("

      %s\n


      \n", + menu_url(req, "menu"), "Cache Manager menu"); + printf("
      \n");
      +            }
      +
      +            istate = isBody;
      +            /* yes, fall through, we do not want to loose the first line */
      +
      +        case isBody:
      +            /* interpret [and reformat] cache response */
      +
      +            if (parse_menu)
      +                fputs(munge_menu_line(buf, req), stdout);
      +            else
      +                fputs(munge_other_line(buf, req), stdout);
      +
      +            break;
      +
      +        case isForward:
      +            /* forward: no modifications allowed */
      +            /*
      +             * Note: we currently do not know any way to get browser.reply to
      +             * 401 to .cgi because web server filters out all auth info. Thus we
      +             * disable authentication headers for now.
      +             */
      +            if (!strncasecmp(buf, "WWW-Authenticate:", 17) || !strncasecmp(buf, "Proxy-Authenticate:", 19))
      +
      +                ;	/* skip */
      +            else
      +                fputs(buf, stdout);
      +
      +            break;
      +
      +        case isEof:
      +            /* print trailers */
      +            if (parse_menu)
      +                printf("
    \n"); + else + printf("
    \n"); + + print_trailer(); + + istate = isSuccess; + + break; + + case isForwardEof: + /* indicate that we finished processing an "error" sequence */ + istate = isError; + + break; + + default: + printf("%s: internal bug: invalid state reached: %d", script_name, istate); + + istate = isError; + } + } + + fclose(fp); +#ifdef _SQUID_MSWIN_ + + remove(tmpfile); + xfree(tmpfile); + close(s); + +#endif + + return 0; +} + +static int +process_request(cachemgr_request * req) +{ + + const struct hostent *hp; + + static struct sockaddr_in S; + int s; + int l; + + static char buf[2 * 1024]; + + if (req == NULL) { + auth_html(CACHEMGR_HOSTNAME, CACHE_HTTP_PORT, ""); + return 1; + } + + if (req->hostname == NULL) { + req->hostname = xstrdup(CACHEMGR_HOSTNAME); + } + + if (req->port == 0) { + req->port = CACHE_HTTP_PORT; + } + + if (req->action == NULL) { + req->action = xstrdup(""); + } + + if (strcmp(req->action, "authenticate") == 0) { + auth_html(req->hostname, req->port, req->user_name); + return 0; + } + + if (!check_target_acl(req->hostname, req->port)) { + snprintf(buf, 1024, "target %s:%d not allowed in cachemgr.conf\n", req->hostname, req->port); + error_html(buf); + return 1; + } + + if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { + snprintf(buf, 1024, "socket: %s\n", xstrerror()); + error_html(buf); + return 1; + } + + memset(&S, '\0', sizeof(S)); + S.sin_family = AF_INET; + + if ((hp = gethostbyname(req->hostname)) != NULL) { + assert(hp->h_length >= 0 && (size_t)hp->h_length <= sizeof(S.sin_addr.s_addr)); + xmemcpy(&S.sin_addr.s_addr, hp->h_addr, hp->h_length); + } else if (safe_inet_addr(req->hostname, &S.sin_addr)) + (void) 0; + else { + snprintf(buf, 1024, "Unknown host: %s\n", req->hostname); + error_html(buf); + return 1; + } + + S.sin_port = htons(req->port); + + if (connect(s, (struct sockaddr *) &S, sizeof(S)) < 0) { + snprintf(buf, 1024, "connect %s:%d: %s\n", + inet_ntoa(S.sin_addr), + ntohs(S.sin_port), + xstrerror()); + error_html(buf); + return 1; + } + + l = snprintf(buf, sizeof(buf), + "GET cache_object://%s/%s HTTP/1.0\r\n" + "Accept: */*\r\n" + "%s" /* Authentication info or nothing */ + "\r\n", + req->hostname, + req->action, + make_auth_header(req)); + write(s, buf, l); + debug(1) fprintf(stderr, "wrote request: '%s'\n", buf); + return read_reply(s, req); +} + +int +main(int argc, char *argv[]) +{ + char *s; + cachemgr_request *req; + + safe_inet_addr("255.255.255.255", &no_addr); + now = time(NULL); +#ifdef _SQUID_MSWIN_ + + Win32SockInit(); + atexit(Win32SockCleanup); + _setmode( _fileno( stdin ), _O_BINARY ); + _setmode( _fileno( stdout ), _O_BINARY ); + _fmode = _O_BINARY; + + if ((s = strrchr(argv[0], '\\'))) +#else + + if ((s = strrchr(argv[0], '/'))) +#endif + + progname = xstrdup(s + 1); + else + progname = xstrdup(argv[0]); + + if ((s = getenv("SCRIPT_NAME")) != NULL) + script_name = xstrdup(s); + + req = read_request(); + + return process_request(req); +} + +static char * +read_post_request(void) +{ + char *s; + char *buf; + int len; + + if ((s = getenv("REQUEST_METHOD")) == NULL) + return NULL; + + if (0 != strcasecmp(s, "POST")) + return NULL; + + if ((s = getenv("CONTENT_LENGTH")) == NULL) + return NULL; + + if ((len = atoi(s)) <= 0) + return NULL; + + buf = (char *)xmalloc(len + 1); + + fread(buf, len, 1, stdin); + + buf[len] = '\0'; + + return buf; +} + +static char * +read_get_request(void) +{ + char *s; + + if ((s = getenv("QUERY_STRING")) == NULL) + return NULL; + + return xstrdup(s); +} + +static cachemgr_request * +read_request(void) +{ + char *buf; + + cachemgr_request *req; + char *s; + char *t; + char *q; + + if ((buf = read_post_request()) != NULL) + (void) 0; + else if ((buf = read_get_request()) != NULL) + (void) 0; + else + return NULL; + +#ifdef _SQUID_MSWIN_ + + if (strlen(buf) == 0 || strlen(buf) == 4000) +#else + + if (strlen(buf) == 0) +#endif + + return NULL; + + req = (cachemgr_request *)xcalloc(1, sizeof(cachemgr_request)); + + for (s = strtok(buf, "&"); s != NULL; s = strtok(NULL, "&")) { + t = xstrdup(s); + + if ((q = strchr(t, '=')) == NULL) + continue; + + *q++ = '\0'; + + rfc1738_unescape(t); + + rfc1738_unescape(q); + + if (0 == strcasecmp(t, "server") && strlen(q)) + req->server = xstrdup(q); + else if (0 == strcasecmp(t, "host") && strlen(q)) + req->hostname = xstrdup(q); + else if (0 == strcasecmp(t, "port") && strlen(q)) + req->port = atoi(q); + else if (0 == strcasecmp(t, "user_name") && strlen(q)) + req->user_name = xstrdup(q); + else if (0 == strcasecmp(t, "passwd") && strlen(q)) + req->passwd = xstrdup(q); + else if (0 == strcasecmp(t, "auth") && strlen(q)) + req->pub_auth = xstrdup(q), decode_pub_auth(req); + else if (0 == strcasecmp(t, "operation")) + req->action = xstrdup(q); + } + + if (req->server && !req->hostname) { + char *p; + req->hostname = strtok(req->server, ":"); + + if ((p = strtok(NULL, ":"))) + req->port = atoi(p); + } + + make_pub_auth(req); + debug(1) fprintf(stderr, "cmgr: got req: host: '%s' port: %d uname: '%s' passwd: '%s' auth: '%s' oper: '%s'\n", + safe_str(req->hostname), req->port, safe_str(req->user_name), safe_str(req->passwd), safe_str(req->pub_auth), safe_str(req->action)); + return req; +} + + +/* Routines to support authentication */ + +/* + * Encodes auth info into a "public" form. + * Currently no powerful encryption is used. + */ +static void +make_pub_auth(cachemgr_request * req) +{ + static char buf[1024]; + safe_free(req->pub_auth); + debug(3) fprintf(stderr, "cmgr: encoding for pub...\n"); + + if (!req->passwd || !strlen(req->passwd)) + return; + + /* host | time | user | passwd */ + snprintf(buf, sizeof(buf), "%s|%d|%s|%s", + req->hostname, + (int) now, + req->user_name ? req->user_name : "", + req->passwd); + + debug(3) fprintf(stderr, "cmgr: pre-encoded for pub: %s\n", buf); + + debug(3) fprintf(stderr, "cmgr: encoded: '%s'\n", base64_encode(buf)); + + req->pub_auth = xstrdup(base64_encode(buf)); +} + +static void +decode_pub_auth(cachemgr_request * req) +{ + char *buf; + const char *host_name; + const char *time_str; + const char *user_name; + const char *passwd; + + debug(2) fprintf(stderr, "cmgr: decoding pub: '%s'\n", safe_str(req->pub_auth)); + safe_free(req->passwd); + + if (!req->pub_auth || strlen(req->pub_auth) < 4 + strlen(safe_str(req->hostname))) + return; + + buf = xstrdup(base64_decode(req->pub_auth)); + + debug(3) fprintf(stderr, "cmgr: length ok\n"); + + /* parse ( a lot of memory leaks, but that is cachemgr style :) */ + if ((host_name = strtok(buf, "|")) == NULL) + return; + + debug(3) fprintf(stderr, "cmgr: decoded host: '%s'\n", host_name); + + if ((time_str = strtok(NULL, "|")) == NULL) + return; + + debug(3) fprintf(stderr, "cmgr: decoded time: '%s' (now: %d)\n", time_str, (int) now); + + if ((user_name = strtok(NULL, "|")) == NULL) + return; + + debug(3) fprintf(stderr, "cmgr: decoded uname: '%s'\n", user_name); + + if ((passwd = strtok(NULL, "|")) == NULL) + return; + + debug(2) fprintf(stderr, "cmgr: decoded passwd: '%s'\n", passwd); + + /* verify freshness and validity */ + if (atoi(time_str) + passwd_ttl < now) + return; + + if (strcasecmp(host_name, req->hostname)) + return; + + debug(1) fprintf(stderr, "cmgr: verified auth. info.\n"); + + /* ok, accept */ + xfree(req->user_name); + + req->user_name = xstrdup(user_name); + + req->passwd = xstrdup(passwd); + + xfree(buf); +} + +static void +reset_auth(cachemgr_request * req) +{ + safe_free(req->passwd); + safe_free(req->pub_auth); +} + +static const char * +make_auth_header(const cachemgr_request * req) +{ + static char buf[1024]; + size_t stringLength = 0; + const char *str64; + + if (!req->passwd) + return ""; + + snprintf(buf, sizeof(buf), "%s:%s", + req->user_name ? req->user_name : "", + req->passwd); + + str64 = base64_encode(buf); + + stringLength += snprintf(buf, sizeof(buf), "Authorization: Basic %s\r\n", str64); + + assert(stringLength < sizeof(buf)); + + stringLength += snprintf(&buf[stringLength], sizeof(buf) - stringLength, + "Proxy-Authorization: Basic %s\r\n", str64); + + return buf; +} + +static int +check_target_acl(const char *hostname, int port) +{ + char config_line[BUFSIZ]; + FILE *fp = NULL; + int ret = 0; + fp = fopen("cachemgr.conf", "r"); + + if (fp == NULL) + fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r"); + + if (fp == NULL) { +#ifdef CACHEMGR_HOSTNAME_DEFINED + + if (strcmp(hostname, CACHEMGR_HOSTNAME) == 0 && port == CACHE_HTTP_PORT) + return 1; + +#else + + if (strcmp(hostname, "localhost") == 0) + return 1; + + if (strcmp(hostname, getfullhostname()) == 0) + return 1; + +#endif + + return 0; + } + + while (fgets(config_line, BUFSIZ, fp)) { + char *token = NULL; + strtok(config_line, " \r\n\t"); + + if (config_line[0] == '#') + continue; + + if (config_line[0] == '\0') + continue; + + if ((token = strtok(config_line, ":")) == NULL) + continue; + +#if HAVE_FNMATCH_H + + if (fnmatch(token, hostname, 0) != 0) + continue; + +#else + + if (strcmp(token, hostname) != 0) + continue; + +#endif + + if ((token = strtok(NULL, ":")) != NULL) { + int i; + + if (strcmp(token, "*") == 0) + + ; /* Wildcard port specification */ + else if (strcasecmp(token, "any") == 0) + + ; /* Wildcard port specification */ + else if (sscanf(token, "%d", &i) != 1) + continue; + + else if (i != port) + continue; + } else if (port != CACHE_HTTP_PORT) + continue; + + ret = 1; + + break; + } + + fclose(fp); + return ret; +} --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/tools/cachemgr.conf Wed Feb 14 13:38:04 2007 @@ -0,0 +1,13 @@ +# This file controls which servers may be managed by +# the cachemgr.cgi script +# +# The file consists of one server per line on the format +# hostname:port description +# +# Specifying :port is optional. If not specified then +# the default proxy port is assumed. :* or :any matches +# any port on the target server. +# +# hostname is matched using shell filename matching, allowing +# * and other shell wildcards. +localhost --- /dev/null Wed Feb 14 13:37:19 2007 +++ squid3/tools/squidclient.cc Wed Feb 14 13:38:04 2007 @@ -0,0 +1,699 @@ + +/* + * $Id: squidclient.cc,v 1.5.2.2 2006/09/29 23:16:08 dwsquid Exp $ + * + * DEBUG: section 0 WWW Client + * AUTHOR: Harvest Derived + * + * SQUID Web Proxy Cache http://www.squid-cache.org/ + * ---------------------------------------------------------- + * + * Squid is the result of efforts by numerous individuals from + * the Internet community; see the CONTRIBUTORS file for full + * details. Many organizations have provided support for Squid's + * development; see the SPONSORS file for full details. Squid is + * Copyrighted (C) 2001 by the Regents of the University of + * California; see the COPYRIGHT file for full details. Squid + * incorporates software developed and/or copyrighted by other + * sources; see the CREDITS file for full details. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. + * + */ + +#include "config.h" + +#ifdef _SQUID_MSWIN_ +using namespace Squid; +#endif + +#ifdef _SQUID_WIN32_ +#include +#endif +#if HAVE_STDIO_H +#include +#endif +#if HAVE_STDLIB_H +#include +#endif +#if HAVE_SYS_TYPES_H +#include +#endif +#if HAVE_SYS_SOCKET_H +#include +#endif +#if HAVE_STRING_H +#include +#endif +#if HAVE_UNISTD_H +#include +#endif +#if HAVE_NETDB_H && !defined(_SQUID_NETDB_H_) /* protect NEXTSTEP */ +#define _SQUID_NETDB_H_ +#include +#endif +#if HAVE_SIGNAL_H +#include +#endif +#if HAVE_ERRNO_H +#include +#endif +#if HAVE_SYS_STAT_H +#include +#endif +#if HAVE_FCNTL_H +#include +#endif +#if HAVE_NETINET_IN_H +#include +#endif +#if HAVE_GETOPT_H +#include +#endif + +#include "util.h" + +#ifndef BUFSIZ +#define BUFSIZ 8192 +#endif + +typedef void SIGHDLR(int sig); + +/* Local functions */ +static int client_comm_bind(int, const char *); + +static int client_comm_connect(int, const char *, u_short, struct timeval *); +static void usage(const char *progname); + +static int Now(struct timeval *); +static SIGHDLR catchSignal; +static SIGHDLR pipe_handler; +static void set_our_signal(void); +static ssize_t myread(int fd, void *buf, size_t len); +static ssize_t mywrite(int fd, void *buf, size_t len); +static int put_fd; +static char *put_file = NULL; + +static struct stat sb; +int total_bytes = 0; +int io_timeout = 120; + +static void +usage(const char *progname) +{ + fprintf(stderr, + "Usage: %s [-arsv] [-i IMS] [-h remote host] [-l local host] [-p port] [-m method] [-t count] [-I ping-interval] [-H 'strings'] [-T timeout] url\n" + "Options:\n" + " -P file PUT request.\n" + " -a Do NOT include Accept: header.\n" + " -r Force cache to reload URL.\n" + " -s Silent. Do not print data to stdout.\n" + " -v Verbose. Print outgoing message to stderr.\n" + " -i IMS If-Modified-Since time (in Epoch seconds).\n" + " -h host Retrieve URL from cache on hostname. Default is localhost.\n" + " -l host Specify a local IP address to bind to. Default is none.\n" + " -p port Port number of cache. Default is %d.\n" + " -m method Request method, default is GET.\n" + " -t count Trace count cache-hops\n" + " -g count Ping mode, \"count\" iterations (0 to loop until interrupted).\n" + " -I interval Ping interval in seconds (default 1 second).\n" + " -H 'string' Extra headers to send. Use '\\n' for new lines.\n" + " -T timeout Timeout value (seconds) for read/write operations.\n" + " -u user Proxy authentication username\n" + " -w password Proxy authentication password\n" + " -U user WWW authentication username\n" + " -W password WWW authentication password\n", + progname, CACHE_HTTP_PORT); + exit(1); +} + +static int interrupted = 0; +int +main(int argc, char *argv[]) +{ + int conn, c, len, bytesWritten; + int port, to_stdout, reload; + int ping, pcount; + int keep_alive = 0; + int opt_noaccept = 0; + int opt_verbose = 0; + const char *hostname, *localhost; + char url[BUFSIZ], msg[49152], buf[BUFSIZ]; + char extra_hdrs[32768]; + const char *method = "GET"; + extern char *optarg; + time_t ims = 0; + int max_forwards = -1; + + struct timeval tv1, tv2; + int i = 0, loops; + long ping_int; + long ping_min = 0, ping_max = 0, ping_sum = 0, ping_mean = 0; + char *proxy_user = NULL; + char *proxy_password = NULL; + char *www_user = NULL; + char *www_password = NULL; + + /* set the defaults */ + hostname = "localhost"; + localhost = NULL; + extra_hdrs[0] = '\0'; + port = CACHE_HTTP_PORT; + to_stdout = 1; + reload = 0; + ping = 0; + pcount = 0; + ping_int = 1 * 1000; + + if (argc < 2) { + usage(argv[0]); /* need URL */ + } else if (argc >= 2) { + strncpy(url, argv[argc - 1], BUFSIZ); + url[BUFSIZ - 1] = '\0'; + + if (url[0] == '-') + usage(argv[0]); + + while ((c = getopt(argc, argv, "ah:l:P:i:km:p:rsvt:g:p:I:H:T:u:U:w:W:?")) != -1) + switch (c) { + + case 'a': + opt_noaccept = 1; + break; + + case 'h': /* remote host */ + + if (optarg != NULL) + hostname = optarg; + + break; + + case 'l': /* local host */ + if (optarg != NULL) + localhost = optarg; + + break; + + case 's': /* silent */ + to_stdout = 0; + + break; + + case 'k': /* backward compat */ + keep_alive = 1; + + break; + + case 'r': /* reload */ + reload = 1; + + break; + + case 'p': /* port number */ + sscanf(optarg, "%d", &port); + + if (port < 1) + port = CACHE_HTTP_PORT; /* default */ + + break; + + case 'P': + put_file = xstrdup(optarg); + + break; + + case 'i': /* IMS */ + ims = (time_t) atoi(optarg); + + break; + + case 'm': + method = xstrdup(optarg); + + break; + + case 't': + method = xstrdup("TRACE"); + + max_forwards = atoi(optarg); + + break; + + case 'g': + ping = 1; + + pcount = atoi(optarg); + + to_stdout = 0; + + break; + + case 'I': + if ((ping_int = atoi(optarg) * 1000) <= 0) + usage(argv[0]); + + break; + + case 'H': + if (strlen(optarg)) { + char *t; + strncpy(extra_hdrs, optarg, sizeof(extra_hdrs)); + + while ((t = strstr(extra_hdrs, "\\n"))) + *t = '\r', *(t + 1) = '\n'; + } + + break; + + case 'T': + io_timeout = atoi(optarg); + break; + + case 'u': + proxy_user = optarg; + break; + + case 'w': + proxy_password = optarg; + break; + + case 'U': + www_user = optarg; + break; + + case 'W': + www_password = optarg; + break; + + case 'v': + /* undocumented: may increase verb-level by giving more -v's */ + opt_verbose++; + break; + + case '?': /* usage */ + + default: + usage(argv[0]); + break; + } + } + +#ifdef _SQUID_MSWIN_ + { + WSADATA wsaData; + WSAStartup(2, &wsaData); + } +#endif + /* Build the HTTP request */ + if (strncmp(url, "mgr:", 4) == 0) { + char *t = xstrdup(url + 4); + snprintf(url, BUFSIZ, "cache_object://%s/%s", hostname, t); + xfree(t); + } + + if (put_file) { + put_fd = open(put_file, O_RDONLY); + set_our_signal(); + + if (put_fd < 0) { + fprintf(stderr, "%s: can't open file (%s)\n", argv[0], + xstrerror()); + exit(-1); + } + +#ifdef _SQUID_WIN32_ + setmode(put_fd, O_BINARY); + +#endif + + fstat(put_fd, &sb); + } + + snprintf(msg, BUFSIZ, "%s %s HTTP/1.0\r\n", method, url); + + if (reload) { + snprintf(buf, BUFSIZ, "Pragma: no-cache\r\n"); + strcat(msg, buf); + } + + if (put_fd > 0) { + snprintf(buf, BUFSIZ, "Content-length: %d\r\n", (int) sb.st_size); + strcat(msg, buf); + } + + if (opt_noaccept == 0) { + snprintf(buf, BUFSIZ, "Accept: */*\r\n"); + strcat(msg, buf); + } + + if (ims) { + snprintf(buf, BUFSIZ, "If-Modified-Since: %s\r\n", mkrfc1123(ims)); + strcat(msg, buf); + } + + if (max_forwards > -1) { + snprintf(buf, BUFSIZ, "Max-Forwards: %d\r\n", max_forwards); + strcat(msg, buf); + } + + if (proxy_user) { + char *user = proxy_user; + char *password = proxy_password; +#if HAVE_GETPASS + + if (!password) + password = getpass("Proxy password: "); + +#endif + + if (!password) { + fprintf(stderr, "ERROR: Proxy password missing\n"); + exit(1); + } + + snprintf(buf, BUFSIZ, "%s:%s", user, password); + snprintf(buf, BUFSIZ, "Proxy-Authorization: Basic %s\r\n", base64_encode(buf)); + strcat(msg, buf); + } + + if (www_user) { + char *user = www_user; + char *password = www_password; +#if HAVE_GETPASS + + if (!password) + password = getpass("WWW password: "); + +#endif + + if (!password) { + fprintf(stderr, "ERROR: WWW password missing\n"); + exit(1); + } + + snprintf(buf, BUFSIZ, "%s:%s", user, password); + snprintf(buf, BUFSIZ, "Authorization: Basic %s\r\n", base64_encode(buf)); + strcat(msg, buf); + } + + if (keep_alive) { + if (port != 80) + snprintf(buf, BUFSIZ, "Proxy-Connection: keep-alive\r\n"); + else + snprintf(buf, BUFSIZ, "Connection: keep-alive\r\n"); + + strcat(msg, buf); + } + + strcat(msg, extra_hdrs); + snprintf(buf, BUFSIZ, "\r\n"); + strcat(msg, buf); + + if (opt_verbose) + fprintf(stderr, "headers: '%s'\n", msg); + + if (ping) { +#if HAVE_SIGACTION + + struct sigaction sa, osa; + + if (sigaction(SIGINT, NULL, &osa) == 0 && osa.sa_handler == SIG_DFL) { + sa.sa_handler = catchSignal; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + (void) sigaction(SIGINT, &sa, NULL); + } + +#else + void (*osig) (int); + + if ((osig = signal(SIGINT, catchSignal)) != SIG_DFL) + (void) signal(SIGINT, osig); + +#endif + + } + + loops = ping ? pcount : 1; + + for (i = 0; loops == 0 || i < loops; i++) { + int fsize = 0; + /* Connect to the server */ + + if ((conn = socket(PF_INET, SOCK_STREAM, 0)) < 0) { + perror("client: socket"); + exit(1); + } + + if (localhost && client_comm_bind(conn, localhost) < 0) { + perror("client: bind"); + exit(1); + } + + if (client_comm_connect(conn, hostname, port, ping ? &tv1 : NULL) < 0) { + if (errno == 0) { + fprintf(stderr, "client: ERROR: Cannot connect to %s:%d: Host unknown.\n", hostname, port); + } else { + char tbuf[BUFSIZ]; + snprintf(tbuf, BUFSIZ, "client: ERROR: Cannot connect to %s:%d", + hostname, port); + perror(tbuf); + } + + exit(1); + } + + /* Send the HTTP request */ + bytesWritten = mywrite(conn, msg, strlen(msg)); + + if (bytesWritten < 0) { + perror("client: ERROR: write"); + exit(1); + } else if ((unsigned) bytesWritten != strlen(msg)) { + fprintf(stderr, "client: ERROR: Cannot send request?: %s\n", msg); + exit(1); + } + + if (put_file) { + int x; + lseek(put_fd, 0, SEEK_SET); +#ifdef _SQUID_MSWIN_ + + while ((x = read(put_fd, buf, sizeof(buf))) > 0) { +#else + + while ((x = myread(put_fd, buf, sizeof(buf))) > 0) { +#endif + x = mywrite(conn, buf, x); + + total_bytes += x; + + if (x <= 0) + break; + } + + if (x != 0) + fprintf(stderr, "client: ERROR: Cannot send file.\n"); + } + + /* Read the data */ + +#ifdef _SQUID_MSWIN_ + setmode(1, O_BINARY); + +#endif + + while ((len = myread(conn, buf, sizeof(buf))) > 0) { + fsize += len; + + if (to_stdout) + fwrite(buf, len, 1, stdout); + } + +#ifdef _SQUID_MSWIN_ + setmode(1, O_TEXT); + +#endif + + (void) close(conn); /* done with socket */ + + if (interrupted) + break; + + if (ping) { + + struct tm *tmp; + time_t t2s; + long elapsed_msec; + + (void) Now(&tv2); + elapsed_msec = tvSubMsec(tv1, tv2); + t2s = tv2.tv_sec; + tmp = localtime(&t2s); + fprintf(stderr, "%d-%02d-%02d %02d:%02d:%02d [%d]: %ld.%03ld secs, %f KB/s\n", + tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, + tmp->tm_hour, tmp->tm_min, tmp->tm_sec, i + 1, + elapsed_msec / 1000, elapsed_msec % 1000, + elapsed_msec ? (double) fsize / elapsed_msec : -1.0); + + if (i == 0 || elapsed_msec < ping_min) + ping_min = elapsed_msec; + + if (i == 0 || elapsed_msec > ping_max) + ping_max = elapsed_msec; + + ping_sum += elapsed_msec; + + /* Delay until next "ping_int" boundary */ + if ((loops == 0 || i + 1 < loops) && elapsed_msec < ping_int) { + + struct timeval tvs; + long msec_left = ping_int - elapsed_msec; + + tvs.tv_sec = msec_left / 1000; + tvs.tv_usec = (msec_left % 1000) * 1000; + select(0, NULL, NULL, NULL, &tvs); + } + } + } + + if (ping && i) { + ping_mean = ping_sum / i; + fprintf(stderr, "%d requests, round-trip (secs) min/avg/max = " + "%ld.%03ld/%ld.%03ld/%ld.%03ld\n", i, + ping_min / 1000, ping_min % 1000, ping_mean / 1000, ping_mean % 1000, + ping_max / 1000, ping_max % 1000); + } + + exit(0); + /*NOTREACHED */ + return 0; +} + +static int +client_comm_bind(int sock, const char *local_host) { + + static const struct hostent *hp = NULL; + + static struct sockaddr_in from_addr; + + /* Set up the source socket address from which to send. */ + + if (hp == NULL) { + from_addr.sin_family = AF_INET; + + if ((hp = gethostbyname(local_host)) == 0) { + return (-1); + } + + xmemcpy(&from_addr.sin_addr, hp->h_addr, hp->h_length); + from_addr.sin_port = 0; + } + + return bind(sock, (struct sockaddr *) &from_addr, sizeof(struct sockaddr_in)); +} + +static int + +client_comm_connect(int sock, const char *dest_host, u_short dest_port, struct timeval *tvp) { + + static const struct hostent *hp = NULL; + + static struct sockaddr_in to_addr; + + /* Set up the destination socket address for message to send to. */ + + if (hp == NULL) + { + to_addr.sin_family = AF_INET; + + if ((hp = gethostbyname(dest_host)) == 0) { + return (-1); + } + + xmemcpy(&to_addr.sin_addr, hp->h_addr, hp->h_length); + to_addr.sin_port = htons(dest_port); + } + + if (tvp) + (void) Now(tvp); + + return connect(sock, (struct sockaddr *) &to_addr, sizeof(struct sockaddr_in)); +} + +static int + +Now(struct timeval *tp) { +#if GETTIMEOFDAY_NO_TZP + return gettimeofday(tp); +#else + + return gettimeofday(tp, NULL); +#endif +} /* ARGSUSED */ + +static void +catchSignal(int sig) { + interrupted = 1; + fprintf(stderr, "Interrupted.\n"); +} + +static void +pipe_handler(int sig) { + fprintf(stderr, "SIGPIPE received.\n"); +} + +static void +set_our_signal(void) { +#if HAVE_SIGACTION + + struct sigaction sa; + sa.sa_handler = pipe_handler; + sa.sa_flags = SA_RESTART; + sigemptyset(&sa.sa_mask); + + if (sigaction(SIGPIPE, &sa, NULL) < 0) { + fprintf(stderr, "Cannot set PIPE signal.\n"); + exit(-1); + } + +#else + signal(SIGPIPE, pipe_handler); + +#endif + +} + +static ssize_t +myread(int fd, void *buf, size_t len) { +#ifndef _SQUID_MSWIN_ + alarm(io_timeout); + return read(fd, buf, len); +#else + + return recv(fd, buf, len, 0); +#endif +} + +static ssize_t +mywrite(int fd, void *buf, size_t len) { +#ifndef _SQUID_MSWIN_ + alarm(io_timeout); + return write(fd, buf, len); +#else + + return send(fd, buf, len, 0); +#endif +}