Debian Codegraph @

dns/rdtypes/ANY/LOC.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 import struct
19
20 import dns.exception
21 import dns.immutable
22 import dns.rdata
23
24 _pows = tuple(10**i for i in range(0, 11))
25
26 # default values are in centimeters
27 _default_size = 100.0
28 _default_hprec = 1000000.0
29 _default_vprec = 1000.0
30
31 # for use by from_wire()
32 _MAX_LATITUDE = 0x80000000 + 90 * 3600000
33 _MIN_LATITUDE = 0x80000000 - 90 * 3600000
34 _MAX_LONGITUDE = 0x80000000 + 180 * 3600000
35 _MIN_LONGITUDE = 0x80000000 - 180 * 3600000
36
37
38 def _exponent_of(what, desc):
39 if what == 0:
40 return 0
41 exp = None
42 for i, pow in enumerate(_pows):
43 if what < pow:
44 exp = i - 1
45 break
46 if exp is None or exp < 0:
47 raise dns.exception.SyntaxError(f"{desc} value out of bounds")
48 return exp
49
50
51 def _float_to_tuple(what):
52 if what < 0:
53 sign = -1
54 what *= -1
55 else:
56 sign = 1
57 what = round(what * 3600000)
58 degrees = int(what // 3600000)
59 what -= degrees * 3600000
60 minutes = int(what // 60000)
61 what -= minutes * 60000
62 seconds = int(what // 1000)
63 what -= int(seconds * 1000)
64 what = int(what)
65 return (degrees, minutes, seconds, what, sign)
66
67
68 def _tuple_to_float(what):
69 value = float(what[0])
70 value += float(what[1]) / 60.0
71 value += float(what[2]) / 3600.0
72 value += float(what[3]) / 3600000.0
73 return float(what[4]) * value
74
75
76 def _encode_size(what, desc):
77 what = int(what)
78 exponent = _exponent_of(what, desc) & 0xF
79 base = what // pow(10, exponent) & 0xF
80 return base * 16 + exponent
81
82
83 def _decode_size(what, desc):
84 exponent = what & 0x0F
85 if exponent > 9:
86 raise dns.exception.FormError(f"bad {desc} exponent")
87 base = (what & 0xF0) >> 4
88 if base > 9:
89 raise dns.exception.FormError(f"bad {desc} base")
90 return base * pow(10, exponent)
91
92
93 def _check_coordinate_list(value, low, high):
94 if value[0] < low or value[0] > high:
95 raise ValueError(f"not in range [{low}, {high}]")
96 if value[1] < 0 or value[1] > 59:
97 raise ValueError("bad minutes value")
98 if value[2] < 0 or value[2] > 59:
99 raise ValueError("bad seconds value")
100 if value[3] < 0 or value[3] > 999:
101 raise ValueError("bad milliseconds value")
102 if value[4] != 1 and value[4] != -1:
103 raise ValueError("bad hemisphere value")
104
105
106 @dns.immutable.immutable
107 class LOC(dns.rdata.Rdata):
108 """LOC record"""
109
110 # see: RFC 1876
111
112 __slots__ = [
113 "latitude",
114 "longitude",
115 "altitude",
116 "size",
117 "horizontal_precision",
118 "vertical_precision",
119 ]
120
121 def __init__(
122 self,
123 rdclass,
124 rdtype,
125 latitude,
126 longitude,
127 altitude,
128 size=_default_size,
129 hprec=_default_hprec,
130 vprec=_default_vprec,
131 ):
132 """Initialize a LOC record instance.
133
134 The parameters I{latitude} and I{longitude} may be either a 4-tuple
135 of integers specifying (degrees, minutes, seconds, milliseconds),
136 or they may be floating point values specifying the number of
137 degrees. The other parameters are floats. Size, horizontal precision,
138 and vertical precision are specified in centimeters."""
139
140 super().__init__(rdclass, rdtype)
141 if isinstance(latitude, int):
142 latitude = float(latitude)
143 if isinstance(latitude, float):
144 latitude = _float_to_tuple(latitude)
145 _check_coordinate_list(latitude, -90, 90)
146 self.latitude = tuple(latitude) # pyright: ignore
147 if isinstance(longitude, int):
148 longitude = float(longitude)
149 if isinstance(longitude, float):
150 longitude = _float_to_tuple(longitude)
151 _check_coordinate_list(longitude, -180, 180)
152 self.longitude = tuple(longitude) # pyright: ignore
153 self.altitude = float(altitude)
154 self.size = float(size)
155 self.horizontal_precision = float(hprec)
156 self.vertical_precision = float(vprec)
157
158 def to_text(self, origin=None, relativize=True, **kw):
159 if self.latitude[4] > 0:
160 lat_hemisphere = "N"
161 else:
162 lat_hemisphere = "S"
163 if self.longitude[4] > 0:
164 long_hemisphere = "E"
165 else:
166 long_hemisphere = "W"
167 text = (
168 f"{self.latitude[0]} {self.latitude[1]} "
169 f"{self.latitude[2]}.{self.latitude[3]:03d} {lat_hemisphere} "
170 f"{self.longitude[0]} {self.longitude[1]} "
171 f"{self.longitude[2]}.{self.longitude[3]:03d} {long_hemisphere} "
172 f"{(self.altitude / 100.0):0.2f}m"
173 )
174
175 # do not print default values
176 if (
177 self.size != _default_size
178 or self.horizontal_precision != _default_hprec
179 or self.vertical_precision != _default_vprec
180 ):
181 text += (
182 f" {self.size / 100.0:0.2f}m {self.horizontal_precision / 100.0:0.2f}m"
183 f" {self.vertical_precision / 100.0:0.2f}m"
184 )
185 return text
186
187 @classmethod
188 def from_text(
189 cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None
190 ):
191 latitude = [0, 0, 0, 0, 1]
192 longitude = [0, 0, 0, 0, 1]
193 size = _default_size
194 hprec = _default_hprec
195 vprec = _default_vprec
196
197 latitude[0] = tok.get_int()
198 t = tok.get_string()
199 if t.isdigit():
200 latitude[1] = int(t)
201 t = tok.get_string()
202 if "." in t:
203 (seconds, milliseconds) = t.split(".")
204 if not seconds.isdigit():
205 raise dns.exception.SyntaxError("bad latitude seconds value")
206 latitude[2] = int(seconds)
207 l = len(milliseconds)
208 if l == 0 or l > 3 or not milliseconds.isdigit():
209 raise dns.exception.SyntaxError("bad latitude milliseconds value")
210 if l == 1:
211 m = 100
212 elif l == 2:
213 m = 10
214 else:
215 m = 1
216 latitude[3] = m * int(milliseconds)
217 t = tok.get_string()
218 elif t.isdigit():
219 latitude[2] = int(t)
220 t = tok.get_string()
221 if t == "S":
222 latitude[4] = -1
223 elif t != "N":
224 raise dns.exception.SyntaxError("bad latitude hemisphere value")
225
226 longitude[0] = tok.get_int()
227 t = tok.get_string()
228 if t.isdigit():
229 longitude[1] = int(t)
230 t = tok.get_string()
231 if "." in t:
232 (seconds, milliseconds) = t.split(".")
233 if not seconds.isdigit():
234 raise dns.exception.SyntaxError("bad longitude seconds value")
235 longitude[2] = int(seconds)
236 l = len(milliseconds)
237 if l == 0 or l > 3 or not milliseconds.isdigit():
238 raise dns.exception.SyntaxError("bad longitude milliseconds value")
239 if l == 1:
240 m = 100
241 elif l == 2:
242 m = 10
243 else:
244 m = 1
245 longitude[3] = m * int(milliseconds)
246 t = tok.get_string()
247 elif t.isdigit():
248 longitude[2] = int(t)
249 t = tok.get_string()
250 if t == "W":
251 longitude[4] = -1
252 elif t != "E":
253 raise dns.exception.SyntaxError("bad longitude hemisphere value")
254
255 t = tok.get_string()
256 if t[-1] == "m":
257 t = t[0:-1]
258 altitude = float(t) * 100.0 # m -> cm
259
260 tokens = tok.get_remaining(max_tokens=3)
261 if len(tokens) >= 1:
262 value = tokens[0].unescape().value
263 if value[-1] == "m":
264 value = value[0:-1]
265 size = float(value) * 100.0 # m -> cm
266 if len(tokens) >= 2:
267 value = tokens[1].unescape().value
268 if value[-1] == "m":
269 value = value[0:-1]
270 hprec = float(value) * 100.0 # m -> cm
271 if len(tokens) >= 3:
272 value = tokens[2].unescape().value
273 if value[-1] == "m":
274 value = value[0:-1]
275 vprec = float(value) * 100.0 # m -> cm
276
277 # Try encoding these now so we raise if they are bad
278 _encode_size(size, "size")
279 _encode_size(hprec, "horizontal precision")
280 _encode_size(vprec, "vertical precision")
281
282 return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec)
283
284 def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
285 milliseconds = (
286 self.latitude[0] * 3600000
287 + self.latitude[1] * 60000
288 + self.latitude[2] * 1000
289 + self.latitude[3]
290 ) * self.latitude[4]
291 latitude = 0x80000000 + milliseconds
292 milliseconds = (
293 self.longitude[0] * 3600000
294 + self.longitude[1] * 60000
295 + self.longitude[2] * 1000
296 + self.longitude[3]
297 ) * self.longitude[4]
298 longitude = 0x80000000 + milliseconds
299 altitude = int(self.altitude) + 10000000
300 size = _encode_size(self.size, "size")
301 hprec = _encode_size(self.horizontal_precision, "horizontal precision")
302 vprec = _encode_size(self.vertical_precision, "vertical precision")
303 wire = struct.pack(
304 "!BBBBIII", 0, size, hprec, vprec, latitude, longitude, altitude
305 )
306 file.write(wire)
307
308 @classmethod
309 def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
310 (
311 version,
312 size,
313 hprec,
314 vprec,
315 latitude,
316 longitude,
317 altitude,
318 ) = parser.get_struct("!BBBBIII")
319 if version != 0:
320 raise dns.exception.FormError("LOC version not zero")
321 if latitude < _MIN_LATITUDE or latitude > _MAX_LATITUDE:
322 raise dns.exception.FormError("bad latitude")
323 if latitude > 0x80000000:
324 latitude = (latitude - 0x80000000) / 3600000
325 else:
326 latitude = -1 * (0x80000000 - latitude) / 3600000
327 if longitude < _MIN_LONGITUDE or longitude > _MAX_LONGITUDE:
328 raise dns.exception.FormError("bad longitude")
329 if longitude > 0x80000000:
330 longitude = (longitude - 0x80000000) / 3600000
331 else:
332 longitude = -1 * (0x80000000 - longitude) / 3600000
333 altitude = float(altitude) - 10000000.0
334 size = _decode_size(size, "size")
335 hprec = _decode_size(hprec, "horizontal precision")
336 vprec = _decode_size(vprec, "vertical precision")
337 return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec)
338
339 @property
340 def float_latitude(self):
341 "latitude as a floating point value"
342 return _tuple_to_float(self.latitude)
343
344 @property
345 def float_longitude(self):
346 "longitude as a floating point value"
347 return _tuple_to_float(self.longitude)