Debian Codegraph @

Pyro5/core.py

raw
1 """
2 Multi purpose stuff used by both clients and servers (URI etc)
3
4 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
5 """
6
7 import re
8 import logging
9 import contextlib
10 import ipaddress
11 import socket
12 import random
13 import serpent
14 from typing import Union, Optional
15 from . import config, errors, socketutil, serializers
16
17
18 __all__ = ["URI", "DAEMON_NAME", "NAMESERVER_NAME", "resolve", "locate_ns", "type_meta"]
19
20 log = logging.getLogger("Pyro5.core")
21
22 # standard object name for the Daemon object
23 DAEMON_NAME = "Pyro.Daemon"
24
25 # standard name for the Name server itself
26 NAMESERVER_NAME = "Pyro.NameServer"
27
28
29 class URI(object):
30 """
31 Pyro object URI (universal resource identifier).
32 The uri format is like this: ``PYRO:objectid@location`` where location is one of:
33
34 - ``hostname:port`` (tcp/ip socket on given port)
35 - ``./u:sockname`` (Unix domain socket on localhost)
36
37 There is also a 'Magic format' for simple name resolution using Name server:
38 ``PYRONAME:objectname[@location]`` (optional name server location, can also omit location port)
39 And one that looks up things in the name server by metadata:
40 ``PYROMETA:meta1,meta2,...[@location]`` (optional name server location, can also omit location port)
41
42 You can write the protocol in lowercase if you like (``pyro:...``) but it will
43 automatically be converted to uppercase internally.
44 """
45 uriRegEx = re.compile(r"(?P<protocol>[Pp][Yy][Rr][Oo][a-zA-Z]*):(?P<object>\S+?)(@(?P<location>.+))?$")
46
47 def __init__(self, uri):
48 if isinstance(uri, URI):
49 state = uri.__getstate__()
50 self.__setstate__(state)
51 return
52 if not isinstance(uri, str):
53 raise TypeError("uri parameter object is of wrong type")
54 self.sockname = self.host = self.port = None
55 match = self.uriRegEx.match(uri)
56 if not match:
57 raise errors.PyroError("invalid uri")
58 self.protocol = match.group("protocol").upper()
59 self.object = match.group("object")
60 location = match.group("location")
61 if self.protocol == "PYRONAME":
62 self._parseLocation(location, config.NS_PORT)
63 elif self.protocol == "PYRO":
64 if not location:
65 raise errors.PyroError("invalid uri")
66 self._parseLocation(location, None)
67 elif self.protocol == "PYROMETA":
68 self.object = set(m.strip() for m in self.object.split(","))
69 self._parseLocation(location, config.NS_PORT)
70 else:
71 raise errors.PyroError("invalid uri (protocol)")
72
73 def _parseLocation(self, location, defaultPort):
74 if not location:
75 return
76 if location.startswith("./u:"):
77 self.sockname = location[4:]
78 if (not self.sockname) or ':' in self.sockname:
79 raise errors.PyroError("invalid uri (location)")
80 else:
81 if location.startswith("["): # ipv6
82 if location.startswith("[["): # possible mistake: double-bracketing
83 raise errors.PyroError("invalid ipv6 address: enclosed in too many brackets")
84 ipv6locationmatch = re.match(r"\[([0-9a-fA-F:%]+)](:(\d+))?", location)
85 if not ipv6locationmatch:
86 raise errors.PyroError("invalid ipv6 address: the part between brackets must be a numeric ipv6 address")
87 self.host, _, self.port = ipv6locationmatch.groups()
88 else:
89 self.host, _, self.port = location.partition(":")
90 if not self.port:
91 self.port = defaultPort
92 try:
93 self.port = int(self.port)
94 except (ValueError, TypeError):
95 raise errors.PyroError("invalid port in uri, port=" + str(self.port))
96
97 @staticmethod
98 def isUnixsockLocation(location):
99 """determine if a location string is for a Unix domain socket"""
100 return location.startswith("./u:")
101
102 @property
103 def location(self):
104 """property containing the location string, for instance ``"servername.you.com:5555"``"""
105 if self.host:
106 if ":" in self.host: # ipv6
107 return "[%s]:%d" % (self.host, self.port)
108 else:
109 return "%s:%d" % (self.host, self.port)
110 elif self.sockname:
111 return "./u:" + self.sockname
112 else:
113 return None
114
115 def __str__(self):
116 if self.protocol == "PYROMETA":
117 result = "PYROMETA:" + ",".join(self.object)
118 else:
119 result = self.protocol + ":" + self.object
120 if self.location:
121 return result + "@" + self.location
122 return result
123
124 def __repr__(self):
125 return "<%s.%s at 0x%x; %s>" % (self.__class__.__module__, self.__class__.__name__, id(self), str(self))
126
127 def __eq__(self, other):
128 if not isinstance(other, URI):
129 return False
130 return self.__getstate__() == other.__getstate__()
131
132 def __ne__(self, other):
133 return not self.__eq__(other)
134
135 def __hash__(self):
136 return hash(self.__getstate__())
137
138 def __getstate__(self):
139 return self.protocol, self.object, self.sockname, self.host, self.port
140
141 def __setstate__(self, state):
142 self.protocol, self.object, self.sockname, self.host, self.port = state
143
144
145 class _ExceptionWrapper(object):
146 """Class that wraps a remote exception. If this is returned, Pyro will
147 re-throw the exception on the receiving side. Usually this is taken care of
148 by a special response message flag, but in the case of batched calls this
149 flag is useless and another mechanism was needed."""
150
151 def __init__(self, exception):
152 self.exception = exception
153
154 def raiseIt(self):
155 raise self.exception
156
157 def __serialized_dict__(self):
158 """serialized form as a dictionary"""
159 return {
160 "__class__": "Pyro5.core._ExceptionWrapper",
161 "exception": serializers.SerializerBase.class_to_dict(self.exception)
162 }
163
164
165 # register the special serializers for the pyro objects with Serpent
166 serpent.register_class(URI, serializers.pyro_class_serpent_serializer)
167 serpent.register_class(_ExceptionWrapper, serializers.pyro_class_serpent_serializer)
168 serializers.SerializerBase.register_class_to_dict(URI, serializers.serialize_pyro_object_to_dict, serpent_too=False)
169 serializers.SerializerBase.register_class_to_dict(_ExceptionWrapper, _ExceptionWrapper.__serialized_dict__, serpent_too=False)
170
171
172 def resolve(uri: Union[str, URI], delay_time: float = 0.0) -> URI:
173 """
174 Resolve a 'magic' uri (PYRONAME, PYROMETA) into the direct PYRO uri.
175 It finds a name server, and use that to resolve a PYRONAME uri into the direct PYRO uri pointing to the named object.
176 If uri is already a PYRO uri, it is returned unmodified.
177 You can consider this a shortcut function so that you don't have to locate and use a name server proxy yourself.
178 Note: if you need to resolve more than a few names, consider using the name server directly instead of repeatedly
179 calling this function, to avoid the name server lookup overhead from each call.
180 You can set delay_time to the maximum number of seconds you are prepared to wait until a name registration
181 becomes available in the nameserver.
182 """
183 if isinstance(uri, str):
184 uri = URI(uri)
185 elif not isinstance(uri, URI):
186 raise TypeError("can only resolve Pyro URIs")
187 if uri.protocol == "PYRO":
188 return uri
189 log.debug("resolving %s", uri)
190 from . import nameserver # doing it here to avoid circular import issues
191 if uri.protocol == "PYRONAME":
192 with locate_ns(uri.host, uri.port) as ns:
193 return nameserver.lookup(ns, uri.object, delay_time)
194 elif uri.protocol == "PYROMETA":
195 with locate_ns(uri.host, uri.port) as ns:
196 candidates = nameserver.yplookup(ns, uri.object, None, False, delay_time)
197 if candidates:
198 candidate = random.choice(list(candidates.values()))
199 log.debug("resolved to candidate %s", candidate)
200 return URI(candidate)
201 raise errors.NamingError("no registrations available with desired metadata properties %s" % uri.object)
202 else:
203 raise errors.PyroError("invalid uri protocol")
204
205
206 def locate_ns(host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = "",
207 port: Optional[int] = None, broadcast: bool = True) -> "client.Proxy":
208 """Get a proxy for a name server somewhere in the network."""
209 from . import client
210 if not host:
211 # first try localhost if we have a good chance of finding it there
212 if config.NS_HOST in ("localhost", "::1") or config.NS_HOST.startswith("127."):
213 if ":" in config.NS_HOST: # ipv6
214 hosts = ["[%s]" % config.NS_HOST]
215 else:
216 # Some systems have 127.0.1.1 in the hosts file assigned to the hostname,
217 # so try this too (only if it's actually used as a valid ip address)
218 try:
219 socket.gethostbyaddr("127.0.1.1")
220 hosts = [config.NS_HOST] if config.NS_HOST == "127.0.1.1" else [config.NS_HOST, "127.0.1.1"]
221 except socket.error:
222 hosts = [config.NS_HOST]
223 for host in hosts:
224 uristring = "PYRO:%s@%s:%d" % (NAMESERVER_NAME, host, port or config.NS_PORT)
225 log.debug("locating the NS: %s", uristring)
226 proxy = client.Proxy(uristring)
227 with contextlib.suppress(errors.PyroError):
228 proxy._pyroBind()
229 log.debug("located NS")
230 return proxy
231 if config.PREFER_IP_VERSION == 6:
232 broadcast = False # ipv6 doesn't have broadcast. We should probably use multicast....
233 if broadcast:
234 # broadcast lookup
235 if not port:
236 port = config.NS_BCPORT
237 log.debug("broadcast locate")
238 sock = socketutil.create_bc_socket(reuseaddr=config.SOCK_REUSE, timeout=0.7)
239 for _ in range(3):
240 try:
241 for bcaddr in config.BROADCAST_ADDRS:
242 try:
243 sock.sendto(b"GET_NSURI", 0, (bcaddr, port))
244 except socket.error as x:
245 err = getattr(x, "errno", x.args[0])
246 # handle some errno's that some platforms like to throw:
247 if err not in socketutil.ERRNO_EADDRNOTAVAIL and err not in socketutil.ERRNO_EADDRINUSE:
248 raise
249 data, _ = sock.recvfrom(100)
250 sock.close()
251 text = data.decode("iso-8859-1")
252 log.debug("located NS: %s", text)
253 proxy = client.Proxy(text)
254 return proxy
255 except socket.timeout:
256 continue
257 with contextlib.suppress(OSError, socket.error):
258 sock.shutdown(socket.SHUT_RDWR)
259 sock.close()
260 log.debug("broadcast locate failed, try direct connection on NS_HOST")
261 else:
262 log.debug("skipping broadcast lookup")
263 # broadcast failed or skipped, try PYRO directly on specific host
264 host = config.NS_HOST
265 port = config.NS_PORT
266 elif not isinstance(host, str):
267 host = str(host) # take care of the occasion where host is an ipaddress.IpAddress
268 # pyro direct lookup
269 port = config.NS_PORT if not port else port
270 if URI.isUnixsockLocation(host):
271 uristring = "PYRO:%s@%s" % (NAMESERVER_NAME, host)
272 else:
273 # if not a unix socket, check for ipv6
274 if host and ":" in str(host):
275 host = "[%s]" % host
276 uristring = "PYRO:%s@%s:%d" % (NAMESERVER_NAME, host, port)
277 uri = URI(uristring)
278 log.debug("locating the NS: %s", uri)
279 proxy = client.Proxy(uri)
280 try:
281 proxy._pyroBind()
282 log.debug("located NS")
283 return proxy
284 except errors.PyroError as x:
285 raise errors.NamingError("Failed to locate the nameserver") from x
286
287
288 def type_meta(class_or_object, prefix="class:"):
289 """extracts type metadata from the given class or object, can be used as Name server metadata."""
290 if hasattr(class_or_object, "__mro__"):
291 return {prefix + c.__module__ + "." + c.__name__
292 for c in class_or_object.__mro__ if c.__module__ not in ("builtins", "__builtin__")}
293 if hasattr(class_or_object, "__class__"):
294 return type_meta(class_or_object.__class__)
295 return frozenset()