Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

install.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. """Installation utilities for Python ISAPI filters and extensions."""
  2. # this code adapted from "Tomcat JK2 ISAPI redirector", part of Apache
  3. # Created July 2004, Mark Hammond.
  4. import imp
  5. import os
  6. import shutil
  7. import stat
  8. import sys
  9. import traceback
  10. import pythoncom
  11. import win32api
  12. import winerror
  13. from win32com.client import Dispatch, GetObject
  14. from win32com.client.gencache import EnsureDispatch, EnsureModule
  15. _APP_INPROC = 0
  16. _APP_OUTPROC = 1
  17. _APP_POOLED = 2
  18. _IIS_OBJECT = "IIS://LocalHost/W3SVC"
  19. _IIS_SERVER = "IIsWebServer"
  20. _IIS_WEBDIR = "IIsWebDirectory"
  21. _IIS_WEBVIRTUALDIR = "IIsWebVirtualDir"
  22. _IIS_FILTERS = "IIsFilters"
  23. _IIS_FILTER = "IIsFilter"
  24. _DEFAULT_SERVER_NAME = "Default Web Site"
  25. _DEFAULT_HEADERS = "X-Powered-By: Python"
  26. _DEFAULT_PROTECTION = _APP_POOLED
  27. # Default is for 'execute' only access - ie, only the extension
  28. # can be used. This can be overridden via your install script.
  29. _DEFAULT_ACCESS_EXECUTE = True
  30. _DEFAULT_ACCESS_READ = False
  31. _DEFAULT_ACCESS_WRITE = False
  32. _DEFAULT_ACCESS_SCRIPT = False
  33. _DEFAULT_CONTENT_INDEXED = False
  34. _DEFAULT_ENABLE_DIR_BROWSING = False
  35. _DEFAULT_ENABLE_DEFAULT_DOC = False
  36. _extensions = [ext for ext, _, _ in imp.get_suffixes()]
  37. is_debug_build = "_d.pyd" in _extensions
  38. this_dir = os.path.abspath(os.path.dirname(__file__))
  39. class FilterParameters:
  40. Name = None
  41. Description = None
  42. Path = None
  43. Server = None
  44. # Params that control if/how AddExtensionFile is called.
  45. AddExtensionFile = True
  46. AddExtensionFile_Enabled = True
  47. AddExtensionFile_GroupID = None # defaults to Name
  48. AddExtensionFile_CanDelete = True
  49. AddExtensionFile_Description = None # defaults to Description.
  50. def __init__(self, **kw):
  51. self.__dict__.update(kw)
  52. class VirtualDirParameters:
  53. Name = None # Must be provided.
  54. Description = None # defaults to Name
  55. AppProtection = _DEFAULT_PROTECTION
  56. Headers = _DEFAULT_HEADERS
  57. Path = None # defaults to WWW root.
  58. Type = _IIS_WEBVIRTUALDIR
  59. AccessExecute = _DEFAULT_ACCESS_EXECUTE
  60. AccessRead = _DEFAULT_ACCESS_READ
  61. AccessWrite = _DEFAULT_ACCESS_WRITE
  62. AccessScript = _DEFAULT_ACCESS_SCRIPT
  63. ContentIndexed = _DEFAULT_CONTENT_INDEXED
  64. EnableDirBrowsing = _DEFAULT_ENABLE_DIR_BROWSING
  65. EnableDefaultDoc = _DEFAULT_ENABLE_DEFAULT_DOC
  66. DefaultDoc = None # Only set in IIS if not None
  67. ScriptMaps = []
  68. ScriptMapUpdate = "end" # can be 'start', 'end', 'replace'
  69. Server = None
  70. def __init__(self, **kw):
  71. self.__dict__.update(kw)
  72. def is_root(self):
  73. "This virtual directory is a root directory if parent and name are blank"
  74. parent, name = self.split_path()
  75. return not parent and not name
  76. def split_path(self):
  77. return split_path(self.Name)
  78. class ScriptMapParams:
  79. Extension = None
  80. Module = None
  81. Flags = 5
  82. Verbs = ""
  83. # Params that control if/how AddExtensionFile is called.
  84. AddExtensionFile = True
  85. AddExtensionFile_Enabled = True
  86. AddExtensionFile_GroupID = None # defaults to Name
  87. AddExtensionFile_CanDelete = True
  88. AddExtensionFile_Description = None # defaults to Description.
  89. def __init__(self, **kw):
  90. self.__dict__.update(kw)
  91. def __str__(self):
  92. "Format this parameter suitable for IIS"
  93. items = [self.Extension, self.Module, self.Flags]
  94. # IIS gets upset if there is a trailing verb comma, but no verbs
  95. if self.Verbs:
  96. items.append(self.Verbs)
  97. items = [str(item) for item in items]
  98. return ",".join(items)
  99. class ISAPIParameters:
  100. ServerName = _DEFAULT_SERVER_NAME
  101. # Description = None
  102. Filters = []
  103. VirtualDirs = []
  104. def __init__(self, **kw):
  105. self.__dict__.update(kw)
  106. verbose = 1 # The level - 0 is quiet.
  107. def log(level, what):
  108. if verbose >= level:
  109. print(what)
  110. # Convert an ADSI COM exception to the Win32 error code embedded in it.
  111. def _GetWin32ErrorCode(com_exc):
  112. hr = com_exc.hresult
  113. # If we have more details in the 'excepinfo' struct, use it.
  114. if com_exc.excepinfo:
  115. hr = com_exc.excepinfo[-1]
  116. if winerror.HRESULT_FACILITY(hr) != winerror.FACILITY_WIN32:
  117. raise
  118. return winerror.SCODE_CODE(hr)
  119. class InstallationError(Exception):
  120. pass
  121. class ItemNotFound(InstallationError):
  122. pass
  123. class ConfigurationError(InstallationError):
  124. pass
  125. def FindPath(options, server, name):
  126. if name.lower().startswith("iis://"):
  127. return name
  128. else:
  129. if name and name[0] != "/":
  130. name = "/" + name
  131. return FindWebServer(options, server) + "/ROOT" + name
  132. def LocateWebServerPath(description):
  133. """
  134. Find an IIS web server whose name or comment matches the provided
  135. description (case-insensitive).
  136. >>> LocateWebServerPath('Default Web Site') # doctest: +SKIP
  137. or
  138. >>> LocateWebServerPath('1') #doctest: +SKIP
  139. """
  140. assert len(description) >= 1, "Server name or comment is required"
  141. iis = GetObject(_IIS_OBJECT)
  142. description = description.lower().strip()
  143. for site in iis:
  144. # Name is generally a number, but no need to assume that.
  145. site_attributes = [
  146. getattr(site, attr, "").lower().strip()
  147. for attr in ("Name", "ServerComment")
  148. ]
  149. if description in site_attributes:
  150. return site.AdsPath
  151. msg = "No web sites match the description '%s'" % description
  152. raise ItemNotFound(msg)
  153. def GetWebServer(description=None):
  154. """
  155. Load the web server instance (COM object) for a given instance
  156. or description.
  157. If None is specified, the default website is retrieved (indicated
  158. by the identifier 1.
  159. """
  160. description = description or "1"
  161. path = LocateWebServerPath(description)
  162. server = LoadWebServer(path)
  163. return server
  164. def LoadWebServer(path):
  165. try:
  166. server = GetObject(path)
  167. except pythoncom.com_error as details:
  168. msg = details.strerror
  169. if exc.excepinfo and exc.excepinfo[2]:
  170. msg = exc.excepinfo[2]
  171. msg = "WebServer %s: %s" % (path, msg)
  172. raise ItemNotFound(msg)
  173. return server
  174. def FindWebServer(options, server_desc):
  175. """
  176. Legacy function to allow options to define a .server property
  177. to override the other parameter. Use GetWebServer instead.
  178. """
  179. # options takes precedence
  180. server_desc = options.server or server_desc
  181. # make sure server_desc is unicode (could be mbcs if passed in
  182. # sys.argv).
  183. if server_desc and not isinstance(server_desc, str):
  184. server_desc = server_desc.decode("mbcs")
  185. # get the server (if server_desc is None, the default site is acquired)
  186. server = GetWebServer(server_desc)
  187. return server.adsPath
  188. def split_path(path):
  189. """
  190. Get the parent path and basename.
  191. >>> split_path('/')
  192. ['', '']
  193. >>> split_path('')
  194. ['', '']
  195. >>> split_path('foo')
  196. ['', 'foo']
  197. >>> split_path('/foo')
  198. ['', 'foo']
  199. >>> split_path('/foo/bar')
  200. ['/foo', 'bar']
  201. >>> split_path('foo/bar')
  202. ['/foo', 'bar']
  203. """
  204. if not path.startswith("/"):
  205. path = "/" + path
  206. return path.rsplit("/", 1)
  207. def _CreateDirectory(iis_dir, name, params):
  208. # We used to go to lengths to keep an existing virtual directory
  209. # in place. However, in some cases the existing directories got
  210. # into a bad state, and an update failed to get them working.
  211. # So we nuke it first. If this is a problem, we could consider adding
  212. # a --keep-existing option.
  213. try:
  214. # Also seen the Class change to a generic IISObject - so nuke
  215. # *any* existing object, regardless of Class
  216. assert name.strip("/"), "mustn't delete the root!"
  217. iis_dir.Delete("", name)
  218. log(2, "Deleted old directory '%s'" % (name,))
  219. except pythoncom.com_error:
  220. pass
  221. newDir = iis_dir.Create(params.Type, name)
  222. log(2, "Creating new directory '%s' in %s..." % (name, iis_dir.Name))
  223. friendly = params.Description or params.Name
  224. newDir.AppFriendlyName = friendly
  225. # Note that the new directory won't be visible in the IIS UI
  226. # unless the directory exists on the filesystem.
  227. try:
  228. path = params.Path or iis_dir.Path
  229. newDir.Path = path
  230. except AttributeError:
  231. # If params.Type is IIS_WEBDIRECTORY, an exception is thrown
  232. pass
  233. newDir.AppCreate2(params.AppProtection)
  234. # XXX - note that these Headers only work in IIS6 and earlier. IIS7
  235. # only supports them on the w3svc node - not even on individial sites,
  236. # let alone individual extensions in the site!
  237. if params.Headers:
  238. newDir.HttpCustomHeaders = params.Headers
  239. log(2, "Setting directory options...")
  240. newDir.AccessExecute = params.AccessExecute
  241. newDir.AccessRead = params.AccessRead
  242. newDir.AccessWrite = params.AccessWrite
  243. newDir.AccessScript = params.AccessScript
  244. newDir.ContentIndexed = params.ContentIndexed
  245. newDir.EnableDirBrowsing = params.EnableDirBrowsing
  246. newDir.EnableDefaultDoc = params.EnableDefaultDoc
  247. if params.DefaultDoc is not None:
  248. newDir.DefaultDoc = params.DefaultDoc
  249. newDir.SetInfo()
  250. return newDir
  251. def CreateDirectory(params, options):
  252. _CallHook(params, "PreInstall", options)
  253. if not params.Name:
  254. raise ConfigurationError("No Name param")
  255. parent, name = params.split_path()
  256. target_dir = GetObject(FindPath(options, params.Server, parent))
  257. if not params.is_root():
  258. target_dir = _CreateDirectory(target_dir, name, params)
  259. AssignScriptMaps(params.ScriptMaps, target_dir, params.ScriptMapUpdate)
  260. _CallHook(params, "PostInstall", options, target_dir)
  261. log(1, "Configured Virtual Directory: %s" % (params.Name,))
  262. return target_dir
  263. def AssignScriptMaps(script_maps, target, update="replace"):
  264. """Updates IIS with the supplied script map information.
  265. script_maps is a list of ScriptMapParameter objects
  266. target is an IIS Virtual Directory to assign the script maps to
  267. update is a string indicating how to update the maps, one of ('start',
  268. 'end', or 'replace')
  269. """
  270. # determine which function to use to assign script maps
  271. script_map_func = "_AssignScriptMaps" + update.capitalize()
  272. try:
  273. script_map_func = eval(script_map_func)
  274. except NameError:
  275. msg = "Unknown ScriptMapUpdate option '%s'" % update
  276. raise ConfigurationError(msg)
  277. # use the str method to format the script maps for IIS
  278. script_maps = [str(s) for s in script_maps]
  279. # call the correct function
  280. script_map_func(target, script_maps)
  281. target.SetInfo()
  282. def get_unique_items(sequence, reference):
  283. "Return items in sequence that can't be found in reference."
  284. return tuple([item for item in sequence if item not in reference])
  285. def _AssignScriptMapsReplace(target, script_maps):
  286. target.ScriptMaps = script_maps
  287. def _AssignScriptMapsEnd(target, script_maps):
  288. unique_new_maps = get_unique_items(script_maps, target.ScriptMaps)
  289. target.ScriptMaps = target.ScriptMaps + unique_new_maps
  290. def _AssignScriptMapsStart(target, script_maps):
  291. unique_new_maps = get_unique_items(script_maps, target.ScriptMaps)
  292. target.ScriptMaps = unique_new_maps + target.ScriptMaps
  293. def CreateISAPIFilter(filterParams, options):
  294. server = FindWebServer(options, filterParams.Server)
  295. _CallHook(filterParams, "PreInstall", options)
  296. try:
  297. filters = GetObject(server + "/Filters")
  298. except pythoncom.com_error as exc:
  299. # Brand new sites don't have the '/Filters' collection - create it.
  300. # Any errors other than 'not found' we shouldn't ignore.
  301. if (
  302. winerror.HRESULT_FACILITY(exc.hresult) != winerror.FACILITY_WIN32
  303. or winerror.HRESULT_CODE(exc.hresult) != winerror.ERROR_PATH_NOT_FOUND
  304. ):
  305. raise
  306. server_ob = GetObject(server)
  307. filters = server_ob.Create(_IIS_FILTERS, "Filters")
  308. filters.FilterLoadOrder = ""
  309. filters.SetInfo()
  310. # As for VirtualDir, delete an existing one.
  311. assert filterParams.Name.strip("/"), "mustn't delete the root!"
  312. try:
  313. filters.Delete(_IIS_FILTER, filterParams.Name)
  314. log(2, "Deleted old filter '%s'" % (filterParams.Name,))
  315. except pythoncom.com_error:
  316. pass
  317. newFilter = filters.Create(_IIS_FILTER, filterParams.Name)
  318. log(2, "Created new ISAPI filter...")
  319. assert os.path.isfile(filterParams.Path)
  320. newFilter.FilterPath = filterParams.Path
  321. newFilter.FilterDescription = filterParams.Description
  322. newFilter.SetInfo()
  323. load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b]
  324. if filterParams.Name not in load_order:
  325. load_order.append(filterParams.Name)
  326. filters.FilterLoadOrder = ",".join(load_order)
  327. filters.SetInfo()
  328. _CallHook(filterParams, "PostInstall", options, newFilter)
  329. log(1, "Configured Filter: %s" % (filterParams.Name,))
  330. return newFilter
  331. def DeleteISAPIFilter(filterParams, options):
  332. _CallHook(filterParams, "PreRemove", options)
  333. server = FindWebServer(options, filterParams.Server)
  334. ob_path = server + "/Filters"
  335. try:
  336. filters = GetObject(ob_path)
  337. except pythoncom.com_error as details:
  338. # failure to open the filters just means a totally clean IIS install
  339. # (IIS5 at least has no 'Filters' key when freshly installed).
  340. log(2, "ISAPI filter path '%s' did not exist." % (ob_path,))
  341. return
  342. try:
  343. assert filterParams.Name.strip("/"), "mustn't delete the root!"
  344. filters.Delete(_IIS_FILTER, filterParams.Name)
  345. log(2, "Deleted ISAPI filter '%s'" % (filterParams.Name,))
  346. except pythoncom.com_error as details:
  347. rc = _GetWin32ErrorCode(details)
  348. if rc != winerror.ERROR_PATH_NOT_FOUND:
  349. raise
  350. log(2, "ISAPI filter '%s' did not exist." % (filterParams.Name,))
  351. # Remove from the load order
  352. load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b]
  353. if filterParams.Name in load_order:
  354. load_order.remove(filterParams.Name)
  355. filters.FilterLoadOrder = ",".join(load_order)
  356. filters.SetInfo()
  357. _CallHook(filterParams, "PostRemove", options)
  358. log(1, "Deleted Filter: %s" % (filterParams.Name,))
  359. def _AddExtensionFile(module, def_groupid, def_desc, params, options):
  360. group_id = params.AddExtensionFile_GroupID or def_groupid
  361. desc = params.AddExtensionFile_Description or def_desc
  362. try:
  363. ob = GetObject(_IIS_OBJECT)
  364. ob.AddExtensionFile(
  365. module,
  366. params.AddExtensionFile_Enabled,
  367. group_id,
  368. params.AddExtensionFile_CanDelete,
  369. desc,
  370. )
  371. log(2, "Added extension file '%s' (%s)" % (module, desc))
  372. except (pythoncom.com_error, AttributeError) as details:
  373. # IIS5 always fails. Probably should upgrade this to
  374. # complain more loudly if IIS6 fails.
  375. log(2, "Failed to add extension file '%s': %s" % (module, details))
  376. def AddExtensionFiles(params, options):
  377. """Register the modules used by the filters/extensions as a trusted
  378. 'extension module' - required by the default IIS6 security settings."""
  379. # Add each module only once.
  380. added = {}
  381. for vd in params.VirtualDirs:
  382. for smp in vd.ScriptMaps:
  383. if smp.Module not in added and smp.AddExtensionFile:
  384. _AddExtensionFile(smp.Module, vd.Name, vd.Description, smp, options)
  385. added[smp.Module] = True
  386. for fd in params.Filters:
  387. if fd.Path not in added and fd.AddExtensionFile:
  388. _AddExtensionFile(fd.Path, fd.Name, fd.Description, fd, options)
  389. added[fd.Path] = True
  390. def _DeleteExtensionFileRecord(module, options):
  391. try:
  392. ob = GetObject(_IIS_OBJECT)
  393. ob.DeleteExtensionFileRecord(module)
  394. log(2, "Deleted extension file record for '%s'" % module)
  395. except (pythoncom.com_error, AttributeError) as details:
  396. log(2, "Failed to remove extension file '%s': %s" % (module, details))
  397. def DeleteExtensionFileRecords(params, options):
  398. deleted = {} # only remove each .dll once.
  399. for vd in params.VirtualDirs:
  400. for smp in vd.ScriptMaps:
  401. if smp.Module not in deleted and smp.AddExtensionFile:
  402. _DeleteExtensionFileRecord(smp.Module, options)
  403. deleted[smp.Module] = True
  404. for filter_def in params.Filters:
  405. if filter_def.Path not in deleted and filter_def.AddExtensionFile:
  406. _DeleteExtensionFileRecord(filter_def.Path, options)
  407. deleted[filter_def.Path] = True
  408. def CheckLoaderModule(dll_name):
  409. suffix = ""
  410. if is_debug_build:
  411. suffix = "_d"
  412. template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll")
  413. if not os.path.isfile(template):
  414. raise ConfigurationError("Template loader '%s' does not exist" % (template,))
  415. # We can't do a simple "is newer" check, as the DLL is specific to the
  416. # Python version. So we check the date-time and size are identical,
  417. # and skip the copy in that case.
  418. src_stat = os.stat(template)
  419. try:
  420. dest_stat = os.stat(dll_name)
  421. except os.error:
  422. same = 0
  423. else:
  424. same = (
  425. src_stat[stat.ST_SIZE] == dest_stat[stat.ST_SIZE]
  426. and src_stat[stat.ST_MTIME] == dest_stat[stat.ST_MTIME]
  427. )
  428. if not same:
  429. log(2, "Updating %s->%s" % (template, dll_name))
  430. shutil.copyfile(template, dll_name)
  431. shutil.copystat(template, dll_name)
  432. else:
  433. log(2, "%s is up to date." % (dll_name,))
  434. def _CallHook(ob, hook_name, options, *extra_args):
  435. func = getattr(ob, hook_name, None)
  436. if func is not None:
  437. args = (ob, options) + extra_args
  438. func(*args)
  439. def Install(params, options):
  440. _CallHook(params, "PreInstall", options)
  441. for vd in params.VirtualDirs:
  442. CreateDirectory(vd, options)
  443. for filter_def in params.Filters:
  444. CreateISAPIFilter(filter_def, options)
  445. AddExtensionFiles(params, options)
  446. _CallHook(params, "PostInstall", options)
  447. def RemoveDirectory(params, options):
  448. if params.is_root():
  449. return
  450. try:
  451. directory = GetObject(FindPath(options, params.Server, params.Name))
  452. except pythoncom.com_error as details:
  453. rc = _GetWin32ErrorCode(details)
  454. if rc != winerror.ERROR_PATH_NOT_FOUND:
  455. raise
  456. log(2, "VirtualDirectory '%s' did not exist" % params.Name)
  457. directory = None
  458. if directory is not None:
  459. # Be robust should IIS get upset about unloading.
  460. try:
  461. directory.AppUnLoad()
  462. except:
  463. exc_val = sys.exc_info()[1]
  464. log(2, "AppUnLoad() for %s failed: %s" % (params.Name, exc_val))
  465. # Continue trying to delete it.
  466. try:
  467. parent = GetObject(directory.Parent)
  468. parent.Delete(directory.Class, directory.Name)
  469. log(1, "Deleted Virtual Directory: %s" % (params.Name,))
  470. except:
  471. exc_val = sys.exc_info()[1]
  472. log(1, "Failed to remove directory %s: %s" % (params.Name, exc_val))
  473. def RemoveScriptMaps(vd_params, options):
  474. "Remove script maps from the already installed virtual directory"
  475. parent, name = vd_params.split_path()
  476. target_dir = GetObject(FindPath(options, vd_params.Server, parent))
  477. installed_maps = list(target_dir.ScriptMaps)
  478. for _map in map(str, vd_params.ScriptMaps):
  479. if _map in installed_maps:
  480. installed_maps.remove(_map)
  481. target_dir.ScriptMaps = installed_maps
  482. target_dir.SetInfo()
  483. def Uninstall(params, options):
  484. _CallHook(params, "PreRemove", options)
  485. DeleteExtensionFileRecords(params, options)
  486. for vd in params.VirtualDirs:
  487. _CallHook(vd, "PreRemove", options)
  488. RemoveDirectory(vd, options)
  489. if vd.is_root():
  490. # if this is installed to the root virtual directory, we can't delete it
  491. # so remove the script maps.
  492. RemoveScriptMaps(vd, options)
  493. _CallHook(vd, "PostRemove", options)
  494. for filter_def in params.Filters:
  495. DeleteISAPIFilter(filter_def, options)
  496. _CallHook(params, "PostRemove", options)
  497. # Patch up any missing module names in the params, replacing them with
  498. # the DLL name that hosts this extension/filter.
  499. def _PatchParamsModule(params, dll_name, file_must_exist=True):
  500. if file_must_exist:
  501. if not os.path.isfile(dll_name):
  502. raise ConfigurationError("%s does not exist" % (dll_name,))
  503. # Patch up all references to the DLL.
  504. for f in params.Filters:
  505. if f.Path is None:
  506. f.Path = dll_name
  507. for d in params.VirtualDirs:
  508. for sm in d.ScriptMaps:
  509. if sm.Module is None:
  510. sm.Module = dll_name
  511. def GetLoaderModuleName(mod_name, check_module=None):
  512. # find the name of the DLL hosting us.
  513. # By default, this is "_{module_base_name}.dll"
  514. if hasattr(sys, "frozen"):
  515. # What to do? The .dll knows its name, but this is likely to be
  516. # executed via a .exe, which does not know.
  517. base, ext = os.path.splitext(mod_name)
  518. path, base = os.path.split(base)
  519. # handle the common case of 'foo.exe'/'foow.exe'
  520. if base.endswith("w"):
  521. base = base[:-1]
  522. # For py2exe, we have '_foo.dll' as the standard pyisapi loader - but
  523. # 'foo.dll' is what we use (it just delegates).
  524. # So no leading '_' on the installed name.
  525. dll_name = os.path.abspath(os.path.join(path, base + ".dll"))
  526. else:
  527. base, ext = os.path.splitext(mod_name)
  528. path, base = os.path.split(base)
  529. dll_name = os.path.abspath(os.path.join(path, "_" + base + ".dll"))
  530. # Check we actually have it.
  531. if check_module is None:
  532. check_module = not hasattr(sys, "frozen")
  533. if check_module:
  534. CheckLoaderModule(dll_name)
  535. return dll_name
  536. # Note the 'log' params to these 'builtin' args - old versions of pywin32
  537. # didn't log at all in this function (by intent; anyone calling this was
  538. # responsible). So existing code that calls this function with the old
  539. # signature (ie, without a 'log' param) still gets the same behaviour as
  540. # before...
  541. def InstallModule(conf_module_name, params, options, log=lambda *args: None):
  542. "Install the extension"
  543. if not hasattr(sys, "frozen"):
  544. conf_module_name = os.path.abspath(conf_module_name)
  545. if not os.path.isfile(conf_module_name):
  546. raise ConfigurationError("%s does not exist" % (conf_module_name,))
  547. loader_dll = GetLoaderModuleName(conf_module_name)
  548. _PatchParamsModule(params, loader_dll)
  549. Install(params, options)
  550. log(1, "Installation complete.")
  551. def UninstallModule(conf_module_name, params, options, log=lambda *args: None):
  552. "Remove the extension"
  553. loader_dll = GetLoaderModuleName(conf_module_name, False)
  554. _PatchParamsModule(params, loader_dll, False)
  555. Uninstall(params, options)
  556. log(1, "Uninstallation complete.")
  557. standard_arguments = {
  558. "install": InstallModule,
  559. "remove": UninstallModule,
  560. }
  561. def build_usage(handler_map):
  562. docstrings = [handler.__doc__ for handler in handler_map.values()]
  563. all_args = dict(zip(iter(handler_map.keys()), docstrings))
  564. arg_names = "|".join(iter(all_args.keys()))
  565. usage_string = "%prog [options] [" + arg_names + "]\n"
  566. usage_string += "commands:\n"
  567. for arg, desc in all_args.items():
  568. usage_string += " %-10s: %s" % (arg, desc) + "\n"
  569. return usage_string[:-1]
  570. def MergeStandardOptions(options, params):
  571. """
  572. Take an options object generated by the command line and merge
  573. the values into the IISParameters object.
  574. """
  575. pass
  576. # We support 2 ways of extending our command-line/install support.
  577. # * Many of the installation items allow you to specify "PreInstall",
  578. # "PostInstall", "PreRemove" and "PostRemove" hooks
  579. # All hooks are called with the 'params' object being operated on, and
  580. # the 'optparser' options for this session (ie, the command-line options)
  581. # PostInstall for VirtualDirectories and Filters both have an additional
  582. # param - the ADSI object just created.
  583. # * You can pass your own option parser for us to use, and/or define a map
  584. # with your own custom arg handlers. It is a map of 'arg'->function.
  585. # The function is called with (options, log_fn, arg). The function's
  586. # docstring is used in the usage output.
  587. def HandleCommandLine(
  588. params,
  589. argv=None,
  590. conf_module_name=None,
  591. default_arg="install",
  592. opt_parser=None,
  593. custom_arg_handlers={},
  594. ):
  595. """Perform installation or removal of an ISAPI filter or extension.
  596. This module handles standard command-line options and configuration
  597. information, and installs, removes or updates the configuration of an
  598. ISAPI filter or extension.
  599. You must pass your configuration information in params - all other
  600. arguments are optional, and allow you to configure the installation
  601. process.
  602. """
  603. global verbose
  604. from optparse import OptionParser
  605. argv = argv or sys.argv
  606. if not conf_module_name:
  607. conf_module_name = sys.argv[0]
  608. # convert to a long name so that if we were somehow registered with
  609. # the "short" version but unregistered with the "long" version we
  610. # still work (that will depend on exactly how the installer was
  611. # started)
  612. try:
  613. conf_module_name = win32api.GetLongPathName(conf_module_name)
  614. except win32api.error as exc:
  615. log(
  616. 2,
  617. "Couldn't determine the long name for %r: %s" % (conf_module_name, exc),
  618. )
  619. if opt_parser is None:
  620. # Build our own parser.
  621. parser = OptionParser(usage="")
  622. else:
  623. # The caller is providing their own filter, presumably with their
  624. # own options all setup.
  625. parser = opt_parser
  626. # build a usage string if we don't have one.
  627. if not parser.get_usage():
  628. all_handlers = standard_arguments.copy()
  629. all_handlers.update(custom_arg_handlers)
  630. parser.set_usage(build_usage(all_handlers))
  631. # allow the user to use uninstall as a synonym for remove if it wasn't
  632. # defined by the custom arg handlers.
  633. all_handlers.setdefault("uninstall", all_handlers["remove"])
  634. parser.add_option(
  635. "-q",
  636. "--quiet",
  637. action="store_false",
  638. dest="verbose",
  639. default=True,
  640. help="don't print status messages to stdout",
  641. )
  642. parser.add_option(
  643. "-v",
  644. "--verbosity",
  645. action="count",
  646. dest="verbose",
  647. default=1,
  648. help="increase the verbosity of status messages",
  649. )
  650. parser.add_option(
  651. "",
  652. "--server",
  653. action="store",
  654. help="Specifies the IIS server to install/uninstall on."
  655. " Default is '%s/1'" % (_IIS_OBJECT,),
  656. )
  657. (options, args) = parser.parse_args(argv[1:])
  658. MergeStandardOptions(options, params)
  659. verbose = options.verbose
  660. if not args:
  661. args = [default_arg]
  662. try:
  663. for arg in args:
  664. handler = all_handlers[arg]
  665. handler(conf_module_name, params, options, log)
  666. except (ItemNotFound, InstallationError) as details:
  667. if options.verbose > 1:
  668. traceback.print_exc()
  669. print("%s: %s" % (details.__class__.__name__, details))
  670. except KeyError:
  671. parser.error("Invalid arg '%s'" % arg)