config.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442
  1. #
  2. # This file is part of gunicorn released under the MIT license.
  3. # See the NOTICE for more information.
  4. # Please remember to run "make -C docs html" after update "desc" attributes.
  5. import argparse
  6. import copy
  7. import grp
  8. import inspect
  9. import ipaddress
  10. import os
  11. import pwd
  12. import re
  13. import shlex
  14. import ssl
  15. import sys
  16. import textwrap
  17. from gunicorn import __version__, util
  18. from gunicorn.errors import ConfigError
  19. from gunicorn.reloader import reloader_engines
  20. KNOWN_SETTINGS = []
  21. PLATFORM = sys.platform
  22. def make_settings(ignore=None):
  23. settings = {}
  24. ignore = ignore or ()
  25. for s in KNOWN_SETTINGS:
  26. setting = s()
  27. if setting.name in ignore:
  28. continue
  29. settings[setting.name] = setting.copy()
  30. return settings
  31. def auto_int(_, x):
  32. # for compatible with octal numbers in python3
  33. if re.match(r'0(\d)', x, re.IGNORECASE):
  34. x = x.replace('0', '0o', 1)
  35. return int(x, 0)
  36. class Config:
  37. def __init__(self, usage=None, prog=None):
  38. self.settings = make_settings()
  39. self.usage = usage
  40. self.prog = prog or os.path.basename(sys.argv[0])
  41. self.env_orig = os.environ.copy()
  42. def __str__(self):
  43. lines = []
  44. kmax = max(len(k) for k in self.settings)
  45. for k in sorted(self.settings):
  46. v = self.settings[k].value
  47. if callable(v):
  48. v = "<{}()>".format(v.__qualname__)
  49. lines.append("{k:{kmax}} = {v}".format(k=k, v=v, kmax=kmax))
  50. return "\n".join(lines)
  51. def __getattr__(self, name):
  52. if name not in self.settings:
  53. raise AttributeError("No configuration setting for: %s" % name)
  54. return self.settings[name].get()
  55. def __setattr__(self, name, value):
  56. if name != "settings" and name in self.settings:
  57. raise AttributeError("Invalid access!")
  58. super().__setattr__(name, value)
  59. def set(self, name, value):
  60. if name not in self.settings:
  61. raise AttributeError("No configuration setting for: %s" % name)
  62. self.settings[name].set(value)
  63. def get_cmd_args_from_env(self):
  64. if 'GUNICORN_CMD_ARGS' in self.env_orig:
  65. return shlex.split(self.env_orig['GUNICORN_CMD_ARGS'])
  66. return []
  67. def parser(self):
  68. kwargs = {
  69. "usage": self.usage,
  70. "prog": self.prog
  71. }
  72. parser = argparse.ArgumentParser(**kwargs)
  73. parser.add_argument("-v", "--version",
  74. action="version", default=argparse.SUPPRESS,
  75. version="%(prog)s (version " + __version__ + ")\n",
  76. help="show program's version number and exit")
  77. parser.add_argument("args", nargs="*", help=argparse.SUPPRESS)
  78. keys = sorted(self.settings, key=self.settings.__getitem__)
  79. for k in keys:
  80. self.settings[k].add_option(parser)
  81. return parser
  82. @property
  83. def worker_class_str(self):
  84. uri = self.settings['worker_class'].get()
  85. if isinstance(uri, str):
  86. # are we using a threaded worker?
  87. is_sync = uri.endswith('SyncWorker') or uri == 'sync'
  88. if is_sync and self.threads > 1:
  89. return "gthread"
  90. return uri
  91. return uri.__name__
  92. @property
  93. def worker_class(self):
  94. uri = self.settings['worker_class'].get()
  95. # are we using a threaded worker?
  96. is_sync = isinstance(uri, str) and (uri.endswith('SyncWorker') or uri == 'sync')
  97. if is_sync and self.threads > 1:
  98. uri = "gunicorn.workers.gthread.ThreadWorker"
  99. worker_class = util.load_class(uri)
  100. if hasattr(worker_class, "setup"):
  101. worker_class.setup()
  102. return worker_class
  103. @property
  104. def address(self):
  105. s = self.settings['bind'].get()
  106. return [util.parse_address(util.bytes_to_str(bind)) for bind in s]
  107. @property
  108. def uid(self):
  109. return self.settings['user'].get()
  110. @property
  111. def gid(self):
  112. return self.settings['group'].get()
  113. @property
  114. def proc_name(self):
  115. pn = self.settings['proc_name'].get()
  116. if pn is not None:
  117. return pn
  118. else:
  119. return self.settings['default_proc_name'].get()
  120. @property
  121. def logger_class(self):
  122. uri = self.settings['logger_class'].get()
  123. if uri == "simple":
  124. # support the default
  125. uri = LoggerClass.default
  126. # if default logger is in use, and statsd is on, automagically switch
  127. # to the statsd logger
  128. if uri == LoggerClass.default:
  129. if 'statsd_host' in self.settings and self.settings['statsd_host'].value is not None:
  130. uri = "gunicorn.instrument.statsd.Statsd"
  131. logger_class = util.load_class(
  132. uri,
  133. default="gunicorn.glogging.Logger",
  134. section="gunicorn.loggers")
  135. if hasattr(logger_class, "install"):
  136. logger_class.install()
  137. return logger_class
  138. @property
  139. def is_ssl(self):
  140. return self.certfile or self.keyfile
  141. @property
  142. def ssl_options(self):
  143. opts = {}
  144. for name, value in self.settings.items():
  145. if value.section == 'SSL':
  146. opts[name] = value.get()
  147. return opts
  148. @property
  149. def env(self):
  150. raw_env = self.settings['raw_env'].get()
  151. env = {}
  152. if not raw_env:
  153. return env
  154. for e in raw_env:
  155. s = util.bytes_to_str(e)
  156. try:
  157. k, v = s.split('=', 1)
  158. except ValueError:
  159. raise RuntimeError("environment setting %r invalid" % s)
  160. env[k] = v
  161. return env
  162. @property
  163. def sendfile(self):
  164. if self.settings['sendfile'].get() is not None:
  165. return False
  166. if 'SENDFILE' in os.environ:
  167. sendfile = os.environ['SENDFILE'].lower()
  168. return sendfile in ['y', '1', 'yes', 'true']
  169. return True
  170. @property
  171. def reuse_port(self):
  172. return self.settings['reuse_port'].get()
  173. @property
  174. def paste_global_conf(self):
  175. raw_global_conf = self.settings['raw_paste_global_conf'].get()
  176. if raw_global_conf is None:
  177. return None
  178. global_conf = {}
  179. for e in raw_global_conf:
  180. s = util.bytes_to_str(e)
  181. try:
  182. k, v = re.split(r'(?<!\\)=', s, 1)
  183. except ValueError:
  184. raise RuntimeError("environment setting %r invalid" % s)
  185. k = k.replace('\\=', '=')
  186. v = v.replace('\\=', '=')
  187. global_conf[k] = v
  188. return global_conf
  189. class SettingMeta(type):
  190. def __new__(cls, name, bases, attrs):
  191. super_new = super().__new__
  192. parents = [b for b in bases if isinstance(b, SettingMeta)]
  193. if not parents:
  194. return super_new(cls, name, bases, attrs)
  195. attrs["order"] = len(KNOWN_SETTINGS)
  196. attrs["validator"] = staticmethod(attrs["validator"])
  197. new_class = super_new(cls, name, bases, attrs)
  198. new_class.fmt_desc(attrs.get("desc", ""))
  199. KNOWN_SETTINGS.append(new_class)
  200. return new_class
  201. def fmt_desc(cls, desc):
  202. desc = textwrap.dedent(desc).strip()
  203. setattr(cls, "desc", desc)
  204. setattr(cls, "short", desc.splitlines()[0])
  205. class Setting:
  206. name = None
  207. value = None
  208. section = None
  209. cli = None
  210. validator = None
  211. type = None
  212. meta = None
  213. action = None
  214. default = None
  215. short = None
  216. desc = None
  217. nargs = None
  218. const = None
  219. def __init__(self):
  220. if self.default is not None:
  221. self.set(self.default)
  222. def add_option(self, parser):
  223. if not self.cli:
  224. return
  225. args = tuple(self.cli)
  226. help_txt = "%s [%s]" % (self.short, self.default)
  227. help_txt = help_txt.replace("%", "%%")
  228. kwargs = {
  229. "dest": self.name,
  230. "action": self.action or "store",
  231. "type": self.type or str,
  232. "default": None,
  233. "help": help_txt
  234. }
  235. if self.meta is not None:
  236. kwargs['metavar'] = self.meta
  237. if kwargs["action"] != "store":
  238. kwargs.pop("type")
  239. if self.nargs is not None:
  240. kwargs["nargs"] = self.nargs
  241. if self.const is not None:
  242. kwargs["const"] = self.const
  243. parser.add_argument(*args, **kwargs)
  244. def copy(self):
  245. return copy.copy(self)
  246. def get(self):
  247. return self.value
  248. def set(self, val):
  249. if not callable(self.validator):
  250. raise TypeError('Invalid validator: %s' % self.name)
  251. self.value = self.validator(val)
  252. def __lt__(self, other):
  253. return (self.section == other.section and
  254. self.order < other.order)
  255. __cmp__ = __lt__
  256. def __repr__(self):
  257. return "<%s.%s object at %x with value %r>" % (
  258. self.__class__.__module__,
  259. self.__class__.__name__,
  260. id(self),
  261. self.value,
  262. )
  263. Setting = SettingMeta('Setting', (Setting,), {})
  264. def validate_bool(val):
  265. if val is None:
  266. return
  267. if isinstance(val, bool):
  268. return val
  269. if not isinstance(val, str):
  270. raise TypeError("Invalid type for casting: %s" % val)
  271. if val.lower().strip() == "true":
  272. return True
  273. elif val.lower().strip() == "false":
  274. return False
  275. else:
  276. raise ValueError("Invalid boolean: %s" % val)
  277. def validate_dict(val):
  278. if not isinstance(val, dict):
  279. raise TypeError("Value is not a dictionary: %s " % val)
  280. return val
  281. def validate_pos_int(val):
  282. if not isinstance(val, int):
  283. val = int(val, 0)
  284. else:
  285. # Booleans are ints!
  286. val = int(val)
  287. if val < 0:
  288. raise ValueError("Value must be positive: %s" % val)
  289. return val
  290. def validate_ssl_version(val):
  291. if val != SSLVersion.default:
  292. sys.stderr.write("Warning: option `ssl_version` is deprecated and it is ignored. Use ssl_context instead.\n")
  293. return val
  294. def validate_string(val):
  295. if val is None:
  296. return None
  297. if not isinstance(val, str):
  298. raise TypeError("Not a string: %s" % val)
  299. return val.strip()
  300. def validate_file_exists(val):
  301. if val is None:
  302. return None
  303. if not os.path.exists(val):
  304. raise ValueError("File %s does not exists." % val)
  305. return val
  306. def validate_list_string(val):
  307. if not val:
  308. return []
  309. # legacy syntax
  310. if isinstance(val, str):
  311. val = [val]
  312. return [validate_string(v) for v in val]
  313. def validate_list_of_existing_files(val):
  314. return [validate_file_exists(v) for v in validate_list_string(val)]
  315. def validate_string_to_addr_list(val):
  316. val = validate_string_to_list(val)
  317. for addr in val:
  318. if addr == "*":
  319. continue
  320. _vaid_ip = ipaddress.ip_address(addr)
  321. return val
  322. def validate_string_to_list(val):
  323. val = validate_string(val)
  324. if not val:
  325. return []
  326. return [v.strip() for v in val.split(",") if v]
  327. def validate_class(val):
  328. if inspect.isfunction(val) or inspect.ismethod(val):
  329. val = val()
  330. if inspect.isclass(val):
  331. return val
  332. return validate_string(val)
  333. def validate_callable(arity):
  334. def _validate_callable(val):
  335. if isinstance(val, str):
  336. try:
  337. mod_name, obj_name = val.rsplit(".", 1)
  338. except ValueError:
  339. raise TypeError("Value '%s' is not import string. "
  340. "Format: module[.submodules...].object" % val)
  341. try:
  342. mod = __import__(mod_name, fromlist=[obj_name])
  343. val = getattr(mod, obj_name)
  344. except ImportError as e:
  345. raise TypeError(str(e))
  346. except AttributeError:
  347. raise TypeError("Can not load '%s' from '%s'"
  348. "" % (obj_name, mod_name))
  349. if not callable(val):
  350. raise TypeError("Value is not callable: %s" % val)
  351. if arity != -1 and arity != util.get_arity(val):
  352. raise TypeError("Value must have an arity of: %s" % arity)
  353. return val
  354. return _validate_callable
  355. def validate_user(val):
  356. if val is None:
  357. return os.geteuid()
  358. if isinstance(val, int):
  359. return val
  360. elif val.isdigit():
  361. return int(val)
  362. else:
  363. try:
  364. return pwd.getpwnam(val).pw_uid
  365. except KeyError:
  366. raise ConfigError("No such user: '%s'" % val)
  367. def validate_group(val):
  368. if val is None:
  369. return os.getegid()
  370. if isinstance(val, int):
  371. return val
  372. elif val.isdigit():
  373. return int(val)
  374. else:
  375. try:
  376. return grp.getgrnam(val).gr_gid
  377. except KeyError:
  378. raise ConfigError("No such group: '%s'" % val)
  379. def validate_post_request(val):
  380. val = validate_callable(-1)(val)
  381. largs = util.get_arity(val)
  382. if largs == 4:
  383. return val
  384. elif largs == 3:
  385. return lambda worker, req, env, _r: val(worker, req, env)
  386. elif largs == 2:
  387. return lambda worker, req, _e, _r: val(worker, req)
  388. else:
  389. raise TypeError("Value must have an arity of: 4")
  390. def validate_chdir(val):
  391. # valid if the value is a string
  392. val = validate_string(val)
  393. # transform relative paths
  394. path = os.path.abspath(os.path.normpath(os.path.join(util.getcwd(), val)))
  395. # test if the path exists
  396. if not os.path.exists(path):
  397. raise ConfigError("can't chdir to %r" % val)
  398. return path
  399. def validate_statsd_address(val):
  400. val = validate_string(val)
  401. if val is None:
  402. return None
  403. # As of major release 20, util.parse_address would recognize unix:PORT
  404. # as a UDS address, breaking backwards compatibility. We defend against
  405. # that regression here (this is also unit-tested).
  406. # Feel free to remove in the next major release.
  407. unix_hostname_regression = re.match(r'^unix:(\d+)$', val)
  408. if unix_hostname_regression:
  409. return ('unix', int(unix_hostname_regression.group(1)))
  410. try:
  411. address = util.parse_address(val, default_port='8125')
  412. except RuntimeError:
  413. raise TypeError("Value must be one of ('host:port', 'unix://PATH')")
  414. return address
  415. def validate_reload_engine(val):
  416. if val not in reloader_engines:
  417. raise ConfigError("Invalid reload_engine: %r" % val)
  418. return val
  419. def get_default_config_file():
  420. config_path = os.path.join(os.path.abspath(os.getcwd()),
  421. 'gunicorn.conf.py')
  422. if os.path.exists(config_path):
  423. return config_path
  424. return None
  425. class ConfigFile(Setting):
  426. name = "config"
  427. section = "Config File"
  428. cli = ["-c", "--config"]
  429. meta = "CONFIG"
  430. validator = validate_string
  431. default = "./gunicorn.conf.py"
  432. desc = """\
  433. :ref:`The Gunicorn config file<configuration_file>`.
  434. A string of the form ``PATH``, ``file:PATH``, or ``python:MODULE_NAME``.
  435. Only has an effect when specified on the command line or as part of an
  436. application specific configuration.
  437. By default, a file named ``gunicorn.conf.py`` will be read from the same
  438. directory where gunicorn is being run.
  439. .. versionchanged:: 19.4
  440. Loading the config from a Python module requires the ``python:``
  441. prefix.
  442. """
  443. class WSGIApp(Setting):
  444. name = "wsgi_app"
  445. section = "Config File"
  446. meta = "STRING"
  447. validator = validate_string
  448. default = None
  449. desc = """\
  450. A WSGI application path in pattern ``$(MODULE_NAME):$(VARIABLE_NAME)``.
  451. .. versionadded:: 20.1.0
  452. """
  453. class Bind(Setting):
  454. name = "bind"
  455. action = "append"
  456. section = "Server Socket"
  457. cli = ["-b", "--bind"]
  458. meta = "ADDRESS"
  459. validator = validate_list_string
  460. if 'PORT' in os.environ:
  461. default = ['0.0.0.0:{0}'.format(os.environ.get('PORT'))]
  462. else:
  463. default = ['127.0.0.1:8000']
  464. desc = """\
  465. The socket to bind.
  466. A string of the form: ``HOST``, ``HOST:PORT``, ``unix:PATH``,
  467. ``fd://FD``. An IP is a valid ``HOST``.
  468. .. versionchanged:: 20.0
  469. Support for ``fd://FD`` got added.
  470. Multiple addresses can be bound. ex.::
  471. $ gunicorn -b 127.0.0.1:8000 -b [::1]:8000 test:app
  472. will bind the `test:app` application on localhost both on ipv6
  473. and ipv4 interfaces.
  474. If the ``PORT`` environment variable is defined, the default
  475. is ``['0.0.0.0:$PORT']``. If it is not defined, the default
  476. is ``['127.0.0.1:8000']``.
  477. """
  478. class Backlog(Setting):
  479. name = "backlog"
  480. section = "Server Socket"
  481. cli = ["--backlog"]
  482. meta = "INT"
  483. validator = validate_pos_int
  484. type = int
  485. default = 2048
  486. desc = """\
  487. The maximum number of pending connections.
  488. This refers to the number of clients that can be waiting to be served.
  489. Exceeding this number results in the client getting an error when
  490. attempting to connect. It should only affect servers under significant
  491. load.
  492. Must be a positive integer. Generally set in the 64-2048 range.
  493. """
  494. class Workers(Setting):
  495. name = "workers"
  496. section = "Worker Processes"
  497. cli = ["-w", "--workers"]
  498. meta = "INT"
  499. validator = validate_pos_int
  500. type = int
  501. default = int(os.environ.get("WEB_CONCURRENCY", 1))
  502. desc = """\
  503. The number of worker processes for handling requests.
  504. A positive integer generally in the ``2-4 x $(NUM_CORES)`` range.
  505. You'll want to vary this a bit to find the best for your particular
  506. application's work load.
  507. By default, the value of the ``WEB_CONCURRENCY`` environment variable,
  508. which is set by some Platform-as-a-Service providers such as Heroku. If
  509. it is not defined, the default is ``1``.
  510. """
  511. class WorkerClass(Setting):
  512. name = "worker_class"
  513. section = "Worker Processes"
  514. cli = ["-k", "--worker-class"]
  515. meta = "STRING"
  516. validator = validate_class
  517. default = "sync"
  518. desc = """\
  519. The type of workers to use.
  520. The default class (``sync``) should handle most "normal" types of
  521. workloads. You'll want to read :doc:`design` for information on when
  522. you might want to choose one of the other worker classes. Required
  523. libraries may be installed using setuptools' ``extras_require`` feature.
  524. A string referring to one of the following bundled classes:
  525. * ``sync``
  526. * ``eventlet`` - Requires eventlet >= 0.24.1 (or install it via
  527. ``pip install gunicorn[eventlet]``)
  528. * ``gevent`` - Requires gevent >= 1.4 (or install it via
  529. ``pip install gunicorn[gevent]``)
  530. * ``tornado`` - Requires tornado >= 0.2 (or install it via
  531. ``pip install gunicorn[tornado]``)
  532. * ``gthread`` - Python 2 requires the futures package to be installed
  533. (or install it via ``pip install gunicorn[gthread]``)
  534. Optionally, you can provide your own worker by giving Gunicorn a
  535. Python path to a subclass of ``gunicorn.workers.base.Worker``.
  536. This alternative syntax will load the gevent class:
  537. ``gunicorn.workers.ggevent.GeventWorker``.
  538. """
  539. class WorkerThreads(Setting):
  540. name = "threads"
  541. section = "Worker Processes"
  542. cli = ["--threads"]
  543. meta = "INT"
  544. validator = validate_pos_int
  545. type = int
  546. default = 1
  547. desc = """\
  548. The number of worker threads for handling requests.
  549. Run each worker with the specified number of threads.
  550. A positive integer generally in the ``2-4 x $(NUM_CORES)`` range.
  551. You'll want to vary this a bit to find the best for your particular
  552. application's work load.
  553. If it is not defined, the default is ``1``.
  554. This setting only affects the Gthread worker type.
  555. .. note::
  556. If you try to use the ``sync`` worker type and set the ``threads``
  557. setting to more than 1, the ``gthread`` worker type will be used
  558. instead.
  559. """
  560. class WorkerConnections(Setting):
  561. name = "worker_connections"
  562. section = "Worker Processes"
  563. cli = ["--worker-connections"]
  564. meta = "INT"
  565. validator = validate_pos_int
  566. type = int
  567. default = 1000
  568. desc = """\
  569. The maximum number of simultaneous clients.
  570. This setting only affects the ``gthread``, ``eventlet`` and ``gevent`` worker types.
  571. """
  572. class MaxRequests(Setting):
  573. name = "max_requests"
  574. section = "Worker Processes"
  575. cli = ["--max-requests"]
  576. meta = "INT"
  577. validator = validate_pos_int
  578. type = int
  579. default = 0
  580. desc = """\
  581. The maximum number of requests a worker will process before restarting.
  582. Any value greater than zero will limit the number of requests a worker
  583. will process before automatically restarting. This is a simple method
  584. to help limit the damage of memory leaks.
  585. If this is set to zero (the default) then the automatic worker
  586. restarts are disabled.
  587. """
  588. class MaxRequestsJitter(Setting):
  589. name = "max_requests_jitter"
  590. section = "Worker Processes"
  591. cli = ["--max-requests-jitter"]
  592. meta = "INT"
  593. validator = validate_pos_int
  594. type = int
  595. default = 0
  596. desc = """\
  597. The maximum jitter to add to the *max_requests* setting.
  598. The jitter causes the restart per worker to be randomized by
  599. ``randint(0, max_requests_jitter)``. This is intended to stagger worker
  600. restarts to avoid all workers restarting at the same time.
  601. .. versionadded:: 19.2
  602. """
  603. class Timeout(Setting):
  604. name = "timeout"
  605. section = "Worker Processes"
  606. cli = ["-t", "--timeout"]
  607. meta = "INT"
  608. validator = validate_pos_int
  609. type = int
  610. default = 30
  611. desc = """\
  612. Workers silent for more than this many seconds are killed and restarted.
  613. Value is a positive number or 0. Setting it to 0 has the effect of
  614. infinite timeouts by disabling timeouts for all workers entirely.
  615. Generally, the default of thirty seconds should suffice. Only set this
  616. noticeably higher if you're sure of the repercussions for sync workers.
  617. For the non sync workers it just means that the worker process is still
  618. communicating and is not tied to the length of time required to handle a
  619. single request.
  620. """
  621. class GracefulTimeout(Setting):
  622. name = "graceful_timeout"
  623. section = "Worker Processes"
  624. cli = ["--graceful-timeout"]
  625. meta = "INT"
  626. validator = validate_pos_int
  627. type = int
  628. default = 30
  629. desc = """\
  630. Timeout for graceful workers restart.
  631. After receiving a restart signal, workers have this much time to finish
  632. serving requests. Workers still alive after the timeout (starting from
  633. the receipt of the restart signal) are force killed.
  634. """
  635. class Keepalive(Setting):
  636. name = "keepalive"
  637. section = "Worker Processes"
  638. cli = ["--keep-alive"]
  639. meta = "INT"
  640. validator = validate_pos_int
  641. type = int
  642. default = 2
  643. desc = """\
  644. The number of seconds to wait for requests on a Keep-Alive connection.
  645. Generally set in the 1-5 seconds range for servers with direct connection
  646. to the client (e.g. when you don't have separate load balancer). When
  647. Gunicorn is deployed behind a load balancer, it often makes sense to
  648. set this to a higher value.
  649. .. note::
  650. ``sync`` worker does not support persistent connections and will
  651. ignore this option.
  652. """
  653. class LimitRequestLine(Setting):
  654. name = "limit_request_line"
  655. section = "Security"
  656. cli = ["--limit-request-line"]
  657. meta = "INT"
  658. validator = validate_pos_int
  659. type = int
  660. default = 4094
  661. desc = """\
  662. The maximum size of HTTP request line in bytes.
  663. This parameter is used to limit the allowed size of a client's
  664. HTTP request-line. Since the request-line consists of the HTTP
  665. method, URI, and protocol version, this directive places a
  666. restriction on the length of a request-URI allowed for a request
  667. on the server. A server needs this value to be large enough to
  668. hold any of its resource names, including any information that
  669. might be passed in the query part of a GET request. Value is a number
  670. from 0 (unlimited) to 8190.
  671. This parameter can be used to prevent any DDOS attack.
  672. """
  673. class LimitRequestFields(Setting):
  674. name = "limit_request_fields"
  675. section = "Security"
  676. cli = ["--limit-request-fields"]
  677. meta = "INT"
  678. validator = validate_pos_int
  679. type = int
  680. default = 100
  681. desc = """\
  682. Limit the number of HTTP headers fields in a request.
  683. This parameter is used to limit the number of headers in a request to
  684. prevent DDOS attack. Used with the *limit_request_field_size* it allows
  685. more safety. By default this value is 100 and can't be larger than
  686. 32768.
  687. """
  688. class LimitRequestFieldSize(Setting):
  689. name = "limit_request_field_size"
  690. section = "Security"
  691. cli = ["--limit-request-field_size"]
  692. meta = "INT"
  693. validator = validate_pos_int
  694. type = int
  695. default = 8190
  696. desc = """\
  697. Limit the allowed size of an HTTP request header field.
  698. Value is a positive number or 0. Setting it to 0 will allow unlimited
  699. header field sizes.
  700. .. warning::
  701. Setting this parameter to a very high or unlimited value can open
  702. up for DDOS attacks.
  703. """
  704. class Reload(Setting):
  705. name = "reload"
  706. section = 'Debugging'
  707. cli = ['--reload']
  708. validator = validate_bool
  709. action = 'store_true'
  710. default = False
  711. desc = '''\
  712. Restart workers when code changes.
  713. This setting is intended for development. It will cause workers to be
  714. restarted whenever application code changes.
  715. The reloader is incompatible with application preloading. When using a
  716. paste configuration be sure that the server block does not import any
  717. application code or the reload will not work as designed.
  718. The default behavior is to attempt inotify with a fallback to file
  719. system polling. Generally, inotify should be preferred if available
  720. because it consumes less system resources.
  721. .. note::
  722. In order to use the inotify reloader, you must have the ``inotify``
  723. package installed.
  724. '''
  725. class ReloadEngine(Setting):
  726. name = "reload_engine"
  727. section = "Debugging"
  728. cli = ["--reload-engine"]
  729. meta = "STRING"
  730. validator = validate_reload_engine
  731. default = "auto"
  732. desc = """\
  733. The implementation that should be used to power :ref:`reload`.
  734. Valid engines are:
  735. * ``'auto'``
  736. * ``'poll'``
  737. * ``'inotify'`` (requires inotify)
  738. .. versionadded:: 19.7
  739. """
  740. class ReloadExtraFiles(Setting):
  741. name = "reload_extra_files"
  742. action = "append"
  743. section = "Debugging"
  744. cli = ["--reload-extra-file"]
  745. meta = "FILES"
  746. validator = validate_list_of_existing_files
  747. default = []
  748. desc = """\
  749. Extends :ref:`reload` option to also watch and reload on additional files
  750. (e.g., templates, configurations, specifications, etc.).
  751. .. versionadded:: 19.8
  752. """
  753. class Spew(Setting):
  754. name = "spew"
  755. section = "Debugging"
  756. cli = ["--spew"]
  757. validator = validate_bool
  758. action = "store_true"
  759. default = False
  760. desc = """\
  761. Install a trace function that spews every line executed by the server.
  762. This is the nuclear option.
  763. """
  764. class ConfigCheck(Setting):
  765. name = "check_config"
  766. section = "Debugging"
  767. cli = ["--check-config"]
  768. validator = validate_bool
  769. action = "store_true"
  770. default = False
  771. desc = """\
  772. Check the configuration and exit. The exit status is 0 if the
  773. configuration is correct, and 1 if the configuration is incorrect.
  774. """
  775. class PrintConfig(Setting):
  776. name = "print_config"
  777. section = "Debugging"
  778. cli = ["--print-config"]
  779. validator = validate_bool
  780. action = "store_true"
  781. default = False
  782. desc = """\
  783. Print the configuration settings as fully resolved. Implies :ref:`check-config`.
  784. """
  785. class PreloadApp(Setting):
  786. name = "preload_app"
  787. section = "Server Mechanics"
  788. cli = ["--preload"]
  789. validator = validate_bool
  790. action = "store_true"
  791. default = False
  792. desc = """\
  793. Load application code before the worker processes are forked.
  794. By preloading an application you can save some RAM resources as well as
  795. speed up server boot times. Although, if you defer application loading
  796. to each worker process, you can reload your application code easily by
  797. restarting workers.
  798. """
  799. class Sendfile(Setting):
  800. name = "sendfile"
  801. section = "Server Mechanics"
  802. cli = ["--no-sendfile"]
  803. validator = validate_bool
  804. action = "store_const"
  805. const = False
  806. desc = """\
  807. Disables the use of ``sendfile()``.
  808. If not set, the value of the ``SENDFILE`` environment variable is used
  809. to enable or disable its usage.
  810. .. versionadded:: 19.2
  811. .. versionchanged:: 19.4
  812. Swapped ``--sendfile`` with ``--no-sendfile`` to actually allow
  813. disabling.
  814. .. versionchanged:: 19.6
  815. added support for the ``SENDFILE`` environment variable
  816. """
  817. class ReusePort(Setting):
  818. name = "reuse_port"
  819. section = "Server Mechanics"
  820. cli = ["--reuse-port"]
  821. validator = validate_bool
  822. action = "store_true"
  823. default = False
  824. desc = """\
  825. Set the ``SO_REUSEPORT`` flag on the listening socket.
  826. .. versionadded:: 19.8
  827. """
  828. class Chdir(Setting):
  829. name = "chdir"
  830. section = "Server Mechanics"
  831. cli = ["--chdir"]
  832. validator = validate_chdir
  833. default = util.getcwd()
  834. default_doc = "``'.'``"
  835. desc = """\
  836. Change directory to specified directory before loading apps.
  837. """
  838. class Daemon(Setting):
  839. name = "daemon"
  840. section = "Server Mechanics"
  841. cli = ["-D", "--daemon"]
  842. validator = validate_bool
  843. action = "store_true"
  844. default = False
  845. desc = """\
  846. Daemonize the Gunicorn process.
  847. Detaches the server from the controlling terminal and enters the
  848. background.
  849. """
  850. class Env(Setting):
  851. name = "raw_env"
  852. action = "append"
  853. section = "Server Mechanics"
  854. cli = ["-e", "--env"]
  855. meta = "ENV"
  856. validator = validate_list_string
  857. default = []
  858. desc = """\
  859. Set environment variables in the execution environment.
  860. Should be a list of strings in the ``key=value`` format.
  861. For example on the command line:
  862. .. code-block:: console
  863. $ gunicorn -b 127.0.0.1:8000 --env FOO=1 test:app
  864. Or in the configuration file:
  865. .. code-block:: python
  866. raw_env = ["FOO=1"]
  867. """
  868. class Pidfile(Setting):
  869. name = "pidfile"
  870. section = "Server Mechanics"
  871. cli = ["-p", "--pid"]
  872. meta = "FILE"
  873. validator = validate_string
  874. default = None
  875. desc = """\
  876. A filename to use for the PID file.
  877. If not set, no PID file will be written.
  878. """
  879. class WorkerTmpDir(Setting):
  880. name = "worker_tmp_dir"
  881. section = "Server Mechanics"
  882. cli = ["--worker-tmp-dir"]
  883. meta = "DIR"
  884. validator = validate_string
  885. default = None
  886. desc = """\
  887. A directory to use for the worker heartbeat temporary file.
  888. If not set, the default temporary directory will be used.
  889. .. note::
  890. The current heartbeat system involves calling ``os.fchmod`` on
  891. temporary file handlers and may block a worker for arbitrary time
  892. if the directory is on a disk-backed filesystem.
  893. See :ref:`blocking-os-fchmod` for more detailed information
  894. and a solution for avoiding this problem.
  895. """
  896. class User(Setting):
  897. name = "user"
  898. section = "Server Mechanics"
  899. cli = ["-u", "--user"]
  900. meta = "USER"
  901. validator = validate_user
  902. default = os.geteuid()
  903. default_doc = "``os.geteuid()``"
  904. desc = """\
  905. Switch worker processes to run as this user.
  906. A valid user id (as an integer) or the name of a user that can be
  907. retrieved with a call to ``pwd.getpwnam(value)`` or ``None`` to not
  908. change the worker process user.
  909. """
  910. class Group(Setting):
  911. name = "group"
  912. section = "Server Mechanics"
  913. cli = ["-g", "--group"]
  914. meta = "GROUP"
  915. validator = validate_group
  916. default = os.getegid()
  917. default_doc = "``os.getegid()``"
  918. desc = """\
  919. Switch worker process to run as this group.
  920. A valid group id (as an integer) or the name of a user that can be
  921. retrieved with a call to ``pwd.getgrnam(value)`` or ``None`` to not
  922. change the worker processes group.
  923. """
  924. class Umask(Setting):
  925. name = "umask"
  926. section = "Server Mechanics"
  927. cli = ["-m", "--umask"]
  928. meta = "INT"
  929. validator = validate_pos_int
  930. type = auto_int
  931. default = 0
  932. desc = """\
  933. A bit mask for the file mode on files written by Gunicorn.
  934. Note that this affects unix socket permissions.
  935. A valid value for the ``os.umask(mode)`` call or a string compatible
  936. with ``int(value, 0)`` (``0`` means Python guesses the base, so values
  937. like ``0``, ``0xFF``, ``0022`` are valid for decimal, hex, and octal
  938. representations)
  939. """
  940. class Initgroups(Setting):
  941. name = "initgroups"
  942. section = "Server Mechanics"
  943. cli = ["--initgroups"]
  944. validator = validate_bool
  945. action = 'store_true'
  946. default = False
  947. desc = """\
  948. If true, set the worker process's group access list with all of the
  949. groups of which the specified username is a member, plus the specified
  950. group id.
  951. .. versionadded:: 19.7
  952. """
  953. class TmpUploadDir(Setting):
  954. name = "tmp_upload_dir"
  955. section = "Server Mechanics"
  956. meta = "DIR"
  957. validator = validate_string
  958. default = None
  959. desc = """\
  960. Directory to store temporary request data as they are read.
  961. This may disappear in the near future.
  962. This path should be writable by the process permissions set for Gunicorn
  963. workers. If not specified, Gunicorn will choose a system generated
  964. temporary directory.
  965. """
  966. class SecureSchemeHeader(Setting):
  967. name = "secure_scheme_headers"
  968. section = "Server Mechanics"
  969. validator = validate_dict
  970. default = {
  971. "X-FORWARDED-PROTOCOL": "ssl",
  972. "X-FORWARDED-PROTO": "https",
  973. "X-FORWARDED-SSL": "on"
  974. }
  975. desc = """\
  976. A dictionary containing headers and values that the front-end proxy
  977. uses to indicate HTTPS requests. If the source IP is permitted by
  978. :ref:`forwarded-allow-ips` (below), *and* at least one request header matches
  979. a key-value pair listed in this dictionary, then Gunicorn will set
  980. ``wsgi.url_scheme`` to ``https``, so your application can tell that the
  981. request is secure.
  982. If the other headers listed in this dictionary are not present in the request, they will be ignored,
  983. but if the other headers are present and do not match the provided values, then
  984. the request will fail to parse. See the note below for more detailed examples of this behaviour.
  985. The dictionary should map upper-case header names to exact string
  986. values. The value comparisons are case-sensitive, unlike the header
  987. names, so make sure they're exactly what your front-end proxy sends
  988. when handling HTTPS requests.
  989. It is important that your front-end proxy configuration ensures that
  990. the headers defined here can not be passed directly from the client.
  991. """
  992. class ForwardedAllowIPS(Setting):
  993. name = "forwarded_allow_ips"
  994. section = "Server Mechanics"
  995. cli = ["--forwarded-allow-ips"]
  996. meta = "STRING"
  997. validator = validate_string_to_addr_list
  998. default = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1,::1")
  999. desc = """\
  1000. Front-end's IPs from which allowed to handle set secure headers.
  1001. (comma separated).
  1002. Set to ``*`` to disable checking of front-end IPs. This is useful for setups
  1003. where you don't know in advance the IP address of front-end, but
  1004. instead have ensured via other means that only your
  1005. authorized front-ends can access Gunicorn.
  1006. By default, the value of the ``FORWARDED_ALLOW_IPS`` environment
  1007. variable. If it is not defined, the default is ``"127.0.0.1,::1"``.
  1008. .. note::
  1009. This option does not affect UNIX socket connections. Connections not associated with
  1010. an IP address are treated as allowed, unconditionally.
  1011. .. note::
  1012. The interplay between the request headers, the value of ``forwarded_allow_ips``, and the value of
  1013. ``secure_scheme_headers`` is complex. Various scenarios are documented below to further elaborate.
  1014. In each case, we have a request from the remote address 134.213.44.18, and the default value of
  1015. ``secure_scheme_headers``:
  1016. .. code::
  1017. secure_scheme_headers = {
  1018. 'X-FORWARDED-PROTOCOL': 'ssl',
  1019. 'X-FORWARDED-PROTO': 'https',
  1020. 'X-FORWARDED-SSL': 'on'
  1021. }
  1022. .. list-table::
  1023. :header-rows: 1
  1024. :align: center
  1025. :widths: auto
  1026. * - ``forwarded-allow-ips``
  1027. - Secure Request Headers
  1028. - Result
  1029. - Explanation
  1030. * - .. code::
  1031. ["127.0.0.1"]
  1032. - .. code::
  1033. X-Forwarded-Proto: https
  1034. - .. code::
  1035. wsgi.url_scheme = "http"
  1036. - IP address was not allowed
  1037. * - .. code::
  1038. "*"
  1039. - <none>
  1040. - .. code::
  1041. wsgi.url_scheme = "http"
  1042. - IP address allowed, but no secure headers provided
  1043. * - .. code::
  1044. "*"
  1045. - .. code::
  1046. X-Forwarded-Proto: https
  1047. - .. code::
  1048. wsgi.url_scheme = "https"
  1049. - IP address allowed, one request header matched
  1050. * - .. code::
  1051. ["134.213.44.18"]
  1052. - .. code::
  1053. X-Forwarded-Ssl: on
  1054. X-Forwarded-Proto: http
  1055. - ``InvalidSchemeHeaders()`` raised
  1056. - IP address allowed, but the two secure headers disagreed on if HTTPS was used
  1057. """
  1058. class AccessLog(Setting):
  1059. name = "accesslog"
  1060. section = "Logging"
  1061. cli = ["--access-logfile"]
  1062. meta = "FILE"
  1063. validator = validate_string
  1064. default = None
  1065. desc = """\
  1066. The Access log file to write to.
  1067. ``'-'`` means log to stdout.
  1068. """
  1069. class DisableRedirectAccessToSyslog(Setting):
  1070. name = "disable_redirect_access_to_syslog"
  1071. section = "Logging"
  1072. cli = ["--disable-redirect-access-to-syslog"]
  1073. validator = validate_bool
  1074. action = 'store_true'
  1075. default = False
  1076. desc = """\
  1077. Disable redirect access logs to syslog.
  1078. .. versionadded:: 19.8
  1079. """
  1080. class AccessLogFormat(Setting):
  1081. name = "access_log_format"
  1082. section = "Logging"
  1083. cli = ["--access-logformat"]
  1084. meta = "STRING"
  1085. validator = validate_string
  1086. default = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
  1087. desc = """\
  1088. The access log format.
  1089. =========== ===========
  1090. Identifier Description
  1091. =========== ===========
  1092. h remote address
  1093. l ``'-'``
  1094. u user name (if HTTP Basic auth used)
  1095. t date of the request
  1096. r status line (e.g. ``GET / HTTP/1.1``)
  1097. m request method
  1098. U URL path without query string
  1099. q query string
  1100. H protocol
  1101. s status
  1102. B response length
  1103. b response length or ``'-'`` (CLF format)
  1104. f referrer (note: header is ``referer``)
  1105. a user agent
  1106. T request time in seconds
  1107. M request time in milliseconds
  1108. D request time in microseconds
  1109. L request time in decimal seconds
  1110. p process ID
  1111. {header}i request header
  1112. {header}o response header
  1113. {variable}e environment variable
  1114. =========== ===========
  1115. Use lowercase for header and environment variable names, and put
  1116. ``{...}x`` names inside ``%(...)s``. For example::
  1117. %({x-forwarded-for}i)s
  1118. """
  1119. class ErrorLog(Setting):
  1120. name = "errorlog"
  1121. section = "Logging"
  1122. cli = ["--error-logfile", "--log-file"]
  1123. meta = "FILE"
  1124. validator = validate_string
  1125. default = '-'
  1126. desc = """\
  1127. The Error log file to write to.
  1128. Using ``'-'`` for FILE makes gunicorn log to stderr.
  1129. .. versionchanged:: 19.2
  1130. Log to stderr by default.
  1131. """
  1132. class Loglevel(Setting):
  1133. name = "loglevel"
  1134. section = "Logging"
  1135. cli = ["--log-level"]
  1136. meta = "LEVEL"
  1137. validator = validate_string
  1138. default = "info"
  1139. desc = """\
  1140. The granularity of Error log outputs.
  1141. Valid level names are:
  1142. * ``'debug'``
  1143. * ``'info'``
  1144. * ``'warning'``
  1145. * ``'error'``
  1146. * ``'critical'``
  1147. """
  1148. class CaptureOutput(Setting):
  1149. name = "capture_output"
  1150. section = "Logging"
  1151. cli = ["--capture-output"]
  1152. validator = validate_bool
  1153. action = 'store_true'
  1154. default = False
  1155. desc = """\
  1156. Redirect stdout/stderr to specified file in :ref:`errorlog`.
  1157. .. versionadded:: 19.6
  1158. """
  1159. class LoggerClass(Setting):
  1160. name = "logger_class"
  1161. section = "Logging"
  1162. cli = ["--logger-class"]
  1163. meta = "STRING"
  1164. validator = validate_class
  1165. default = "gunicorn.glogging.Logger"
  1166. desc = """\
  1167. The logger you want to use to log events in Gunicorn.
  1168. The default class (``gunicorn.glogging.Logger``) handles most
  1169. normal usages in logging. It provides error and access logging.
  1170. You can provide your own logger by giving Gunicorn a Python path to a
  1171. class that quacks like ``gunicorn.glogging.Logger``.
  1172. """
  1173. class LogConfig(Setting):
  1174. name = "logconfig"
  1175. section = "Logging"
  1176. cli = ["--log-config"]
  1177. meta = "FILE"
  1178. validator = validate_string
  1179. default = None
  1180. desc = """\
  1181. The log config file to use.
  1182. Gunicorn uses the standard Python logging module's Configuration
  1183. file format.
  1184. """
  1185. class LogConfigDict(Setting):
  1186. name = "logconfig_dict"
  1187. section = "Logging"
  1188. validator = validate_dict
  1189. default = {}
  1190. desc = """\
  1191. The log config dictionary to use, using the standard Python
  1192. logging module's dictionary configuration format. This option
  1193. takes precedence over the :ref:`logconfig` and :ref:`logconfig-json` options,
  1194. which uses the older file configuration format and JSON
  1195. respectively.
  1196. Format: https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig
  1197. For more context you can look at the default configuration dictionary for logging,
  1198. which can be found at ``gunicorn.glogging.CONFIG_DEFAULTS``.
  1199. .. versionadded:: 19.8
  1200. """
  1201. class LogConfigJson(Setting):
  1202. name = "logconfig_json"
  1203. section = "Logging"
  1204. cli = ["--log-config-json"]
  1205. meta = "FILE"
  1206. validator = validate_string
  1207. default = None
  1208. desc = """\
  1209. The log config to read config from a JSON file
  1210. Format: https://docs.python.org/3/library/logging.config.html#logging.config.jsonConfig
  1211. .. versionadded:: 20.0
  1212. """
  1213. class SyslogTo(Setting):
  1214. name = "syslog_addr"
  1215. section = "Logging"
  1216. cli = ["--log-syslog-to"]
  1217. meta = "SYSLOG_ADDR"
  1218. validator = validate_string
  1219. if PLATFORM == "darwin":
  1220. default = "unix:///var/run/syslog"
  1221. elif PLATFORM in ('freebsd', 'dragonfly', ):
  1222. default = "unix:///var/run/log"
  1223. elif PLATFORM == "openbsd":
  1224. default = "unix:///dev/log"
  1225. else:
  1226. default = "udp://localhost:514"
  1227. desc = """\
  1228. Address to send syslog messages.
  1229. Address is a string of the form:
  1230. * ``unix://PATH#TYPE`` : for unix domain socket. ``TYPE`` can be ``stream``
  1231. for the stream driver or ``dgram`` for the dgram driver.
  1232. ``stream`` is the default.
  1233. * ``udp://HOST:PORT`` : for UDP sockets
  1234. * ``tcp://HOST:PORT`` : for TCP sockets
  1235. """
  1236. class Syslog(Setting):
  1237. name = "syslog"
  1238. section = "Logging"
  1239. cli = ["--log-syslog"]
  1240. validator = validate_bool
  1241. action = 'store_true'
  1242. default = False
  1243. desc = """\
  1244. Send *Gunicorn* logs to syslog.
  1245. .. versionchanged:: 19.8
  1246. You can now disable sending access logs by using the
  1247. :ref:`disable-redirect-access-to-syslog` setting.
  1248. """
  1249. class SyslogPrefix(Setting):
  1250. name = "syslog_prefix"
  1251. section = "Logging"
  1252. cli = ["--log-syslog-prefix"]
  1253. meta = "SYSLOG_PREFIX"
  1254. validator = validate_string
  1255. default = None
  1256. desc = """\
  1257. Makes Gunicorn use the parameter as program-name in the syslog entries.
  1258. All entries will be prefixed by ``gunicorn.<prefix>``. By default the
  1259. program name is the name of the process.
  1260. """
  1261. class SyslogFacility(Setting):
  1262. name = "syslog_facility"
  1263. section = "Logging"
  1264. cli = ["--log-syslog-facility"]
  1265. meta = "SYSLOG_FACILITY"
  1266. validator = validate_string
  1267. default = "user"
  1268. desc = """\
  1269. Syslog facility name
  1270. """
  1271. class EnableStdioInheritance(Setting):
  1272. name = "enable_stdio_inheritance"
  1273. section = "Logging"
  1274. cli = ["-R", "--enable-stdio-inheritance"]
  1275. validator = validate_bool
  1276. default = False
  1277. action = "store_true"
  1278. desc = """\
  1279. Enable stdio inheritance.
  1280. Enable inheritance for stdio file descriptors in daemon mode.
  1281. Note: To disable the Python stdout buffering, you can to set the user
  1282. environment variable ``PYTHONUNBUFFERED`` .
  1283. """
  1284. # statsD monitoring
  1285. class StatsdHost(Setting):
  1286. name = "statsd_host"
  1287. section = "Logging"
  1288. cli = ["--statsd-host"]
  1289. meta = "STATSD_ADDR"
  1290. default = None
  1291. validator = validate_statsd_address
  1292. desc = """\
  1293. The address of the StatsD server to log to.
  1294. Address is a string of the form:
  1295. * ``unix://PATH`` : for a unix domain socket.
  1296. * ``HOST:PORT`` : for a network address
  1297. .. versionadded:: 19.1
  1298. """
  1299. # Datadog Statsd (dogstatsd) tags. https://docs.datadoghq.com/developers/dogstatsd/
  1300. class DogstatsdTags(Setting):
  1301. name = "dogstatsd_tags"
  1302. section = "Logging"
  1303. cli = ["--dogstatsd-tags"]
  1304. meta = "DOGSTATSD_TAGS"
  1305. default = ""
  1306. validator = validate_string
  1307. desc = """\
  1308. A comma-delimited list of datadog statsd (dogstatsd) tags to append to
  1309. statsd metrics.
  1310. .. versionadded:: 20
  1311. """
  1312. class StatsdPrefix(Setting):
  1313. name = "statsd_prefix"
  1314. section = "Logging"
  1315. cli = ["--statsd-prefix"]
  1316. meta = "STATSD_PREFIX"
  1317. default = ""
  1318. validator = validate_string
  1319. desc = """\
  1320. Prefix to use when emitting statsd metrics (a trailing ``.`` is added,
  1321. if not provided).
  1322. .. versionadded:: 19.2
  1323. """
  1324. class Procname(Setting):
  1325. name = "proc_name"
  1326. section = "Process Naming"
  1327. cli = ["-n", "--name"]
  1328. meta = "STRING"
  1329. validator = validate_string
  1330. default = None
  1331. desc = """\
  1332. A base to use with setproctitle for process naming.
  1333. This affects things like ``ps`` and ``top``. If you're going to be
  1334. running more than one instance of Gunicorn you'll probably want to set a
  1335. name to tell them apart. This requires that you install the setproctitle
  1336. module.
  1337. If not set, the *default_proc_name* setting will be used.
  1338. """
  1339. class DefaultProcName(Setting):
  1340. name = "default_proc_name"
  1341. section = "Process Naming"
  1342. validator = validate_string
  1343. default = "gunicorn"
  1344. desc = """\
  1345. Internal setting that is adjusted for each type of application.
  1346. """
  1347. class PythonPath(Setting):
  1348. name = "pythonpath"
  1349. section = "Server Mechanics"
  1350. cli = ["--pythonpath"]
  1351. meta = "STRING"
  1352. validator = validate_string
  1353. default = None
  1354. desc = """\
  1355. A comma-separated list of directories to add to the Python path.
  1356. e.g.
  1357. ``'/home/djangoprojects/myproject,/home/python/mylibrary'``.
  1358. """
  1359. class Paste(Setting):
  1360. name = "paste"
  1361. section = "Server Mechanics"
  1362. cli = ["--paste", "--paster"]
  1363. meta = "STRING"
  1364. validator = validate_string
  1365. default = None
  1366. desc = """\
  1367. Load a PasteDeploy config file. The argument may contain a ``#``
  1368. symbol followed by the name of an app section from the config file,
  1369. e.g. ``production.ini#admin``.
  1370. At this time, using alternate server blocks is not supported. Use the
  1371. command line arguments to control server configuration instead.
  1372. """
  1373. class OnStarting(Setting):
  1374. name = "on_starting"
  1375. section = "Server Hooks"
  1376. validator = validate_callable(1)
  1377. type = callable
  1378. def on_starting(server):
  1379. pass
  1380. default = staticmethod(on_starting)
  1381. desc = """\
  1382. Called just before the master process is initialized.
  1383. The callable needs to accept a single instance variable for the Arbiter.
  1384. """
  1385. class OnReload(Setting):
  1386. name = "on_reload"
  1387. section = "Server Hooks"
  1388. validator = validate_callable(1)
  1389. type = callable
  1390. def on_reload(server):
  1391. pass
  1392. default = staticmethod(on_reload)
  1393. desc = """\
  1394. Called to recycle workers during a reload via SIGHUP.
  1395. The callable needs to accept a single instance variable for the Arbiter.
  1396. """
  1397. class WhenReady(Setting):
  1398. name = "when_ready"
  1399. section = "Server Hooks"
  1400. validator = validate_callable(1)
  1401. type = callable
  1402. def when_ready(server):
  1403. pass
  1404. default = staticmethod(when_ready)
  1405. desc = """\
  1406. Called just after the server is started.
  1407. The callable needs to accept a single instance variable for the Arbiter.
  1408. """
  1409. class Prefork(Setting):
  1410. name = "pre_fork"
  1411. section = "Server Hooks"
  1412. validator = validate_callable(2)
  1413. type = callable
  1414. def pre_fork(server, worker):
  1415. pass
  1416. default = staticmethod(pre_fork)
  1417. desc = """\
  1418. Called just before a worker is forked.
  1419. The callable needs to accept two instance variables for the Arbiter and
  1420. new Worker.
  1421. """
  1422. class Postfork(Setting):
  1423. name = "post_fork"
  1424. section = "Server Hooks"
  1425. validator = validate_callable(2)
  1426. type = callable
  1427. def post_fork(server, worker):
  1428. pass
  1429. default = staticmethod(post_fork)
  1430. desc = """\
  1431. Called just after a worker has been forked.
  1432. The callable needs to accept two instance variables for the Arbiter and
  1433. new Worker.
  1434. """
  1435. class PostWorkerInit(Setting):
  1436. name = "post_worker_init"
  1437. section = "Server Hooks"
  1438. validator = validate_callable(1)
  1439. type = callable
  1440. def post_worker_init(worker):
  1441. pass
  1442. default = staticmethod(post_worker_init)
  1443. desc = """\
  1444. Called just after a worker has initialized the application.
  1445. The callable needs to accept one instance variable for the initialized
  1446. Worker.
  1447. """
  1448. class WorkerInt(Setting):
  1449. name = "worker_int"
  1450. section = "Server Hooks"
  1451. validator = validate_callable(1)
  1452. type = callable
  1453. def worker_int(worker):
  1454. pass
  1455. default = staticmethod(worker_int)
  1456. desc = """\
  1457. Called just after a worker exited on SIGINT or SIGQUIT.
  1458. The callable needs to accept one instance variable for the initialized
  1459. Worker.
  1460. """
  1461. class WorkerAbort(Setting):
  1462. name = "worker_abort"
  1463. section = "Server Hooks"
  1464. validator = validate_callable(1)
  1465. type = callable
  1466. def worker_abort(worker):
  1467. pass
  1468. default = staticmethod(worker_abort)
  1469. desc = """\
  1470. Called when a worker received the SIGABRT signal.
  1471. This call generally happens on timeout.
  1472. The callable needs to accept one instance variable for the initialized
  1473. Worker.
  1474. """
  1475. class PreExec(Setting):
  1476. name = "pre_exec"
  1477. section = "Server Hooks"
  1478. validator = validate_callable(1)
  1479. type = callable
  1480. def pre_exec(server):
  1481. pass
  1482. default = staticmethod(pre_exec)
  1483. desc = """\
  1484. Called just before a new master process is forked.
  1485. The callable needs to accept a single instance variable for the Arbiter.
  1486. """
  1487. class PreRequest(Setting):
  1488. name = "pre_request"
  1489. section = "Server Hooks"
  1490. validator = validate_callable(2)
  1491. type = callable
  1492. def pre_request(worker, req):
  1493. worker.log.debug("%s %s", req.method, req.path)
  1494. default = staticmethod(pre_request)
  1495. desc = """\
  1496. Called just before a worker processes the request.
  1497. The callable needs to accept two instance variables for the Worker and
  1498. the Request.
  1499. """
  1500. class PostRequest(Setting):
  1501. name = "post_request"
  1502. section = "Server Hooks"
  1503. validator = validate_post_request
  1504. type = callable
  1505. def post_request(worker, req, environ, resp):
  1506. pass
  1507. default = staticmethod(post_request)
  1508. desc = """\
  1509. Called after a worker processes the request.
  1510. The callable needs to accept two instance variables for the Worker and
  1511. the Request.
  1512. """
  1513. class ChildExit(Setting):
  1514. name = "child_exit"
  1515. section = "Server Hooks"
  1516. validator = validate_callable(2)
  1517. type = callable
  1518. def child_exit(server, worker):
  1519. pass
  1520. default = staticmethod(child_exit)
  1521. desc = """\
  1522. Called just after a worker has been exited, in the master process.
  1523. The callable needs to accept two instance variables for the Arbiter and
  1524. the just-exited Worker.
  1525. .. versionadded:: 19.7
  1526. """
  1527. class WorkerExit(Setting):
  1528. name = "worker_exit"
  1529. section = "Server Hooks"
  1530. validator = validate_callable(2)
  1531. type = callable
  1532. def worker_exit(server, worker):
  1533. pass
  1534. default = staticmethod(worker_exit)
  1535. desc = """\
  1536. Called just after a worker has been exited, in the worker process.
  1537. The callable needs to accept two instance variables for the Arbiter and
  1538. the just-exited Worker.
  1539. """
  1540. class NumWorkersChanged(Setting):
  1541. name = "nworkers_changed"
  1542. section = "Server Hooks"
  1543. validator = validate_callable(3)
  1544. type = callable
  1545. def nworkers_changed(server, new_value, old_value):
  1546. pass
  1547. default = staticmethod(nworkers_changed)
  1548. desc = """\
  1549. Called just after *num_workers* has been changed.
  1550. The callable needs to accept an instance variable of the Arbiter and
  1551. two integers of number of workers after and before change.
  1552. If the number of workers is set for the first time, *old_value* would
  1553. be ``None``.
  1554. """
  1555. class OnExit(Setting):
  1556. name = "on_exit"
  1557. section = "Server Hooks"
  1558. validator = validate_callable(1)
  1559. def on_exit(server):
  1560. pass
  1561. default = staticmethod(on_exit)
  1562. desc = """\
  1563. Called just before exiting Gunicorn.
  1564. The callable needs to accept a single instance variable for the Arbiter.
  1565. """
  1566. class NewSSLContext(Setting):
  1567. name = "ssl_context"
  1568. section = "Server Hooks"
  1569. validator = validate_callable(2)
  1570. type = callable
  1571. def ssl_context(config, default_ssl_context_factory):
  1572. return default_ssl_context_factory()
  1573. default = staticmethod(ssl_context)
  1574. desc = """\
  1575. Called when SSLContext is needed.
  1576. Allows customizing SSL context.
  1577. The callable needs to accept an instance variable for the Config and
  1578. a factory function that returns default SSLContext which is initialized
  1579. with certificates, private key, cert_reqs, and ciphers according to
  1580. config and can be further customized by the callable.
  1581. The callable needs to return SSLContext object.
  1582. Following example shows a configuration file that sets the minimum TLS version to 1.3:
  1583. .. code-block:: python
  1584. def ssl_context(conf, default_ssl_context_factory):
  1585. import ssl
  1586. context = default_ssl_context_factory()
  1587. context.minimum_version = ssl.TLSVersion.TLSv1_3
  1588. return context
  1589. .. versionadded:: 21.0
  1590. """
  1591. class ProxyProtocol(Setting):
  1592. name = "proxy_protocol"
  1593. section = "Server Mechanics"
  1594. cli = ["--proxy-protocol"]
  1595. validator = validate_bool
  1596. default = False
  1597. action = "store_true"
  1598. desc = """\
  1599. Enable detect PROXY protocol (PROXY mode).
  1600. Allow using HTTP and Proxy together. It may be useful for work with
  1601. stunnel as HTTPS frontend and Gunicorn as HTTP server.
  1602. PROXY protocol: http://haproxy.1wt.eu/download/1.5/doc/proxy-protocol.txt
  1603. Example for stunnel config::
  1604. [https]
  1605. protocol = proxy
  1606. accept = 443
  1607. connect = 80
  1608. cert = /etc/ssl/certs/stunnel.pem
  1609. key = /etc/ssl/certs/stunnel.key
  1610. """
  1611. class ProxyAllowFrom(Setting):
  1612. name = "proxy_allow_ips"
  1613. section = "Server Mechanics"
  1614. cli = ["--proxy-allow-from"]
  1615. validator = validate_string_to_addr_list
  1616. default = "127.0.0.1,::1"
  1617. desc = """\
  1618. Front-end's IPs from which allowed accept proxy requests (comma separated).
  1619. Set to ``*`` to disable checking of front-end IPs. This is useful for setups
  1620. where you don't know in advance the IP address of front-end, but
  1621. instead have ensured via other means that only your
  1622. authorized front-ends can access Gunicorn.
  1623. .. note::
  1624. This option does not affect UNIX socket connections. Connections not associated with
  1625. an IP address are treated as allowed, unconditionally.
  1626. """
  1627. class KeyFile(Setting):
  1628. name = "keyfile"
  1629. section = "SSL"
  1630. cli = ["--keyfile"]
  1631. meta = "FILE"
  1632. validator = validate_string
  1633. default = None
  1634. desc = """\
  1635. SSL key file
  1636. """
  1637. class CertFile(Setting):
  1638. name = "certfile"
  1639. section = "SSL"
  1640. cli = ["--certfile"]
  1641. meta = "FILE"
  1642. validator = validate_string
  1643. default = None
  1644. desc = """\
  1645. SSL certificate file
  1646. """
  1647. class SSLVersion(Setting):
  1648. name = "ssl_version"
  1649. section = "SSL"
  1650. cli = ["--ssl-version"]
  1651. validator = validate_ssl_version
  1652. if hasattr(ssl, "PROTOCOL_TLS"):
  1653. default = ssl.PROTOCOL_TLS
  1654. else:
  1655. default = ssl.PROTOCOL_SSLv23
  1656. default = ssl.PROTOCOL_SSLv23
  1657. desc = """\
  1658. SSL version to use (see stdlib ssl module's).
  1659. .. deprecated:: 21.0
  1660. The option is deprecated and it is currently ignored. Use :ref:`ssl-context` instead.
  1661. ============= ============
  1662. --ssl-version Description
  1663. ============= ============
  1664. SSLv3 SSLv3 is not-secure and is strongly discouraged.
  1665. SSLv23 Alias for TLS. Deprecated in Python 3.6, use TLS.
  1666. TLS Negotiate highest possible version between client/server.
  1667. Can yield SSL. (Python 3.6+)
  1668. TLSv1 TLS 1.0
  1669. TLSv1_1 TLS 1.1 (Python 3.4+)
  1670. TLSv1_2 TLS 1.2 (Python 3.4+)
  1671. TLS_SERVER Auto-negotiate the highest protocol version like TLS,
  1672. but only support server-side SSLSocket connections.
  1673. (Python 3.6+)
  1674. ============= ============
  1675. .. versionchanged:: 19.7
  1676. The default value has been changed from ``ssl.PROTOCOL_TLSv1`` to
  1677. ``ssl.PROTOCOL_SSLv23``.
  1678. .. versionchanged:: 20.0
  1679. This setting now accepts string names based on ``ssl.PROTOCOL_``
  1680. constants.
  1681. .. versionchanged:: 20.0.1
  1682. The default value has been changed from ``ssl.PROTOCOL_SSLv23`` to
  1683. ``ssl.PROTOCOL_TLS`` when Python >= 3.6 .
  1684. """
  1685. class CertReqs(Setting):
  1686. name = "cert_reqs"
  1687. section = "SSL"
  1688. cli = ["--cert-reqs"]
  1689. validator = validate_pos_int
  1690. default = ssl.CERT_NONE
  1691. desc = """\
  1692. Whether client certificate is required (see stdlib ssl module's)
  1693. =========== ===========================
  1694. --cert-reqs Description
  1695. =========== ===========================
  1696. `0` no client verification
  1697. `1` ssl.CERT_OPTIONAL
  1698. `2` ssl.CERT_REQUIRED
  1699. =========== ===========================
  1700. """
  1701. class CACerts(Setting):
  1702. name = "ca_certs"
  1703. section = "SSL"
  1704. cli = ["--ca-certs"]
  1705. meta = "FILE"
  1706. validator = validate_string
  1707. default = None
  1708. desc = """\
  1709. CA certificates file
  1710. """
  1711. class SuppressRaggedEOFs(Setting):
  1712. name = "suppress_ragged_eofs"
  1713. section = "SSL"
  1714. cli = ["--suppress-ragged-eofs"]
  1715. action = "store_true"
  1716. default = True
  1717. validator = validate_bool
  1718. desc = """\
  1719. Suppress ragged EOFs (see stdlib ssl module's)
  1720. """
  1721. class DoHandshakeOnConnect(Setting):
  1722. name = "do_handshake_on_connect"
  1723. section = "SSL"
  1724. cli = ["--do-handshake-on-connect"]
  1725. validator = validate_bool
  1726. action = "store_true"
  1727. default = False
  1728. desc = """\
  1729. Whether to perform SSL handshake on socket connect (see stdlib ssl module's)
  1730. """
  1731. class Ciphers(Setting):
  1732. name = "ciphers"
  1733. section = "SSL"
  1734. cli = ["--ciphers"]
  1735. validator = validate_string
  1736. default = None
  1737. desc = """\
  1738. SSL Cipher suite to use, in the format of an OpenSSL cipher list.
  1739. By default we use the default cipher list from Python's ``ssl`` module,
  1740. which contains ciphers considered strong at the time of each Python
  1741. release.
  1742. As a recommended alternative, the Open Web App Security Project (OWASP)
  1743. offers `a vetted set of strong cipher strings rated A+ to C-
  1744. <https://www.owasp.org/index.php/TLS_Cipher_String_Cheat_Sheet>`_.
  1745. OWASP provides details on user-agent compatibility at each security level.
  1746. See the `OpenSSL Cipher List Format Documentation
  1747. <https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT>`_
  1748. for details on the format of an OpenSSL cipher list.
  1749. """
  1750. class PasteGlobalConf(Setting):
  1751. name = "raw_paste_global_conf"
  1752. action = "append"
  1753. section = "Server Mechanics"
  1754. cli = ["--paste-global"]
  1755. meta = "CONF"
  1756. validator = validate_list_string
  1757. default = []
  1758. desc = """\
  1759. Set a PasteDeploy global config variable in ``key=value`` form.
  1760. The option can be specified multiple times.
  1761. The variables are passed to the PasteDeploy entrypoint. Example::
  1762. $ gunicorn -b 127.0.0.1:8000 --paste development.ini --paste-global FOO=1 --paste-global BAR=2
  1763. .. versionadded:: 19.7
  1764. """
  1765. class PermitObsoleteFolding(Setting):
  1766. name = "permit_obsolete_folding"
  1767. section = "Server Mechanics"
  1768. cli = ["--permit-obsolete-folding"]
  1769. validator = validate_bool
  1770. action = "store_true"
  1771. default = False
  1772. desc = """\
  1773. Permit requests employing obsolete HTTP line folding mechanism
  1774. The folding mechanism was deprecated by rfc7230 Section 3.2.4 and will not be
  1775. employed in HTTP request headers from standards-compliant HTTP clients.
  1776. This option is provided to diagnose backwards-incompatible changes.
  1777. Use with care and only if necessary. Temporary; the precise effect of this option may
  1778. change in a future version, or it may be removed altogether.
  1779. .. versionadded:: 23.0.0
  1780. """
  1781. class StripHeaderSpaces(Setting):
  1782. name = "strip_header_spaces"
  1783. section = "Server Mechanics"
  1784. cli = ["--strip-header-spaces"]
  1785. validator = validate_bool
  1786. action = "store_true"
  1787. default = False
  1788. desc = """\
  1789. Strip spaces present between the header name and the the ``:``.
  1790. This is known to induce vulnerabilities and is not compliant with the HTTP/1.1 standard.
  1791. See https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn.
  1792. Use with care and only if necessary. Deprecated; scheduled for removal in 25.0.0
  1793. .. versionadded:: 20.0.1
  1794. """
  1795. class PermitUnconventionalHTTPMethod(Setting):
  1796. name = "permit_unconventional_http_method"
  1797. section = "Server Mechanics"
  1798. cli = ["--permit-unconventional-http-method"]
  1799. validator = validate_bool
  1800. action = "store_true"
  1801. default = False
  1802. desc = """\
  1803. Permit HTTP methods not matching conventions, such as IANA registration guidelines
  1804. This permits request methods of length less than 3 or more than 20,
  1805. methods with lowercase characters or methods containing the # character.
  1806. HTTP methods are case sensitive by definition, and merely uppercase by convention.
  1807. If unset, Gunicorn will apply nonstandard restrictions and cause 400 response status
  1808. in cases where otherwise 501 status is expected. While this option does modify that
  1809. behaviour, it should not be depended upon to guarantee standards-compliant behaviour.
  1810. Rather, it is provided temporarily, to assist in diagnosing backwards-incompatible
  1811. changes around the incomplete application of those restrictions.
  1812. Use with care and only if necessary. Temporary; scheduled for removal in 24.0.0
  1813. .. versionadded:: 22.0.0
  1814. """
  1815. class PermitUnconventionalHTTPVersion(Setting):
  1816. name = "permit_unconventional_http_version"
  1817. section = "Server Mechanics"
  1818. cli = ["--permit-unconventional-http-version"]
  1819. validator = validate_bool
  1820. action = "store_true"
  1821. default = False
  1822. desc = """\
  1823. Permit HTTP version not matching conventions of 2023
  1824. This disables the refusal of likely malformed request lines.
  1825. It is unusual to specify HTTP 1 versions other than 1.0 and 1.1.
  1826. This option is provided to diagnose backwards-incompatible changes.
  1827. Use with care and only if necessary. Temporary; the precise effect of this option may
  1828. change in a future version, or it may be removed altogether.
  1829. .. versionadded:: 22.0.0
  1830. """
  1831. class CasefoldHTTPMethod(Setting):
  1832. name = "casefold_http_method"
  1833. section = "Server Mechanics"
  1834. cli = ["--casefold-http-method"]
  1835. validator = validate_bool
  1836. action = "store_true"
  1837. default = False
  1838. desc = """\
  1839. Transform received HTTP methods to uppercase
  1840. HTTP methods are case sensitive by definition, and merely uppercase by convention.
  1841. This option is provided because previous versions of gunicorn defaulted to this behaviour.
  1842. Use with care and only if necessary. Deprecated; scheduled for removal in 24.0.0
  1843. .. versionadded:: 22.0.0
  1844. """
  1845. def validate_header_map_behaviour(val):
  1846. # FIXME: refactor all of this subclassing stdlib argparse
  1847. if val is None:
  1848. return
  1849. if not isinstance(val, str):
  1850. raise TypeError("Invalid type for casting: %s" % val)
  1851. if val.lower().strip() == "drop":
  1852. return "drop"
  1853. elif val.lower().strip() == "refuse":
  1854. return "refuse"
  1855. elif val.lower().strip() == "dangerous":
  1856. return "dangerous"
  1857. else:
  1858. raise ValueError("Invalid header map behaviour: %s" % val)
  1859. class ForwarderHeaders(Setting):
  1860. name = "forwarder_headers"
  1861. section = "Server Mechanics"
  1862. cli = ["--forwarder-headers"]
  1863. validator = validate_string_to_list
  1864. default = "SCRIPT_NAME,PATH_INFO"
  1865. desc = """\
  1866. A list containing upper-case header field names that the front-end proxy
  1867. (see :ref:`forwarded-allow-ips`) sets, to be used in WSGI environment.
  1868. This option has no effect for headers not present in the request.
  1869. This option can be used to transfer ``SCRIPT_NAME``, ``PATH_INFO``
  1870. and ``REMOTE_USER``.
  1871. It is important that your front-end proxy configuration ensures that
  1872. the headers defined here can not be passed directly from the client.
  1873. """
  1874. class HeaderMap(Setting):
  1875. name = "header_map"
  1876. section = "Server Mechanics"
  1877. cli = ["--header-map"]
  1878. validator = validate_header_map_behaviour
  1879. default = "drop"
  1880. desc = """\
  1881. Configure how header field names are mapped into environ
  1882. Headers containing underscores are permitted by RFC9110,
  1883. but gunicorn joining headers of different names into
  1884. the same environment variable will dangerously confuse applications as to which is which.
  1885. The safe default ``drop`` is to silently drop headers that cannot be unambiguously mapped.
  1886. The value ``refuse`` will return an error if a request contains *any* such header.
  1887. The value ``dangerous`` matches the previous, not advisable, behaviour of mapping different
  1888. header field names into the same environ name.
  1889. If the source is permitted as explained in :ref:`forwarded-allow-ips`, *and* the header name is
  1890. present in :ref:`forwarder-headers`, the header is mapped into environment regardless of
  1891. the state of this setting.
  1892. Use with care and only if necessary and after considering if your problem could
  1893. instead be solved by specifically renaming or rewriting only the intended headers
  1894. on a proxy in front of Gunicorn.
  1895. .. versionadded:: 22.0.0
  1896. """