install.py 27 KB

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