-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathphpdev.py
More file actions
190 lines (158 loc) · 6.99 KB
/
phpdev.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.
"""
import os
import sys
import urllib
import httplib
import subprocess
import cStringIO
import traceback
import posixpath
import mimetypes
from urlparse import urlparse
from wsgiref.simple_server import make_server
from SimpleHTTPServer import SimpleHTTPRequestHandler
HERE = os.path.abspath(os.path.dirname(__file__))
def parse_url(url):
po = urlparse(url)
file_path = po.path.lstrip('/')
file_path_part = []
path_info_part = []
php_part_done = False
for segment in file_path.split('/'):
if '.php' in segment:
php_part_done = True
file_path_part.append(segment)
continue
if not php_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
return file_path, path_info, query_string
class PHPApp(object):
def __init__(self, doc_root=None):
self.doc_root = doc_root
if doc_root:
self.cwd = os.path.join(HERE, doc_root)
else:
self.cwd = HERE
def _abs_file_path(self, path):
return os.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)
if os.path.isdir(file_path):
file_path = os.path.join(file_path, 'index.php')
extension = file_path.split('/')[-1][-3:]
if extension != 'php':
return self.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'])
if php_env['QUERY_STRING']:
php_env['REQUEST_URI'] += '?' + php_env['QUERY_STRING']
if 'CONTENT_TYPE' in environ:
php_env['CONTENT_TYPE'] = environ['CONTENT_TYPE']
php_env['HTTP_CONTENT_TYPE'] = environ['CONTENT_TYPE']
# POST data
if 'CONTENT_LENGTH' in environ:
if environ['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']))
return self.serve_php(environ, start_response, php_args, php_env, content)
def serve_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)
except Exception as e:
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' in message, 'invalid CGI response: %r' % stdout
if 'Status' in message:
status = message['Status']
del message['Status']
else:
status = '200 OK'
# Ensures that we avoid merging repeat headers into a single header,
# allowing use of multiple Set-Cookie headers.
headers = []
for name in message:
for value in message.getheaders(name):
headers.append((name, value))
start_response(status, headers)
return [message.fp.read()]
def serve_static(self, environ, start_response, file_path):
if not os.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", mimetype if mimetype else 'text/plain'),
("Content-length", str(size)),
]
start_response("200 OK", headers)
return self.send_file(file_path, size)
def send_file(self, file_path, size):
BLOCK_SIZE = 4096
fh = open(file_path, 'r')
while True:
block = fh.read(BLOCK_SIZE)
if not block:
fh.close()
break
yield block
if __name__ == '__main__':
import optparse
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()
except KeyboardInterrupt:
sys.exit()