##// END OF EJS Templates
test-http-proxy: redirect proxy stdout to /dev/null...
Matt Harbison -
r32916:88c1d13b default
parent child Browse files
Show More
@@ -1,120 +1,120 b''
1 #require serve
1 #require serve
2
2
3 $ hg init a
3 $ hg init a
4 $ cd a
4 $ cd a
5 $ echo a > a
5 $ echo a > a
6 $ hg ci -Ama -d '1123456789 0'
6 $ hg ci -Ama -d '1123456789 0'
7 adding a
7 adding a
8 $ hg serve --config server.uncompressed=True -p $HGPORT -d --pid-file=hg.pid
8 $ hg serve --config server.uncompressed=True -p $HGPORT -d --pid-file=hg.pid
9 $ cat hg.pid >> $DAEMON_PIDS
9 $ cat hg.pid >> $DAEMON_PIDS
10 $ cd ..
10 $ cd ..
11 $ tinyproxy.py $HGPORT1 localhost >proxy.log 2>&1 </dev/null &
11 $ tinyproxy.py $HGPORT1 localhost 2>proxy.log >/dev/null </dev/null &
12 $ while [ ! -f proxy.pid ]; do sleep 0; done
12 $ while [ ! -f proxy.pid ]; do sleep 0; done
13 $ cat proxy.pid >> $DAEMON_PIDS
13 $ cat proxy.pid >> $DAEMON_PIDS
14
14
15 url for proxy, stream
15 url for proxy, stream
16
16
17 $ http_proxy=http://localhost:$HGPORT1/ hg --config http_proxy.always=True clone --uncompressed http://localhost:$HGPORT/ b
17 $ http_proxy=http://localhost:$HGPORT1/ hg --config http_proxy.always=True clone --uncompressed http://localhost:$HGPORT/ b
18 streaming all changes
18 streaming all changes
19 3 files to transfer, 303 bytes of data
19 3 files to transfer, 303 bytes of data
20 transferred * bytes in * seconds (*/sec) (glob)
20 transferred * bytes in * seconds (*/sec) (glob)
21 searching for changes
21 searching for changes
22 no changes found
22 no changes found
23 updating to branch default
23 updating to branch default
24 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
24 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
25 $ cd b
25 $ cd b
26 $ hg verify
26 $ hg verify
27 checking changesets
27 checking changesets
28 checking manifests
28 checking manifests
29 crosschecking files in changesets and manifests
29 crosschecking files in changesets and manifests
30 checking files
30 checking files
31 1 files, 1 changesets, 1 total revisions
31 1 files, 1 changesets, 1 total revisions
32 $ cd ..
32 $ cd ..
33
33
34 url for proxy, pull
34 url for proxy, pull
35
35
36 $ http_proxy=http://localhost:$HGPORT1/ hg --config http_proxy.always=True clone http://localhost:$HGPORT/ b-pull
36 $ http_proxy=http://localhost:$HGPORT1/ hg --config http_proxy.always=True clone http://localhost:$HGPORT/ b-pull
37 requesting all changes
37 requesting all changes
38 adding changesets
38 adding changesets
39 adding manifests
39 adding manifests
40 adding file changes
40 adding file changes
41 added 1 changesets with 1 changes to 1 files
41 added 1 changesets with 1 changes to 1 files
42 updating to branch default
42 updating to branch default
43 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
43 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
44 $ cd b-pull
44 $ cd b-pull
45 $ hg verify
45 $ hg verify
46 checking changesets
46 checking changesets
47 checking manifests
47 checking manifests
48 crosschecking files in changesets and manifests
48 crosschecking files in changesets and manifests
49 checking files
49 checking files
50 1 files, 1 changesets, 1 total revisions
50 1 files, 1 changesets, 1 total revisions
51 $ cd ..
51 $ cd ..
52
52
53 host:port for proxy
53 host:port for proxy
54
54
55 $ http_proxy=localhost:$HGPORT1 hg clone --config http_proxy.always=True http://localhost:$HGPORT/ c
55 $ http_proxy=localhost:$HGPORT1 hg clone --config http_proxy.always=True http://localhost:$HGPORT/ c
56 requesting all changes
56 requesting all changes
57 adding changesets
57 adding changesets
58 adding manifests
58 adding manifests
59 adding file changes
59 adding file changes
60 added 1 changesets with 1 changes to 1 files
60 added 1 changesets with 1 changes to 1 files
61 updating to branch default
61 updating to branch default
62 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
62 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
63
63
64 proxy url with user name and password
64 proxy url with user name and password
65
65
66 $ http_proxy=http://user:passwd@localhost:$HGPORT1 hg clone --config http_proxy.always=True http://localhost:$HGPORT/ d
66 $ http_proxy=http://user:passwd@localhost:$HGPORT1 hg clone --config http_proxy.always=True http://localhost:$HGPORT/ d
67 requesting all changes
67 requesting all changes
68 adding changesets
68 adding changesets
69 adding manifests
69 adding manifests
70 adding file changes
70 adding file changes
71 added 1 changesets with 1 changes to 1 files
71 added 1 changesets with 1 changes to 1 files
72 updating to branch default
72 updating to branch default
73 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
73 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
74
74
75 url with user name and password
75 url with user name and password
76
76
77 $ http_proxy=http://user:passwd@localhost:$HGPORT1 hg clone --config http_proxy.always=True http://user:passwd@localhost:$HGPORT/ e
77 $ http_proxy=http://user:passwd@localhost:$HGPORT1 hg clone --config http_proxy.always=True http://user:passwd@localhost:$HGPORT/ e
78 requesting all changes
78 requesting all changes
79 adding changesets
79 adding changesets
80 adding manifests
80 adding manifests
81 adding file changes
81 adding file changes
82 added 1 changesets with 1 changes to 1 files
82 added 1 changesets with 1 changes to 1 files
83 updating to branch default
83 updating to branch default
84 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
84 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
85
85
86 bad host:port for proxy ("Protocol not supported" can happen on
86 bad host:port for proxy ("Protocol not supported" can happen on
87 misconfigured hosts)
87 misconfigured hosts)
88
88
89 $ http_proxy=localhost:$HGPORT2 hg clone --config http_proxy.always=True http://localhost:$HGPORT/ f
89 $ http_proxy=localhost:$HGPORT2 hg clone --config http_proxy.always=True http://localhost:$HGPORT/ f
90 abort: error: (Connection refused|Protocol not supported|.* actively refused it|Cannot assign requested address) (re)
90 abort: error: (Connection refused|Protocol not supported|.* actively refused it|Cannot assign requested address) (re)
91 [255]
91 [255]
92
92
93 do not use the proxy if it is in the no list
93 do not use the proxy if it is in the no list
94
94
95 $ http_proxy=localhost:$HGPORT1 hg clone --config http_proxy.no=localhost http://localhost:$HGPORT/ g
95 $ http_proxy=localhost:$HGPORT1 hg clone --config http_proxy.no=localhost http://localhost:$HGPORT/ g
96 requesting all changes
96 requesting all changes
97 adding changesets
97 adding changesets
98 adding manifests
98 adding manifests
99 adding file changes
99 adding file changes
100 added 1 changesets with 1 changes to 1 files
100 added 1 changesets with 1 changes to 1 files
101 updating to branch default
101 updating to branch default
102 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
102 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
103 $ cat proxy.log
103 $ cat proxy.log
104 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
104 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
105 * - - [*] "GET http://localhost:$HGPORT/?cmd=branchmap HTTP/1.1" - - x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
105 * - - [*] "GET http://localhost:$HGPORT/?cmd=branchmap HTTP/1.1" - - x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
106 * - - [*] "GET http://localhost:$HGPORT/?cmd=stream_out HTTP/1.1" - - x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
106 * - - [*] "GET http://localhost:$HGPORT/?cmd=stream_out HTTP/1.1" - - x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
107 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D83180e7845de420a1bb46896fd5fe05294f8d629 x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
107 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D83180e7845de420a1bb46896fd5fe05294f8d629 x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
108 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=0&common=83180e7845de420a1bb46896fd5fe05294f8d629&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
108 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=0&common=83180e7845de420a1bb46896fd5fe05294f8d629&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
109 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
109 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
110 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
110 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
111 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
111 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
112 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
112 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
113 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
113 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
114 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
114 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
115 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
115 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
116 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
116 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
117 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
117 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
118 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
118 * - - [*] "GET http://localhost:$HGPORT/?cmd=capabilities HTTP/1.1" - - (glob)
119 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
119 * - - [*] "GET http://localhost:$HGPORT/?cmd=batch HTTP/1.1" - - x-hgarg-1:cmds=heads+%3Bknown+nodes%3D x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
120 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
120 * - - [*] "GET http://localhost:$HGPORT/?cmd=getbundle HTTP/1.1" - - x-hgarg-1:bundlecaps=HG20%2Cbundle2%3DHG20%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=1&common=0000000000000000000000000000000000000000&heads=83180e7845de420a1bb46896fd5fe05294f8d629&listkeys=phases%2Cbookmarks x-hgproto-1:0.1 0.2 comp=*zlib,none,bzip2 (glob)
@@ -1,191 +1,192 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 from __future__ import absolute_import, print_function
3 from __future__ import absolute_import, print_function
4
4
5 __doc__ = """Tiny HTTP Proxy.
5 __doc__ = """Tiny HTTP Proxy.
6
6
7 This module implements GET, HEAD, POST, PUT and DELETE methods
7 This module implements GET, HEAD, POST, PUT and DELETE methods
8 on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
8 on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
9 method is also implemented experimentally, but has not been
9 method is also implemented experimentally, but has not been
10 tested yet.
10 tested yet.
11
11
12 Any help will be greatly appreciated. SUZUKI Hisao
12 Any help will be greatly appreciated. SUZUKI Hisao
13 """
13 """
14
14
15 __version__ = "0.2.1"
15 __version__ = "0.2.1"
16
16
17 import optparse
17 import optparse
18 import os
18 import os
19 import select
19 import select
20 import socket
20 import socket
21 import sys
21 import sys
22
22
23 from mercurial import util
23 from mercurial import util
24
24
25 httpserver = util.httpserver
25 httpserver = util.httpserver
26 socketserver = util.socketserver
26 socketserver = util.socketserver
27 urlreq = util.urlreq
27 urlreq = util.urlreq
28
28
29 if os.environ.get('HGIPV6', '0') == '1':
29 if os.environ.get('HGIPV6', '0') == '1':
30 family = socket.AF_INET6
30 family = socket.AF_INET6
31 else:
31 else:
32 family = socket.AF_INET
32 family = socket.AF_INET
33
33
34 class ProxyHandler (httpserver.basehttprequesthandler):
34 class ProxyHandler (httpserver.basehttprequesthandler):
35 __base = httpserver.basehttprequesthandler
35 __base = httpserver.basehttprequesthandler
36 __base_handle = __base.handle
36 __base_handle = __base.handle
37
37
38 server_version = "TinyHTTPProxy/" + __version__
38 server_version = "TinyHTTPProxy/" + __version__
39 rbufsize = 0 # self.rfile Be unbuffered
39 rbufsize = 0 # self.rfile Be unbuffered
40
40
41 def handle(self):
41 def handle(self):
42 (ip, port) = self.client_address
42 (ip, port) = self.client_address
43 allowed = getattr(self, 'allowed_clients', None)
43 allowed = getattr(self, 'allowed_clients', None)
44 if allowed is not None and ip not in allowed:
44 if allowed is not None and ip not in allowed:
45 self.raw_requestline = self.rfile.readline()
45 self.raw_requestline = self.rfile.readline()
46 if self.parse_request():
46 if self.parse_request():
47 self.send_error(403)
47 self.send_error(403)
48 else:
48 else:
49 self.__base_handle()
49 self.__base_handle()
50
50
51 def log_request(self, code='-', size='-'):
51 def log_request(self, code='-', size='-'):
52 xheaders = [h for h in self.headers.items() if h[0].startswith('x-')]
52 xheaders = [h for h in self.headers.items() if h[0].startswith('x-')]
53 self.log_message('"%s" %s %s%s',
53 self.log_message('"%s" %s %s%s',
54 self.requestline, str(code), str(size),
54 self.requestline, str(code), str(size),
55 ''.join([' %s:%s' % h for h in sorted(xheaders)]))
55 ''.join([' %s:%s' % h for h in sorted(xheaders)]))
56 # Flush for Windows, so output isn't lost on TerminateProcess()
56 # Flush for Windows, so output isn't lost on TerminateProcess()
57 sys.stdout.flush()
57 sys.stderr.flush()
58 sys.stderr.flush()
58
59
59 def _connect_to(self, netloc, soc):
60 def _connect_to(self, netloc, soc):
60 i = netloc.find(':')
61 i = netloc.find(':')
61 if i >= 0:
62 if i >= 0:
62 host_port = netloc[:i], int(netloc[i + 1:])
63 host_port = netloc[:i], int(netloc[i + 1:])
63 else:
64 else:
64 host_port = netloc, 80
65 host_port = netloc, 80
65 print("\t" "connect to %s:%d" % host_port)
66 print("\t" "connect to %s:%d" % host_port)
66 try: soc.connect(host_port)
67 try: soc.connect(host_port)
67 except socket.error as arg:
68 except socket.error as arg:
68 try: msg = arg[1]
69 try: msg = arg[1]
69 except (IndexError, TypeError): msg = arg
70 except (IndexError, TypeError): msg = arg
70 self.send_error(404, msg)
71 self.send_error(404, msg)
71 return 0
72 return 0
72 return 1
73 return 1
73
74
74 def do_CONNECT(self):
75 def do_CONNECT(self):
75 soc = socket.socket(family, socket.SOCK_STREAM)
76 soc = socket.socket(family, socket.SOCK_STREAM)
76 try:
77 try:
77 if self._connect_to(self.path, soc):
78 if self._connect_to(self.path, soc):
78 self.log_request(200)
79 self.log_request(200)
79 self.wfile.write(self.protocol_version +
80 self.wfile.write(self.protocol_version +
80 " 200 Connection established\r\n")
81 " 200 Connection established\r\n")
81 self.wfile.write("Proxy-agent: %s\r\n" % self.version_string())
82 self.wfile.write("Proxy-agent: %s\r\n" % self.version_string())
82 self.wfile.write("\r\n")
83 self.wfile.write("\r\n")
83 self._read_write(soc, 300)
84 self._read_write(soc, 300)
84 finally:
85 finally:
85 print("\t" "bye")
86 print("\t" "bye")
86 soc.close()
87 soc.close()
87 self.connection.close()
88 self.connection.close()
88
89
89 def do_GET(self):
90 def do_GET(self):
90 (scm, netloc, path, params, query, fragment) = urlreq.urlparse(
91 (scm, netloc, path, params, query, fragment) = urlreq.urlparse(
91 self.path, 'http')
92 self.path, 'http')
92 if scm != 'http' or fragment or not netloc:
93 if scm != 'http' or fragment or not netloc:
93 self.send_error(400, "bad url %s" % self.path)
94 self.send_error(400, "bad url %s" % self.path)
94 return
95 return
95 soc = socket.socket(family, socket.SOCK_STREAM)
96 soc = socket.socket(family, socket.SOCK_STREAM)
96 try:
97 try:
97 if self._connect_to(netloc, soc):
98 if self._connect_to(netloc, soc):
98 self.log_request()
99 self.log_request()
99 soc.send("%s %s %s\r\n" % (
100 soc.send("%s %s %s\r\n" % (
100 self.command,
101 self.command,
101 urlreq.urlunparse(('', '', path, params, query, '')),
102 urlreq.urlunparse(('', '', path, params, query, '')),
102 self.request_version))
103 self.request_version))
103 self.headers['Connection'] = 'close'
104 self.headers['Connection'] = 'close'
104 del self.headers['Proxy-Connection']
105 del self.headers['Proxy-Connection']
105 for key_val in self.headers.items():
106 for key_val in self.headers.items():
106 soc.send("%s: %s\r\n" % key_val)
107 soc.send("%s: %s\r\n" % key_val)
107 soc.send("\r\n")
108 soc.send("\r\n")
108 self._read_write(soc)
109 self._read_write(soc)
109 finally:
110 finally:
110 print("\t" "bye")
111 print("\t" "bye")
111 soc.close()
112 soc.close()
112 self.connection.close()
113 self.connection.close()
113
114
114 def _read_write(self, soc, max_idling=20):
115 def _read_write(self, soc, max_idling=20):
115 iw = [self.connection, soc]
116 iw = [self.connection, soc]
116 ow = []
117 ow = []
117 count = 0
118 count = 0
118 while True:
119 while True:
119 count += 1
120 count += 1
120 (ins, _, exs) = select.select(iw, ow, iw, 3)
121 (ins, _, exs) = select.select(iw, ow, iw, 3)
121 if exs:
122 if exs:
122 break
123 break
123 if ins:
124 if ins:
124 for i in ins:
125 for i in ins:
125 if i is soc:
126 if i is soc:
126 out = self.connection
127 out = self.connection
127 else:
128 else:
128 out = soc
129 out = soc
129 try:
130 try:
130 data = i.recv(8192)
131 data = i.recv(8192)
131 except socket.error:
132 except socket.error:
132 break
133 break
133 if data:
134 if data:
134 out.send(data)
135 out.send(data)
135 count = 0
136 count = 0
136 else:
137 else:
137 print("\t" "idle", count)
138 print("\t" "idle", count)
138 if count == max_idling:
139 if count == max_idling:
139 break
140 break
140
141
141 do_HEAD = do_GET
142 do_HEAD = do_GET
142 do_POST = do_GET
143 do_POST = do_GET
143 do_PUT = do_GET
144 do_PUT = do_GET
144 do_DELETE = do_GET
145 do_DELETE = do_GET
145
146
146 class ThreadingHTTPServer (socketserver.ThreadingMixIn,
147 class ThreadingHTTPServer (socketserver.ThreadingMixIn,
147 httpserver.httpserver):
148 httpserver.httpserver):
148 def __init__(self, *args, **kwargs):
149 def __init__(self, *args, **kwargs):
149 httpserver.httpserver.__init__(self, *args, **kwargs)
150 httpserver.httpserver.__init__(self, *args, **kwargs)
150 a = open("proxy.pid", "w")
151 a = open("proxy.pid", "w")
151 a.write(str(os.getpid()) + "\n")
152 a.write(str(os.getpid()) + "\n")
152 a.close()
153 a.close()
153
154
154 def runserver(port=8000, bind=""):
155 def runserver(port=8000, bind=""):
155 server_address = (bind, port)
156 server_address = (bind, port)
156 ProxyHandler.protocol_version = "HTTP/1.0"
157 ProxyHandler.protocol_version = "HTTP/1.0"
157 httpd = ThreadingHTTPServer(server_address, ProxyHandler)
158 httpd = ThreadingHTTPServer(server_address, ProxyHandler)
158 sa = httpd.socket.getsockname()
159 sa = httpd.socket.getsockname()
159 print("Serving HTTP on", sa[0], "port", sa[1], "...")
160 print("Serving HTTP on", sa[0], "port", sa[1], "...")
160 try:
161 try:
161 httpd.serve_forever()
162 httpd.serve_forever()
162 except KeyboardInterrupt:
163 except KeyboardInterrupt:
163 print("\nKeyboard interrupt received, exiting.")
164 print("\nKeyboard interrupt received, exiting.")
164 httpd.server_close()
165 httpd.server_close()
165 sys.exit(0)
166 sys.exit(0)
166
167
167 if __name__ == '__main__':
168 if __name__ == '__main__':
168 argv = sys.argv
169 argv = sys.argv
169 if argv[1:] and argv[1] in ('-h', '--help'):
170 if argv[1:] and argv[1] in ('-h', '--help'):
170 print(argv[0], "[port [allowed_client_name ...]]")
171 print(argv[0], "[port [allowed_client_name ...]]")
171 else:
172 else:
172 if argv[2:]:
173 if argv[2:]:
173 allowed = []
174 allowed = []
174 for name in argv[2:]:
175 for name in argv[2:]:
175 client = socket.gethostbyname(name)
176 client = socket.gethostbyname(name)
176 allowed.append(client)
177 allowed.append(client)
177 print("Accept: %s (%s)" % (client, name))
178 print("Accept: %s (%s)" % (client, name))
178 ProxyHandler.allowed_clients = allowed
179 ProxyHandler.allowed_clients = allowed
179 del argv[2:]
180 del argv[2:]
180 else:
181 else:
181 print("Any clients will be served...")
182 print("Any clients will be served...")
182
183
183 parser = optparse.OptionParser()
184 parser = optparse.OptionParser()
184 parser.add_option('-b', '--bind', metavar='ADDRESS',
185 parser.add_option('-b', '--bind', metavar='ADDRESS',
185 help='Specify alternate bind address '
186 help='Specify alternate bind address '
186 '[default: all interfaces]', default='')
187 '[default: all interfaces]', default='')
187 (options, args) = parser.parse_args()
188 (options, args) = parser.parse_args()
188 port = 8000
189 port = 8000
189 if len(args) == 1:
190 if len(args) == 1:
190 port = int(args[0])
191 port = int(args[0])
191 runserver(port, options.bind)
192 runserver(port, options.bind)
General Comments 0
You need to be logged in to leave comments. Login now