1 # Copyright (c) 2010, 2012, 2014, 2015 Nicira, Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
22 import ovs.fatal_signal
26 vlog = ovs.vlog.Vlog("socket_util")
29 def make_short_name(long_name):
32 long_name = os.path.abspath(long_name)
33 long_dirname = os.path.dirname(long_name)
34 tmpdir = os.getenv('TMPDIR', '/tmp')
35 for x in xrange(0, 1000):
37 '%s/ovs-un-py-%d-%d' % (tmpdir, random.randint(0, 10000), x)
39 os.symlink(long_dirname, link_name)
40 ovs.fatal_signal.add_file_to_unlink(link_name)
41 return os.path.join(link_name, os.path.basename(long_name))
43 if e.errno != errno.EEXIST:
45 raise Exception("Failed to create temporary symlink")
48 def free_short_name(short_name):
49 if short_name is None:
51 link_name = os.path.dirname(short_name)
52 ovs.fatal_signal.unlink_file_now(link_name)
55 def make_unix_socket(style, nonblock, bind_path, connect_path, short=False):
56 """Creates a Unix domain socket in the given 'style' (either
57 socket.SOCK_DGRAM or socket.SOCK_STREAM) that is bound to 'bind_path' (if
58 'bind_path' is not None) and connected to 'connect_path' (if 'connect_path'
59 is not None). If 'nonblock' is true, the socket is made non-blocking.
61 Returns (error, socket): on success 'error' is 0 and 'socket' is a new
62 socket object, on failure 'error' is a positive errno value and 'socket' is
66 sock = socket.socket(socket.AF_UNIX, style)
67 except socket.error, e:
68 return get_exception_errno(e), None
73 if bind_path is not None:
74 # Delete bind_path but ignore ENOENT.
78 if e.errno != errno.ENOENT:
81 ovs.fatal_signal.add_file_to_unlink(bind_path)
85 if sys.hexversion >= 0x02060000:
86 os.fchmod(sock.fileno(), 0700)
88 os.chmod("/dev/fd/%d" % sock.fileno(), 0700)
91 if connect_path is not None:
93 sock.connect(connect_path)
94 except socket.error, e:
95 if get_exception_errno(e) != errno.EINPROGRESS:
98 except socket.error, e:
100 if (bind_path is not None and
101 os.path.exists(bind_path)):
102 ovs.fatal_signal.unlink_file_now(bind_path)
103 eno = ovs.socket_util.get_exception_errno(e)
104 if (eno == "AF_UNIX path too long" and
105 os.uname()[0] == "Linux"):
106 short_connect_path = None
107 short_bind_path = None
110 # Try workaround using /proc/self/fd
111 if connect_path is not None:
112 dirname = os.path.dirname(connect_path)
113 basename = os.path.basename(connect_path)
115 connect_dirfd = os.open(dirname, os.O_DIRECTORY | os.O_RDONLY)
117 return get_exception_errno(err), None
118 short_connect_path = "/proc/self/fd/%d/%s" % (connect_dirfd, basename)
120 if bind_path is not None:
121 dirname = os.path.dirname(bind_path)
122 basename = os.path.basename(bind_path)
124 bind_dirfd = os.open(dirname, os.O_DIRECTORY | os.O_RDONLY)
126 return get_exception_errno(err), None
127 short_bind_path = "/proc/self/fd/%d/%s" % (bind_dirfd, basename)
130 return make_unix_socket(style, nonblock, short_bind_path, short_connect_path)
132 if connect_dirfd is not None:
133 os.close(connect_dirfd)
134 if bind_dirfd is not None:
136 elif (eno == "AF_UNIX path too long"):
138 return get_exception_errno(e), None
139 short_bind_path = None
141 short_bind_path = make_short_name(bind_path)
142 short_connect_path = make_short_name(connect_path)
144 free_short_name(short_bind_path)
145 return errno.ENAMETOOLONG, None
147 return make_unix_socket(style, nonblock, short_bind_path,
148 short_connect_path, short=True)
150 free_short_name(short_bind_path)
151 free_short_name(short_connect_path)
153 return get_exception_errno(e), None
156 def check_connection_completion(sock):
157 p = ovs.poller.SelectPoll()
158 p.register(sock, ovs.poller.POLLOUT)
162 if revents & ovs.poller.POLLERR:
164 # The following should raise an exception.
165 socket.send("\0", socket.MSG_DONTWAIT)
167 # (Here's where we end up if it didn't.)
169 vlog.err("poll return POLLERR but send succeeded")
171 except socket.error, e:
172 return get_exception_errno(e)
179 def is_valid_ipv4_address(address):
181 socket.inet_pton(socket.AF_INET, address)
182 except AttributeError:
184 socket.inet_aton(address)
193 def inet_parse_active(target, default_port):
194 address = target.split(":")
195 if len(address) >= 2:
196 host_name = ":".join(address[0:-1]).lstrip('[').rstrip(']')
197 port = int(address[-1])
202 raise ValueError("%s: port number must be specified" % target)
203 host_name = address[0]
205 raise ValueError("%s: bad peer name format" % target)
206 return (host_name, port)
209 def inet_open_active(style, target, default_port, dscp):
210 address = inet_parse_active(target, default_port)
212 is_addr_inet = is_valid_ipv4_address(address[0])
214 sock = socket.socket(socket.AF_INET, style, 0)
215 family = socket.AF_INET
217 sock = socket.socket(socket.AF_INET6, style, 0)
218 family = socket.AF_INET6
219 except socket.error, e:
220 return get_exception_errno(e), None
223 set_nonblocking(sock)
224 set_dscp(sock, family, dscp)
226 sock.connect(address)
227 except socket.error, e:
228 if get_exception_errno(e) != errno.EINPROGRESS:
231 except socket.error, e:
233 return get_exception_errno(e), None
236 def get_exception_errno(e):
237 """A lot of methods on Python socket objects raise socket.error, but that
238 exception is documented as having two completely different forms of
239 arguments: either a string or a (errno, string) tuple. We only want the
241 if type(e.args) == tuple:
251 """Returns a readable and writable fd for /dev/null, if successful,
252 otherwise a negative errno value. The caller must not close the returned
253 fd (because the same fd will be handed out to subsequent callers)."""
257 null_fd = os.open("/dev/null", os.O_RDWR)
259 vlog.err("could not open /dev/null: %s" % os.strerror(e.errno))
264 def write_fully(fd, buf):
265 """Returns an (error, bytes_written) tuple where 'error' is 0 on success,
266 otherwise a positive errno value, and 'bytes_written' is the number of
267 bytes that were written before the error occurred. 'error' is 0 if and
268 only if 'bytes_written' is len(buf)."""
274 retval = os.write(fd, buf)
276 if retval == len(buf):
277 return 0, bytes_written + len(buf)
279 vlog.warn("write returned 0")
280 return errno.EPROTO, bytes_written
282 bytes_written += retval
285 return e.errno, bytes_written
288 def set_nonblocking(sock):
291 except socket.error, e:
292 vlog.err("could not set nonblocking mode on socket: %s"
293 % os.strerror(get_exception_errno(e)))
296 def set_dscp(sock, family, dscp):
298 raise ValueError("Invalid dscp %d" % dscp)
301 if family == socket.AF_INET:
302 sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, val)
303 elif family == socket.AF_INET6:
304 sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, val)
306 raise ValueError('Invalid family %d' % family)