z2_2_6_1.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  4. #
  5. # This software is subject to the provisions of the Zope Public License,
  6. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  7. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  8. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  9. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  10. # FOR A PARTICULAR PURPOSE
  11. #
  12. ##############################################################################
  13. """Zope 2 ZServer start-up file
  14. Usage: %(program)s [options] [environment settings]
  15. Options:
  16. -h
  17. Output this text.
  18. -z path
  19. The location of the Zope installation.
  20. The default is the location of this script, %(here)s.
  21. -Z 0 or 1
  22. UNIX only! This option is ignored on Windows.
  23. This option controls whether a management process will be created
  24. that restarts Zope after a shutdown or crash.
  25. If the argument to -Z is non-null (e.g. "-Z1" or "-Zyes"), a
  26. management process will be used. If the argument to -Z is "-", or
  27. "0", (e.g. "-Z-" or "-Z0"), a management process will not be used.
  28. On UNIX, the default behavior is to create a separate management
  29. process (e.g. -Z1) if the -Z option is not specified.
  30. (Note: the -Z option in Zopes before Zope 2.6 used to be used to specify
  31. a pidfile name for the management process. This pidfile no longer
  32. exists).
  33. -t n
  34. The number of threads to use, if ZODB3 is used. The default is
  35. %(NUMBER_OF_THREADS)s.
  36. -i n
  37. Set the interpreter check interval. This integer value
  38. determines how often the interpreter checks for periodic things
  39. such as thread switches and signal handlers. The Zope default
  40. is 500, but you may want to experiment with other values that
  41. may increase performance in your particular environment.
  42. -D
  43. Run in Zope debug mode. This causes the Zope process not to
  44. detach from the controlling terminal, and is equivalent to
  45. supplying the environment variable setting Z_DEBUG_MODE=1
  46. -a ipaddress
  47. The IP address to listen on. If this is an empty string
  48. (e.g. -a ''), then all addresses on the machine are used. The
  49. default is %(IP_ADDRESS)s.
  50. -d ipaddress
  51. IP address of your DNS server. If this is an empty string
  52. (e.g. -d ''), then IP addresses will not be logged. If you have
  53. DNS service on your local machine then you can set this to
  54. 127.0.0.1. The default is: %(DNS_IP)s.
  55. -u username or uid number
  56. The username to run ZServer as. You may want to run ZServer as
  57. a dedicated user. This only works under Unix, and if ZServer
  58. is started as root, and is required in that case.
  59. -P [ipaddress:]number
  60. Set the web, ftp and monitor port numbers simultaneously
  61. as offsets from the number. The web port number will be number+80.
  62. The FTP port number will be number+21. The monitor port number will
  63. be number+99.
  64. The number can be preeceeded by an ip address follwed by a colon
  65. to specify an address to listen on. This allows different servers
  66. to listen on different addresses.
  67. Multiple -P options can be provided to run multiple sets of servers.
  68. -w port
  69. The Web server (HTTP) port. This defaults to %(HTTP_PORT)s. The
  70. standard port for HTTP services is 80. If this is a dash
  71. (e.g. -w -), then HTTP is disabled.
  72. The number can be preeceeded by an ip address follwed by a colon
  73. to specify an address to listen on. This allows different servers
  74. to listen on different addresses.
  75. Multiple -w options can be provided to run multiple servers.
  76. -y port
  77. The Web secure server (HTTPS) port. This defaults to %(HTTPS_PORT)s.
  78. The standard port for HTTPS services is 443. If this is a dash
  79. (e.g. -y -), then HTTPS is disabled.
  80. The number can be preeceeded by an ip address follwed by a colon
  81. to specify an address to listen on. This allows different servers
  82. to listen on different addresses.
  83. Multiple -w options can be provided to run multiple servers.
  84. -W port
  85. The "WebDAV source" port. If this is a dash (e.g. -w -), then
  86. "WebDAV source" is disabled. The default is disabled. Note that
  87. this feature is a workaround for the lack of "source-link" support
  88. in standard WebDAV clients.
  89. The port can be preeceeded by an ip address follwed by a colon
  90. to specify an address to listen on. This allows different servers
  91. to listen on different addresses.
  92. Multiple -W options can be provided to run multiple servers.
  93. -C
  94. --force-http-connection-close
  95. If present, this option causes Zope to close all HTTP connections,
  96. regardless of the 'Connection:' header (or lack of one) sent by
  97. the client.
  98. -f port
  99. The FTP port. If this is a dash (e.g. -f -), then FTP
  100. is disabled. The standard port for FTP services is 21. The
  101. default is %(FTP_PORT)s.
  102. The port can be preeceeded by an ip address follwed by a colon
  103. to specify an address to listen on. This allows different servers
  104. to listen on different addresses.
  105. Multiple -f options can be provided to run multiple servers.
  106. -p path
  107. Path to the PCGI resource file. The default value is
  108. %(PCGI_FILE)s, relative to the Zope location. If this is a dash
  109. (-p -) or the file does not exist, then PCGI is disabled.
  110. -F path_or_port
  111. Either a port number (for inet sockets) or a path name (for unix
  112. domain sockets) for the FastCGI Server. If the flag and value are
  113. not specified then the FastCGI Server is disabled.
  114. -m port
  115. The secure monitor server port. If this is a dash
  116. (-m -), then the monitor server is disabled. The monitor server
  117. allows interactive Python style access to a running ZServer. To
  118. access the server see medusa/monitor_client.py or
  119. medusa/monitor_client_win32.py. The monitor server password is the
  120. same as the Zope emergency user password set in the 'access'
  121. file. The default is to not start up a monitor server.
  122. The port can be preeceeded by an ip address follwed by a colon
  123. to specify an address to listen on. This allows different servers
  124. to listen on different addresses.
  125. Multiple -m options can be provided to run multiple servers.
  126. --icp port
  127. The ICP port. ICP can be used to distribute load between back-end
  128. zope servers, if you are using an ICP-aware front-end proxy such
  129. as Squid.
  130. The port can be preeceeded by an ip address follwed by a colon
  131. to specify an address to listen on. This allows different servers
  132. to listen on different addresses.
  133. Multiple --icp options can be provided to run multiple servers.
  134. -l path
  135. Path to the ZServer log file. If this is a relative path then the
  136. log file will be written to the 'var' directory. The default is
  137. %(LOG_FILE)s.
  138. -r
  139. Run ZServer is read-only mode. ZServer won't write anything to disk.
  140. No log files, no pid files, nothing. This means that you can't do a
  141. lot of stuff like use PCGI, and zdaemon. ZServer will log hits to
  142. STDOUT and zLOG will log to STDERR.
  143. -L
  144. Enable locale (internationalization) support. The value passed for
  145. this option should be the name of the locale to be used (see your
  146. operating system documentation for locale information specific to
  147. your system). If an empty string is passed for this option (-L ''),
  148. Zope will set the locale to the user's default setting (typically
  149. specified in the $LANG environment variable). If your Python
  150. installation does not support the locale module, the requested
  151. locale is not supported by your system or an empty string was
  152. passed but no default locale can be found, an error will be raised
  153. and Zope will not start.
  154. -X
  155. Disable servers. This might be used to effectively disable all
  156. default server settings or previous server settings in the option
  157. list before providing new settings. For example to provide just a
  158. web server:
  159. %(program)s -X -w80
  160. -M file
  161. Save detailed logging information to the given file.
  162. This log includes separate entries for:
  163. - The start of a request,
  164. - The start of processing the request in an application thread,
  165. - The start of response output, and
  166. - The end of the request.
  167. Environment settings are of the form: NAME=VALUE.
  168. Note: you *must* use Python 2.1 or later!
  169. """
  170. # This is required path hackery for the win32 binary distribution
  171. # that ensures that the bundled python libraries are used. In a
  172. # win32 binary distribution, the installer will have replaced the
  173. # marker string with the actual software home. If that has not
  174. # happened, then the path munging code is skipped.
  175. swhome=r'INSERT_SOFTWARE_HOME'
  176. if swhome != 'INSERT_SOFTWARE_HOME':
  177. import sys
  178. sys.path.insert(0, '%s/lib/python' % swhome)
  179. sys.path.insert(1, '%s/bin/lib' % swhome)
  180. sys.path.insert(2, '%s/bin/lib/plat-win' % swhome)
  181. sys.path.insert(3, '%s/bin/lib/win32' % swhome)
  182. sys.path.insert(4, '%s/bin/lib/win32/lib' % swhome)
  183. sys.path.insert(5, '%s' % swhome)
  184. import os, sys, getopt, codecs, string
  185. import socket
  186. from types import StringType, IntType
  187. # workaround to allow unicode encoding conversions in DTML
  188. dummy = codecs.lookup('iso-8859-1')
  189. sys.setcheckinterval(500)
  190. program=sys.argv[0]
  191. here=os.path.join(os.getcwd(), os.path.split(program)[0])
  192. ########################################################################
  193. # Configuration section
  194. ## General configuration options
  195. ##
  196. # This is the IP address of the network interface you want your servers to
  197. # be visible from. This can be changed to '' to listen on all interfaces.
  198. IP_ADDRESS=''
  199. # IP address of your DNS server. Set to '' if you do not want to resolve
  200. # IP addresses. If you have DNS service on your local machine then you can
  201. # set this to '127.0.0.1'
  202. DNS_IP=''
  203. # User id to run ZServer as. Note that this only works under Unix, and if
  204. # ZServer is started by root. This no longer defaults to 'nobody' since
  205. # that can lead to a Zope file compromise.
  206. UID=None
  207. # Log file location. If this is a relative path, then it is joined the
  208. # the 'var' directory.
  209. LOG_FILE='Z2.log'
  210. ## HTTP configuration
  211. ##
  212. # HTTP enivornment settings.
  213. HTTP_ENV={}
  214. # Port for HTTP Server. The standard port for HTTP services is 80.
  215. HTTP_PORT=8080
  216. ## HTTPS configuration
  217. ##
  218. # HTTPS enivornment settings.
  219. HTTPS_ENV={}
  220. # Port for HTTP Server. The standard port for HTTP services is 80.
  221. HTTPS_PORT=8443
  222. # Should we close all HTTP connections, ignoring the (usually absent)
  223. # 'Connection:' header?
  224. FORCE_HTTP_CONNECTION_CLOSE=0
  225. # Port for the special "WebDAV source view" HTTP handler. There is no
  226. # standard port for this handler, which is disabled by default.
  227. WEBDAV_SOURCE_PORT=[]
  228. ## FTP configuration
  229. # Port for the FTP Server. The standard port for FTP services is 21.
  230. FTP_PORT=8021
  231. ## PCGI configuration
  232. # You can configure the PCGI server manually, or have it read its
  233. # configuration information from a PCGI info file.
  234. PCGI_FILE='Zope.cgi'
  235. ## Monitor configuration
  236. MONITOR_PORT=0
  237. ## ICP configuration
  238. ICP_PORT=0
  239. # Module to be published, which must be Main or Zope
  240. MODULE='Zope'
  241. # The size of the thread pool, if ZODB3 is used.
  242. NUMBER_OF_THREADS=4
  243. # Localization support
  244. LOCALE_ID=None
  245. # Socket path or port for the FastCGI Server
  246. FCGI_PORT=None
  247. # Detailed log file
  248. DETAILED_LOG_FILE=''
  249. # Use a daemon process
  250. USE_DAEMON = 1
  251. #
  252. ########################################################################
  253. ########################################################################
  254. # Handle command-line arguments:
  255. def server_info(old, v, offset=0):
  256. # interpret v as a port or address/port and get new value
  257. if v == '-': v=''
  258. l=v.find(':')
  259. if l >= 0:
  260. a=v[:l]
  261. v=v[l+1:]
  262. else:
  263. a=IP_ADDRESS
  264. if not v: return v
  265. try:
  266. v=int(v)
  267. if v < 0: raise 'Invalid port', v
  268. v=v+offset
  269. except: raise 'Invalid port', v
  270. if isinstance(old, IntType): old=[(a,v)]
  271. else: old.append((a,v))
  272. return old
  273. try:
  274. python_version = sys.version.split()[0]
  275. if python_version < '2.1':
  276. raise 'Invalid python version', python_version
  277. if python_version[:3] == '2.1':
  278. if python_version[4:5] < '3':
  279. import warnings
  280. err = ('You are running Python version %s. This Python version '
  281. 'has known bugs that may cause Zope to run improperly. '
  282. 'Consider upgrading to a Python in the 2.1 series '
  283. 'with at least version number 2.1.3. (Note that Zope does '
  284. 'not yet run under any Python 2.2 version).' %
  285. python_version)
  286. warnings.warn(err)
  287. if python_version[:3] == '2.2':
  288. import warnings
  289. err = ('You are running Python version %s. This Python version '
  290. 'has not yet been tested with Zope and you may experience '
  291. 'operational problems as a result. Consider using '
  292. 'Python 2.1.3 instead.' % python_version)
  293. warnings.warn(err)
  294. opts, args = getopt.getopt(sys.argv[1:],
  295. 'hz:Z:t:i:a:d:u:w:y:W:f:p:m:Sl:2DP:rF:L:XM:C',
  296. ['icp=', 'force-http-connection-close'
  297. ])
  298. DEBUG=0
  299. READ_ONLY=0
  300. if sys.platform == 'win32':
  301. USE_DAEMON = 0
  302. # Get environment variables
  303. for a in args:
  304. if a.find('='):
  305. a=a.split('=')
  306. o=a[0]
  307. v='='.join(a[1:])
  308. if o:
  309. os.environ[o]=v
  310. HTTP_ENV[o]=v
  311. HTTPS_ENV[o]=v
  312. else:
  313. raise 'Invalid argument', a
  314. for o, v in opts:
  315. if o=='-z': here=v
  316. elif o=='-Z':
  317. if v in ('-', '0', ''):
  318. USE_DAEMON=0
  319. elif sys.platform != 'win32':
  320. USE_DAEMON = 1
  321. elif o=='-r': READ_ONLY=1
  322. elif o=='-t':
  323. try: v=int(v)
  324. except: raise 'Invalid number of threads', v
  325. NUMBER_OF_THREADS=v
  326. elif o=='-i':
  327. try: v=int(v)
  328. except: raise 'Invalid value for -i option', v
  329. sys.setcheckinterval(v)
  330. elif o=='-a': IP_ADDRESS=v
  331. elif o=='-d':
  332. if v=='-': v=''
  333. DNS_IP=v
  334. elif o=='-u': UID=v
  335. elif o=='-D':
  336. os.environ['Z_DEBUG_MODE']='1'
  337. DEBUG=1
  338. elif o=='-S': sys.ZMANAGED=1
  339. elif o=='-X':
  340. MONITOR_PORT=HTTP_PORT=HTTPS_PORT=FTP_PORT=FCGI_PORT=ICP_PORT=0
  341. WEBDAV_SOURCE_PORT=0
  342. PCGI_FILE=''
  343. elif o=='-m':
  344. MONITOR_PORT=server_info(MONITOR_PORT, v)
  345. elif o=='-w':
  346. HTTP_PORT=server_info(HTTP_PORT, v)
  347. elif o=='-y':
  348. HTTPS_PORT=server_info(HTTPS_PORT, v)
  349. elif o=='-C' or o=='--force-http-connection-close':
  350. FORCE_HTTP_CONNECTION_CLOSE=1
  351. elif o=='-W':
  352. WEBDAV_SOURCE_PORT=server_info(WEBDAV_SOURCE_PORT, v)
  353. elif o=='-f':
  354. FTP_PORT=server_info(FTP_PORT, v)
  355. elif o=='-P':
  356. HTTP_PORT=server_info(HTTP_PORT, v, 80)
  357. HTTPS_PORT=server_info(HTTPS_PORT, v, 443)
  358. FTP_PORT=server_info(FTP_PORT, v, 21)
  359. elif o=='--icp':
  360. ICP_PORT=server_info(ICP_PORT, v)
  361. elif o=='-p':
  362. if v=='-': v=''
  363. PCGI_FILE=v
  364. elif o=='-h':
  365. print __doc__ % vars()
  366. sys.exit(0)
  367. elif o=='-2': MODULE='Main'
  368. elif o=='-l': LOG_FILE=v
  369. elif o=='-L':
  370. if v: LOCALE_ID=v
  371. else: LOCALE_ID=''
  372. elif o=='-F':
  373. if v=='-': v=''
  374. FCGI_PORT=v
  375. elif o=='-M': DETAILED_LOG_FILE=v
  376. except SystemExit: sys.exit(0)
  377. except:
  378. print __doc__ % vars()
  379. print
  380. print 'Error:'
  381. print "%s: %s" % (sys.exc_type, sys.exc_value)
  382. sys.exit(1)
  383. #
  384. ########################################################################
  385. ########################################################################
  386. # OK, let's get going!
  387. # Jigger path:
  388. sys.path=[os.path.join(here,'lib','python'),here
  389. ]+filter(None, sys.path)
  390. # Try to set the locale if specified on the command
  391. # line. If the locale module is not available or the
  392. # requested locale is not supported by the local
  393. # machine, raise an error so that the user is made
  394. # aware of the problem.
  395. def set_locale(val):
  396. try:
  397. import locale
  398. except:
  399. raise SystemExit, (
  400. 'The locale module could not be imported.\n'
  401. 'To use localization options, you must ensure\n'
  402. 'that the locale module is compiled into your\n'
  403. 'Python installation.'
  404. )
  405. try:
  406. locale.setlocale(locale.LC_ALL, val)
  407. except:
  408. raise SystemExit, (
  409. 'The specified locale is not supported by your system.\n'
  410. 'See your operating system documentation for more\n'
  411. 'information on locale support.'
  412. )
  413. if LOCALE_ID is not None:
  414. set_locale(LOCALE_ID)
  415. import zdaemon
  416. # from this point forward we can use the zope logger
  417. # importing ZDaemon before importing ZServer causes ZServer logging
  418. # not to work.
  419. # Import ZServer before we open the database or get at interesting
  420. # application code so that ZServer's asyncore gets to be the
  421. # official one. Also gets SOFTWARE_HOME, INSTANCE_HOME, and CLIENT_HOME
  422. import ZServer
  423. # install signal handlers if on posix
  424. if os.name == 'posix':
  425. from Signals import Signals
  426. Signals.registerZopeSignals()
  427. # Location of the ZServer pid file. When Zope starts up it will write
  428. # its PID to this file. If Zope is run under zdaemon control, zdaemon
  429. # will write to this pidfile instead of Zope.
  430. PID_FILE=os.path.join(CLIENT_HOME, 'Z2.pid')
  431. if USE_DAEMON and not READ_ONLY:
  432. import App.FindHomes
  433. sys.ZMANAGED=1
  434. # zdaemon.run creates a process which "manages" the actual Zope
  435. # process (restarts it if it dies). The management process passes along
  436. # signals that it receives to its child.
  437. zdaemon.run(sys.argv, os.path.join(CLIENT_HOME, PID_FILE))
  438. os.chdir(CLIENT_HOME)
  439. def _warn_nobody():
  440. zLOG.LOG("z2", zLOG.INFO, ("Running Zope as 'nobody' can compromise "
  441. "your Zope files; consider using a "
  442. "dedicated user account for Zope") )
  443. try:
  444. # Import logging support
  445. import zLOG
  446. import ZLogger
  447. if READ_ONLY:
  448. if hasattr(zLOG, '_set_stupid_dest'):
  449. zLOG._set_stupid_dest(sys.stderr)
  450. else:
  451. zLOG._stupid_dest = sys.stderr
  452. else:
  453. zLOG.log_write = ZLogger.ZLogger.log_write
  454. if DETAILED_LOG_FILE:
  455. from ZServer import DebugLogger
  456. logfile=os.path.join(CLIENT_HOME, DETAILED_LOG_FILE)
  457. zLOG.LOG('z2', zLOG.BLATHER,
  458. 'Using detailed request log file %s' % logfile)
  459. DL=DebugLogger.DebugLogger(logfile)
  460. DebugLogger.log=DL.log
  461. DebugLogger.reopen=DL.reopen
  462. sys.__detailedlog=DL
  463. # Import Zope (or Main)
  464. if MODULE == 'Zope':
  465. import Zope
  466. Zope.startup()
  467. else:
  468. exec "import "+MODULE in {}
  469. # Location of the ZServer log file. This file logs all ZServer activity.
  470. # You may wish to create different logs for different servers. See
  471. # medusa/logger.py for more information.
  472. if not os.path.isabs(LOG_FILE):
  473. LOG_PATH=os.path.join(CLIENT_HOME, LOG_FILE)
  474. else:
  475. LOG_PATH=LOG_FILE
  476. # import ZServer stuff
  477. # First, we need to increase the number of threads
  478. if MODULE=='Zope':
  479. from ZServer import setNumberOfThreads
  480. setNumberOfThreads(NUMBER_OF_THREADS)
  481. from ZServer import resolver, logger, asyncore
  482. from ZServer import zhttp_server, zhttp_handler
  483. from ZServer.WebDAVSrcHandler import WebDAVSrcHandler
  484. from ZServer import PCGIServer,FTPServer,FCGIServer
  485. from ZServer import secure_monitor_server
  486. ## ZServer startup
  487. ##
  488. # Resolver and Logger, used by other servers
  489. if DNS_IP:
  490. rs = resolver.caching_resolver(DNS_IP)
  491. else:
  492. rs=None
  493. if READ_ONLY:
  494. lg = logger.file_logger('-') # log to stdout
  495. zLOG.LOG('z2', zLOG.BLATHER, 'Logging access log to stdout')
  496. elif os.environ.has_key('ZSYSLOG_ACCESS'):
  497. if os.environ.has_key("ZSYSLOG_ACCESS_FACILITY"):
  498. lg = logger.syslog_logger(
  499. os.environ['ZSYSLOG_ACCESS'],
  500. facility=os.environ['ZSYSLOG_ACCESS_FACILITY'])
  501. else:
  502. lg = logger.syslog_logger(os.environ['ZSYSLOG_ACCESS'])
  503. zLOG.LOG('z2', zLOG.BLATHER, 'Using local syslog access log')
  504. elif os.environ.has_key('ZSYSLOG_ACCESS_SERVER'):
  505. (addr, port) = os.environ['ZSYSLOG_ACCESS_SERVER'].split( ':')
  506. lg = logger.syslog_logger((addr, int(port)))
  507. zLOG.LOG('z2', zLOG.BLATHER, 'Using remote syslog access log')
  508. else:
  509. lg = logger.file_logger(LOG_PATH)
  510. zLOG.LOG('z2', zLOG.BLATHER, 'Using access log file %s' % LOG_PATH)
  511. sys.__lg = lg
  512. port_err=('\n\nZope wants to use %(socktype)s port %(port)s for its '
  513. '%(protocol)s service, but it is already in use by another '
  514. 'application on this machine. Either shut the application down '
  515. 'which is using this port, or start Zope with a different '
  516. '%(protocol)s port via the "%(switch)s" command-line switch.\n')
  517. # HTTP Server
  518. if HTTP_PORT:
  519. if isinstance(HTTP_PORT, IntType): HTTP_PORT=((IP_ADDRESS, HTTP_PORT),)
  520. for address, port in HTTP_PORT:
  521. try:
  522. hs = zhttp_server(
  523. ip=address,
  524. port=port,
  525. resolver=rs,
  526. logger_object=lg)
  527. except socket.error, why:
  528. if why[0] == 98: # address in use
  529. raise port_err % {'port':port,
  530. 'socktype':'TCP',
  531. 'protocol':'HTTP',
  532. 'switch':'-w'}
  533. raise
  534. # Handler for a published module. zhttp_handler takes 3 arguments:
  535. # The name of the module to publish, and optionally the URI base
  536. # which is basically the SCRIPT_NAME, and optionally a dictionary
  537. # with CGI environment variables which override default
  538. # settings. The URI base setting is useful when you want to
  539. # publish more than one module with the same HTTP server. The CGI
  540. # environment setting is useful when you want to proxy requests
  541. # from another web server to ZServer, and would like the CGI
  542. # environment to reflect the CGI environment of the other web
  543. # server.
  544. zh = zhttp_handler(MODULE, '', HTTP_ENV)
  545. if FORCE_HTTP_CONNECTION_CLOSE:
  546. zh._force_connection_close = 1
  547. hs.install_handler(zh)
  548. # HTTPS Server
  549. if HTTPS_PORT:
  550. if isinstance(HTTPS_PORT, IntType): HTTPS_PORT=((IP_ADDRESS, HTTPS_PORT),)
  551. for address, port in HTTPS_PORT:
  552. try:
  553. hs = zhttp_server(
  554. ip=address,
  555. port=port,
  556. resolver=rs,
  557. logger_object=lg)
  558. except socket.error, why:
  559. if why[0] == 98: # address in use
  560. raise port_err % {'port':port,
  561. 'socktype':'TCP',
  562. 'protocol':'HTTPS',
  563. 'switch':'-y'}
  564. raise
  565. # Handler for a published module. zhttp_handler takes 3 arguments:
  566. # The name of the module to publish, and optionally the URI base
  567. # which is basically the SCRIPT_NAME, and optionally a dictionary
  568. # with CGI environment variables which override default
  569. # settings. The URI base setting is useful when you want to
  570. # publish more than one module with the same HTTP server. The CGI
  571. # environment setting is useful when you want to proxy requests
  572. # from another web server to ZServer, and would like the CGI
  573. # environment to reflect the CGI environment of the other web
  574. # server.
  575. try:
  576. del HTTPS_ENV['HTTP']
  577. except KeyError:
  578. pass
  579. HTTPS_ENV['HTTPS']='ON'
  580. zh = zhttp_handler(MODULE, '', HTTPS_ENV)
  581. if FORCE_HTTP_CONNECTION_CLOSE:
  582. zh._force_connection_close = 1
  583. hs.install_handler(zh)
  584. # WebDAV source Server (runs HTTP, but munges request to return
  585. # 'manage_FTPget').
  586. if WEBDAV_SOURCE_PORT:
  587. if isinstance(WEBDAV_SOURCE_PORT, IntType):
  588. WEBDAV_SOURCE_PORT=((IP_ADDRESS, WEBDAV_SOURCE_PORT),)
  589. for address, port in WEBDAV_SOURCE_PORT:
  590. try:
  591. hs = zhttp_server(
  592. ip=address,
  593. port=port,
  594. resolver=rs,
  595. logger_object=lg)
  596. except socket.error, why:
  597. if why[0] == 98: # address in use
  598. raise port_err % {'port':port,
  599. 'socktype':'TCP',
  600. 'protocol':'WebDAV source',
  601. 'switch':'-W'}
  602. raise
  603. # Handler for a published module. zhttp_handler takes 3 arguments:
  604. # The name of the module to publish, and optionally the URI base
  605. # which is basically the SCRIPT_NAME, and optionally a dictionary
  606. # with CGI environment variables which override default
  607. # settings. The URI base setting is useful when you want to
  608. # publish more than one module with the same HTTP server. The CGI
  609. # environment setting is useful when you want to proxy requests
  610. # from another web server to ZServer, and would like the CGI
  611. # environment to reflect the CGI environment of the other web
  612. # server.
  613. zh = WebDAVSrcHandler(MODULE, '', HTTP_ENV)
  614. hs.install_handler(zh)
  615. # enable document retrieval of the document source on the
  616. # standard HTTP port
  617. clients = os.environ.get('WEBDAV_SOURCE_PORT_CLIENTS')
  618. if clients:
  619. import re
  620. sys.WEBDAV_SOURCE_PORT_CLIENTS = re.compile(clients).search
  621. else:
  622. sys.WEBDAV_SOURCE_PORT_CLIENTS = None
  623. # FTP Server
  624. if FTP_PORT:
  625. if isinstance(FTP_PORT, IntType): FTP_PORT=((IP_ADDRESS, FTP_PORT),)
  626. for address, port in FTP_PORT:
  627. try:
  628. FTPServer(
  629. module=MODULE,
  630. ip=address,
  631. port=port,
  632. resolver=rs,
  633. logger_object=lg)
  634. except socket.error, why:
  635. if why[0] == 98: # address in use
  636. raise port_err % {'port':port,
  637. 'socktype':'TCP',
  638. 'protocol':'FTP',
  639. 'switch':'-f'}
  640. raise
  641. # PCGI Server
  642. if PCGI_FILE and not READ_ONLY:
  643. PCGI_FILE=os.path.join(here, PCGI_FILE)
  644. if os.path.exists(PCGI_FILE):
  645. zpcgi = PCGIServer(
  646. module=MODULE,
  647. ip=IP_ADDRESS,
  648. pcgi_file=PCGI_FILE,
  649. resolver=rs,
  650. logger_object=lg)
  651. # FastCGI Server
  652. if FCGI_PORT and not READ_ONLY:
  653. fcgiPort = None
  654. fcgiPath = None
  655. try:
  656. fcgiPort = int(FCGI_PORT)
  657. except ValueError:
  658. fcgiPath = FCGI_PORT
  659. try:
  660. zfcgi = FCGIServer(module=MODULE,
  661. ip=IP_ADDRESS,
  662. port=fcgiPort,
  663. socket_file=fcgiPath,
  664. resolver=rs,
  665. logger_object=lg)
  666. except socket.error, why:
  667. if why[0] == 98: # address in use
  668. raise port_err % {'port':fcgiPort,
  669. 'socktype':'TCP',
  670. 'protocol':'FastCGI',
  671. 'switch':'-F'}
  672. raise
  673. # Monitor Server
  674. if MONITOR_PORT:
  675. from AccessControl.User import emergency_user
  676. if not hasattr(emergency_user, '__null_user__'):
  677. pw = emergency_user._getPassword()
  678. else:
  679. pw = None
  680. zLOG.LOG("z2", zLOG.WARNING, 'Monitor server not started'
  681. ' because no emergency user exists.')
  682. if pw:
  683. if isinstance(MONITOR_PORT, IntType):
  684. MONITOR_PORT=((IP_ADDRESS, MONITOR_PORT),)
  685. for address, port in MONITOR_PORT:
  686. try:
  687. monitor=secure_monitor_server(
  688. password=pw,
  689. hostname=address,
  690. port=port)
  691. except socket.error, why:
  692. if why[0] == 98: # address in use
  693. raise port_err % {'port':port,
  694. 'socktype':'TCP',
  695. 'protocol':'monitor server',
  696. 'switch':'-m'}
  697. raise
  698. if ICP_PORT:
  699. if isinstance(ICP_PORT, IntType): ICP_PORT=((IP_ADDRESS, ICP_PORT),)
  700. from ZServer.ICPServer import ICPServer
  701. for address, port in ICP_PORT:
  702. try:
  703. ICPServer(address,port)
  704. except socket.error, why:
  705. if why[0] == 98: # address in use
  706. raise port_err % {'port':port,
  707. 'socktype':'UDP',
  708. 'protocol':'ICP',
  709. 'switch':'--icp'}
  710. raise
  711. if not USE_DAEMON and not READ_ONLY:
  712. if os.path.exists(PID_FILE): os.unlink(PID_FILE)
  713. pf = open(PID_FILE, 'w')
  714. pid='%s\n' % os.getpid()
  715. pf.write(pid)
  716. pf.close()
  717. # Warn if we were started as nobody.
  718. try:
  719. import pwd
  720. if os.getuid():
  721. if pwd.getpwuid(os.getuid())[0] == 'nobody':
  722. _warn_nobody()
  723. except:
  724. pass
  725. # Drop root privileges if we have them, and do some sanity checking
  726. # to make sure we're not starting with an obviously insecure setup.
  727. try:
  728. if os.getuid() == 0:
  729. try:
  730. import initgroups
  731. except:
  732. raise SystemExit, 'initgroups is required to safely setuid'
  733. if UID == None:
  734. raise SystemExit, ('A user was not specified to setuid '
  735. 'to; fix this to start as root (see '
  736. 'doc/SETUID.txt)')
  737. import stat
  738. client_home_stat = os.stat(CLIENT_HOME)
  739. client_home_faults = []
  740. if not (client_home_stat[stat.ST_MODE]&01000):
  741. client_home_faults.append('does not have the sticky bit set')
  742. if client_home_stat[stat.ST_UID] != 0:
  743. client_home_faults.append('is not owned by root')
  744. if client_home_faults:
  745. client_home_faults.append('fix this to start as root (see '
  746. 'doc/SETUID.txt)')
  747. err = '%s %s' % (CLIENT_HOME, ', '.join(client_home_faults))
  748. raise SystemExit, err
  749. try:
  750. try: UID = string.atoi(UID)
  751. except: pass
  752. gid = None
  753. if isinstance(UID, StringType):
  754. uid = pwd.getpwnam(UID)[2]
  755. gid = pwd.getpwnam(UID)[3]
  756. elif isinstance(UID, IntType):
  757. uid = pwd.getpwuid(UID)[2]
  758. gid = pwd.getpwuid(UID)[3]
  759. UID = pwd.getpwuid(UID)[0]
  760. else:
  761. raise KeyError
  762. if UID == 'nobody':
  763. _warn_nobody()
  764. try:
  765. initgroups.initgroups(UID, gid)
  766. if gid is not None:
  767. try:
  768. os.setgid(gid)
  769. except OSError:
  770. pass
  771. os.setuid(uid)
  772. except OSError:
  773. pass
  774. except KeyError:
  775. zLOG.LOG("z2", zLOG.ERROR, ("Can't find UID %s" % UID))
  776. except AttributeError:
  777. pass
  778. except:
  779. raise
  780. # Check umask sanity if we're on posix.
  781. if os.name == 'posix' and not os.environ.get('Z_DEBUG_MODE'):
  782. # umask is silly, blame POSIX. We have to set it to get its value.
  783. current_umask = os.umask(0)
  784. os.umask(current_umask)
  785. if current_umask != 077:
  786. current_umask = '%03o' % current_umask
  787. zLOG.LOG("z2", zLOG.INFO, (
  788. 'Your umask of %s may be too permissive; for the security of '
  789. 'your Zope data, it is recommended you use 077' % current_umask
  790. ))
  791. except:
  792. # Log startup exception and tell zdaemon not to restart us.
  793. try:
  794. zLOG.LOG("z2", zLOG.PANIC, "Startup exception",
  795. error=sys.exc_info())
  796. except: pass
  797. sys.exit(0)
  798. # Start Medusa, Ye Hass!
  799. sys.ZServerExitCode=0
  800. asyncore.loop()
  801. sys.exit(sys.ZServerExitCode)