| 1 |
# Copyright (c) 2024, Felix Fontein <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import datetime |
| 11 |
import re |
| 12 |
|
| 13 |
from ansible.module_utils.common.text.converters import to_text |
| 14 |
|
| 15 |
from ansible_collections.community.crypto.plugins.module_utils._crypto.basic import ( |
| 16 |
OpenSSLObjectError, |
| 17 |
) |
| 18 |
|
| 19 |
UTC = datetime.timezone.utc |
| 20 |
|
| 21 |
|
| 22 |
def get_now_datetime(*, with_timezone: bool) -> datetime.datetime: |
| 23 |
if with_timezone: |
| 24 |
return datetime.datetime.now(tz=UTC) |
| 25 |
return datetime.datetime.utcnow() |
| 26 |
|
| 27 |
|
| 28 |
def ensure_utc_timezone(timestamp: datetime.datetime) -> datetime.datetime: |
| 29 |
if timestamp.tzinfo is UTC: |
| 30 |
return timestamp |
| 31 |
if timestamp.tzinfo is None: |
| 32 |
# We assume that naive datetime objects use timezone UTC! |
| 33 |
return timestamp.replace(tzinfo=UTC) |
| 34 |
return timestamp.astimezone(UTC) |
| 35 |
|
| 36 |
|
| 37 |
def remove_timezone(timestamp: datetime.datetime) -> datetime.datetime: |
| 38 |
# Convert to native datetime object |
| 39 |
if timestamp.tzinfo is None: |
| 40 |
return timestamp |
| 41 |
if timestamp.tzinfo is not UTC: |
| 42 |
timestamp = timestamp.astimezone(UTC) |
| 43 |
return timestamp.replace(tzinfo=None) |
| 44 |
|
| 45 |
|
| 46 |
def add_or_remove_timezone( |
| 47 |
timestamp: datetime.datetime, *, with_timezone: bool |
| 48 |
) -> datetime.datetime: |
| 49 |
return ( |
| 50 |
ensure_utc_timezone(timestamp) if with_timezone else remove_timezone(timestamp) |
| 51 |
) |
| 52 |
|
| 53 |
|
| 54 |
def get_epoch_seconds(timestamp: datetime.datetime) -> float: |
| 55 |
if timestamp.tzinfo is None: |
| 56 |
# timestamp.timestamp() is offset by the local timezone if timestamp has no timezone |
| 57 |
timestamp = ensure_utc_timezone(timestamp) |
| 58 |
return timestamp.timestamp() |
| 59 |
|
| 60 |
|
| 61 |
def from_epoch_seconds( |
| 62 |
timestamp: int | float, *, with_timezone: bool |
| 63 |
) -> datetime.datetime: |
| 64 |
if with_timezone: |
| 65 |
return datetime.datetime.fromtimestamp(timestamp, UTC) |
| 66 |
return datetime.datetime.utcfromtimestamp(timestamp) |
| 67 |
|
| 68 |
|
| 69 |
def convert_relative_to_datetime( |
| 70 |
relative_time_string: str, |
| 71 |
*, |
| 72 |
with_timezone: bool = False, |
| 73 |
now: datetime.datetime | None = None, |
| 74 |
) -> datetime.datetime | None: |
| 75 |
"""Get a datetime.datetime or None from a string in the time format described in sshd_config(5)""" |
| 76 |
|
| 77 |
parsed_result = re.match( |
| 78 |
r"^(?P<prefix>[+-])((?P<weeks>\d+)[wW])?((?P<days>\d+)[dD])?((?P<hours>\d+)[hH])?((?P<minutes>\d+)[mM])?((?P<seconds>\d+)[sS]?)?$", |
| 79 |
relative_time_string, |
| 80 |
) |
| 81 |
|
| 82 |
if parsed_result is None or len(relative_time_string) == 1: |
| 83 |
# not matched or only a single "+" or "-" |
| 84 |
return None |
| 85 |
|
| 86 |
offset = datetime.timedelta(0) |
| 87 |
if parsed_result.group("weeks") is not None: |
| 88 |
offset += datetime.timedelta(weeks=int(parsed_result.group("weeks"))) |
| 89 |
if parsed_result.group("days") is not None: |
| 90 |
offset += datetime.timedelta(days=int(parsed_result.group("days"))) |
| 91 |
if parsed_result.group("hours") is not None: |
| 92 |
offset += datetime.timedelta(hours=int(parsed_result.group("hours"))) |
| 93 |
if parsed_result.group("minutes") is not None: |
| 94 |
offset += datetime.timedelta(minutes=int(parsed_result.group("minutes"))) |
| 95 |
if parsed_result.group("seconds") is not None: |
| 96 |
offset += datetime.timedelta(seconds=int(parsed_result.group("seconds"))) |
| 97 |
|
| 98 |
if now is None: |
| 99 |
now = get_now_datetime(with_timezone=with_timezone) |
| 100 |
else: |
| 101 |
now = add_or_remove_timezone(now, with_timezone=with_timezone) |
| 102 |
|
| 103 |
if parsed_result.group("prefix") == "+": |
| 104 |
return now + offset |
| 105 |
return now - offset |
| 106 |
|
| 107 |
|
| 108 |
def get_relative_time_option( |
| 109 |
input_string: str, |
| 110 |
*, |
| 111 |
input_name: str, |
| 112 |
with_timezone: bool = False, |
| 113 |
now: datetime.datetime | None = None, |
| 114 |
) -> datetime.datetime: |
| 115 |
""" |
| 116 |
Return an absolute timespec if a relative timespec or an ASN1 formatted |
| 117 |
string is provided. |
| 118 |
|
| 119 |
The return value will be a datetime object. |
| 120 |
""" |
| 121 |
result = to_text(input_string) |
| 122 |
if result is None: |
| 123 |
raise OpenSSLObjectError( |
| 124 |
f'The timespec "{input_string}" for {input_name} is not valid' |
| 125 |
) |
| 126 |
# Relative time |
| 127 |
if result.startswith("+") or result.startswith("-"): |
| 128 |
res = convert_relative_to_datetime(result, with_timezone=with_timezone, now=now) |
| 129 |
if res is None: |
| 130 |
raise OpenSSLObjectError( |
| 131 |
f'The timespec "{input_string}" for {input_name} is invalid' |
| 132 |
) |
| 133 |
return res |
| 134 |
# Absolute time |
| 135 |
for date_fmt, length in [ |
| 136 |
( |
| 137 |
"%Y%m%d%H%M%SZ", |
| 138 |
15, |
| 139 |
), # this also parses '202401020304Z', but as datetime(2024, 1, 2, 3, 0, 4) |
| 140 |
("%Y%m%d%H%MZ", 13), |
| 141 |
( |
| 142 |
"%Y%m%d%H%M%S%z", |
| 143 |
14 + 5, |
| 144 |
), # this also parses '202401020304+0000', but as datetime(2024, 1, 2, 3, 0, 4, tzinfo=...) |
| 145 |
("%Y%m%d%H%M%z", 12 + 5), |
| 146 |
]: |
| 147 |
if len(result) != length: |
| 148 |
continue |
| 149 |
try: |
| 150 |
res = datetime.datetime.strptime(result, date_fmt) |
| 151 |
except ValueError: |
| 152 |
pass |
| 153 |
else: |
| 154 |
return add_or_remove_timezone(res, with_timezone=with_timezone) |
| 155 |
|
| 156 |
raise OpenSSLObjectError( |
| 157 |
f'The time spec "{input_string}" for {input_name} is invalid' |
| 158 |
) |
| 159 |
|
| 160 |
|
| 161 |
__all__ = ( |
| 162 |
"add_or_remove_timezone", |
| 163 |
"convert_relative_to_datetime", |
| 164 |
"ensure_utc_timezone", |
| 165 |
"from_epoch_seconds", |
| 166 |
"get_epoch_seconds", |
| 167 |
"get_now_datetime", |
| 168 |
"get_relative_time_option", |
| 169 |
"remove_timezone", |
| 170 |
) |