~ubuntu-branches/ubuntu/lucid/prewikka/lucid

« back to all changes in this revision

Viewing changes to scripts/prewikka-httpd~

  • Committer: Bazaar Package Importer
  • Author(s): Pierre Chifflier
  • Date: 2008-07-02 16:49:06 UTC
  • mfrom: (6.1.2 intrepid)
  • Revision ID: james.westby@ubuntu.com-20080702164906-q2bkfn6i40hd95tt
Tags: 0.9.14-2
* Update watch file
* Bump Standards version to 3.8.0 (no changes)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
# Copyright (C) 2004,2005 PreludeIDS Technologies. All Rights Reserved.
 
4
# Author: Nicolas Delon <nicolas.delon@prelude-ids.com>
 
5
#
 
6
# This file is part of the PreludeDB library.
 
7
#
 
8
# This program is free software; you can redistribute it and/or modify
 
9
# it under the terms of the GNU General Public License as published by
 
10
# the Free Software Foundation; either version 2, or (at your option)
 
11
# any later version.
 
12
#
 
13
# This program is distributed in the hope that it will be useful,
 
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
# GNU General Public License for more details.
 
17
#
 
18
# You should have received a copy of the GNU General Public License
 
19
# along with this program; see the file COPYING.  If not, write to
 
20
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 
21
 
 
22
import sys
 
23
import os, os.path
 
24
import time
 
25
 
 
26
import cgi
 
27
import urllib
 
28
import mimetypes
 
29
import shutil
 
30
import getopt
 
31
 
 
32
import SocketServer
 
33
import BaseHTTPServer
 
34
from prewikka import localization
 
35
from prewikka import Core, Request, siteconfig
 
36
 
 
37
 
 
38
class PrewikkaServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
 
39
    def __init__(self, core, *args, **kwargs):
 
40
        self.core = core
 
41
        apply(BaseHTTPServer.HTTPServer.__init__, (self,) + args, kwargs)
 
42
        
 
43
 
 
44
 
 
45
class PrewikkaRequestHandler(Request.Request, BaseHTTPServer.BaseHTTPRequestHandler):
 
46
    def getCookieString(self):
 
47
        return self.headers.get("Cookie")
 
48
 
 
49
    def getQueryString(self):
 
50
        return self._query_string
 
51
 
 
52
    def getReferer(self):
 
53
        try:
 
54
            return self.input_headers["referer"]
 
55
        except KeyError:
 
56
            return ""
 
57
 
 
58
    def write(self, data):
 
59
        self.wfile.write(data)
 
60
    
 
61
    def read(self, *args, **kwargs):
 
62
        return apply(self.rfile.read, args, kwargs)
 
63
    
 
64
    def log_request(self, *args, **kwargs):
 
65
        pass
 
66
 
 
67
    def log_error(self, *args, **kwargs):
 
68
        pass
 
69
 
 
70
    def _processDynamic(self, arguments):
 
71
        self.input_headers.update(self.headers)
 
72
        
 
73
        for name, value in arguments.items():
 
74
            self.arguments[name] = (len(value) == 1) and value[0] or value
 
75
 
 
76
        self.server.core.process(self)
 
77
        
 
78
    def sendResponse(self):
 
79
        self.send_response(200)
 
80
        Request.Request.sendResponse(self)
 
81
 
 
82
    def _processStatic(self):
 
83
        filename = os.path.abspath(siteconfig.htdocs_dir + "/" + urllib.unquote(self.path[len("prewikka/"):]))
 
84
        if filename.find(os.path.abspath(siteconfig.htdocs_dir)) != 0:
 
85
            self.send_error(403, "Request Forbidden")
 
86
            return
 
87
        
 
88
        # the following piece of code is from tracd of the trac project
 
89
        # (http://www.edgewall.com/products/trac/)
 
90
        try:
 
91
            f = open(filename, 'r')
 
92
        except IOError:
 
93
            self.send_error(404, "File not found")
 
94
            return
 
95
        
 
96
        self.send_response(200)
 
97
        mtype, enc = mimetypes.guess_type(filename)
 
98
        stat = os.fstat(f.fileno())
 
99
        content_length = stat[6]
 
100
        last_modified = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stat[8]))
 
101
        self.send_header('Content-Type', mtype)
 
102
        self.send_header('Content-Length', str(content_length))
 
103
        self.send_header('Last-Modified', last_modified)
 
104
        self.end_headers()
 
105
        shutil.copyfileobj(f, self.wfile)
 
106
        
 
107
    def do_GET(self):
 
108
        self._query_string = self.path
 
109
        self.init()
 
110
        if self.path == "/":
 
111
            self._processDynamic({ })
 
112
        elif self.path.find("?") == 1:
 
113
            self._processDynamic(cgi.parse_qs(self.path[2:]))
 
114
        else:
 
115
            self._processStatic()
 
116
 
 
117
    def do_HEAD(self):
 
118
        self.do_GET()
 
119
 
 
120
    def do_POST(self):
 
121
        self._query_string = self.rfile.read(int(self.headers["Content-Length"]))
 
122
        self.init()
 
123
        self._processDynamic(cgi.parse_qs((self._query_string)))
 
124
 
 
125
    def getClientAddr(self):
 
126
        return self.client_address[0]
 
127
 
 
128
    def getClientPort(self):
 
129
        return self.client_address[1]
 
130
 
 
131
 
 
132
def usage():
 
133
    print "Usage: %s [options]" % sys.argv[0]
 
134
    print
 
135
    print "Options:"
 
136
    print "-c --config [config]\tConfiguration file to use (default: %s/prewikka.conf)" % siteconfig.conf_dir
 
137
    print "-p --port [port]\tPort number to use (default: 8000)"
 
138
    print "-a --address [address]\tIP to bind to (default: 0.0.0.0)"
 
139
    print
 
140
    sys.exit(1)
 
141
 
 
142
 
 
143
if __name__ == "__main__":
 
144
    config = None
 
145
    addr, port = "0.0.0.0", 8000
 
146
    
 
147
    opts, args = getopt.getopt(sys.argv[1:], "hc:a:p:", ["help", "config=", "address=", "port="])
 
148
    for opt, arg in opts:
 
149
        if opt in ("-h", "--help"):
 
150
            usage()
 
151
 
 
152
        elif opt in ("-a", "--address"):
 
153
            addr = arg
 
154
                
 
155
        elif opt in ("-p", "--port"):
 
156
            port = int(arg)
 
157
 
 
158
        elif opt in ("-c", "--config"):
 
159
            config = arg
 
160
 
 
161
    core = Core.get_core_from_config(config)
 
162
    server = PrewikkaServer(core, (addr, port), PrewikkaRequestHandler)
 
163
    server.serve_forever()