January Star
  • Home
  • Categories
  • Tags
  • Archives

CGIHTTPServer标准库源码学习

Contents

  • 简介
  • CGIHTTPRequestHandler
    • rbufsize = 0
    • cgi_directories
    • _url_collapse_path
    • CGI 环境变量
    • bug #427345
    • nobody_uid
    • executable

简介

CGIHTTPRequestHandler 是继承自 SimpleHTTPServer.SimpleHTTPRequestHandler 的。

它定义了一个 POST 方法来支持 CGI 脚本。

Tip

GET 、 HEAD 都是支持用 CGI 脚本的,但是本模块仅定义了 POST 方法。

如果当前系统(比如 Windows)没有 os.fork() 函数,那么就会调用 os.popen2() 函数。

如果连该函数也没有(比如 Macntosh),那么只能利用当前 Python 进程执行 Python 代码编写的 CGI 脚本。

本模块处理所有 HTTP 请求都是同步模式。

Warning

本模块实现的 CGIHTTPServer 在安全方面未作考虑,它可以执行任意的 Python 代码或者外部程序。

最好不要使用在生产环境当中,除非你有严格的防护设备(防火墙等等)。

Note

由于在调用 CGI 脚本之前, 200 OK 的返回码已经写入到 wfile 中了,

所以在 CGI 脚本中是不能再写入其它返回码的。

Tip

如果想深入了解 CGI,参见 CGI 101

CGIHTTPRequestHandler

  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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    # 检测运行服务的平台为哪类操作系统 
    have_fork = hasattr(os, 'fork')
    have_popen2 = hasattr(os, 'popen2')
    have_popen3 = hasattr(os, 'popen3')

    # 关闭输入的缓存功能 
    rbufsize = 0

    def do_POST(self):
        if self.is_cgi():
            self.run_cgi()
        else:
            self.send_error(501, "Can only POST to CGI scripts")

    def send_head(self):
        if self.is_cgi():
            return self.run_cgi()
        else:
            return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)

    def is_cgi(self):
        """ 判断请求的路径是否为一个 CGI 脚本 

        如果为一个 CGI 脚本,则更新 self.cgi_info 属性 (dir, rest), 并返回 True,否则返回 False
        """
        collapsed_path = _url_collapse_path(self.path)
        # 下面两行代码可以用一行代码代替 
        # head, _, tail = collapsed_path.partition('/')
        dir_sep = collapsed_path.find('/', 1)
        head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
        # 只允许运行 CGI 脚本存放目录中的脚本 / 程序,
        # 由于 `_url_collapse_path` 已经对请求路径进行压缩过滤,所以这里简单判断即可 
        if head in self.cgi_directories:
            self.cgi_info = head, tail
            return True
        return False

    cgi_directories = ['/cgi-bin', '/htbin'] # CGI 脚本的存放目录 

    def is_executable(self, path):
        return executable(path)

    def is_python(self, path):
        """ 判断某文件是否为 Python 脚本 """
        head, tail = os.path.splitext(path)
        return tail.lower() in (".py", ".pyw") # 其实还有 pyc,pyo... ...

    def run_cgi(self):
        # 这个函数巨长无比 ... ...
        # 解析请求路径 
        path = self.path
        dir, rest = self.cgi_info

        i = path.find('/', len(dir) + 1)
        while i >= 0:
            nextdir = path[:i]
            nextrest = path[i+1:]

            scriptdir = self.translate_path(nextdir)
            if os.path.isdir(scriptdir):
                dir, rest = nextdir, nextrest
                i = path.find('/', len(dir) + 1)
            else:
                break

        # find an explicit query string, if present.
        i = rest.rfind('?')
        if i >= 0:
            rest, query = rest[:i], rest[i+1:]
        else:
            query = ''

        # dissect the part after the directory name into a script name &
        # a possible additional path, to be stored in PATH_INFO.
        i = rest.find('/')
        if i >= 0:
            script, rest = rest[:i], rest[i:]
        else:
            script, rest = rest, ''

        scriptname = dir + '/' + script
        scriptfile = self.translate_path(scriptname)
        if not os.path.exists(scriptfile):
            self.send_error(404, "No such CGI script (%r)" % scriptname)
            return
        if not os.path.isfile(scriptfile):
            self.send_error(403, "CGI script is not a plain file (%r)" %
                            scriptname)
            return
        ispy = self.is_python(scriptname)
        if not ispy:
            if not (self.have_fork or self.have_popen2 or self.have_popen3):
                self.send_error(403, "CGI script is not a Python script (%r)" %
                                scriptname)
                return
            if not self.is_executable(scriptfile):
                self.send_error(403, "CGI script is not executable (%r)" %
                                scriptname)
                return

        # 启动 CGI 脚本所需要的环境变量 
        env = copy.deepcopy(os.environ)
        env['SERVER_SOFTWARE'] = self.version_string()
        env['SERVER_NAME'] = self.server.server_name
        env['GATEWAY_INTERFACE'] = 'CGI/1.1'
        env['SERVER_PROTOCOL'] = self.protocol_version
        env['SERVER_PORT'] = str(self.server.server_port)
        env['REQUEST_METHOD'] = self.command
        uqrest = urllib.unquote(rest)
        env['PATH_INFO'] = uqrest
        env['PATH_TRANSLATED'] = self.translate_path(uqrest)
        env['SCRIPT_NAME'] = scriptname
        if query:
            env['QUERY_STRING'] = query
        host = self.address_string()
        if host != self.client_address[0]:
            env['REMOTE_HOST'] = host
        env['REMOTE_ADDR'] = self.client_address[0]
        authorization = self.headers.getheader("authorization")
        if authorization:
            authorization = authorization.split()
            if len(authorization) == 2:
                import base64, binascii
                env['AUTH_TYPE'] = authorization[0]
                if authorization[0].lower() == "basic":
                    try:
                        authorization = base64.decodestring(authorization[1])
                    except binascii.Error:
                        pass
                    else:
                        authorization = authorization.split(':')
                        if len(authorization) == 2:
                            env['REMOTE_USER'] = authorization[0]
        # XXX REMOTE_IDENT
        if self.headers.typeheader is None:
            env['CONTENT_TYPE'] = self.headers.type
        else:
            env['CONTENT_TYPE'] = self.headers.typeheader
        length = self.headers.getheader('content-length')
        if length:
            env['CONTENT_LENGTH'] = length
        referer = self.headers.getheader('referer')
        if referer:
            env['HTTP_REFERER'] = referer
        accept = []
        for line in self.headers.getallmatchingheaders('accept'):
            if line[:1] in "\t\n\r ":
                accept.append(line.strip())
            else:
                accept = accept + line[7:].split(',')
        env['HTTP_ACCEPT'] = ','.join(accept)
        ua = self.headers.getheader('user-agent')
        if ua:
            env['HTTP_USER_AGENT'] = ua
        co = filter(None, self.headers.getheaders('cookie'))
        if co:
            env['HTTP_COOKIE'] = ', '.join(co)
        # XXX Other HTTP_* headers
        # Since we're setting the env in the parent, provide empty
        # values to override previously set values
        for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
                  'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
            env.setdefault(k, "")

        self.send_response(200, "Script output follows")

        decoded_query = query.replace('+', ' ')

        if self.have_fork:
            # 在 Unix 平台上,使用 fork&&exec 形式启动子进程 
            args = [script]
            if '=' not in decoded_query:
                args.append(decoded_query)
            nobody = nobody_uid()
            self.wfile.flush() # Always flush before forking
            pid = os.fork()
            if pid != 0:
                # Parent
                pid, sts = os.waitpid(pid, 0)
                # throw away additional data [see bug #427345]
                while select.select([self.rfile], [], [], 0)[0]:
                    if not self.rfile.read(1):
                        break
                if sts:
                    self.log_error("CGI script exit status %#x", sts)
                return
            # Child
            try:
                try:
                    os.setuid(nobody)
                except os.error:
                    pass
                # 将请求内容读取及响应写入文件映射到子进程的标准输入 / 输出接口 
                os.dup2(self.rfile.fileno(), 0)
                os.dup2(self.wfile.fileno(), 1)
                os.execve(scriptfile, args, env)
            except:
                self.server.handle_error(self.request, self.client_address)
                os._exit(127)
        else:
            # 非 Unix 平台,使用 subprocess 来启动子进程 
            import subprocess
            cmdline = [scriptfile]
            if self.is_python(scriptfile):
                interp = sys.executable
                if interp.lower().endswith("w.exe"):
                    # On Windows, use python.exe, not pythonw.exe
                    interp = interp[:-5] + interp[-4:]
                cmdline = [interp, '-u'] + cmdline
            if '=' not in query:
                cmdline.append(query)

            self.log_message("command: %s", subprocess.list2cmdline(cmdline))
            try:
                nbytes = int(length)
            except (TypeError, ValueError):
                nbytes = 0
            p = subprocess.Popen(cmdline,
                                 stdin = subprocess.PIPE,
                                 stdout = subprocess.PIPE,
                                 stderr = subprocess.PIPE,
                                 env = env
                                )
            # 注意:请求及响应的数据,是在父进程处理的 
            if self.command.lower() == "post" and nbytes > 0:
                data = self.rfile.read(nbytes)
            else:
                data = None
            # throw away additional data [see bug #427345]
            while select.select([self.rfile._sock], [], [], 0)[0]:
                if not self.rfile._sock.recv(1):
                    break
            stdout, stderr = p.communicate(data)
            self.wfile.write(stdout)
            if stderr:
                self.log_error('%s', stderr)
            p.stderr.close()
            p.stdout.close()
            status = p.returncode
            if status:
                self.log_error("CGI script exit status %#x", status)
            else:
                self.log_message("CGI script exited OK")

rbufsize = 0

上面的代码中这样做,主要是为了关闭输入的缓存功能。

父进程从输入中读取一行,然后根据第一行中的 path 来以子进程的形式调用 CGI 脚本。

在启动子进程时,子进程便会拥有父进程所有资源的一份拷贝,

这样,CGI 脚本就可以从输入中读取剩下的数据。

cgi_directories

CGI 程序的存放目录

CGIHTTPRequestHandler 类中定义了两个目录

1
cgi_directories = ['/cgi-bin', '/htbin']

_url_collapse_path

本函数主要是将 CGI 脚本请求路径进行压缩过滤( .. 表示上级目录, . 表示当前目录),防止其指向 CGI 脚本存放目录之外的程序。

比如:

cgi-bin 目录安装在 /opt 目录下, /cgi-bin/../../bin/ls 就指向了 /bin/ls 程序。

Warning

如果 CGI 脚本的请求路径有过多的 .. ,且导致真实的引用路径为 CGI 脚本存放目录之外的目录,

就会导致本函数抛出 IndexError 异常。

Tip

本文部分参考了 RFC-2396:5.2 规范的相对路径解析算法。

Tip

一般在解析路径时,将路径按照 dirname 、 basename 来解析是很常见的思路。

 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
def _url_collapse_path(path):
    path_parts = path.split('/')
    head_parts = []
    # dirname: path_parts[:-1]
    # 压缩 dirname 中过多的 `..` ,去除 dirname 中的 `.`
    for part in path_parts[:-1]:
        if part == '..':
            head_parts.pop() # IndexError if more '..' than prior parts
        elif part and part != '.':
            head_parts.append( part )

    # basename: tail_part
    if path_parts:
        tail_part = path_parts.pop()
        if tail_part:
            if tail_part == '..':
                head_parts.pop()
                tail_part = ''
            elif tail_part == '.':
                tail_part = ''
    else:
        tail_part = ''

    # 将经过压缩处理的 dirname, basename 再合并为新的路径 
    splitpath = ('/' + '/'.join(head_parts), tail_part)
    collapsed_path = "/".join(splitpath)

    return collapsed_path

CGI 环境变量

一个客户端的 HTTP 请求到服务端,有很多与其相关的附属信息,比如客户端的主机名、客户端 IP 等等,

那么 CGI 服务端是通过将这些信息写入到环境变量中来让 CGI 脚本读取的。

详细内容参见 CGI ENV

Note

原代码中引用的网页为 http://hoohoo.ncsa.uiuc.edu/cgi/env.html ,

但该网页貌似打不开了,我就重新找了一个有关 CGI 环境变量说明的网页。

bug #427345

详见 bug #427345

该 Bug 主要由于 Windows 平台的 IE 浏览器导致的。

IE 浏览器发送的数据和其指定的 Content-length 不对应,它在请求数据的结尾多传入了 rn ,但并没有在 Content-length 中体现。

所以在代码中就出现了如下代码,用于忽略多余的请求数据:

1
2
3
while select.select([self.rfile._sock], [], [], 0)[0]:
    if not self.rfile._sock.recv(1):
        break

nobody_uid

获取 nobody 用户的 UID。

目前许多 Unix 系统都会默认创建一个 nobody 用户,它一个不能登陆的帐号。

1
2
$ grep nobody /etc/passwd
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh

创建该帐号主要是为了尽量限制该用户的权限至最小,当服务器向外提供服务时,可能会让 client 以 nobody 的身份登录。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
nobody = None

def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        # 如果系统没有 nobody 则找到系统中最大的 UID+1 即为 nobody 的 UID
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody

executable

检查某文件是否为可执行文件

1
2
3
4
5
6
def executable(path):
    try:
        st = os.stat(path)
    except os.error:
        return False
    return st.st_mode & 0111 != 0

嗯,有个魔法数字 0111 ,这个我先不直接解释,咱们从头理一下。

os.stat 对应 C 语言的 stat 函数。

1
2
3
4
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *file_name, struct stat *buf);

stat 函数执行成功返回 0,失败返回 -1。取得的文件状态存放在 buf 指针指向的 struct stat 结构体中。

该结构体结构如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
struct stat
{
    dev_t       st_dev;     /* ID of device containing file - 文件所在设备的 ID*/
    ino_t       st_ino;     /* inode number -inode 节点号 */
    mode_t      st_mode;    /* 文件的类型和存取的权限 */
    nlink_t     st_nlink;   /* number of hard links - 链向此文件的连接数 ( 硬连接 )*/
    uid_t       st_uid;     /* user ID of owner - 用户 ID*/
    gid_t       st_gid;     /* group ID of owner - 组 ID*/
    dev_t       st_rdev;    /* device ID (if special file) - 设备号,针对设备文件 */
    off_t       st_size;    /* total size, in bytes - 文件大小,字节为单位 */
    blksize_t   st_blksize; /* blocksize for filesystem I/O - 系统块的大小 */
    blkcnt_t    st_blocks;  /* number of blocks allocated - 文件所占块数 */
    time_t      st_atime;   /* time of last access - 最近存取时间 */
    time_t      st_mtime;   /* time of last modification - 最近修改时间 */
    time_t      st_ctime;   /* time of last status change - 最近状态改变时间 */
};

我们只看其中的 st_mode 。

mode_t 其实就是普通的 unsigned int.

目前,st_mode 只使用了其低 16 位 (00001~0170000) 来表示各个特征位,高 16 位估计为了以后扩展吧。

每个特征位的定义如下:

 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
/* 12~15 位表示类型 */
S_IFMT      0170000      文件类型的位遮罩 
S_IFSOCK    0140000     socket
S_IFLNK     0120000      符号链接 (symbolic link)
S_IFREG     0100000      一般文件 
S_IFBLK     0060000      区块装置 (block device)
S_IFDIR     0040000      目录 
S_IFCHR     0020000      字符装置 (character device)
S_IFIFO     0010000      管道 (fifo)

/* 9~11 位表示特殊属性 */
S_ISUID     0004000      文件的 (set user-id on execution) 位 
S_ISGID     0002000      文件的 (set group-id on execution) 位 
S_ISVTX     0001000      文件的 sticky 位 

/* 0~8 位表示权限 */
S_IRWXU     00700        文件所有者的遮罩值 ( 即所有权限值 )
S_IRUSR     00400        文件所有者具可读取权限 
S_IWUSR     00200        文件所有者具可写入权限 
S_IXUSR     00100        文件所有者具可执行权限 

S_IRWXG     00070        用户组的遮罩值 ( 即所有权限值 )
S_IRGRP     00040        用户组具可读取权限 
S_IWGRP     00020        用户组具可写入权限 
S_IXGRP     00010        用户组具可执行权限 

S_IRWXO     00007        其他用户的遮罩值 ( 即所有权限值 )
S_IROTH     00004        其他用户具可读取权限 
S_IWOTH     00002        其他用户具可写入权限 
S_IXOTH     00001        其他用户具可执行权限 

一般用法是用相应的特征位与文件的 st_mode 的值相与,再比较。

比如下面判断 chapter_1.rst 是否为一个文件。

1
2
In [257]: os.stat("chapter_1.rst").st_mode & stat.S_IFREG == stat.S_IFREG
Out[257]: True

经过上面的解释, executable 函数中的那个魔法数字 0111 就能够知道是

1
2
In [269]: oct(stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
Out[269]: '0111'

至于为什么要等于 0, 看下面的代码就知道了。

1
2
In [258]: stat.S_IXUSR & stat.S_IXGRP & stat.S_IXOTH
Out[267]: 0
Comments
comments powered by Disqus

Published

Dec 1, 2014

Category

Python

Tags

  • python 23
  • stdlibs 15

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor