File: http_header.py

package info (click to toggle)
ntlmaps 0.9.9-2sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 424 kB
  • ctags: 219
  • sloc: python: 2,525; sh: 138; makefile: 39
file content (363 lines) | stat: -rw-r--r-- 11,644 bytes parent folder | download | duplicates (7)
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# This file is part of 'NTLM Authorization Proxy Server'
# Copyright 2001 Dmitry A. Rozmanov <dima@xenon.spb.ru>
#
# NTLM APS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# NTLM APS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the sofware; see the file COPYING. If not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#

import string, urlparse

http_debug_file_name = 'http.debug'

#-----------------------------------------------------------------------
# tests client's header for correctness
def test_client_http_header(header_str):
    ""
    request = string.split(header_str, '\012')[0]
    parts = string.split(request)

    # we have to have at least 3 words in the request
    # poor check
    if len(parts) < 3:
        return 0
    else:
        return 1


#-----------------------------------------------------------------------
# tests server's response header for correctness
def test_server_http_header(header_str):
    ""
    response = string.split(header_str, '\012')[0]
    parts = string.split(response)
    
    # we have to have at least 2 words in the response
    # poor check
    if len(parts) < 2:
        return 0
    else:
        return 1

#-----------------------------------------------------------------------
def extract_http_header_str(buffer):
    ""
    # let's remove possible leading newlines
    t = string.lstrip(buffer)

    # searching for the RFC header's end
    delimiter = '\015\012\015\012'
    header_end = string.find(t, delimiter)

    if header_end < 0:
        # may be it is defective header made by junkbuster
        delimiter = '\012\012'
        header_end = string.find(t, delimiter)

    if header_end >=0:
        # we have found it, possibly
        ld = len(delimiter)
        header_str = t[0:header_end + ld]

        # Let's check if it is a proper header
        if test_server_http_header(header_str) or test_client_http_header(header_str):
            # if yes then let's do our work
            if (header_end + ld) >= len(t):
                rest_str = ''
            else:
                rest_str = t[header_end + ld:]
        else:
            # if not then let's leave the buffer as it is
            # NOTE: if there is some junk before right header we will never
            # find that header. Till timeout, I think. Not that good solution.
            header_str = ''
            rest_str = buffer

    else:
        # there is no complete header in the buffer
        header_str = ''
        rest_str = buffer

    return (header_str, rest_str)

#-----------------------------------------------------------------------
def extract_server_header(buffer):
    ""
    header_str, rest_str = extract_http_header_str(buffer)
    if header_str:
        header_obj = HTTP_SERVER_HEAD(header_str)
    else:
        header_obj = None

    return (header_obj, rest_str)

#-----------------------------------------------------------------------
def extract_client_header(buffer):
    ""
    header_str, rest_str = extract_http_header_str(buffer)
    if header_str:
        header_obj = HTTP_CLIENT_HEAD(header_str)
    else:
        header_obj = None

    return (header_obj, rest_str)

#-----------------------------------------------------------------------
def capitalize_value_name(str):
    ""
    tl = string.split(str, '-')
    for i in range(len(tl)):
        tl[i] = string.capitalize(tl[i])

    return string.join(tl, '-')


#-----------------------------------------------------------------------
# some helper classes
#-----------------------------------------------------------------------
class HTTP_HEAD:
    ""
    pass

    #-------------------------------
    def __init__(self, head_str):
        ""
        self.head_source = ''
        self.params = None
        self.fields = None
        self.order_list = []

        self.head_source = head_str
        head_str = string.strip(head_str)
        records = string.split(head_str, '\012')

        # Dealing with response line
        #fields = string.split(records[0], ' ', 2)
        t = string.split(string.strip(records[0]))
        fields = t[:2] + [string.join(t[2:])]

        self.fields = []
        for i in fields:
            self.fields.append(string.strip(i))

        # Dealing with params
        params = {}
        order_list = []
        for i in records[1:]:
            parts = string.split(string.strip(i), ':', 1)
            pname = string.lower(string.strip(parts[0]))
            if not params.has_key(pname):
                params[pname] = []
                order_list.append(string.lower(pname))
            try:
                params[pname].append(string.strip(parts[1]))
            except:
                msg = "ERROR: Exception in head parsing. ValueName: '%s'" % pname
                #print msg
                self.debug(msg)

        self.params = params
        self.order_list = order_list


    #-------------------------------
    def debug(self, message):
        ""
        try:
            f = open(http_debug_file_name, 'a')
            f.write(message)
            f.write('\n=====\n')
            f.write(self.head_source)
            f.close()
        except IOError:
            pass
            # Yes, yes, I know, this is just sweeping it under the rug...
            # TODO: implement a persistent filehandle for logging debug messages to.

    #-------------------------------
    def copy(self):
        ""
        import copy
        return copy.deepcopy(self)


    #-------------------------------
    def get_param_values(self, param_name):
        ""
        param_name = string.lower(param_name)
        if self.params.has_key(param_name):
            return self.params[param_name]
        else:
            return []

    #-------------------------------
    def del_param(self, param_name):
        ""
        param_name = string.lower(param_name)
        if self.params.has_key(param_name): del self.params[param_name]

    #-------------------------------
    def has_param(self, param_name):
        ""
        param_name = string.lower(param_name)
        return self.params.has_key(param_name)

    #-------------------------------
    def add_param_value(self, param_name, value):
        ""
        param_name = string.lower(param_name)
        if not self.params.has_key(param_name):
            self.params[param_name] = []
        if param_name not in self.order_list:
            self.order_list.append(param_name)
        self.params[param_name].append(value)

    #-------------------------------
    def replace_param_value(self, param_name, value):
        ""
        self.del_param(param_name)
        self.add_param_value(param_name, value)

    #-------------------------------
    def __repr__(self, delimiter='\n'):
        ""
        res = ''
        cookies = ''
        res = string.join(self.fields, ' ') + '\n'

        for i in self.order_list:
            if self.params.has_key(i):
                if i == 'cookie':
                    for k in self.params[i]:
                        cookies = cookies + capitalize_value_name(i) + ': ' + k + '\n'
                else:
                    for k in self.params[i]:
                        res = res + capitalize_value_name(i) + ': ' + k + '\n'
        res = res + cookies
        res = res + '\n'

        return res

    #-------------------------------
    def send(self, socket):
        ""
        #"""
        res = ''
        cookies = ''
        res = string.join(self.fields, ' ') + '\015\012'

        for i in self.order_list:
            if self.params.has_key(i):
                if i == 'cookie':
                    for k in self.params[i]:
                        cookies = cookies + capitalize_value_name(i) + ': ' + k + '\015\012'
                else:
                    for k in self.params[i]:
                        res = res + capitalize_value_name(i) + ': ' + k + '\015\012'
        res = res + cookies
        res = res + '\015\012'
        #"""
        #res = self.__repr__('\015\012')
        # NOTE!!! 0.9.1 worked, 0.9.5 and 0.9.7 did not with MSN Messenger.
        # We had problem here that prevent MSN Messenger from working.
        # Some work is needed to make __rerp__ working instead of current code..
        try:
            #socket.send(self.head_source)
            socket.send(res)
            # self.debug(res)
            return 1
        except:
            return 0

#-----------------------------------------------------------------------
class HTTP_SERVER_HEAD(HTTP_HEAD):

    #-------------------------------
    def get_http_version(self):
        ""
        return self.fields[0]

    #-------------------------------
    def get_http_code(self):
        ""
        return self.fields[1]

    #-------------------------------
    def get_http_message(self):
        ""
        return self.fields[2]

#-----------------------------------------------------------------------
class HTTP_CLIENT_HEAD(HTTP_HEAD):

    #-------------------------------
    def get_http_version(self):
        ""
        return self.fields[2]

    #-------------------------------
    def get_http_method(self):
        ""
        return self.fields[0]

    #-------------------------------
    def get_http_url(self):
        ""
        return self.fields[1]

    #-------------------------------
    def set_http_url(self, new_url):
        ""
        self.fields[1] = new_url

    #-------------------------------
    # There is some problem with www request header...
    # not all servers want to answer to requests with full url in request
    # but want have net location in 'Host' value and path in url.
    def make_right_header(self):
        ""
        url_tuple = urlparse.urlparse(self.get_http_url())
        net_location = url_tuple[1]
        self.replace_param_value('Host', net_location)

        path = urlparse.urlunparse(tuple(['', ''] + list(url_tuple[2:])))
        self.set_http_url(path)

    #-------------------------------
    def get_http_server(self):
        ""
        # trying to get host from url
        url_tuple = urlparse.urlparse(self.get_http_url())
        net_location = url_tuple[1]

        # if there was no host in url then get it from 'Host' value
        if not net_location:
            net_location = self.get_param_values('Host')[0]

        if not net_location:
            net_location = 'localhost'

        # trying to parse user:passwd@www.some.domain:8080
        # is it needed?
        if '@' in net_location:
            cred, net_location = string.split(net_location, '@')
        if ':' in net_location:
            server, port = string.split(net_location, ':')
            port = int(port)
        else:
            server = net_location
            port = 80

        return server, port