Debian Codegraph @

hgext/zeroconf/__init__.py

raw
1 # zeroconf.py - zeroconf support for Mercurial
2 #
3 # Copyright 2005-2007 Olivia Mackall <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7 '''discover and advertise repositories on the local network
8
9 The zeroconf extension will advertise :hg:`serve` instances over
10 DNS-SD so that they can be discovered using the :hg:`paths` command
11 without knowing the server's IP address.
12
13 To allow other people to discover your repository using run
14 :hg:`serve` in your repository::
15
16 $ cd test
17 $ hg serve
18
19 You can discover Zeroconf-enabled repositories by running
20 :hg:`paths`::
21
22 $ hg paths
23 zc-test = http://example.com:8000/test
24 '''
25
26 from __future__ import annotations
27
28 import os
29 import socket
30 import time
31
32 from . import Zeroconf
33 from mercurial import (
34 dispatch,
35 encoding,
36 extensions,
37 pycompat,
38 ui as uimod,
39 )
40 from mercurial.cmd_impls import clone as clone_impl
41 from mercurial.configuration import rcutil
42 from mercurial.hgweb import server as servermod
43
44 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
45 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
46 # be specifying the version(s) of Mercurial they are tested with, or
47 # leave the attribute unspecified.
48 testedwith = b'ships-with-hg-core'
49
50 # publish
51
52 server = None
53 localip = None
54
55
56 def getip():
57 # finds external-facing interface without sending any packets (Linux)
58 try:
59 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
60 s.connect(('1.0.0.1', 0))
61 ip = s.getsockname()[0]
62 return ip
63 except OSError:
64 pass
65
66 # Generic method, sometimes gives useless results
67 try:
68 dumbip = socket.gethostbyaddr(socket.gethostname())[2][0]
69 if ':' in dumbip:
70 dumbip = '127.0.0.1'
71 if not dumbip.startswith('127.'):
72 return dumbip
73 except (socket.gaierror, socket.herror):
74 dumbip = '127.0.0.1'
75
76 # works elsewhere, but actually sends a packet
77 try:
78 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
79 s.connect(('1.0.0.1', 1))
80 ip = s.getsockname()[0]
81 return ip
82 except OSError:
83 pass
84
85 return dumbip
86
87
88 def publish(name, desc, path, port):
89 global server, localip
90 if not server:
91 ip = getip()
92 if ip.startswith('127.'):
93 # if we have no internet connection, this can happen.
94 return
95 localip = socket.inet_aton(ip)
96 server = Zeroconf.Zeroconf(ip)
97
98 hostname = socket.gethostname().split('.')[0]
99 host = hostname + ".local"
100 name = "%s-%s" % (hostname, name)
101
102 # advertise to browsers
103 svc = Zeroconf.ServiceInfo(
104 b'_http._tcp.local.',
105 pycompat.bytestr(name + '._http._tcp.local.'),
106 server=host,
107 port=port,
108 properties={b'description': desc, b'path': b"/" + path},
109 address=localip,
110 weight=0,
111 priority=0,
112 )
113 server.registerService(svc)
114
115 # advertise to Mercurial clients
116 svc = Zeroconf.ServiceInfo(
117 b'_hg._tcp.local.',
118 pycompat.bytestr(name + '._hg._tcp.local.'),
119 server=host,
120 port=port,
121 properties={b'description': desc, b'path': b"/" + path},
122 address=localip,
123 weight=0,
124 priority=0,
125 )
126 server.registerService(svc)
127
128
129 def zc_create_server(create_server, ui, app):
130 httpd = create_server(ui, app)
131 port = httpd.port
132
133 try:
134 repos = app.repos
135 except AttributeError:
136 # single repo
137 with app._obtainrepo() as repo:
138 name = app.reponame or os.path.basename(repo.root)
139 path = repo.ui.config(b"web", b"prefix", b"").strip(b'/')
140 desc = repo.ui.config(b"web", b"description")
141 if not desc:
142 desc = name
143 publish(name, desc, path, port)
144 else:
145 # webdir
146 prefix = app.ui.config(b"web", b"prefix", b"").strip(b'/') + b'/'
147 for repo, path in repos:
148 u = app.ui.copy()
149 if rcutil.use_repo_hgrc():
150 u.readconfig(os.path.join(path, b'.hg', b'hgrc'))
151 name = os.path.basename(repo)
152 path = (prefix + repo).strip(b'/')
153 desc = u.config(b'web', b'description')
154 if not desc:
155 desc = name
156 publish(name, desc, path, port)
157 return httpd
158
159
160 # listen
161
162
163 class listener:
164 def __init__(self):
165 self.found = {}
166
167 def removeService(self, server, type, name):
168 if repr(name) in self.found:
169 del self.found[repr(name)]
170
171 def addService(self, server, type, name):
172 self.found[repr(name)] = server.getServiceInfo(type, name)
173
174
175 def getzcpaths():
176 ip = getip()
177 if ip.startswith('127.'):
178 return
179 server = Zeroconf.Zeroconf(ip)
180 l = listener()
181 Zeroconf.ServiceBrowser(server, b"_hg._tcp.local.", l)
182 time.sleep(1)
183 server.close()
184 for value in l.found.values():
185 name = value.name[: value.name.index(b'.')]
186 url = "http://%s:%s%s" % (
187 socket.inet_ntoa(value.address),
188 value.port,
189 value.properties.get("path", "/"),
190 )
191 yield b"zc-" + name, pycompat.bytestr(url)
192
193
194 def config(orig, self, section, key, *args, **kwargs):
195 if section == b"paths" and key.startswith(b"zc-"):
196 for name, path in getzcpaths():
197 if name == key:
198 return path
199 return orig(self, section, key, *args, **kwargs)
200
201
202 def configitems(orig, self, section, *args, **kwargs):
203 repos = orig(self, section, *args, **kwargs)
204 if section == b"paths":
205 repos += getzcpaths()
206 return repos
207
208
209 def configsuboptions(orig, self, section, name, *args, **kwargs):
210 opt, sub = orig(self, section, name, *args, **kwargs)
211 if section == b"paths" and name.startswith(b"zc-"):
212 # We have to find the URL in the zeroconf paths. We can't cons up any
213 # suboptions, so we use any that we found in the original config.
214 for zcname, zcurl in getzcpaths():
215 if zcname == name:
216 return zcurl, sub
217 return opt, sub
218
219
220 def default_dest(orig, source):
221 for name, path in getzcpaths():
222 if path == source:
223 return name.encode(encoding.encoding)
224 return orig(source)
225
226
227 def cleanupafterdispatch(orig, ui, options, cmd, cmdfunc):
228 try:
229 return orig(ui, options, cmd, cmdfunc)
230 finally:
231 # we need to call close() on the server to notify() the various
232 # threading Conditions and allow the background threads to exit
233 global server
234 if server:
235 server.close()
236
237
238 extensions.wrapfunction(dispatch, '_runcommand', cleanupafterdispatch)
239
240 extensions.wrapfunction(uimod.ui, 'config', config)
241 extensions.wrapfunction(uimod.ui, 'configitems', configitems)
242 extensions.wrapfunction(uimod.ui, 'configsuboptions', configsuboptions)
243 extensions.wrapfunction(clone_impl, 'default_dest', default_dest)
244 extensions.wrapfunction(servermod, 'create_server', zc_create_server)