This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
util.py
589 lines (477 loc) · 16.1 KB
/
util.py
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
##
# Copyright (c) 2007-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
import os
import re
import sys
import base64
import itertools
from subprocess import Popen, PIPE, STDOUT
from hashlib import md5, sha1
from twisted.internet import reactor
from twisted.web import client
from twisted.python import failure
from twext.python.log import Logger
log = Logger()
from twext.internet.gaiendpoint import GAIEndpoint
from twext.internet.adaptendpoint import connect
from twext.internet.ssl import simpleClientContextFactory
##
# System Resources (Memory size and processor count)
##
try:
from ctypes import (
cdll,
c_int, c_uint64, c_ulong,
c_char_p, c_void_p,
addressof, sizeof, c_size_t,
)
from ctypes.util import find_library
hasCtypes = True
except ImportError:
hasCtypes = False
if (
sys.platform == "darwin" or
sys.platform.startswith("freebsd")
) and hasCtypes:
libc = cdll.LoadLibrary(find_library("libc"))
def getNCPU():
"""
Returns the number of processors detected
"""
ncpu = c_int(0)
size = c_size_t(sizeof(ncpu))
libc.sysctlbyname.argtypes = [
c_char_p, c_void_p, c_void_p, c_void_p, c_ulong
]
libc.sysctlbyname(
"hw.ncpu",
c_void_p(addressof(ncpu)),
c_void_p(addressof(size)),
None,
0
)
return int(ncpu.value)
def getMemorySize():
"""
Returns the physical amount of RAM installed, in bytes
"""
memsize = c_uint64(0)
size = c_size_t(sizeof(memsize))
libc.sysctlbyname.argtypes = [
c_char_p, c_void_p, c_void_p, c_void_p, c_ulong
]
libc.sysctlbyname(
"hw.memsize",
c_void_p(addressof(memsize)),
c_void_p(addressof(size)),
None,
0
)
return int(memsize.value)
elif sys.platform == "linux2" and hasCtypes:
libc = cdll.LoadLibrary(find_library("libc"))
def getNCPU():
return libc.get_nprocs()
def getMemorySize():
return libc.getpagesize() * libc.get_phys_pages()
else:
def getNCPU():
if not hasCtypes:
msg = " without ctypes"
else:
msg = ""
raise NotImplementedError("getNCPU not supported on %s%s" % (sys.platform, msg))
def getMemorySize():
raise NotImplementedError("getMemorySize not yet supported on %s" % (sys.platform))
def computeProcessCount(minimum, perCPU, perGB, cpuCount=None, memSize=None):
"""
Determine how many process to spawn based on installed RAM and CPUs,
returning at least "mininum"
"""
if cpuCount is None:
try:
cpuCount = getNCPU()
except NotImplementedError, e:
log.error("Unable to detect number of CPUs: {ex}", ex=str(e))
return minimum
if memSize is None:
try:
memSize = getMemorySize()
except NotImplementedError, e:
log.error("Unable to detect amount of installed RAM: {ex}", ex=str(e))
return minimum
countByCore = perCPU * cpuCount
countByMemory = perGB * (memSize / (1024 * 1024 * 1024))
# Pick the smaller of the two:
count = min(countByCore, countByMemory)
# ...but at least "minimum"
return max(count, minimum)
##
# Module management
##
def submodule(module, name):
fullname = module.__name__ + "." + name
try:
submodule = __import__(fullname)
except ImportError, e:
raise ImportError("Unable to import submodule %s from module %s: %s" % (name, module, e))
for m in fullname.split(".")[1:]:
submodule = getattr(submodule, m)
return submodule
##
# Tracebacks
##
from twisted.python.failure import Failure
def printTracebacks(f):
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
Failure().printTraceback()
raise
return wrapper
##
# Helpers
##
class Alternator (object):
"""
Object that alternates between True and False states.
"""
def __init__(self, state=False):
self._state = bool(state)
def state(self):
"""
@return: the current state
"""
state = self._state
self._state = not state
return state
def utf8String(s):
if isinstance(s, unicode):
s = s.encode("utf-8")
return s
##
# Keychain access
##
class KeychainPasswordNotFound(Exception):
"""
Exception raised when the password does not exist
"""
class KeychainAccessError(Exception):
"""
Exception raised when not able to access keychain
"""
passwordRegExp = re.compile(r'password: "(.*)"')
def getPasswordFromKeychain(account):
if os.path.isfile("/usr/bin/security"):
child = Popen(
args=[
"/usr/bin/security", "find-generic-password",
"-a", account, "-g",
],
stdout=PIPE, stderr=STDOUT,
)
output, error = child.communicate()
if child.returncode:
raise KeychainPasswordNotFound(error)
else:
match = passwordRegExp.search(output)
if not match:
error = "Password for %s not found in keychain" % (account,)
raise KeychainPasswordNotFound(error)
else:
return match.group(1)
else:
error = "Keychain access utility ('security') not found"
raise KeychainAccessError(error)
##
# Digest/Basic-capable HTTP GET factory
##
algorithms = {
'md5': md5,
'md5-sess': md5,
'sha': sha1,
}
# DigestCalcHA1
def calcHA1(
pszAlg,
pszUserName,
pszRealm,
pszPassword,
pszNonce,
pszCNonce,
preHA1=None
):
"""
@param pszAlg: The name of the algorithm to use to calculate the digest.
Currently supported are md5 md5-sess and sha.
@param pszUserName: The username
@param pszRealm: The realm
@param pszPassword: The password
@param pszNonce: The nonce
@param pszCNonce: The cnonce
@param preHA1: If available this is a str containing a previously
calculated HA1 as a hex string. If this is given then the values for
pszUserName, pszRealm, and pszPassword are ignored.
"""
if (preHA1 and (pszUserName or pszRealm or pszPassword)):
raise TypeError(("preHA1 is incompatible with the pszUserName, "
"pszRealm, and pszPassword arguments"))
if preHA1 is None:
# We need to calculate the HA1 from the username:realm:password
m = algorithms[pszAlg]()
m.update(pszUserName)
m.update(":")
m.update(pszRealm)
m.update(":")
m.update(pszPassword)
HA1 = m.digest()
else:
# We were given a username:realm:password
HA1 = preHA1.decode('hex')
if pszAlg == "md5-sess":
m = algorithms[pszAlg]()
m.update(HA1)
m.update(":")
m.update(pszNonce)
m.update(":")
m.update(pszCNonce)
HA1 = m.digest()
return HA1.encode('hex')
# DigestCalcResponse
def calcResponse(
HA1,
algo,
pszNonce,
pszNonceCount,
pszCNonce,
pszQop,
pszMethod,
pszDigestUri,
pszHEntity,
):
m = algorithms[algo]()
m.update(pszMethod)
m.update(":")
m.update(pszDigestUri)
if pszQop == "auth-int":
m.update(":")
m.update(pszHEntity)
HA2 = m.digest().encode('hex')
m = algorithms[algo]()
m.update(HA1)
m.update(":")
m.update(pszNonce)
m.update(":")
if pszNonceCount and pszCNonce and pszQop:
m.update(pszNonceCount)
m.update(":")
m.update(pszCNonce)
m.update(":")
m.update(pszQop)
m.update(":")
m.update(HA2)
respHash = m.digest().encode('hex')
return respHash
class Unauthorized(Exception):
pass
class AuthorizedHTTPGetter(client.HTTPPageGetter):
log = Logger()
def handleStatus_401(self):
self.quietLoss = 1
self.transport.loseConnection()
if not hasattr(self.factory, "username"):
self.factory.deferred.errback(failure.Failure(Unauthorized("Authentication required")))
return self.factory.deferred
if hasattr(self.factory, "retried"):
self.factory.deferred.errback(failure.Failure(Unauthorized("Could not authenticate user %s with calendar server" % (self.factory.username,))))
return self.factory.deferred
self.factory.retried = True
# self.log.debug("Got a 401 trying to inject [{hdrs}]", hdrs=self.headers)
details = {}
basicAvailable = digestAvailable = False
wwwauth = self.headers.get("www-authenticate")
for item in wwwauth:
if item.startswith("basic "):
basicAvailable = True
if item.startswith("digest "):
digestAvailable = True
wwwauth = item[7:]
def unq(s):
if s[0] == s[-1] == '"':
return s[1:-1]
return s
parts = wwwauth.split(',')
for (k, v) in [p.split('=', 1) for p in parts]:
details[k.strip()] = unq(v.strip())
user = self.factory.username
pswd = self.factory.password
if digestAvailable and details:
digest = calcResponse(
calcHA1(
details.get('algorithm'),
user,
details.get('realm'),
pswd,
details.get('nonce'),
details.get('cnonce')
),
details.get('algorithm'),
details.get('nonce'),
details.get('nc'),
details.get('cnonce'),
details.get('qop'),
self.factory.method,
self.factory.url,
None
)
if details.get('qop'):
response = (
'Digest username="%s", realm="%s", nonce="%s", uri="%s", '
'response=%s, algorithm=%s, cnonce="%s", qop=%s, nc=%s' %
(
user,
details.get('realm'),
details.get('nonce'),
self.factory.url,
digest,
details.get('algorithm'),
details.get('cnonce'),
details.get('qop'),
details.get('nc'),
)
)
else:
response = (
'Digest username="%s", realm="%s", nonce="%s", uri="%s", '
'response=%s, algorithm=%s' %
(
user,
details.get('realm'),
details.get('nonce'),
self.factory.url,
digest,
details.get('algorithm'),
)
)
self.factory.headers['Authorization'] = response
if self.factory.scheme == 'https':
connect(
GAIEndpoint(reactor, self.factory.host, self.factory.port, simpleClientContextFactory(self.factory.host)),
self.factory)
else:
connect(
GAIEndpoint(reactor, self.factory.host, self.factory.port),
self.factory)
# self.log.debug("Retrying with digest after 401")
return self.factory.deferred
elif basicAvailable:
basicauth = "%s:%s" % (user, pswd)
basicauth = "Basic " + base64.encodestring(basicauth)
basicauth = basicauth.replace("\n", "")
self.factory.headers['Authorization'] = basicauth
if self.factory.scheme == 'https':
connect(
GAIEndpoint(reactor, self.factory.host, self.factory.port, simpleClientContextFactory(self.factory.host)),
self.factory)
else:
connect(
GAIEndpoint(reactor, self.factory.host, self.factory.port),
self.factory)
# self.log.debug("Retrying with basic after 401")
return self.factory.deferred
else:
self.factory.deferred.errback(failure.Failure(Unauthorized("Mail gateway not able to process reply; calendar server returned 401 and doesn't support basic or digest")))
return self.factory.deferred
def bestAcceptType(accepts, allowedTypes):
"""
Given a set of Accept headers and the set of types the server can return, determine the best choice
of format to return to the client.
@param accepts: parsed accept headers
@type accepts: C{dict}
@param allowedTypes: list of allowed types in server preferred order
@type allowedTypes: C{list}
"""
# If no Accept present just use the first allowed type - the server's preference
if not accepts:
return allowedTypes[0]
# Get mapping for ordered top-level types for use in subtype wildcard match
toptypes = {}
for allowed in allowedTypes:
mediaType = allowed.split("/")[0]
if mediaType not in toptypes:
toptypes[mediaType] = allowed
result = None
result_qval = 0.0
for content_type, qval in accepts.items():
# Exact match
ctype = "%s/%s" % (content_type.mediaType, content_type.mediaSubtype,)
if ctype in allowedTypes:
if qval > result_qval:
result = ctype
result_qval = qval
# Subtype wildcard match
elif content_type.mediaType != "*" and content_type.mediaSubtype == "*":
if content_type.mediaType in toptypes:
if qval > result_qval:
result = toptypes[content_type.mediaType]
result_qval = qval
# Full wildcard match
elif content_type.mediaType == "*" and content_type.mediaSubtype == "*":
if qval > result_qval:
result = allowedTypes[0]
result_qval = qval
return result
def userAgentProductTokens(user_agent):
"""
Parse an HTTP User-Agent header to extract the product tokens and ignore
any parenthesized comment strings in the header.
@param user_agent: text of User-Agent header value
@type user_agent: L{str}
@return: list of product tokens extracted from the header
@rtype: L{list}
"""
ua_hdr = user_agent.split()
ua_tokens = []
comment = False
for token in ua_hdr:
if comment:
if token.endswith(")"):
comment = False
elif token.startswith("("):
if not token.endswith(")"):
comment = True
else:
ua_tokens.append(token)
return ua_tokens
def matchClientFixes(config, user_agent):
"""
Given a user-agent string, see if it matches any of the configured client fixes.
@param config: the L{config} to match against.
@type config: L{ConfigDict}
@param user_agent: the HTTP User-Agent header value to test.
@type user_agent: L{str}
"""
if len(config.ClientFixesCompiled) == 0 or not user_agent:
return set()
ua_tokens = userAgentProductTokens(user_agent)
client_fixes = set()
for fix, patterns in config.ClientFixesCompiled.items():
for pattern, token in itertools.product(patterns, ua_tokens):
if pattern.match(token) is not None:
client_fixes.add(fix)
break
return client_fixes