utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  5. # Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import datetime
  20. import os
  21. import ssl
  22. import sys
  23. import textwrap
  24. from hashlib import sha256
  25. from importlib import import_module, metadata
  26. from string import ascii_letters, digits, punctuation
  27. from typing import Callable, Sequence, Tuple, Type, TypeVar, Union
  28. from radicale import config
  29. from radicale.log import logger
  30. if sys.platform != "win32":
  31. import grp
  32. import pwd
  33. _T_co = TypeVar("_T_co", covariant=True)
  34. RADICALE_MODULES: Sequence[str] = ("radicale", "vobject", "passlib", "defusedxml",
  35. "bcrypt",
  36. "argon2-cffi",
  37. "pika",
  38. "ldap",
  39. "ldap3",
  40. "pam")
  41. # IPv4 (host, port) and IPv6 (host, port, flowinfo, scopeid)
  42. ADDRESS_TYPE = Union[Tuple[Union[str, bytes, bytearray], int],
  43. Tuple[str, int, int, int]]
  44. # Max/Min YEAR in datetime in unixtime
  45. DATETIME_MAX_UNIXTIME: int = (datetime.MAXYEAR - 1970) * 365 * 24 * 60 * 60
  46. DATETIME_MIN_UNIXTIME: int = (datetime.MINYEAR - 1970) * 365 * 24 * 60 * 60
  47. # Number units
  48. UNIT_g: int = (1000 * 1000 * 1000)
  49. UNIT_m: int = (1000 * 1000)
  50. UNIT_k: int = (1000)
  51. UNIT_G: int = (1024 * 1024 * 1024)
  52. UNIT_M: int = (1024 * 1024)
  53. UNIT_K: int = (1024)
  54. def load_plugin(internal_types: Sequence[str], module_name: str,
  55. class_name: str, base_class: Type[_T_co],
  56. configuration: "config.Configuration") -> _T_co:
  57. type_: Union[str, Callable] = configuration.get(module_name, "type")
  58. if callable(type_):
  59. logger.info("%s type is %r", module_name, type_)
  60. return type_(configuration)
  61. if type_ in internal_types:
  62. module = "radicale.%s.%s" % (module_name, type_)
  63. else:
  64. module = type_
  65. try:
  66. class_ = getattr(import_module(module), class_name)
  67. except Exception as e:
  68. raise RuntimeError("Failed to load %s module %r: %s" %
  69. (module_name, module, e)) from e
  70. logger.info("%s type is %r", module_name, module)
  71. return class_(configuration)
  72. def package_version(name):
  73. return metadata.version(name)
  74. def packages_version():
  75. versions = []
  76. versions.append("python=%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]))
  77. for pkg in RADICALE_MODULES:
  78. try:
  79. versions.append("%s=%s" % (pkg, package_version(pkg)))
  80. except Exception:
  81. try:
  82. versions.append("%s=%s" % (pkg, package_version("python-" + pkg)))
  83. except Exception:
  84. versions.append("%s=%s" % (pkg, "n/a"))
  85. return " ".join(versions)
  86. def format_address(address: ADDRESS_TYPE) -> str:
  87. host, port, *_ = address
  88. if not isinstance(host, str):
  89. raise NotImplementedError("Unsupported address format: %r" %
  90. (address,))
  91. if host.find(":") == -1:
  92. return "%s:%d" % (host, port)
  93. else:
  94. return "[%s]:%d" % (host, port)
  95. def ssl_context_options_by_protocol(protocol: str, ssl_context_options):
  96. logger.debug("SSL protocol string: '%s' and current SSL context options: '0x%x'", protocol, ssl_context_options)
  97. # disable any protocol by default
  98. logger.debug("SSL context options, disable ALL by default")
  99. ssl_context_options |= ssl.OP_NO_SSLv2
  100. ssl_context_options |= ssl.OP_NO_SSLv3
  101. ssl_context_options |= ssl.OP_NO_TLSv1
  102. ssl_context_options |= ssl.OP_NO_TLSv1_1
  103. ssl_context_options |= ssl.OP_NO_TLSv1_2
  104. ssl_context_options |= ssl.OP_NO_TLSv1_3
  105. logger.debug("SSL cleared SSL context options: '0x%x'", ssl_context_options)
  106. for entry in protocol.split():
  107. entry = entry.strip('+') # remove trailing '+'
  108. if entry == "ALL":
  109. logger.debug("SSL context options, enable ALL (some maybe not supported by underlying OpenSSL, SSLv2 not enabled at all)")
  110. ssl_context_options &= ~ssl.OP_NO_SSLv3
  111. ssl_context_options &= ~ssl.OP_NO_TLSv1
  112. ssl_context_options &= ~ssl.OP_NO_TLSv1_1
  113. ssl_context_options &= ~ssl.OP_NO_TLSv1_2
  114. ssl_context_options &= ~ssl.OP_NO_TLSv1_3
  115. elif entry == "SSLv2":
  116. logger.warning("SSL context options, ignore SSLv2 (totally insecure)")
  117. elif entry == "SSLv3":
  118. ssl_context_options &= ~ssl.OP_NO_SSLv3
  119. logger.debug("SSL context options, enable SSLv3 (maybe not supported by underlying OpenSSL)")
  120. elif entry == "TLSv1":
  121. ssl_context_options &= ~ssl.OP_NO_TLSv1
  122. logger.debug("SSL context options, enable TLSv1 (maybe not supported by underlying OpenSSL)")
  123. elif entry == "TLSv1.1":
  124. logger.debug("SSL context options, enable TLSv1.1 (maybe not supported by underlying OpenSSL)")
  125. ssl_context_options &= ~ssl.OP_NO_TLSv1_1
  126. elif entry == "TLSv1.2":
  127. logger.debug("SSL context options, enable TLSv1.2")
  128. ssl_context_options &= ~ssl.OP_NO_TLSv1_2
  129. elif entry == "TLSv1.3":
  130. logger.debug("SSL context options, enable TLSv1.3")
  131. ssl_context_options &= ~ssl.OP_NO_TLSv1_3
  132. elif entry == "-ALL":
  133. logger.debug("SSL context options, disable ALL")
  134. ssl_context_options |= ssl.OP_NO_SSLv2
  135. ssl_context_options |= ssl.OP_NO_SSLv3
  136. ssl_context_options |= ssl.OP_NO_TLSv1
  137. ssl_context_options |= ssl.OP_NO_TLSv1_1
  138. ssl_context_options |= ssl.OP_NO_TLSv1_2
  139. ssl_context_options |= ssl.OP_NO_TLSv1_3
  140. elif entry == "-SSLv2":
  141. ssl_context_options |= ssl.OP_NO_SSLv2
  142. logger.debug("SSL context options, disable SSLv2")
  143. elif entry == "-SSLv3":
  144. ssl_context_options |= ssl.OP_NO_SSLv3
  145. logger.debug("SSL context options, disable SSLv3")
  146. elif entry == "-TLSv1":
  147. logger.debug("SSL context options, disable TLSv1")
  148. ssl_context_options |= ssl.OP_NO_TLSv1
  149. elif entry == "-TLSv1.1":
  150. logger.debug("SSL context options, disable TLSv1.1")
  151. ssl_context_options |= ssl.OP_NO_TLSv1_1
  152. elif entry == "-TLSv1.2":
  153. logger.debug("SSL context options, disable TLSv1.2")
  154. ssl_context_options |= ssl.OP_NO_TLSv1_2
  155. elif entry == "-TLSv1.3":
  156. logger.debug("SSL context options, disable TLSv1.3")
  157. ssl_context_options |= ssl.OP_NO_TLSv1_3
  158. else:
  159. raise RuntimeError("SSL protocol config contains unsupported entry '%s'" % (entry))
  160. logger.debug("SSL resulting context options: '0x%x'", ssl_context_options)
  161. return ssl_context_options
  162. def ssl_context_minimum_version_by_options(ssl_context_options):
  163. logger.debug("SSL calculate minimum version by context options: '0x%x'", ssl_context_options)
  164. ssl_context_minimum_version = ssl.TLSVersion.SSLv3 # default
  165. if ((ssl_context_options & ssl.OP_NO_SSLv3) and (ssl_context_minimum_version == ssl.TLSVersion.SSLv3)):
  166. ssl_context_minimum_version = ssl.TLSVersion.TLSv1
  167. if ((ssl_context_options & ssl.OP_NO_TLSv1) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1)):
  168. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_1
  169. if ((ssl_context_options & ssl.OP_NO_TLSv1_1) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_1)):
  170. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_2
  171. if ((ssl_context_options & ssl.OP_NO_TLSv1_2) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_2)):
  172. ssl_context_minimum_version = ssl.TLSVersion.TLSv1_3
  173. if ((ssl_context_options & ssl.OP_NO_TLSv1_3) and (ssl_context_minimum_version == ssl.TLSVersion.TLSv1_3)):
  174. ssl_context_minimum_version = 0 # all disabled
  175. logger.debug("SSL context options: '0x%x' results in minimum version: %s", ssl_context_options, ssl_context_minimum_version)
  176. return ssl_context_minimum_version
  177. def ssl_context_maximum_version_by_options(ssl_context_options):
  178. logger.debug("SSL calculate maximum version by context options: '0x%x'", ssl_context_options)
  179. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_3 # default
  180. if ((ssl_context_options & ssl.OP_NO_TLSv1_3) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_3)):
  181. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_2
  182. if ((ssl_context_options & ssl.OP_NO_TLSv1_2) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_2)):
  183. ssl_context_maximum_version = ssl.TLSVersion.TLSv1_1
  184. if ((ssl_context_options & ssl.OP_NO_TLSv1_1) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1_1)):
  185. ssl_context_maximum_version = ssl.TLSVersion.TLSv1
  186. if ((ssl_context_options & ssl.OP_NO_TLSv1) and (ssl_context_maximum_version == ssl.TLSVersion.TLSv1)):
  187. ssl_context_maximum_version = ssl.TLSVersion.SSLv3
  188. if ((ssl_context_options & ssl.OP_NO_SSLv3) and (ssl_context_maximum_version == ssl.TLSVersion.SSLv3)):
  189. ssl_context_maximum_version = 0
  190. logger.debug("SSL context options: '0x%x' results in maximum version: %s", ssl_context_options, ssl_context_maximum_version)
  191. return ssl_context_maximum_version
  192. def ssl_get_protocols(context):
  193. protocols = []
  194. if not (context.options & ssl.OP_NO_SSLv3):
  195. if (context.minimum_version < ssl.TLSVersion.TLSv1):
  196. protocols.append("SSLv3")
  197. if not (context.options & ssl.OP_NO_TLSv1):
  198. if (context.minimum_version < ssl.TLSVersion.TLSv1_1) and (context.maximum_version >= ssl.TLSVersion.TLSv1):
  199. protocols.append("TLSv1")
  200. if not (context.options & ssl.OP_NO_TLSv1_1):
  201. if (context.minimum_version < ssl.TLSVersion.TLSv1_2) and (context.maximum_version >= ssl.TLSVersion.TLSv1_1):
  202. protocols.append("TLSv1.1")
  203. if not (context.options & ssl.OP_NO_TLSv1_2):
  204. if (context.minimum_version <= ssl.TLSVersion.TLSv1_2) and (context.maximum_version >= ssl.TLSVersion.TLSv1_2):
  205. protocols.append("TLSv1.2")
  206. if not (context.options & ssl.OP_NO_TLSv1_3):
  207. if (context.minimum_version <= ssl.TLSVersion.TLSv1_3) and (context.maximum_version >= ssl.TLSVersion.TLSv1_3):
  208. protocols.append("TLSv1.3")
  209. return protocols
  210. def unknown_if_empty(value):
  211. if value == "":
  212. return "UNKNOWN"
  213. else:
  214. return value
  215. def user_groups_as_string():
  216. if sys.platform != "win32":
  217. euid = os.geteuid()
  218. try:
  219. username = pwd.getpwuid(euid)[0]
  220. user = "%s(%d)" % (unknown_if_empty(username), euid)
  221. except Exception:
  222. # name of user not found
  223. user = "UNKNOWN(%d)" % euid
  224. egid = os.getegid()
  225. groups = []
  226. try:
  227. gids = os.getgrouplist(username, egid)
  228. for gid in gids:
  229. try:
  230. gi = grp.getgrgid(gid)
  231. groups.append("%s(%d)" % (unknown_if_empty(gi.gr_name), gid))
  232. except Exception:
  233. groups.append("UNKNOWN(%d)" % gid)
  234. except Exception:
  235. try:
  236. groups.append("%s(%d)" % (grp.getgrnam(egid)[0], egid))
  237. except Exception:
  238. # workaround to get groupid by name
  239. groups_all = grp.getgrall()
  240. found = False
  241. for entry in groups_all:
  242. if entry[2] == egid:
  243. groups.append("%s(%d)" % (unknown_if_empty(entry[0]), egid))
  244. found = True
  245. break
  246. if not found:
  247. groups.append("UNKNOWN(%d)" % egid)
  248. s = "user=%s groups=%s" % (user, ','.join(groups))
  249. else:
  250. username = os.getlogin()
  251. s = "user=%s" % (username)
  252. return s
  253. def format_ut(unixtime: int) -> str:
  254. if sys.platform == "win32":
  255. # TODO check how to support this better
  256. return str(unixtime)
  257. if unixtime <= DATETIME_MIN_UNIXTIME:
  258. r = str(unixtime) + "(<=MIN:" + str(DATETIME_MIN_UNIXTIME) + ")"
  259. elif unixtime >= DATETIME_MAX_UNIXTIME:
  260. r = str(unixtime) + "(>=MAX:" + str(DATETIME_MAX_UNIXTIME) + ")"
  261. else:
  262. if sys.version_info < (3, 11):
  263. dt = datetime.datetime.utcfromtimestamp(unixtime)
  264. else:
  265. dt = datetime.datetime.fromtimestamp(unixtime, datetime.UTC)
  266. r = str(unixtime) + "(" + dt.strftime('%Y-%m-%dT%H:%M:%SZ') + ")"
  267. return r
  268. def format_unit(value: float, binary: bool = False) -> str:
  269. if binary:
  270. if value > UNIT_G:
  271. value = value / UNIT_G
  272. unit = "G"
  273. elif value > UNIT_M:
  274. value = value / UNIT_M
  275. unit = "M"
  276. elif value > UNIT_K:
  277. value = value / UNIT_K
  278. unit = "K"
  279. else:
  280. unit = ""
  281. else:
  282. if value > UNIT_g:
  283. value = value / UNIT_g
  284. unit = "g"
  285. elif value > UNIT_m:
  286. value = value / UNIT_m
  287. unit = "m"
  288. elif value > UNIT_k:
  289. value = value / UNIT_k
  290. unit = "k"
  291. else:
  292. unit = ""
  293. return ("%.1f %s" % (value, unit))
  294. def limit_str(content: str, limit: int) -> str:
  295. length = len(content)
  296. if limit > 0 and length >= limit:
  297. return content[:limit] + ("...(shortened because original length %d > limit %d)" % (length, limit))
  298. else:
  299. return content
  300. def textwrap_str(content: str, limit: int = 2000) -> str:
  301. # TODO: add support for config option and prefix
  302. return textwrap.indent(limit_str(content, limit), " ", lambda line: True)
  303. def dataToHex(data, count):
  304. result = ''
  305. for item in range(count):
  306. if ((item > 0) and ((item % 8) == 0)):
  307. result += ' '
  308. if (item < len(data)):
  309. result += '%02x' % data[item] + ' '
  310. else:
  311. result += ' '
  312. return result
  313. def dataToAscii(data, count):
  314. result = ''
  315. for item in range(count):
  316. if (item < len(data)):
  317. char = chr(data[item])
  318. if char in ascii_letters or \
  319. char in digits or \
  320. char in punctuation or \
  321. char == ' ':
  322. result += char
  323. else:
  324. result += '.'
  325. return result
  326. def dataToSpecial(data, count):
  327. result = ''
  328. for item in range(count):
  329. if (item < len(data)):
  330. char = chr(data[item])
  331. if char == '\r':
  332. result += 'C'
  333. elif char == '\n':
  334. result += 'L'
  335. elif ord(char) == 0xc2:
  336. result += 'u'
  337. else:
  338. result += '.'
  339. return result
  340. def hexdump_str(content: str, limit: int = 2000) -> str:
  341. result = ""
  342. index = 0
  343. size = 16
  344. bytestring = content.encode("utf-8")
  345. length = len(bytestring)
  346. while (index < length) and (index < limit):
  347. data = bytestring[index:index+size]
  348. hex = dataToHex(data, size)
  349. ascii = dataToAscii(data, size)
  350. special = dataToSpecial(data, size)
  351. result += '%08x ' % index
  352. result += hex
  353. result += '|'
  354. result += '%-16s' % ascii
  355. result += '|'
  356. result += '%-16s' % special
  357. result += '|'
  358. result += '\n'
  359. index += size
  360. return result
  361. def hexdump_line(line: str, limit: int = 200) -> str:
  362. result = ""
  363. length_str = len(line)
  364. bytestring = line.encode("utf-8")
  365. length = len(bytestring)
  366. size = length
  367. if (size > limit):
  368. size = limit
  369. hex = dataToHex(bytestring, size)
  370. ascii = dataToAscii(bytestring, size)
  371. special = dataToSpecial(bytestring, size)
  372. result += '%3d/%3d' % (length_str, length)
  373. result += ': '
  374. result += hex
  375. result += '|'
  376. result += ascii
  377. result += '|'
  378. result += special
  379. result += '|'
  380. result += '\n'
  381. return result
  382. def hexdump_lines(lines: str, limit: int = 200) -> str:
  383. result = ""
  384. counter = 0
  385. for line in lines.splitlines(True):
  386. result += '% 4d ' % counter
  387. result += hexdump_line(line)
  388. counter += 1
  389. return result
  390. def sha256_str(content: str) -> str:
  391. _hash = sha256()
  392. _hash.update(content.encode("utf-8"))
  393. return _hash.hexdigest()