- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathphpdev.py
More file actions
Latest commit
190 lines (158 loc) · 6.99 KB
/
Copy pathphpdev.py
File metadata and controls
190 lines (158 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
Copyright (c) 2013 Mohd. Kamal Bin Mustafa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
importos
importsys
importurllib
importhttplib
importsubprocess
importcStringIO
importtraceback
importposixpath
importmimetypes
fromurlparseimporturlparse
fromwsgiref.simple_serverimportmake_server
fromSimpleHTTPServerimportSimpleHTTPRequestHandler
HERE=os.path.abspath(os.path.dirname(__file__))
defparse_url(url):
po=urlparse(url)
file_path=po.path.lstrip('/')
file_path_part= []
path_info_part= []
php_part_done=False
forsegmentinfile_path.split('/'):
if'.php'insegment:
php_part_done=True
file_path_part.append(segment)
continue
ifnotphp_part_done:
file_path_part.append(segment)
else:
path_info_part.append(segment)
path_info='/'.join(path_info_part)
file_path='/'.join(file_path_part)
query_string=po.query
returnfile_path, path_info, query_string
classPHPApp(object):
def__init__(self, doc_root=None):
self.doc_root=doc_root
ifdoc_root:
self.cwd=os.path.join(HERE, doc_root)
else:
self.cwd=HERE
def_abs_file_path(self, path):
returnos.path.join(self.cwd, path)
def__call__(self, environ, start_response):
php_env= {}
content=None
file_path, path_info, query_string=parse_url(environ['PATH_INFO'])
php_env['PHP_SELF'] =file_path+path_info
php_env['REMOTE_ADDR'] =environ.get('REMOTE_ADDR', '')
file_path=self._abs_file_path(file_path)
ifos.path.isdir(file_path):
file_path=os.path.join(file_path, 'index.php')
extension=file_path.split('/')[-1][-3:]
ifextension!='php':
returnself.serve_static(environ, start_response, file_path)
php_args= ['php5-cgi', file_path]
# REDIRECT_STATUS must be set. See:
# http://php.net/manual/en/security.cgi-bin.force-redirect.php
php_env['REDIRECT_STATUS'] ='1'
php_env['REQUEST_METHOD'] =environ.get('REQUEST_METHOD', 'GET')
php_env['PATH_INFO'] =path_info
php_env['QUERY_STRING'] =environ['QUERY_STRING']
php_env['SCRIPT_FILENAME'] =os.path.join(HERE, file_path)
php_env['SCRIPT_NAME'] =''
php_env['HTTP_HOST'] =environ['HTTP_HOST']
php_env['SERVER_SOFTWARE'] ='phpdev.py'
php_env['HTTP_COOKIE'] =environ.get('HTTP_COOKIE', '')
# Construct the partial URL that PHP expects for REQUEST_URI
# (http://php.net/manual/en/reserved.variables.server.php) using part of
# the process described in PEP-333
# (http://www.python.org/dev/peps/pep-0333/#url-reconstruction).
php_env['REQUEST_URI'] =urllib.quote(environ['PATH_INFO'])
ifphp_env['QUERY_STRING']:
php_env['REQUEST_URI'] +='?'+php_env['QUERY_STRING']
if'CONTENT_TYPE'inenviron:
php_env['CONTENT_TYPE'] =environ['CONTENT_TYPE']
php_env['HTTP_CONTENT_TYPE'] =environ['CONTENT_TYPE']
# POST data
if'CONTENT_LENGTH'inenviron:
ifenviron['CONTENT_LENGTH'].strip():
php_env['CONTENT_LENGTH'] =environ['CONTENT_LENGTH']
php_env['HTTP_CONTENT_LENGTH'] =environ['CONTENT_LENGTH']
content=environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
returnself.serve_php(environ, start_response, php_args, php_env, content)
defserve_php(self, environ, start_response, php_args, php_env, content):
try:
p=subprocess.Popen(php_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=php_env, cwd=self.cwd)
exceptExceptionase:
start_response('500 Internal Server Error', [('Content-Type', 'text/html')])
return [traceback.format_exc()]
stdout, stderr=p.communicate(content)
message=httplib.HTTPMessage(cStringIO.StringIO(stdout))
assert'Content-Type'inmessage, 'invalid CGI response: %r'%stdout
if'Status'inmessage:
status=message['Status']
delmessage['Status']
else:
status='200 OK'
# Ensures that we avoid merging repeat headers into a single header,
# allowing use of multiple Set-Cookie headers.
headers= []
fornameinmessage:
forvalueinmessage.getheaders(name):
headers.append((name, value))
start_response(status, headers)
return [message.fp.read()]
defserve_static(self, environ, start_response, file_path):
ifnotos.path.exists(file_path):
start_response("404 Not Found", [('Content-type', 'text/plain')])
return ['Not Found',]
mimetype, encoding=mimetypes.guess_type(file_path)
size=os.path.getsize(file_path)
headers= [
("Content-type", mimetypeifmimetypeelse'text/plain'),
("Content-length", str(size)),
]
start_response("200 OK", headers)
returnself.send_file(file_path, size)
defsend_file(self, file_path, size):
BLOCK_SIZE=4096
fh=open(file_path, 'r')
whileTrue:
block=fh.read(BLOCK_SIZE)
ifnotblock:
fh.close()
break
yieldblock
if__name__=='__main__':
importoptparse
parser=optparse.OptionParser()
parser.add_option('-d', '--doc_root', default=None)
parser.add_option('-p', '--port', default=8080, type='int')
parser.add_option('-a', '--address', default='127.0.0.1', help='Address to listen, default to 127.0.0.1')
options, remainder=parser.parse_args()
application=PHPApp(doc_root=options.doc_root)
server=make_server(options.address, options.port, application)
print"Running at http://%s:%d ..."% (options.address, options.port)
try:
server.serve_forever()
exceptKeyboardInterrupt:
sys.exit()