techprotrade commited on
Commit
0eedeef
·
verified ·
1 Parent(s): 91c0a8e

Add loan-advisor-agent

Browse files
loan-advisor-agent/.venv/Lib/site-packages/isapi/PyISAPI_loader.dll ADDED
Binary file (69.1 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/isapi/README.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ A Python ISAPI extension. Contributed by Phillip Frantz, and is
2
+ Copyright 2002-2003 by Blackdog Software Pty Ltd.
3
+
4
+ See the 'samples' directory, and particularly samples\README.txt
5
+
6
+ You can find documentation in the PyWin32.chm file that comes with pywin32 -
7
+ you can open this from Pythonwin->Help, or from the start menu.
loan-advisor-agent/.venv/Lib/site-packages/isapi/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Python ISAPI package.
2
+
3
+
4
+ # Exceptions thrown by the DLL framework.
5
+ class ISAPIError(Exception):
6
+ def __init__(self, errno, strerror=None, funcname=None):
7
+ # named attributes match OSError etc.
8
+ self.errno = errno
9
+ self.strerror = strerror
10
+ self.funcname = funcname
11
+ Exception.__init__(self, errno, strerror, funcname)
12
+
13
+ def __str__(self):
14
+ if self.strerror is None:
15
+ try:
16
+ import win32api
17
+
18
+ self.strerror = win32api.FormatMessage(self.errno).strip()
19
+ except:
20
+ self.strerror = "no error message is available"
21
+ # str() looks like a win32api error.
22
+ return str((self.errno, self.strerror, self.funcname))
23
+
24
+
25
+ class FilterError(ISAPIError):
26
+ pass
27
+
28
+
29
+ class ExtensionError(ISAPIError):
30
+ pass
31
+
32
+
33
+ # A little development aid - a filter or extension callback function can
34
+ # raise one of these exceptions, and the handler module will be reloaded.
35
+ # This means you can change your code without restarting IIS.
36
+ # After a reload, your filter/extension will have the GetFilterVersion/
37
+ # GetExtensionVersion function called, but with None as the first arg.
38
+ class InternalReloadException(Exception):
39
+ pass
loan-advisor-agent/.venv/Lib/site-packages/isapi/doc/isapi.html ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- NOTE: This HTML is displayed inside the CHM file - hence some hrefs
2
+ will only work in that environment
3
+ -->
4
+ <HTML>
5
+ <BODY>
6
+ <TITLE>Introduction to Python ISAPI support</TITLE>
7
+
8
+ <h2>Introduction to Python ISAPI support</h2>
9
+
10
+ <h3>See also</h3>
11
+ <ul>
12
+ <li><a href="/isapi_modules.html">The isapi related modules</a>
13
+ </li>
14
+ <li><a href="/isapi_objects.html">The isapi related objects</a>
15
+ </li>
16
+ </ul>
17
+ <p><i>Note: if you are viewing this documentation directly from disk,
18
+ most links in this document will fail - you can also find this document in the
19
+ CHM file that comes with pywin32, where the links will work</i>
20
+
21
+ <h3>Introduction</h3>
22
+ This documents Python support for hosting ISAPI exensions and filters inside
23
+ Microsoft Internet Information Server (IIS). It assumes a basic understanding
24
+ of the ISAPI filter and extension mechanism.
25
+ <p>
26
+ In summary, to implement a filter or extension, you provide a Python module
27
+ which defines a Filter and/or Extension class. Once your class has been
28
+ loaded, IIS/ISAPI will, via an extension DLL, call methods on your class.
29
+ <p>
30
+ A filter and a class instance need only provide 3 methods - for filters they
31
+ are called <code>GetFilterVersion</code>, <code>HttpFilterProc</code> and
32
+ <code>TerminateFilter</code>. For extensions they
33
+ are named <code>GetExtensionVersion</code>, <code>HttpExtensionProc</code> and
34
+ <code>TerminateExtension</code>. If you are familiar with writing ISAPI
35
+ extensions in C/C++, these names and their purpose will be familiar.
36
+ <p>
37
+ Most of the work is done in the <code>HttpFilterProc</code> and
38
+ <code>HttpExtensionProc</code> methods. These both take a single
39
+ parameter - an <a href="/HTTP_FILTER_CONTEXT.html">HTTP_FILTER_CONTEXT</a> and
40
+ <a href="/EXTENSION_CONTROL_BLOCK.html">EXTENSION_CONTROL_BLOCK</a>
41
+ object respectively.
42
+ <p>
43
+ In addition to these components, there is an 'isapi' package, containing
44
+ support facilities (base-classes, exceptions, etc) which can be leveraged
45
+ by the extension.
46
+
47
+ <h4>Base classes</h4>
48
+ There are a number of base classes provided to make writing extensions a little
49
+ simpler. Of particular note is <code>isapi.threaded_extension.ThreadPoolExtension</code>.
50
+ This implements a thread-pool and informs IIS that the request is progressing
51
+ in the background. Your sub-class need only provide a <code>Dispatch</code>
52
+ method, which is called on one of the worker threads rather than the thread
53
+ that the request came in on.
54
+ <p>
55
+ There is base-class for a filter in <code>isapi.simple</code>, but there is no
56
+ equivilent threaded filter - filters work under a different model, where
57
+ background processing is not possible.
58
+ <h4>Samples</h4>
59
+ Please see the <code>isapi/samples</code> directory for some sample filters
60
+ and extensions.
61
+
62
+ <H3>Implementation</H3>
63
+ A Python ISAPI filter extension consists of 2 main components:
64
+ <UL>
65
+ <LI>A DLL used by ISAPI to interface with Python.</LI>
66
+ <LI>A Python script used by that DLL to implement the filter or extension
67
+ functionality</LI>
68
+ </UL>
69
+
70
+ <h4>Extension DLL</h4>
71
+ The DLL is usually managed automatically by the isapi.install module. As the
72
+ Python script for the extension is installed, a generic DLL provided with
73
+ the isapi package is installed next to the script, and IIS configured to
74
+ use this DLL.
75
+ <p>
76
+ The name of the DLL always has the same base name as the Python script, but
77
+ with a leading underscore (_), and an extension of .dll. For example, the
78
+ sample "redirector.py" will, when installed, have "_redirector.dll" created
79
+ in the same directory.
80
+ <p/>
81
+ The Python script may provide 2 entry points - methods named __FilterFactory__
82
+ and __ExtensionFactory__, both taking no arguments and returning a filter or
83
+ extension object.
84
+
85
+ <h3>Using py2exe and the isapi package</h3>
86
+ You can instruct py2exe to create a 'frozen' Python ISAPI filter/extension.
87
+ In this case, py2exe will create a package with everything you need in one
88
+ directory, and the Python source file embedded in the .zip file.
89
+ <p>
90
+ In general, you will want to build a seperate installation executable along
91
+ with the ISAPI extension. This executable will be built from the same script.
92
+ See the ISAPI sample in the py2exe distribution.
loan-advisor-agent/.venv/Lib/site-packages/isapi/install.py ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Installation utilities for Python ISAPI filters and extensions."""
2
+
3
+ # this code adapted from "Tomcat JK2 ISAPI redirector", part of Apache
4
+ # Created July 2004, Mark Hammond.
5
+ from __future__ import annotations
6
+
7
+ import importlib.machinery
8
+ import os
9
+ import shutil
10
+ import stat
11
+ import sys
12
+ import traceback
13
+ from collections.abc import Mapping
14
+
15
+ import pythoncom
16
+ import win32api
17
+ import winerror
18
+ from win32com.client import GetObject
19
+
20
+ _APP_INPROC = 0
21
+ _APP_OUTPROC = 1
22
+ _APP_POOLED = 2
23
+ _IIS_OBJECT = "IIS://LocalHost/W3SVC"
24
+ _IIS_SERVER = "IIsWebServer"
25
+ _IIS_WEBDIR = "IIsWebDirectory"
26
+ _IIS_WEBVIRTUALDIR = "IIsWebVirtualDir"
27
+ _IIS_FILTERS = "IIsFilters"
28
+ _IIS_FILTER = "IIsFilter"
29
+
30
+ _DEFAULT_SERVER_NAME = "Default Web Site"
31
+ _DEFAULT_HEADERS = "X-Powered-By: Python"
32
+ _DEFAULT_PROTECTION = _APP_POOLED
33
+
34
+ # Default is for 'execute' only access - ie, only the extension
35
+ # can be used. This can be overridden via your install script.
36
+ _DEFAULT_ACCESS_EXECUTE = True
37
+ _DEFAULT_ACCESS_READ = False
38
+ _DEFAULT_ACCESS_WRITE = False
39
+ _DEFAULT_ACCESS_SCRIPT = False
40
+ _DEFAULT_CONTENT_INDEXED = False
41
+ _DEFAULT_ENABLE_DIR_BROWSING = False
42
+ _DEFAULT_ENABLE_DEFAULT_DOC = False
43
+
44
+ this_dir = os.path.abspath(os.path.dirname(__file__))
45
+
46
+
47
+ class FilterParameters:
48
+ Name = None
49
+ Description = None
50
+ Path = None
51
+ Server = None
52
+ # Params that control if/how AddExtensionFile is called.
53
+ AddExtensionFile = True
54
+ AddExtensionFile_Enabled = True
55
+ AddExtensionFile_GroupID = None # defaults to Name
56
+ AddExtensionFile_CanDelete = True
57
+ AddExtensionFile_Description = None # defaults to Description.
58
+
59
+ def __init__(self, **kw):
60
+ self.__dict__.update(kw)
61
+
62
+
63
+ class VirtualDirParameters:
64
+ Name = None # Must be provided.
65
+ Description = None # defaults to Name
66
+ AppProtection = _DEFAULT_PROTECTION
67
+ Headers = _DEFAULT_HEADERS
68
+ Path = None # defaults to WWW root.
69
+ Type = _IIS_WEBVIRTUALDIR
70
+ AccessExecute = _DEFAULT_ACCESS_EXECUTE
71
+ AccessRead = _DEFAULT_ACCESS_READ
72
+ AccessWrite = _DEFAULT_ACCESS_WRITE
73
+ AccessScript = _DEFAULT_ACCESS_SCRIPT
74
+ ContentIndexed = _DEFAULT_CONTENT_INDEXED
75
+ EnableDirBrowsing = _DEFAULT_ENABLE_DIR_BROWSING
76
+ EnableDefaultDoc = _DEFAULT_ENABLE_DEFAULT_DOC
77
+ DefaultDoc = None # Only set in IIS if not None
78
+ ScriptMaps: list[ScriptMapParams] = []
79
+ ScriptMapUpdate = "end" # can be 'start', 'end', 'replace'
80
+ Server = None
81
+
82
+ def __init__(self, **kw):
83
+ self.__dict__.update(kw)
84
+
85
+ def is_root(self):
86
+ "This virtual directory is a root directory if parent and name are blank"
87
+ parent, name = self.split_path()
88
+ return not parent and not name
89
+
90
+ def split_path(self):
91
+ return split_path(self.Name)
92
+
93
+
94
+ class ScriptMapParams:
95
+ Extension = None
96
+ Module = None
97
+ Flags = 5
98
+ Verbs = ""
99
+ # Params that control if/how AddExtensionFile is called.
100
+ AddExtensionFile = True
101
+ AddExtensionFile_Enabled = True
102
+ AddExtensionFile_GroupID = None # defaults to Name
103
+ AddExtensionFile_CanDelete = True
104
+ AddExtensionFile_Description = None # defaults to Description.
105
+
106
+ def __init__(self, **kw):
107
+ self.__dict__.update(kw)
108
+
109
+ def __str__(self):
110
+ "Format this parameter suitable for IIS"
111
+ items = [self.Extension, self.Module, self.Flags]
112
+ # IIS gets upset if there is a trailing verb comma, but no verbs
113
+ if self.Verbs:
114
+ items.append(self.Verbs)
115
+ items = [str(item) for item in items]
116
+ return ",".join(items)
117
+
118
+
119
+ class ISAPIParameters:
120
+ ServerName = _DEFAULT_SERVER_NAME
121
+ # Description = None
122
+ Filters: list[FilterParameters] = []
123
+ VirtualDirs: list[VirtualDirParameters] = []
124
+
125
+ def __init__(self, **kw):
126
+ self.__dict__.update(kw)
127
+
128
+
129
+ verbose = 1 # The level - 0 is quiet.
130
+
131
+
132
+ def log(level, what):
133
+ if verbose >= level:
134
+ print(what)
135
+
136
+
137
+ # Convert an ADSI COM exception to the Win32 error code embedded in it.
138
+ def _GetWin32ErrorCode(com_exc):
139
+ hr = com_exc.hresult
140
+ # If we have more details in the 'excepinfo' struct, use it.
141
+ if com_exc.excepinfo:
142
+ hr = com_exc.excepinfo[-1]
143
+ if winerror.HRESULT_FACILITY(hr) != winerror.FACILITY_WIN32:
144
+ raise
145
+ return winerror.SCODE_CODE(hr)
146
+
147
+
148
+ class InstallationError(Exception):
149
+ pass
150
+
151
+
152
+ class ItemNotFound(InstallationError):
153
+ pass
154
+
155
+
156
+ class ConfigurationError(InstallationError):
157
+ pass
158
+
159
+
160
+ def FindPath(options, server, name):
161
+ if name.lower().startswith("iis://"):
162
+ return name
163
+ else:
164
+ if name and name[0] != "/":
165
+ name = "/" + name
166
+ return FindWebServer(options, server) + "/ROOT" + name
167
+
168
+
169
+ def LocateWebServerPath(description):
170
+ """
171
+ Find an IIS web server whose name or comment matches the provided
172
+ description (case-insensitive).
173
+
174
+ >>> LocateWebServerPath('Default Web Site') # doctest: +SKIP
175
+
176
+ or
177
+
178
+ >>> LocateWebServerPath('1') #doctest: +SKIP
179
+ """
180
+ assert len(description) >= 1, "Server name or comment is required"
181
+ iis = GetObject(_IIS_OBJECT)
182
+ description = description.lower().strip()
183
+ for site in iis:
184
+ # Name is generally a number, but no need to assume that.
185
+ site_attributes = [
186
+ getattr(site, attr, "").lower().strip()
187
+ for attr in ("Name", "ServerComment")
188
+ ]
189
+ if description in site_attributes:
190
+ return site.AdsPath
191
+ msg = "No web sites match the description '%s'" % description
192
+ raise ItemNotFound(msg)
193
+
194
+
195
+ def GetWebServer(description=None):
196
+ """
197
+ Load the web server instance (COM object) for a given instance
198
+ or description.
199
+ If None is specified, the default website is retrieved (indicated
200
+ by the identifier 1.
201
+ """
202
+ description = description or "1"
203
+ path = LocateWebServerPath(description)
204
+ server = LoadWebServer(path)
205
+ return server
206
+
207
+
208
+ def LoadWebServer(path):
209
+ try:
210
+ server = GetObject(path)
211
+ except pythoncom.com_error as exc:
212
+ msg = exc.strerror
213
+ if exc.excepinfo and exc.excepinfo[2]:
214
+ msg = exc.excepinfo[2]
215
+ msg = f"WebServer {path}: {msg}"
216
+ raise ItemNotFound(msg)
217
+ return server
218
+
219
+
220
+ def FindWebServer(options, server_desc):
221
+ """
222
+ Legacy function to allow options to define a .server property
223
+ to override the other parameter. Use GetWebServer instead.
224
+ """
225
+ # options takes precedence
226
+ server_desc = options.server or server_desc
227
+ # make sure server_desc is unicode (could be mbcs if passed in
228
+ # sys.argv).
229
+ if server_desc and not isinstance(server_desc, str):
230
+ server_desc = server_desc.decode("mbcs")
231
+
232
+ # get the server (if server_desc is None, the default site is acquired)
233
+ server = GetWebServer(server_desc)
234
+ return server.adsPath
235
+
236
+
237
+ def split_path(path):
238
+ """
239
+ Get the parent path and basename.
240
+
241
+ >>> split_path('/')
242
+ ['', '']
243
+
244
+ >>> split_path('')
245
+ ['', '']
246
+
247
+ >>> split_path('foo')
248
+ ['', 'foo']
249
+
250
+ >>> split_path('/foo')
251
+ ['', 'foo']
252
+
253
+ >>> split_path('/foo/bar')
254
+ ['/foo', 'bar']
255
+
256
+ >>> split_path('foo/bar')
257
+ ['/foo', 'bar']
258
+ """
259
+
260
+ if not path.startswith("/"):
261
+ path = "/" + path
262
+ return path.rsplit("/", 1)
263
+
264
+
265
+ def _CreateDirectory(iis_dir, name, params):
266
+ # We used to go to lengths to keep an existing virtual directory
267
+ # in place. However, in some cases the existing directories got
268
+ # into a bad state, and an update failed to get them working.
269
+ # So we nuke it first. If this is a problem, we could consider adding
270
+ # a --keep-existing option.
271
+ try:
272
+ # Also seen the Class change to a generic IISObject - so nuke
273
+ # *any* existing object, regardless of Class
274
+ assert name.strip("/"), "mustn't delete the root!"
275
+ iis_dir.Delete("", name)
276
+ log(2, f"Deleted old directory '{name}'")
277
+ except pythoncom.com_error:
278
+ pass
279
+
280
+ newDir = iis_dir.Create(params.Type, name)
281
+ log(2, f"Creating new directory '{name}' in {iis_dir.Name}...")
282
+
283
+ friendly = params.Description or params.Name
284
+ newDir.AppFriendlyName = friendly
285
+
286
+ # Note that the new directory won't be visible in the IIS UI
287
+ # unless the directory exists on the filesystem.
288
+ try:
289
+ path = params.Path or iis_dir.Path
290
+ newDir.Path = path
291
+ except AttributeError:
292
+ # If params.Type is IIS_WEBDIRECTORY, an exception is thrown
293
+ pass
294
+ newDir.AppCreate2(params.AppProtection)
295
+ # XXX - note that these Headers only work in IIS6 and earlier. IIS7
296
+ # only supports them on the w3svc node - not even on individial sites,
297
+ # let alone individual extensions in the site!
298
+ if params.Headers:
299
+ newDir.HttpCustomHeaders = params.Headers
300
+
301
+ log(2, "Setting directory options...")
302
+ newDir.AccessExecute = params.AccessExecute
303
+ newDir.AccessRead = params.AccessRead
304
+ newDir.AccessWrite = params.AccessWrite
305
+ newDir.AccessScript = params.AccessScript
306
+ newDir.ContentIndexed = params.ContentIndexed
307
+ newDir.EnableDirBrowsing = params.EnableDirBrowsing
308
+ newDir.EnableDefaultDoc = params.EnableDefaultDoc
309
+ if params.DefaultDoc is not None:
310
+ newDir.DefaultDoc = params.DefaultDoc
311
+ newDir.SetInfo()
312
+ return newDir
313
+
314
+
315
+ def CreateDirectory(params, options):
316
+ _CallHook(params, "PreInstall", options)
317
+ if not params.Name:
318
+ raise ConfigurationError("No Name param")
319
+ parent, name = params.split_path()
320
+ target_dir = GetObject(FindPath(options, params.Server, parent))
321
+
322
+ if not params.is_root():
323
+ target_dir = _CreateDirectory(target_dir, name, params)
324
+
325
+ AssignScriptMaps(params.ScriptMaps, target_dir, params.ScriptMapUpdate)
326
+
327
+ _CallHook(params, "PostInstall", options, target_dir)
328
+ log(1, f"Configured Virtual Directory: {params.Name}")
329
+ return target_dir
330
+
331
+
332
+ def AssignScriptMaps(script_maps, target, update="replace"):
333
+ """Updates IIS with the supplied script map information.
334
+
335
+ script_maps is a list of ScriptMapParameter objects
336
+
337
+ target is an IIS Virtual Directory to assign the script maps to
338
+
339
+ update is a string indicating how to update the maps, one of ('start',
340
+ 'end', or 'replace')
341
+ """
342
+ # determine which function to use to assign script maps
343
+ script_map_func = "_AssignScriptMaps" + update.capitalize()
344
+ try:
345
+ script_map_func = eval(script_map_func)
346
+ except NameError:
347
+ msg = "Unknown ScriptMapUpdate option '%s'" % update
348
+ raise ConfigurationError(msg)
349
+ # use the str method to format the script maps for IIS
350
+ script_maps = [str(s) for s in script_maps]
351
+ # call the correct function
352
+ script_map_func(target, script_maps)
353
+ target.SetInfo()
354
+
355
+
356
+ def get_unique_items(sequence, reference):
357
+ "Return items in sequence that can't be found in reference."
358
+ return tuple([item for item in sequence if item not in reference])
359
+
360
+
361
+ def _AssignScriptMapsReplace(target, script_maps):
362
+ target.ScriptMaps = script_maps
363
+
364
+
365
+ def _AssignScriptMapsEnd(target, script_maps):
366
+ unique_new_maps = get_unique_items(script_maps, target.ScriptMaps)
367
+ target.ScriptMaps += unique_new_maps
368
+
369
+
370
+ def _AssignScriptMapsStart(target, script_maps):
371
+ unique_new_maps = get_unique_items(script_maps, target.ScriptMaps)
372
+ target.ScriptMaps = unique_new_maps + target.ScriptMaps
373
+
374
+
375
+ def CreateISAPIFilter(filterParams, options):
376
+ server = FindWebServer(options, filterParams.Server)
377
+ _CallHook(filterParams, "PreInstall", options)
378
+ try:
379
+ filters = GetObject(server + "/Filters")
380
+ except pythoncom.com_error as exc:
381
+ # Brand new sites don't have the '/Filters' collection - create it.
382
+ # Any errors other than 'not found' we shouldn't ignore.
383
+ if (
384
+ winerror.HRESULT_FACILITY(exc.hresult) != winerror.FACILITY_WIN32
385
+ or winerror.HRESULT_CODE(exc.hresult) != winerror.ERROR_PATH_NOT_FOUND
386
+ ):
387
+ raise
388
+ server_ob = GetObject(server)
389
+ filters = server_ob.Create(_IIS_FILTERS, "Filters")
390
+ filters.FilterLoadOrder = ""
391
+ filters.SetInfo()
392
+
393
+ # As for VirtualDir, delete an existing one.
394
+ assert filterParams.Name.strip("/"), "mustn't delete the root!"
395
+ try:
396
+ filters.Delete(_IIS_FILTER, filterParams.Name)
397
+ log(2, f"Deleted old filter '{filterParams.Name}'")
398
+ except pythoncom.com_error:
399
+ pass
400
+ newFilter = filters.Create(_IIS_FILTER, filterParams.Name)
401
+ log(2, "Created new ISAPI filter...")
402
+ assert os.path.isfile(filterParams.Path)
403
+ newFilter.FilterPath = filterParams.Path
404
+ newFilter.FilterDescription = filterParams.Description
405
+ newFilter.SetInfo()
406
+ load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b]
407
+ if filterParams.Name not in load_order:
408
+ load_order.append(filterParams.Name)
409
+ filters.FilterLoadOrder = ",".join(load_order)
410
+ filters.SetInfo()
411
+ _CallHook(filterParams, "PostInstall", options, newFilter)
412
+ log(1, f"Configured Filter: {filterParams.Name}")
413
+ return newFilter
414
+
415
+
416
+ def DeleteISAPIFilter(filterParams, options):
417
+ _CallHook(filterParams, "PreRemove", options)
418
+ server = FindWebServer(options, filterParams.Server)
419
+ ob_path = server + "/Filters"
420
+ try:
421
+ filters = GetObject(ob_path)
422
+ except pythoncom.com_error as details:
423
+ # failure to open the filters just means a totally clean IIS install
424
+ # (IIS5 at least has no 'Filters' key when freshly installed).
425
+ log(2, f"ISAPI filter path '{ob_path}' did not exist.")
426
+ return
427
+ try:
428
+ assert filterParams.Name.strip("/"), "mustn't delete the root!"
429
+ filters.Delete(_IIS_FILTER, filterParams.Name)
430
+ log(2, f"Deleted ISAPI filter '{filterParams.Name}'")
431
+ except pythoncom.com_error as details:
432
+ rc = _GetWin32ErrorCode(details)
433
+ if rc != winerror.ERROR_PATH_NOT_FOUND:
434
+ raise
435
+ log(2, f"ISAPI filter '{filterParams.Name}' did not exist.")
436
+ # Remove from the load order
437
+ load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b]
438
+ if filterParams.Name in load_order:
439
+ load_order.remove(filterParams.Name)
440
+ filters.FilterLoadOrder = ",".join(load_order)
441
+ filters.SetInfo()
442
+ _CallHook(filterParams, "PostRemove", options)
443
+ log(1, f"Deleted Filter: {filterParams.Name}")
444
+
445
+
446
+ def _AddExtensionFile(module, def_groupid, def_desc, params, options):
447
+ group_id = params.AddExtensionFile_GroupID or def_groupid
448
+ desc = params.AddExtensionFile_Description or def_desc
449
+ try:
450
+ ob = GetObject(_IIS_OBJECT)
451
+ ob.AddExtensionFile(
452
+ module,
453
+ params.AddExtensionFile_Enabled,
454
+ group_id,
455
+ params.AddExtensionFile_CanDelete,
456
+ desc,
457
+ )
458
+ log(2, f"Added extension file '{module}' ({desc})")
459
+ except (pythoncom.com_error, AttributeError) as details:
460
+ # IIS5 always fails. Probably should upgrade this to
461
+ # complain more loudly if IIS6 fails.
462
+ log(2, f"Failed to add extension file '{module}': {details}")
463
+
464
+
465
+ def AddExtensionFiles(params, options):
466
+ """Register the modules used by the filters/extensions as a trusted
467
+ 'extension module' - required by the default IIS6 security settings."""
468
+ # Add each module only once.
469
+ added = {}
470
+ for vd in params.VirtualDirs:
471
+ for smp in vd.ScriptMaps:
472
+ if smp.Module not in added and smp.AddExtensionFile:
473
+ _AddExtensionFile(smp.Module, vd.Name, vd.Description, smp, options)
474
+ added[smp.Module] = True
475
+
476
+ for fd in params.Filters:
477
+ if fd.Path not in added and fd.AddExtensionFile:
478
+ _AddExtensionFile(fd.Path, fd.Name, fd.Description, fd, options)
479
+ added[fd.Path] = True
480
+
481
+
482
+ def _DeleteExtensionFileRecord(module, options):
483
+ try:
484
+ ob = GetObject(_IIS_OBJECT)
485
+ ob.DeleteExtensionFileRecord(module)
486
+ log(2, "Deleted extension file record for '%s'" % module)
487
+ except (pythoncom.com_error, AttributeError) as details:
488
+ log(2, f"Failed to remove extension file '{module}': {details}")
489
+
490
+
491
+ def DeleteExtensionFileRecords(params, options):
492
+ deleted = {} # only remove each .dll once.
493
+ for vd in params.VirtualDirs:
494
+ for smp in vd.ScriptMaps:
495
+ if smp.Module not in deleted and smp.AddExtensionFile:
496
+ _DeleteExtensionFileRecord(smp.Module, options)
497
+ deleted[smp.Module] = True
498
+
499
+ for filter_def in params.Filters:
500
+ if filter_def.Path not in deleted and filter_def.AddExtensionFile:
501
+ _DeleteExtensionFileRecord(filter_def.Path, options)
502
+ deleted[filter_def.Path] = True
503
+
504
+
505
+ def CheckLoaderModule(dll_name):
506
+ suffix = "_d" if "_d.pyd" in importlib.machinery.EXTENSION_SUFFIXES else ""
507
+ template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll")
508
+ if not os.path.isfile(template):
509
+ raise ConfigurationError(f"Template loader '{template}' does not exist")
510
+ # We can't do a simple "is newer" check, as the DLL is specific to the
511
+ # Python version. So we check the date-time and size are identical,
512
+ # and skip the copy in that case.
513
+ src_stat = os.stat(template)
514
+ try:
515
+ dest_stat = os.stat(dll_name)
516
+ except OSError:
517
+ same = 0
518
+ else:
519
+ same = (
520
+ src_stat[stat.ST_SIZE] == dest_stat[stat.ST_SIZE]
521
+ and src_stat[stat.ST_MTIME] == dest_stat[stat.ST_MTIME]
522
+ )
523
+ if not same:
524
+ log(2, f"Updating {template}->{dll_name}")
525
+ shutil.copyfile(template, dll_name)
526
+ shutil.copystat(template, dll_name)
527
+ else:
528
+ log(2, f"{dll_name} is up to date.")
529
+
530
+
531
+ def _CallHook(ob, hook_name, options, *extra_args):
532
+ func = getattr(ob, hook_name, None)
533
+ if func is not None:
534
+ args = (ob, options) + extra_args
535
+ func(*args)
536
+
537
+
538
+ def Install(params, options):
539
+ _CallHook(params, "PreInstall", options)
540
+ for vd in params.VirtualDirs:
541
+ CreateDirectory(vd, options)
542
+
543
+ for filter_def in params.Filters:
544
+ CreateISAPIFilter(filter_def, options)
545
+
546
+ AddExtensionFiles(params, options)
547
+
548
+ _CallHook(params, "PostInstall", options)
549
+
550
+
551
+ def RemoveDirectory(params, options):
552
+ if params.is_root():
553
+ return
554
+ try:
555
+ directory = GetObject(FindPath(options, params.Server, params.Name))
556
+ except pythoncom.com_error as details:
557
+ rc = _GetWin32ErrorCode(details)
558
+ if rc != winerror.ERROR_PATH_NOT_FOUND:
559
+ raise
560
+ log(2, "VirtualDirectory '%s' did not exist" % params.Name)
561
+ directory = None
562
+ if directory is not None:
563
+ # Be robust should IIS get upset about unloading.
564
+ try:
565
+ directory.AppUnLoad()
566
+ except:
567
+ exc_val = sys.exc_info()[1]
568
+ log(2, f"AppUnLoad() for {params.Name} failed: {exc_val}")
569
+ # Continue trying to delete it.
570
+ try:
571
+ parent = GetObject(directory.Parent)
572
+ parent.Delete(directory.Class, directory.Name)
573
+ log(1, f"Deleted Virtual Directory: {params.Name}")
574
+ except:
575
+ exc_val = sys.exc_info()[1]
576
+ log(1, f"Failed to remove directory {params.Name}: {exc_val}")
577
+
578
+
579
+ def RemoveScriptMaps(vd_params, options):
580
+ "Remove script maps from the already installed virtual directory"
581
+ parent, name = vd_params.split_path()
582
+ target_dir = GetObject(FindPath(options, vd_params.Server, parent))
583
+ installed_maps = list(target_dir.ScriptMaps)
584
+ for _map in map(str, vd_params.ScriptMaps):
585
+ if _map in installed_maps:
586
+ installed_maps.remove(_map)
587
+ target_dir.ScriptMaps = installed_maps
588
+ target_dir.SetInfo()
589
+
590
+
591
+ def Uninstall(params, options):
592
+ _CallHook(params, "PreRemove", options)
593
+
594
+ DeleteExtensionFileRecords(params, options)
595
+
596
+ for vd in params.VirtualDirs:
597
+ _CallHook(vd, "PreRemove", options)
598
+
599
+ RemoveDirectory(vd, options)
600
+ if vd.is_root():
601
+ # if this is installed to the root virtual directory, we can't delete it
602
+ # so remove the script maps.
603
+ RemoveScriptMaps(vd, options)
604
+
605
+ _CallHook(vd, "PostRemove", options)
606
+
607
+ for filter_def in params.Filters:
608
+ DeleteISAPIFilter(filter_def, options)
609
+ _CallHook(params, "PostRemove", options)
610
+
611
+
612
+ # Patch up any missing module names in the params, replacing them with
613
+ # the DLL name that hosts this extension/filter.
614
+ def _PatchParamsModule(params, dll_name, file_must_exist=True):
615
+ if file_must_exist:
616
+ if not os.path.isfile(dll_name):
617
+ raise ConfigurationError(f"{dll_name} does not exist")
618
+
619
+ # Patch up all references to the DLL.
620
+ for f in params.Filters:
621
+ if f.Path is None:
622
+ f.Path = dll_name
623
+ for d in params.VirtualDirs:
624
+ for sm in d.ScriptMaps:
625
+ if sm.Module is None:
626
+ sm.Module = dll_name
627
+
628
+
629
+ def GetLoaderModuleName(mod_name, check_module=None):
630
+ # find the name of the DLL hosting us.
631
+ # By default, this is "_{module_base_name}.dll"
632
+ if hasattr(sys, "frozen"):
633
+ # What to do? The .dll knows its name, but this is likely to be
634
+ # executed via a .exe, which does not know.
635
+ base, ext = os.path.splitext(mod_name)
636
+ path, base = os.path.split(base)
637
+ # handle the common case of 'foo.exe'/'foow.exe'
638
+ if base.endswith("w"):
639
+ base = base[:-1]
640
+ # For py2exe, we have '_foo.dll' as the standard pyisapi loader - but
641
+ # 'foo.dll' is what we use (it just delegates).
642
+ # So no leading '_' on the installed name.
643
+ dll_name = os.path.abspath(os.path.join(path, base + ".dll"))
644
+ else:
645
+ base, ext = os.path.splitext(mod_name)
646
+ path, base = os.path.split(base)
647
+ dll_name = os.path.abspath(os.path.join(path, "_" + base + ".dll"))
648
+ # Check we actually have it.
649
+ if check_module is None:
650
+ check_module = not hasattr(sys, "frozen")
651
+ if check_module:
652
+ CheckLoaderModule(dll_name)
653
+ return dll_name
654
+
655
+
656
+ # Note the 'log' params to these 'builtin' args - old versions of pywin32
657
+ # didn't log at all in this function (by intent; anyone calling this was
658
+ # responsible). So existing code that calls this function with the old
659
+ # signature (ie, without a 'log' param) still gets the same behaviour as
660
+ # before...
661
+
662
+
663
+ def InstallModule(conf_module_name, params, options, log=lambda *args: None):
664
+ "Install the extension"
665
+ if not hasattr(sys, "frozen"):
666
+ conf_module_name = os.path.abspath(conf_module_name)
667
+ if not os.path.isfile(conf_module_name):
668
+ raise ConfigurationError(f"{conf_module_name} does not exist")
669
+
670
+ loader_dll = GetLoaderModuleName(conf_module_name)
671
+ _PatchParamsModule(params, loader_dll)
672
+ Install(params, options)
673
+ log(1, "Installation complete.")
674
+
675
+
676
+ def UninstallModule(conf_module_name, params, options, log=lambda *args: None):
677
+ "Remove the extension"
678
+ loader_dll = GetLoaderModuleName(conf_module_name, False)
679
+ _PatchParamsModule(params, loader_dll, False)
680
+ Uninstall(params, options)
681
+ log(1, "Uninstallation complete.")
682
+
683
+
684
+ standard_arguments = {
685
+ "install": InstallModule,
686
+ "remove": UninstallModule,
687
+ }
688
+
689
+
690
+ def build_usage(handler_map: Mapping[str, object]) -> str:
691
+ arg_names = "|".join(handler_map)
692
+ lines = [
693
+ " %-10s: %s" % (arg, handler.__doc__) for arg, handler in handler_map.items()
694
+ ]
695
+ return f"%prog [options] [{arg_names}]\ncommands:\n" + "\n".join(lines)
696
+
697
+
698
+ def MergeStandardOptions(options, params):
699
+ """
700
+ Take an options object generated by the command line and merge
701
+ the values into the IISParameters object.
702
+ """
703
+ pass
704
+
705
+
706
+ # We support 2 ways of extending our command-line/install support.
707
+ # * Many of the installation items allow you to specify "PreInstall",
708
+ # "PostInstall", "PreRemove" and "PostRemove" hooks
709
+ # All hooks are called with the 'params' object being operated on, and
710
+ # the 'optparser' options for this session (ie, the command-line options)
711
+ # PostInstall for VirtualDirectories and Filters both have an additional
712
+ # param - the ADSI object just created.
713
+ # * You can pass your own option parser for us to use, and/or define a map
714
+ # with your own custom arg handlers. It is a map of 'arg'->function.
715
+ # The function is called with (options, log_fn, arg). The function's
716
+ # docstring is used in the usage output.
717
+ def HandleCommandLine(
718
+ params,
719
+ argv=None,
720
+ conf_module_name=None,
721
+ default_arg="install",
722
+ opt_parser=None,
723
+ custom_arg_handlers={},
724
+ ):
725
+ """Perform installation or removal of an ISAPI filter or extension.
726
+
727
+ This module handles standard command-line options and configuration
728
+ information, and installs, removes or updates the configuration of an
729
+ ISAPI filter or extension.
730
+
731
+ You must pass your configuration information in params - all other
732
+ arguments are optional, and allow you to configure the installation
733
+ process.
734
+ """
735
+ global verbose
736
+ from optparse import OptionParser
737
+
738
+ argv = argv or sys.argv
739
+ if not conf_module_name:
740
+ conf_module_name = sys.argv[0]
741
+ # convert to a long name so that if we were somehow registered with
742
+ # the "short" version but unregistered with the "long" version we
743
+ # still work (that will depend on exactly how the installer was
744
+ # started)
745
+ try:
746
+ conf_module_name = win32api.GetLongPathName(conf_module_name)
747
+ except win32api.error as exc:
748
+ log(
749
+ 2,
750
+ f"Couldn't determine the long name for {conf_module_name!r}: {exc}",
751
+ )
752
+
753
+ if opt_parser is None:
754
+ # Build our own parser.
755
+ parser = OptionParser(usage="")
756
+ else:
757
+ # The caller is providing their own filter, presumably with their
758
+ # own options all setup.
759
+ parser = opt_parser
760
+
761
+ # build a usage string if we don't have one.
762
+ if not parser.get_usage():
763
+ all_handlers = standard_arguments.copy()
764
+ all_handlers.update(custom_arg_handlers)
765
+ parser.set_usage(build_usage(all_handlers))
766
+
767
+ # allow the user to use uninstall as a synonym for remove if it wasn't
768
+ # defined by the custom arg handlers.
769
+ all_handlers.setdefault("uninstall", all_handlers["remove"])
770
+
771
+ parser.add_option(
772
+ "-q",
773
+ "--quiet",
774
+ action="store_false",
775
+ dest="verbose",
776
+ default=True,
777
+ help="don't print status messages to stdout",
778
+ )
779
+ parser.add_option(
780
+ "-v",
781
+ "--verbosity",
782
+ action="count",
783
+ dest="verbose",
784
+ default=1,
785
+ help="increase the verbosity of status messages",
786
+ )
787
+ parser.add_option(
788
+ "",
789
+ "--server",
790
+ action="store",
791
+ help="Specifies the IIS server to install/uninstall on."
792
+ f" Default is '{_IIS_OBJECT}/1'",
793
+ )
794
+
795
+ (options, args) = parser.parse_args(argv[1:])
796
+ MergeStandardOptions(options, params)
797
+ verbose = options.verbose
798
+ if not args:
799
+ args = [default_arg]
800
+ try:
801
+ for arg in args:
802
+ handler = all_handlers[arg]
803
+ handler(conf_module_name, params, options, log)
804
+ except (ItemNotFound, InstallationError) as details:
805
+ if options.verbose > 1:
806
+ traceback.print_exc()
807
+ print(f"{details.__class__.__name__}: {details}")
808
+ except KeyError:
809
+ parser.error("Invalid arg '%s'" % arg)
loan-advisor-agent/.venv/Lib/site-packages/isapi/isapicon.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constants needed by ISAPI filters and extensions."""
2
+
3
+ # ======================================================================
4
+ # Copyright 2002-2003 by Blackdog Software Pty Ltd.
5
+ #
6
+ # All Rights Reserved
7
+ #
8
+ # Permission to use, copy, modify, and distribute this software and
9
+ # its documentation for any purpose and without fee is hereby
10
+ # granted, provided that the above copyright notice appear in all
11
+ # copies and that both that copyright notice and this permission
12
+ # notice appear in supporting documentation, and that the name of
13
+ # Blackdog Software not be used in advertising or publicity pertaining to
14
+ # distribution of the software without specific, written prior
15
+ # permission.
16
+ #
17
+ # BLACKDOG SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
18
+ # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
19
+ # NO EVENT SHALL BLACKDOG SOFTWARE BE LIABLE FOR ANY SPECIAL, INDIRECT OR
20
+ # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
21
+ # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
22
+ # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23
+ # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24
+ # ======================================================================
25
+
26
+ # HTTP reply codes
27
+
28
+ HTTP_CONTINUE = 100
29
+ HTTP_SWITCHING_PROTOCOLS = 101
30
+ HTTP_PROCESSING = 102
31
+ HTTP_OK = 200
32
+ HTTP_CREATED = 201
33
+ HTTP_ACCEPTED = 202
34
+ HTTP_NON_AUTHORITATIVE = 203
35
+ HTTP_NO_CONTENT = 204
36
+ HTTP_RESET_CONTENT = 205
37
+ HTTP_PARTIAL_CONTENT = 206
38
+ HTTP_MULTI_STATUS = 207
39
+ HTTP_MULTIPLE_CHOICES = 300
40
+ HTTP_MOVED_PERMANENTLY = 301
41
+ HTTP_MOVED_TEMPORARILY = 302
42
+ HTTP_SEE_OTHER = 303
43
+ HTTP_NOT_MODIFIED = 304
44
+ HTTP_USE_PROXY = 305
45
+ HTTP_TEMPORARY_REDIRECT = 307
46
+ HTTP_BAD_REQUEST = 400
47
+ HTTP_UNAUTHORIZED = 401
48
+ HTTP_PAYMENT_REQUIRED = 402
49
+ HTTP_FORBIDDEN = 403
50
+ HTTP_NOT_FOUND = 404
51
+ HTTP_METHOD_NOT_ALLOWED = 405
52
+ HTTP_NOT_ACCEPTABLE = 406
53
+ HTTP_PROXY_AUTHENTICATION_REQUIRED = 407
54
+ HTTP_REQUEST_TIME_OUT = 408
55
+ HTTP_CONFLICT = 409
56
+ HTTP_GONE = 410
57
+ HTTP_LENGTH_REQUIRED = 411
58
+ HTTP_PRECONDITION_FAILED = 412
59
+ HTTP_REQUEST_ENTITY_TOO_LARGE = 413
60
+ HTTP_REQUEST_URI_TOO_LARGE = 414
61
+ HTTP_UNSUPPORTED_MEDIA_TYPE = 415
62
+ HTTP_RANGE_NOT_SATISFIABLE = 416
63
+ HTTP_EXPECTATION_FAILED = 417
64
+ HTTP_UNPROCESSABLE_ENTITY = 422
65
+ HTTP_INTERNAL_SERVER_ERROR = 500
66
+ HTTP_NOT_IMPLEMENTED = 501
67
+ HTTP_BAD_GATEWAY = 502
68
+ HTTP_SERVICE_UNAVAILABLE = 503
69
+ HTTP_GATEWAY_TIME_OUT = 504
70
+ HTTP_VERSION_NOT_SUPPORTED = 505
71
+ HTTP_VARIANT_ALSO_VARIES = 506
72
+
73
+ HSE_STATUS_SUCCESS = 1
74
+ HSE_STATUS_SUCCESS_AND_KEEP_CONN = 2
75
+ HSE_STATUS_PENDING = 3
76
+ HSE_STATUS_ERROR = 4
77
+
78
+ SF_NOTIFY_SECURE_PORT = 0x00000001
79
+ SF_NOTIFY_NONSECURE_PORT = 0x00000002
80
+ SF_NOTIFY_READ_RAW_DATA = 0x00008000
81
+ SF_NOTIFY_PREPROC_HEADERS = 0x00004000
82
+ SF_NOTIFY_AUTHENTICATION = 0x00002000
83
+ SF_NOTIFY_URL_MAP = 0x00001000
84
+ SF_NOTIFY_ACCESS_DENIED = 0x00000800
85
+ SF_NOTIFY_SEND_RESPONSE = 0x00000040
86
+ SF_NOTIFY_SEND_RAW_DATA = 0x00000400
87
+ SF_NOTIFY_LOG = 0x00000200
88
+ SF_NOTIFY_END_OF_REQUEST = 0x00000080
89
+ SF_NOTIFY_END_OF_NET_SESSION = 0x00000100
90
+
91
+ SF_NOTIFY_ORDER_HIGH = 0x00080000
92
+ SF_NOTIFY_ORDER_MEDIUM = 0x00040000
93
+ SF_NOTIFY_ORDER_LOW = 0x00020000
94
+ SF_NOTIFY_ORDER_DEFAULT = SF_NOTIFY_ORDER_LOW
95
+
96
+ SF_NOTIFY_ORDER_MASK = (
97
+ SF_NOTIFY_ORDER_HIGH | SF_NOTIFY_ORDER_MEDIUM | SF_NOTIFY_ORDER_LOW
98
+ )
99
+
100
+ SF_STATUS_REQ_FINISHED = 134217728 # 0x8000000
101
+ SF_STATUS_REQ_FINISHED_KEEP_CONN = 134217728 + 1
102
+ SF_STATUS_REQ_NEXT_NOTIFICATION = 134217728 + 2
103
+ SF_STATUS_REQ_HANDLED_NOTIFICATION = 134217728 + 3
104
+ SF_STATUS_REQ_ERROR = 134217728 + 4
105
+ SF_STATUS_REQ_READ_NEXT = 134217728 + 5
106
+
107
+ HSE_IO_SYNC = 0x00000001 # for WriteClient
108
+ HSE_IO_ASYNC = 0x00000002 # for WriteClient/TF/EU
109
+ HSE_IO_DISCONNECT_AFTER_SEND = 0x00000004 # for TF
110
+ HSE_IO_SEND_HEADERS = 0x00000008 # for TF
111
+ HSE_IO_NODELAY = 0x00001000 # turn off nagling
112
+ # These two are only used by VectorSend
113
+ HSE_IO_FINAL_SEND = 0x00000010
114
+ HSE_IO_CACHE_RESPONSE = 0x00000020
115
+
116
+ HSE_EXEC_URL_NO_HEADERS = 0x02
117
+ HSE_EXEC_URL_IGNORE_CURRENT_INTERCEPTOR = 0x04
118
+ HSE_EXEC_URL_IGNORE_VALIDATION_AND_RANGE = 0x10
119
+ HSE_EXEC_URL_DISABLE_CUSTOM_ERROR = 0x20
120
+ HSE_EXEC_URL_SSI_CMD = 0x40
121
+ HSE_EXEC_URL_HTTP_CACHE_ELIGIBLE = 0x80
loan-advisor-agent/.venv/Lib/site-packages/isapi/samples/README.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ In this directory you will find examples of ISAPI filters and extensions.
2
+
3
+ The filter loading mechanism works like this:
4
+ * IIS loads the special Python "loader" DLL. This DLL will generally have a
5
+ leading underscore as part of its name.
6
+ * This loader DLL looks for a Python module, by removing the first letter of
7
+ the DLL base name.
8
+
9
+ This means that an ISAPI extension module consists of 2 key files - the loader
10
+ DLL (eg, "_MyIISModule.dll", and a Python module (which for this example
11
+ would be "MyIISModule.py")
12
+
13
+ When you install an ISAPI extension, the installation code checks to see if
14
+ there is a loader DLL for your implementation file - if one does not exist,
15
+ or the standard loader is different, it is copied and renamed accordingly.
16
+
17
+ We use this mechanism to provide the maximum separation between different
18
+ Python extensions installed on the same server - otherwise filter order and
19
+ other tricky IIS semantics would need to be replicated. Also, each filter
20
+ gets its own thread-pool, etc.
loan-advisor-agent/.venv/Lib/site-packages/isapi/samples/advanced.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This extension demonstrates some advanced features of the Python ISAPI
2
+ # framework.
3
+ # We demonstrate:
4
+ # * Reloading your Python module without shutting down IIS (eg, when your
5
+ # .py implementation file changes.)
6
+ # * Custom command-line handling - both additional options and commands.
7
+ # * Using a query string - any part of the URL after a '?' is assumed to
8
+ # be "variable names" separated by '&' - we will print the values of
9
+ # these server variables.
10
+ # * If the tail portion of the URL is "ReportUnhealthy", IIS will be
11
+ # notified we are unhealthy via a HSE_REQ_REPORT_UNHEALTHY request.
12
+ # Whether this is acted upon depends on if the IIS health-checking
13
+ # tools are installed, but you should always see the reason written
14
+ # to the Windows event log - see the IIS documentation for more.
15
+
16
+ import os
17
+ import stat
18
+ import sys
19
+
20
+ from isapi import isapicon
21
+ from isapi.simple import SimpleExtension
22
+
23
+ if hasattr(sys, "isapidllhandle"):
24
+ import win32traceutil
25
+
26
+ # Notes on reloading
27
+ # If your HttpFilterProc or HttpExtensionProc functions raises
28
+ # 'isapi.InternalReloadException', the framework will not treat it
29
+ # as an error but instead will terminate your extension, reload your
30
+ # extension module, re-initialize the instance, and re-issue the request.
31
+ # The Initialize functions are called with None as their param. The
32
+ # return code from the terminate function is ignored.
33
+ #
34
+ # This is all the framework does to help you. It is up to your code
35
+ # when you raise this exception. This sample uses a Win32 "find
36
+ # notification". Whenever windows tells us one of the files in the
37
+ # directory has changed, we check if the time of our source-file has
38
+ # changed, and set a flag. Next imcoming request, we check the flag and
39
+ # raise the special exception if set.
40
+ #
41
+ # The end result is that the module is automatically reloaded whenever
42
+ # the source-file changes - you need take no further action to see your
43
+ # changes reflected in the running server.
44
+
45
+ # The framework only reloads your module - if you have libraries you
46
+ # depend on and also want reloaded, you must arrange for this yourself.
47
+ # One way of doing this would be to special case the import of these
48
+ # modules. Eg:
49
+ # --
50
+ # try:
51
+ # my_module = reload(my_module) # module already imported - reload it
52
+ # except NameError:
53
+ # import my_module # first time around - import it.
54
+ # --
55
+ # When your module is imported for the first time, the NameError will
56
+ # be raised, and the module imported. When the ISAPI framework reloads
57
+ # your module, the existing module will avoid the NameError, and allow
58
+ # you to reload that module.
59
+
60
+ import threading
61
+
62
+ import win32con
63
+ import win32event
64
+ import win32file
65
+ import winerror
66
+
67
+ from isapi import InternalReloadException
68
+
69
+ try:
70
+ reload_counter += 1 # type: ignore[used-before-def]
71
+ except NameError:
72
+ reload_counter = 0
73
+
74
+
75
+ # A watcher thread that checks for __file__ changing.
76
+ # When it detects it, it simply sets "change_detected" to true.
77
+ class ReloadWatcherThread(threading.Thread):
78
+ def __init__(self):
79
+ self.change_detected = False
80
+ self.filename = __file__
81
+ if self.filename.endswith("c") or self.filename.endswith("o"):
82
+ self.filename = self.filename[:-1]
83
+ self.handle = win32file.FindFirstChangeNotification(
84
+ os.path.dirname(self.filename),
85
+ False, # watch tree?
86
+ win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
87
+ )
88
+ threading.Thread.__init__(self)
89
+
90
+ def run(self):
91
+ last_time = os.stat(self.filename)[stat.ST_MTIME]
92
+ while 1:
93
+ try:
94
+ rc = win32event.WaitForSingleObject(self.handle, win32event.INFINITE)
95
+ win32file.FindNextChangeNotification(self.handle)
96
+ except win32event.error as details:
97
+ # handle closed - thread should terminate.
98
+ if details.winerror != winerror.ERROR_INVALID_HANDLE:
99
+ raise
100
+ break
101
+ this_time = os.stat(self.filename)[stat.ST_MTIME]
102
+ if this_time != last_time:
103
+ print("Detected file change - flagging for reload.")
104
+ self.change_detected = True
105
+ last_time = this_time
106
+
107
+ def stop(self):
108
+ win32file.FindCloseChangeNotification(self.handle)
109
+
110
+
111
+ # The ISAPI extension - handles requests in our virtual dir, and sends the
112
+ # response to the client.
113
+ class Extension(SimpleExtension):
114
+ "Python advanced sample Extension"
115
+
116
+ def __init__(self):
117
+ self.reload_watcher = ReloadWatcherThread()
118
+ self.reload_watcher.start()
119
+
120
+ def HttpExtensionProc(self, ecb):
121
+ # NOTE: If you use a ThreadPoolExtension, you must still perform
122
+ # this check in HttpExtensionProc - raising the exception from
123
+ # The "Dispatch" method will just cause the exception to be
124
+ # rendered to the browser.
125
+ if self.reload_watcher.change_detected:
126
+ print("Doing reload")
127
+ raise InternalReloadException
128
+
129
+ url = ecb.GetServerVariable("UNICODE_URL")
130
+ if url.endswith("ReportUnhealthy"):
131
+ ecb.ReportUnhealthy("I'm a little sick")
132
+
133
+ ecb.SendResponseHeaders("200 OK", "Content-Type: text/html\r\n\r\n", 0)
134
+ print("<HTML><BODY>", file=ecb)
135
+
136
+ qs = ecb.GetServerVariable("QUERY_STRING")
137
+ if qs:
138
+ queries = qs.split("&")
139
+ print("<PRE>", file=ecb)
140
+ for q in queries:
141
+ val = ecb.GetServerVariable(q, "&lt;no such variable&gt;")
142
+ print(f"{q}={val!r}", file=ecb)
143
+ print("</PRE><P/>", file=ecb)
144
+
145
+ print("This module has been imported", file=ecb)
146
+ print("%d times" % (reload_counter,), file=ecb)
147
+ print("</BODY></HTML>", file=ecb)
148
+ ecb.close()
149
+ return isapicon.HSE_STATUS_SUCCESS
150
+
151
+ def TerminateExtension(self, status):
152
+ self.reload_watcher.stop()
153
+
154
+
155
+ # The entry points for the ISAPI extension.
156
+ def __ExtensionFactory__():
157
+ return Extension()
158
+
159
+
160
+ # Our special command line customization.
161
+ # Pre-install hook for our virtual directory.
162
+ def PreInstallDirectory(params, options):
163
+ # If the user used our special '--description' option,
164
+ # then we override our default.
165
+ if options.description:
166
+ params.Description = options.description
167
+
168
+
169
+ # Post install hook for our entire script
170
+ def PostInstall(params, options):
171
+ print()
172
+ print("The sample has been installed.")
173
+ print("Point your browser to /AdvancedPythonSample")
174
+ print("If you modify the source file and reload the page,")
175
+ print("you should see the reload counter increment")
176
+
177
+
178
+ # Handler for our custom 'status' argument.
179
+ def status_handler(options, log, arg):
180
+ "Query the status of something"
181
+ print("Everything seems to be fine!")
182
+
183
+
184
+ custom_arg_handlers = {"status": status_handler}
185
+
186
+ if __name__ == "__main__":
187
+ # If run from the command-line, install ourselves.
188
+ from isapi.install import *
189
+
190
+ params = ISAPIParameters(PostInstall=PostInstall)
191
+ # Setup the virtual directories - this is a list of directories our
192
+ # extension uses - in this case only 1.
193
+ # Each extension has a "script map" - this is the mapping of ISAPI
194
+ # extensions.
195
+ sm = [ScriptMapParams(Extension="*", Flags=0)]
196
+ vd = VirtualDirParameters(
197
+ Name="AdvancedPythonSample",
198
+ Description=Extension.__doc__,
199
+ ScriptMaps=sm,
200
+ ScriptMapUpdate="replace",
201
+ # specify the pre-install hook.
202
+ PreInstall=PreInstallDirectory,
203
+ )
204
+ params.VirtualDirs = [vd]
205
+ # Setup our custom option parser.
206
+ from optparse import OptionParser
207
+
208
+ parser = OptionParser("") # blank usage, so isapi sets it.
209
+ parser.add_option(
210
+ "",
211
+ "--description",
212
+ action="store",
213
+ help="custom description to use for the virtual directory",
214
+ )
215
+
216
+ HandleCommandLine(
217
+ params, opt_parser=parser, custom_arg_handlers=custom_arg_handlers
218
+ )
loan-advisor-agent/.venv/Lib/site-packages/isapi/samples/redirector.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a sample ISAPI extension written in Python.
2
+ #
3
+ # Please see README.txt in this directory, and specifically the
4
+ # information about the "loader" DLL - installing this sample will create
5
+ # "_redirector.dll" in the current directory. The readme explains this.
6
+
7
+ # Executing this script (or any server config script) will install the extension
8
+ # into your web server. As the server executes, the PyISAPI framework will load
9
+ # this module and create your Extension and Filter objects.
10
+
11
+ # This is the simplest possible redirector (or proxy) we can write. The
12
+ # extension installs with a mask of '*' in the root of the site.
13
+ # As an added bonus though, we optionally show how, on IIS6 and later, we
14
+ # can use HSE_ERQ_EXEC_URL to ignore certain requests - in IIS5 and earlier
15
+ # we can only do this with an ISAPI filter - see redirector_with_filter for
16
+ # an example. If this sample is run on IIS5 or earlier it simply ignores
17
+ # any excludes.
18
+
19
+ import sys
20
+ from urllib.request import urlopen
21
+
22
+ import win32api
23
+
24
+ from isapi import isapicon, threaded_extension
25
+
26
+ # sys.isapidllhandle will exist when we are loaded by the IIS framework.
27
+ # In this case we redirect our output to the win32traceutil collector.
28
+ if hasattr(sys, "isapidllhandle"):
29
+ import win32traceutil
30
+
31
+ # The site we are proxying.
32
+ proxy = "https://www.python.org"
33
+
34
+ # Urls we exclude (ie, allow IIS to handle itself) - all are lowered,
35
+ # and these entries exist by default on Vista...
36
+ excludes = ["/iisstart.htm", "/welcome.png"]
37
+
38
+
39
+ # An "io completion" function, called when ecb.ExecURL completes...
40
+ def io_callback(ecb, url, cbIO, errcode):
41
+ # Get the status of our ExecURL
42
+ httpstatus, substatus, win32 = ecb.GetExecURLStatus()
43
+ print(
44
+ "ExecURL of %r finished with http status %d.%d, win32 status %d (%s)"
45
+ % (url, httpstatus, substatus, win32, win32api.FormatMessage(win32).strip())
46
+ )
47
+ # nothing more to do!
48
+ ecb.DoneWithSession()
49
+
50
+
51
+ # The ISAPI extension - handles all requests in the site.
52
+ class Extension(threaded_extension.ThreadPoolExtension):
53
+ "Python sample Extension"
54
+
55
+ def Dispatch(self, ecb):
56
+ # Note that our ThreadPoolExtension base class will catch exceptions
57
+ # in our Dispatch method, and write the traceback to the client.
58
+ # That is perfect for this sample, so we don't catch our own.
59
+ # print(f'IIS dispatching "{ecb.GetServerVariable("URL")}"')
60
+ url = ecb.GetServerVariable("URL").decode("ascii")
61
+ for exclude in excludes:
62
+ if url.lower().startswith(exclude):
63
+ print("excluding %s" % url)
64
+ if ecb.Version < 0x60000:
65
+ print("(but this is IIS5 or earlier - can't do 'excludes')")
66
+ else:
67
+ ecb.IOCompletion(io_callback, url)
68
+ ecb.ExecURL(
69
+ None,
70
+ None,
71
+ None,
72
+ None,
73
+ None,
74
+ isapicon.HSE_EXEC_URL_IGNORE_CURRENT_INTERCEPTOR,
75
+ )
76
+ return isapicon.HSE_STATUS_PENDING
77
+
78
+ new_url = proxy + url
79
+ print("Opening %s" % new_url)
80
+ fp = urlopen(new_url)
81
+ headers = fp.info()
82
+ # subtle breakage: str(headers) normalizes \r\n
83
+ # back to \n and also sticks an extra \n term.
84
+ # take *all* trailing \n off, replace remaining with
85
+ # \r\n, then add the 2 trailing \r\n.
86
+ header_text = str(headers).rstrip("\n").replace("\n", "\r\n") + "\r\n\r\n"
87
+ ecb.SendResponseHeaders("200 OK", header_text, False)
88
+ ecb.WriteClient(fp.read())
89
+ ecb.DoneWithSession()
90
+ print(f"Returned data from '{new_url}'")
91
+ return isapicon.HSE_STATUS_SUCCESS
92
+
93
+
94
+ # The entry points for the ISAPI extension.
95
+ def __ExtensionFactory__():
96
+ return Extension()
97
+
98
+
99
+ if __name__ == "__main__":
100
+ # If run from the command-line, install ourselves.
101
+ from isapi.install import *
102
+
103
+ params = ISAPIParameters()
104
+ # Setup the virtual directories - this is a list of directories our
105
+ # extension uses - in this case only 1.
106
+ # Each extension has a "script map" - this is the mapping of ISAPI
107
+ # extensions.
108
+ sm = [ScriptMapParams(Extension="*", Flags=0)]
109
+ vd = VirtualDirParameters(
110
+ Name="/",
111
+ Description=Extension.__doc__,
112
+ ScriptMaps=sm,
113
+ ScriptMapUpdate="replace",
114
+ )
115
+ params.VirtualDirs = [vd]
116
+ HandleCommandLine(params)
loan-advisor-agent/.venv/Lib/site-packages/isapi/samples/redirector_asynch.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a sample ISAPI extension written in Python.
2
+
3
+ # This is like the other 'redirector' samples, but uses asnch IO when writing
4
+ # back to the client (it does *not* use asynch io talking to the remote
5
+ # server!)
6
+
7
+ import sys
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+
12
+ from isapi import isapicon, threaded_extension
13
+
14
+ # sys.isapidllhandle will exist when we are loaded by the IIS framework.
15
+ # In this case we redirect our output to the win32traceutil collector.
16
+ if hasattr(sys, "isapidllhandle"):
17
+ import win32traceutil
18
+
19
+ # The site we are proxying.
20
+ proxy = "https://www.python.org"
21
+
22
+ # We synchronously read chunks of this size then asynchronously write them.
23
+ CHUNK_SIZE = 8192
24
+
25
+
26
+ # The callback made when IIS completes the asynch write.
27
+ def io_callback(ecb, fp, cbIO, errcode):
28
+ print("IO callback", ecb, fp, cbIO, errcode)
29
+ chunk = fp.read(CHUNK_SIZE)
30
+ if chunk:
31
+ ecb.WriteClient(chunk, isapicon.HSE_IO_ASYNC)
32
+ # and wait for the next callback to say this chunk is done.
33
+ else:
34
+ # eof - say we are complete.
35
+ fp.close()
36
+ ecb.DoneWithSession()
37
+
38
+
39
+ # The ISAPI extension - handles all requests in the site.
40
+ class Extension(threaded_extension.ThreadPoolExtension):
41
+ "Python sample proxy server - asynch version."
42
+
43
+ def Dispatch(self, ecb):
44
+ print('IIS dispatching "{}"'.format(ecb.GetServerVariable("URL")))
45
+ url = ecb.GetServerVariable("URL")
46
+
47
+ new_url = proxy + url
48
+ print("Opening %s" % new_url)
49
+ fp = urllib.request.urlopen(new_url)
50
+ headers = fp.info()
51
+ ecb.SendResponseHeaders("200 OK", str(headers) + "\r\n", False)
52
+ # now send the first chunk asynchronously
53
+ ecb.ReqIOCompletion(io_callback, fp)
54
+ chunk = fp.read(CHUNK_SIZE)
55
+ if chunk:
56
+ ecb.WriteClient(chunk, isapicon.HSE_IO_ASYNC)
57
+ return isapicon.HSE_STATUS_PENDING
58
+ # no data - just close things now.
59
+ ecb.DoneWithSession()
60
+ return isapicon.HSE_STATUS_SUCCESS
61
+
62
+
63
+ # The entry points for the ISAPI extension.
64
+ def __ExtensionFactory__():
65
+ return Extension()
66
+
67
+
68
+ if __name__ == "__main__":
69
+ # If run from the command-line, install ourselves.
70
+ from isapi.install import *
71
+
72
+ params = ISAPIParameters()
73
+ # Setup the virtual directories - this is a list of directories our
74
+ # extension uses - in this case only 1.
75
+ # Each extension has a "script map" - this is the mapping of ISAPI
76
+ # extensions.
77
+ sm = [ScriptMapParams(Extension="*", Flags=0)]
78
+ vd = VirtualDirParameters(
79
+ Name="/",
80
+ Description=Extension.__doc__,
81
+ ScriptMaps=sm,
82
+ ScriptMapUpdate="replace",
83
+ )
84
+ params.VirtualDirs = [vd]
85
+ HandleCommandLine(params)
loan-advisor-agent/.venv/Lib/site-packages/isapi/samples/redirector_with_filter.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a sample configuration file for an ISAPI filter and extension
2
+ # written in Python.
3
+ #
4
+ # Please see README.txt in this directory, and specifically the
5
+ # information about the "loader" DLL - installing this sample will create
6
+ # "_redirector_with_filter.dll" in the current directory. The readme explains
7
+ # this.
8
+
9
+ # Executing this script (or any server config script) will install the extension
10
+ # into your web server. As the server executes, the PyISAPI framework will load
11
+ # this module and create your Extension and Filter objects.
12
+
13
+ # This sample provides sample redirector:
14
+ # It is implemented by a filter and an extension, so that some requests can
15
+ # be ignored. Compare with 'redirector_simple' which avoids the filter, but
16
+ # is unable to selectively ignore certain requests.
17
+ # The process is sample uses is:
18
+ # * The filter is installed globally, as all filters are.
19
+ # * A Virtual Directory named "python" is setup. This dir has our ISAPI
20
+ # extension as the only application, mapped to file-extension '*'. Thus, our
21
+ # extension handles *all* requests in this directory.
22
+ # The basic process is that the filter does URL rewriting, redirecting every
23
+ # URL to our Virtual Directory. Our extension then handles this request,
24
+ # forwarding the data from the proxied site.
25
+ # For example:
26
+ # * URL of "index.html" comes in.
27
+ # * Filter rewrites this to "/python/index.html"
28
+ # * Our extension sees the full "/python/index.html", removes the leading
29
+ # portion, and opens and forwards the remote URL.
30
+
31
+
32
+ # This sample is very small - it avoid most error handling, etc. It is for
33
+ # demonstration purposes only.
34
+
35
+ import sys
36
+ import urllib.error
37
+ import urllib.parse
38
+ import urllib.request
39
+
40
+ from isapi import isapicon, threaded_extension
41
+ from isapi.simple import SimpleFilter
42
+
43
+ # sys.isapidllhandle will exist when we are loaded by the IIS framework.
44
+ # In this case we redirect our output to the win32traceutil collector.
45
+ if hasattr(sys, "isapidllhandle"):
46
+ import win32traceutil
47
+
48
+ # The site we are proxying.
49
+ proxy = "https://www.python.org"
50
+ # The name of the virtual directory we install in, and redirect from.
51
+ virtualdir = "/python"
52
+
53
+ # The key feature of this redirector over the simple redirector is that it
54
+ # can choose to ignore certain responses by having the filter not rewrite them
55
+ # to our virtual dir. For this sample, we just exclude the IIS help directory.
56
+
57
+
58
+ # The ISAPI extension - handles requests in our virtual dir, and sends the
59
+ # response to the client.
60
+ class Extension(threaded_extension.ThreadPoolExtension):
61
+ "Python sample Extension"
62
+
63
+ def Dispatch(self, ecb):
64
+ # Note that our ThreadPoolExtension base class will catch exceptions
65
+ # in our Dispatch method, and write the traceback to the client.
66
+ # That is perfect for this sample, so we don't catch our own.
67
+ # print(f'IIS dispatching "{ecb.GetServerVariable("URL")}"')
68
+ url = ecb.GetServerVariable("URL")
69
+ if url.startswith(virtualdir):
70
+ new_url = proxy + url[len(virtualdir) :]
71
+ print("Opening", new_url)
72
+ fp = urllib.request.urlopen(new_url)
73
+ headers = fp.info()
74
+ ecb.SendResponseHeaders("200 OK", str(headers) + "\r\n", False)
75
+ ecb.WriteClient(fp.read())
76
+ ecb.DoneWithSession()
77
+ print(f"Returned data from '{new_url}'!")
78
+ else:
79
+ # this should never happen - we should only see requests that
80
+ # start with our virtual directory name.
81
+ print(f"Not proxying '{url}'")
82
+
83
+
84
+ # The ISAPI filter.
85
+ class Filter(SimpleFilter):
86
+ "Sample Python Redirector"
87
+
88
+ filter_flags = isapicon.SF_NOTIFY_PREPROC_HEADERS | isapicon.SF_NOTIFY_ORDER_DEFAULT
89
+
90
+ def HttpFilterProc(self, fc):
91
+ # print("Filter Dispatch")
92
+ nt = fc.NotificationType
93
+ if nt != isapicon.SF_NOTIFY_PREPROC_HEADERS:
94
+ return isapicon.SF_STATUS_REQ_NEXT_NOTIFICATION
95
+
96
+ pp = fc.GetData()
97
+ url = pp.GetHeader("url")
98
+ # print(f"URL is '{url}'")
99
+ prefix = virtualdir
100
+ if not url.startswith(prefix):
101
+ new_url = prefix + url
102
+ print(f"New proxied URL is '{new_url}'")
103
+ pp.SetHeader("url", new_url)
104
+ # For the sake of demonstration, show how the FilterContext
105
+ # attribute is used. It always starts out life as None, and
106
+ # any assignments made are automatically decref'd by the
107
+ # framework during a SF_NOTIFY_END_OF_NET_SESSION notification.
108
+ if fc.FilterContext is None:
109
+ fc.FilterContext = 0
110
+ fc.FilterContext += 1
111
+ print("This is request number %d on this connection" % fc.FilterContext)
112
+ return isapicon.SF_STATUS_REQ_HANDLED_NOTIFICATION
113
+ else:
114
+ print(f"Filter ignoring URL '{url}'")
115
+
116
+ # Some older code that handled SF_NOTIFY_URL_MAP.
117
+ # print("Have URL_MAP notify")
118
+ # urlmap = fc.GetData()
119
+ # print("URI is", urlmap.URL)
120
+ # print("Path is", urlmap.PhysicalPath)
121
+ # if urlmap.URL.startswith("/UC/"):
122
+ # # Find the /UC/ in the physical path, and nuke it (except
123
+ # # as the path is physical, it is \)
124
+ # p = urlmap.PhysicalPath
125
+ # pos = p.index("\\UC\\")
126
+ # p = p[:pos] + p[pos+3:]
127
+ # p = r"E:\src\pyisapi\webroot\PyTest\formTest.htm"
128
+ # print("New path is", p)
129
+ # urlmap.PhysicalPath = p
130
+
131
+
132
+ # The entry points for the ISAPI extension.
133
+ def __FilterFactory__():
134
+ return Filter()
135
+
136
+
137
+ def __ExtensionFactory__():
138
+ return Extension()
139
+
140
+
141
+ if __name__ == "__main__":
142
+ # If run from the command-line, install ourselves.
143
+ from isapi.install import *
144
+
145
+ params = ISAPIParameters()
146
+ # Setup all filters - these are global to the site.
147
+ params.Filters = [
148
+ FilterParameters(Name="PythonRedirector", Description=Filter.__doc__),
149
+ ]
150
+ # Setup the virtual directories - this is a list of directories our
151
+ # extension uses - in this case only 1.
152
+ # Each extension has a "script map" - this is the mapping of ISAPI
153
+ # extensions.
154
+ sm = [ScriptMapParams(Extension="*", Flags=0)]
155
+ vd = VirtualDirParameters(
156
+ Name=virtualdir[1:],
157
+ Description=Extension.__doc__,
158
+ ScriptMaps=sm,
159
+ ScriptMapUpdate="replace",
160
+ )
161
+ params.VirtualDirs = [vd]
162
+ HandleCommandLine(params)
loan-advisor-agent/.venv/Lib/site-packages/isapi/samples/test.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This extension is used mainly for testing purposes - it is not
2
+ # designed to be a simple sample, but instead is a hotch-potch of things
3
+ # that attempts to exercise the framework.
4
+
5
+ import os
6
+ import stat
7
+ import sys
8
+
9
+ from isapi import isapicon
10
+ from isapi.simple import SimpleExtension
11
+
12
+ if hasattr(sys, "isapidllhandle"):
13
+ import win32traceutil
14
+
15
+ # We use the same reload support as 'advanced.py' demonstrates.
16
+ import threading
17
+
18
+ import win32con
19
+ import win32event
20
+ import win32file
21
+ import winerror
22
+
23
+ from isapi import InternalReloadException
24
+
25
+
26
+ # A watcher thread that checks for __file__ changing.
27
+ # When it detects it, it simply sets "change_detected" to true.
28
+ class ReloadWatcherThread(threading.Thread):
29
+ def __init__(self):
30
+ self.change_detected = False
31
+ self.filename = __file__
32
+ if self.filename.endswith("c") or self.filename.endswith("o"):
33
+ self.filename = self.filename[:-1]
34
+ self.handle = win32file.FindFirstChangeNotification(
35
+ os.path.dirname(self.filename),
36
+ False, # watch tree?
37
+ win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
38
+ )
39
+ threading.Thread.__init__(self)
40
+
41
+ def run(self):
42
+ last_time = os.stat(self.filename)[stat.ST_MTIME]
43
+ while 1:
44
+ try:
45
+ rc = win32event.WaitForSingleObject(self.handle, win32event.INFINITE)
46
+ win32file.FindNextChangeNotification(self.handle)
47
+ except win32event.error as details:
48
+ # handle closed - thread should terminate.
49
+ if details.winerror != winerror.ERROR_INVALID_HANDLE:
50
+ raise
51
+ break
52
+ this_time = os.stat(self.filename)[stat.ST_MTIME]
53
+ if this_time != last_time:
54
+ print("Detected file change - flagging for reload.")
55
+ self.change_detected = True
56
+ last_time = this_time
57
+
58
+ def stop(self):
59
+ win32file.FindCloseChangeNotification(self.handle)
60
+
61
+
62
+ def TransmitFileCallback(ecb, hFile, cbIO, errCode):
63
+ print("Transmit complete!")
64
+ ecb.close()
65
+
66
+
67
+ # The ISAPI extension - handles requests in our virtual dir, and sends the
68
+ # response to the client.
69
+ class Extension(SimpleExtension):
70
+ "Python test Extension"
71
+
72
+ def __init__(self):
73
+ self.reload_watcher = ReloadWatcherThread()
74
+ self.reload_watcher.start()
75
+
76
+ def HttpExtensionProc(self, ecb):
77
+ # NOTE: If you use a ThreadPoolExtension, you must still perform
78
+ # this check in HttpExtensionProc - raising the exception from
79
+ # The "Dispatch" method will just cause the exception to be
80
+ # rendered to the browser.
81
+ if self.reload_watcher.change_detected:
82
+ print("Doing reload")
83
+ raise InternalReloadException
84
+
85
+ if ecb.GetServerVariable("UNICODE_URL").endswith("test.py"):
86
+ file_flags = (
87
+ win32con.FILE_FLAG_SEQUENTIAL_SCAN | win32con.FILE_FLAG_OVERLAPPED
88
+ )
89
+ hfile = win32file.CreateFile(
90
+ __file__,
91
+ win32con.GENERIC_READ,
92
+ 0,
93
+ None,
94
+ win32con.OPEN_EXISTING,
95
+ file_flags,
96
+ None,
97
+ )
98
+ flags = (
99
+ isapicon.HSE_IO_ASYNC
100
+ | isapicon.HSE_IO_DISCONNECT_AFTER_SEND
101
+ | isapicon.HSE_IO_SEND_HEADERS
102
+ )
103
+ # We pass hFile to the callback simply as a way of keeping it alive
104
+ # for the duration of the transmission
105
+ try:
106
+ ecb.TransmitFile(
107
+ TransmitFileCallback,
108
+ hfile,
109
+ int(hfile),
110
+ "200 OK",
111
+ 0,
112
+ 0,
113
+ None,
114
+ None,
115
+ flags,
116
+ )
117
+ except:
118
+ # Errors keep this source file open!
119
+ hfile.Close()
120
+ raise
121
+ else:
122
+ # default response
123
+ ecb.SendResponseHeaders("200 OK", "Content-Type: text/html\r\n\r\n", 0)
124
+ print("<HTML><BODY>", file=ecb)
125
+ print("The root of this site is at", ecb.MapURLToPath("/"), file=ecb)
126
+ print("</BODY></HTML>", file=ecb)
127
+ ecb.close()
128
+ return isapicon.HSE_STATUS_SUCCESS
129
+
130
+ def TerminateExtension(self, status):
131
+ self.reload_watcher.stop()
132
+
133
+
134
+ # The entry points for the ISAPI extension.
135
+ def __ExtensionFactory__():
136
+ return Extension()
137
+
138
+
139
+ # Our special command line customization.
140
+ # Pre-install hook for our virtual directory.
141
+ def PreInstallDirectory(params, options):
142
+ # If the user used our special '--description' option,
143
+ # then we override our default.
144
+ if options.description:
145
+ params.Description = options.description
146
+
147
+
148
+ # Post install hook for our entire script
149
+ def PostInstall(params, options):
150
+ print()
151
+ print("The sample has been installed.")
152
+ print("Point your browser to /PyISAPITest")
153
+
154
+
155
+ # Handler for our custom 'status' argument.
156
+ def status_handler(options, log, arg):
157
+ "Query the status of something"
158
+ print("Everything seems to be fine!")
159
+
160
+
161
+ custom_arg_handlers = {"status": status_handler}
162
+
163
+ if __name__ == "__main__":
164
+ # If run from the command-line, install ourselves.
165
+ from isapi.install import *
166
+
167
+ params = ISAPIParameters(PostInstall=PostInstall)
168
+ # Setup the virtual directories - this is a list of directories our
169
+ # extension uses - in this case only 1.
170
+ # Each extension has a "script map" - this is the mapping of ISAPI
171
+ # extensions.
172
+ sm = [ScriptMapParams(Extension="*", Flags=0)]
173
+ vd = VirtualDirParameters(
174
+ Name="PyISAPITest",
175
+ Description=Extension.__doc__,
176
+ ScriptMaps=sm,
177
+ ScriptMapUpdate="replace",
178
+ # specify the pre-install hook.
179
+ PreInstall=PreInstallDirectory,
180
+ )
181
+ params.VirtualDirs = [vd]
182
+ # Setup our custom option parser.
183
+ from optparse import OptionParser
184
+
185
+ parser = OptionParser("") # blank usage, so isapi sets it.
186
+ parser.add_option(
187
+ "",
188
+ "--description",
189
+ action="store",
190
+ help="custom description to use for the virtual directory",
191
+ )
192
+
193
+ HandleCommandLine(
194
+ params, opt_parser=parser, custom_arg_handlers=custom_arg_handlers
195
+ )
loan-advisor-agent/.venv/Lib/site-packages/isapi/simple.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple base-classes for extensions and filters.
2
+
3
+ None of the filter and extension functions are considered 'optional' by the
4
+ framework. These base-classes provide simple implementations for the
5
+ Initialize and Terminate functions, allowing you to omit them,
6
+
7
+ It is not necessary to use these base-classes - but if you don't, you
8
+ must ensure each of the required methods are implemented.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+
14
+ class SimpleExtension:
15
+ "Base class for a simple ISAPI extension"
16
+
17
+ def __init__(self):
18
+ pass
19
+
20
+ def GetExtensionVersion(self, vi):
21
+ """Called by the ISAPI framework to get the extension version
22
+
23
+ The default implementation uses the classes docstring to
24
+ set the extension description."""
25
+ # nod to our reload capability - vi is None when we are reloaded.
26
+ if vi is not None:
27
+ vi.ExtensionDesc = self.__doc__
28
+
29
+ def HttpExtensionProc(self, control_block):
30
+ """Called by the ISAPI framework for each extension request.
31
+
32
+ sub-classes must provide an implementation for this method.
33
+ """
34
+ raise NotImplementedError("sub-classes should override HttpExtensionProc")
35
+
36
+ def TerminateExtension(self, status):
37
+ """Called by the ISAPI framework as the extension terminates."""
38
+ pass
39
+
40
+
41
+ class SimpleFilter:
42
+ "Base class for a a simple ISAPI filter"
43
+
44
+ filter_flags: int | None = None
45
+
46
+ def __init__(self):
47
+ pass
48
+
49
+ def GetFilterVersion(self, fv):
50
+ """Called by the ISAPI framework to get the extension version
51
+
52
+ The default implementation uses the classes docstring to
53
+ set the extension description, and uses the classes
54
+ filter_flags attribute to set the ISAPI filter flags - you
55
+ must specify filter_flags in your class.
56
+ """
57
+ if self.filter_flags is None:
58
+ raise RuntimeError("You must specify the filter flags")
59
+ # nod to our reload capability - fv is None when we are reloaded.
60
+ if fv is not None:
61
+ fv.Flags = self.filter_flags
62
+ fv.FilterDesc = self.__doc__
63
+
64
+ def HttpFilterProc(self, fc):
65
+ """Called by the ISAPI framework for each filter request.
66
+
67
+ sub-classes must provide an implementation for this method.
68
+ """
69
+ raise NotImplementedError("sub-classes should override HttpExtensionProc")
70
+
71
+ def TerminateFilter(self, status):
72
+ """Called by the ISAPI framework as the filter terminates."""
73
+ pass
loan-advisor-agent/.venv/Lib/site-packages/isapi/test/README.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ This is a directory for tests of the PyISAPI framework.
2
+
3
+ For demos, please see the pyisapi 'samples' directory.
loan-advisor-agent/.venv/Lib/site-packages/isapi/test/extension_simple.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is an ISAPI extension purely for testing purposes. It is NOT
2
+ # a 'demo' (even though it may be useful!)
3
+ #
4
+ # Install this extension, then point your browser to:
5
+ # "http://localhost/pyisapi_test/test1"
6
+ # This will execute the method 'test1' below. See below for the list of
7
+ # test methods that are acceptable.
8
+
9
+ # If we have no console (eg, am running from inside IIS), redirect output
10
+ # somewhere useful - in this case, the standard win32 trace collector.
11
+ import win32api
12
+ import winerror
13
+
14
+ from isapi import ExtensionError, threaded_extension
15
+
16
+ try:
17
+ win32api.GetConsoleTitle()
18
+ except win32api.error:
19
+ # No console - redirect
20
+ import win32traceutil
21
+
22
+
23
+ # The ISAPI extension - handles requests in our virtual dir, and sends the
24
+ # response to the client.
25
+ class Extension(threaded_extension.ThreadPoolExtension):
26
+ "Python ISAPI Tester"
27
+
28
+ def Dispatch(self, ecb):
29
+ print('Tester dispatching "{}"'.format(ecb.GetServerVariable("URL")))
30
+ url = ecb.GetServerVariable("URL")
31
+ test_name = url.split("/")[-1]
32
+ meth = getattr(self, test_name, None)
33
+ if meth is None:
34
+ raise AttributeError(f"No test named '{test_name}'")
35
+ result = meth(ecb)
36
+ if result is None:
37
+ # This means the test finalized everything
38
+ return
39
+ ecb.SendResponseHeaders("200 OK", "Content-type: text/html\r\n\r\n", False)
40
+ print("<HTML><BODY>Finished running test <i>", test_name, "</i>", file=ecb)
41
+ print("<pre>", file=ecb)
42
+ print(result, file=ecb)
43
+ print("</pre>", file=ecb)
44
+ print("</BODY></HTML>", file=ecb)
45
+ ecb.DoneWithSession()
46
+
47
+ def test1(self, ecb):
48
+ try:
49
+ ecb.GetServerVariable("foo bar")
50
+ raise AssertionError("should have failed!")
51
+ except ExtensionError as err:
52
+ assert err.errno == winerror.ERROR_INVALID_INDEX, err
53
+ return "worked!"
54
+
55
+ def test_long_vars(self, ecb):
56
+ qs = ecb.GetServerVariable("QUERY_STRING")
57
+ # Our implementation has a default buffer size of 8k - so we test
58
+ # the code that handles an overflow by ensuring there are more
59
+ # than 8k worth of chars in the URL.
60
+ expected_query = "x" * 8500
61
+ if len(qs) == 0:
62
+ # Just the URL with no query part - redirect to myself, but with
63
+ # a huge query portion.
64
+ me = ecb.GetServerVariable("URL")
65
+ headers = "Location: " + me + "?" + expected_query + "\r\n\r\n"
66
+ ecb.SendResponseHeaders("301 Moved", headers)
67
+ ecb.DoneWithSession()
68
+ return None
69
+ if qs == expected_query:
70
+ return "Total length of variable is %d - test worked!" % (len(qs),)
71
+ else:
72
+ return "Unexpected query portion! Got %d chars, expected %d" % (
73
+ len(qs),
74
+ len(expected_query),
75
+ )
76
+
77
+ def test_unicode_vars(self, ecb):
78
+ # We need to check that we are running IIS6! This seems the only
79
+ # effective way from an extension.
80
+ ver = float(ecb.GetServerVariable("SERVER_SOFTWARE").split("/")[1])
81
+ if ver < 6.0:
82
+ return "This is IIS version %g - unicode only works in IIS6 and later" % ver
83
+
84
+ us = ecb.GetServerVariable("UNICODE_SERVER_NAME")
85
+ assert isinstance(us, str), "unexpected type!"
86
+ assert us == str(ecb.GetServerVariable("SERVER_NAME")), (
87
+ "Unicode and non-unicode values were not the same"
88
+ )
89
+ return "worked!"
90
+
91
+
92
+ # The entry points for the ISAPI extension.
93
+ def __ExtensionFactory__():
94
+ return Extension()
95
+
96
+
97
+ if __name__ == "__main__":
98
+ # If run from the command-line, install ourselves.
99
+ from isapi.install import *
100
+
101
+ params = ISAPIParameters()
102
+ # Setup the virtual directories - this is a list of directories our
103
+ # extension uses - in this case only 1.
104
+ # Each extension has a "script map" - this is the mapping of ISAPI
105
+ # extensions.
106
+ sm = [ScriptMapParams(Extension="*", Flags=0)]
107
+ vd = VirtualDirParameters(
108
+ Name="pyisapi_test",
109
+ Description=Extension.__doc__,
110
+ ScriptMaps=sm,
111
+ ScriptMapUpdate="replace",
112
+ )
113
+ params.VirtualDirs = [vd]
114
+ HandleCommandLine(params)
loan-advisor-agent/.venv/Lib/site-packages/isapi/threaded_extension.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An ISAPI extension base class implemented using a thread-pool."""
2
+
3
+ # $Id$
4
+
5
+ import sys
6
+ import threading
7
+ import time
8
+ import traceback
9
+
10
+ from pywintypes import OVERLAPPED
11
+ from win32event import INFINITE
12
+ from win32file import (
13
+ CloseHandle,
14
+ CreateIoCompletionPort,
15
+ GetQueuedCompletionStatus,
16
+ PostQueuedCompletionStatus,
17
+ )
18
+ from win32security import SetThreadToken
19
+
20
+ import isapi.simple
21
+ from isapi import ExtensionError, isapicon
22
+
23
+ ISAPI_REQUEST = 1
24
+ ISAPI_SHUTDOWN = 2
25
+
26
+
27
+ class WorkerThread(threading.Thread):
28
+ def __init__(self, extension, io_req_port):
29
+ self.running = False
30
+ self.io_req_port = io_req_port
31
+ self.extension = extension
32
+ threading.Thread.__init__(
33
+ self,
34
+ # We wait 15 seconds for a thread to terminate, but if it fails to,
35
+ # we don't want the process to hang at exit waiting for it...
36
+ daemon=True,
37
+ )
38
+
39
+ def run(self):
40
+ self.running = True
41
+ while self.running:
42
+ errCode, bytes, key, overlapped = GetQueuedCompletionStatus(
43
+ self.io_req_port, INFINITE
44
+ )
45
+ if key == ISAPI_SHUTDOWN and overlapped is None:
46
+ break
47
+
48
+ # Let the parent extension handle the command.
49
+ dispatcher = self.extension.dispatch_map.get(key)
50
+ if dispatcher is None:
51
+ raise RuntimeError(f"Bad request '{key}'")
52
+
53
+ dispatcher(errCode, bytes, key, overlapped)
54
+
55
+ def call_handler(self, cblock):
56
+ self.extension.Dispatch(cblock)
57
+
58
+
59
+ # A generic thread-pool based extension, using IO Completion Ports.
60
+ # Sub-classes can override one method to implement a simple extension, or
61
+ # may leverage the CompletionPort to queue their own requests, and implement a
62
+ # fully asynch extension.
63
+ class ThreadPoolExtension(isapi.simple.SimpleExtension):
64
+ "Base class for an ISAPI extension based around a thread-pool"
65
+
66
+ max_workers = 20
67
+ worker_shutdown_wait = 15000 # 15 seconds for workers to quit...
68
+
69
+ def __init__(self):
70
+ self.workers = []
71
+ # extensible dispatch map, for sub-classes that need to post their
72
+ # own requests to the completion port.
73
+ # Each of these functions is called with the result of
74
+ # GetQueuedCompletionStatus for our port.
75
+ self.dispatch_map = {
76
+ ISAPI_REQUEST: self.DispatchConnection,
77
+ }
78
+
79
+ def GetExtensionVersion(self, vi):
80
+ isapi.simple.SimpleExtension.GetExtensionVersion(self, vi)
81
+ # As per Q192800, the CompletionPort should be created with the number
82
+ # of processors, even if the number of worker threads is much larger.
83
+ # Passing 0 means the system picks the number.
84
+ self.io_req_port = CreateIoCompletionPort(-1, None, 0, 0)
85
+ # start up the workers
86
+ self.workers = []
87
+ for i in range(self.max_workers):
88
+ worker = WorkerThread(self, self.io_req_port)
89
+ worker.start()
90
+ self.workers.append(worker)
91
+
92
+ def HttpExtensionProc(self, control_block):
93
+ overlapped = OVERLAPPED()
94
+ overlapped.object = control_block
95
+ PostQueuedCompletionStatus(self.io_req_port, 0, ISAPI_REQUEST, overlapped)
96
+ return isapicon.HSE_STATUS_PENDING
97
+
98
+ def TerminateExtension(self, status):
99
+ for worker in self.workers:
100
+ worker.running = False
101
+ for worker in self.workers:
102
+ PostQueuedCompletionStatus(self.io_req_port, 0, ISAPI_SHUTDOWN, None)
103
+ # wait for them to terminate - pity we aren't using 'native' threads
104
+ # as then we could do a smart wait - but now we need to poll....
105
+ end_time = time.time() + self.worker_shutdown_wait / 1000
106
+ alive = self.workers
107
+ while alive:
108
+ if time.time() > end_time:
109
+ # xxx - might be nice to log something here.
110
+ break
111
+ time.sleep(0.2)
112
+ alive = [w for w in alive if w.is_alive()]
113
+ self.dispatch_map = {} # break circles
114
+ CloseHandle(self.io_req_port)
115
+
116
+ # This is the one operation the base class supports - a simple
117
+ # Connection request. We setup the thread-token, and dispatch to the
118
+ # sub-class's 'Dispatch' method.
119
+ def DispatchConnection(self, errCode, bytes, key, overlapped):
120
+ control_block = overlapped.object
121
+ # setup the correct user for this request
122
+ hRequestToken = control_block.GetImpersonationToken()
123
+ SetThreadToken(None, hRequestToken)
124
+ try:
125
+ try:
126
+ self.Dispatch(control_block)
127
+ except:
128
+ self.HandleDispatchError(control_block)
129
+ finally:
130
+ # reset the security context
131
+ SetThreadToken(None, None)
132
+
133
+ def Dispatch(self, ecb):
134
+ """Overridden by the sub-class to handle connection requests.
135
+
136
+ This class creates a thread-pool using a Windows completion port,
137
+ and dispatches requests via this port. Sub-classes can generally
138
+ implement each connection request using blocking reads and writes, and
139
+ the thread-pool will still provide decent response to the end user.
140
+
141
+ The sub-class can set a max_workers attribute (default is 20). Note
142
+ that this generally does *not* mean 20 threads will all be concurrently
143
+ running, via the magic of Windows completion ports.
144
+
145
+ There is no default implementation - sub-classes must implement this.
146
+ """
147
+ raise NotImplementedError("sub-classes should override Dispatch")
148
+
149
+ def HandleDispatchError(self, ecb):
150
+ """Handles errors in the Dispatch method.
151
+
152
+ When a Dispatch method call fails, this method is called to handle
153
+ the exception. The default implementation formats the traceback
154
+ in the browser.
155
+ """
156
+ ecb.HttpStatusCode = isapicon.HSE_STATUS_ERROR
157
+ # control_block.LogData = "we failed!"
158
+ exc_typ, exc_val, exc_tb = sys.exc_info()
159
+ limit = None
160
+ try:
161
+ try:
162
+ import html
163
+
164
+ ecb.SendResponseHeaders(
165
+ "200 OK", "Content-type: text/html\r\n\r\n", False
166
+ )
167
+ print(file=ecb)
168
+ print("<H3>Traceback (most recent call last):</H3>", file=ecb)
169
+ list = traceback.format_tb(
170
+ exc_tb, limit
171
+ ) + traceback.format_exception_only(exc_typ, exc_val)
172
+ bold = list.pop()
173
+ print(
174
+ "<PRE>{}<B>{}</B></PRE>".format(
175
+ html.escape("".join(list)),
176
+ html.escape(bold),
177
+ ),
178
+ file=ecb,
179
+ )
180
+ except ExtensionError:
181
+ # The client disconnected without reading the error body -
182
+ # it's probably not a real browser at the other end, ignore it.
183
+ pass
184
+ except:
185
+ print("FAILED to render the error message!")
186
+ traceback.print_exc()
187
+ print("ORIGINAL extension error:")
188
+ traceback.print_exception(exc_typ, exc_val, exc_tb)
189
+ finally:
190
+ # holding tracebacks in a local of a frame that may itself be
191
+ # part of a traceback used to be evil and cause leaks!
192
+ exc_tb = None
193
+ ecb.DoneWithSession()