• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/router/avahi-0.6.31/avahi-python/
1#!@PYTHON@
2# -*-python-*-
3# This file is part of avahi.
4#
5# avahi is free software; you can redistribute it and/or modify it
6# under the terms of the GNU Lesser General Public License as
7# published by the Free Software Foundation; either version 2 of the
8# License, or (at your option) any later version.
9#
10# avahi is distributed in the hope that it will be useful, but WITHOUT
11# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
13# License for more details.
14#
15# You should have received a copy of the GNU Lesser General Public
16# License along with avahi; if not, write to the Free Software
17# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18# USA.
19
20import sys, getopt, os
21
22try:
23    import avahi, gobject, dbus
24except ImportError:
25    print "Sorry, to use this tool you need to install Avahi and python-dbus."
26    sys.exit(1)
27
28try:
29    import dbus.glib
30except ImportError:
31    pass
32
33urlproto = { "_http._tcp" : "http",  "_https._tcp" : "https", "_ftp._tcp" : "ftp" }
34
35port = 8080
36address = "127.0.0.1"
37use_host_names = None
38use_CGI = None
39domain = "local"
40timeout = 3000
41
42class AvahiBookmarks:
43    services = {}
44
45    def __init__(self, use_host_names):
46
47        self.bus = dbus.SystemBus()
48        self.server = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
49
50        self.version_string = self.server.GetVersionString()
51
52        self.browse_service_type("_http._tcp")
53        self.browse_service_type("_https._tcp")
54        self.browse_service_type("_ftp._tcp")
55
56        if use_host_names is None:
57            try: 
58                self.use_host_names = self.server.IsNSSSupportAvailable()
59            except:
60                self.use_host_names = False
61        else:
62            self.use_host_names = use_host_names
63
64    def browse_service_type(self, stype):
65
66        global domain, use_CGI
67
68        browser = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, stype, domain, dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER)
69        browser.connect_to_signal('ItemNew', self.new_service)
70        browser.connect_to_signal('ItemRemove', self.remove_service)
71        if use_CGI:
72            browser.connect_to_signal('AllForNow', self.all_for_now)
73
74    def find_path(self, txt):
75
76        l = avahi.txt_array_to_string_array(txt)
77
78        for k in l:
79            if k[:5] == "path=":
80                if k[5:].startswith("/"):
81                    return k[5:]
82                else:
83                    return "/" + k[5:]
84
85        return "/"
86
87    def render_html(self):
88
89        global domain
90
91        t = '<html><head><title>%s Zeroconf Bookmarks</title></head><body><h1>%s Zeroconf Bookmarks</h1>' % (domain, domain)
92
93        if len(self.services) == 0:
94            t += '<p>Sorry, no Zeroconf web services have been registered on the %s domain.</p>' % domain
95        else:
96            t += '<ul style="padding: 0px; margin: 20px; list-style-type: none">'
97
98            for k, v in self.services.iteritems():
99            
100                if v[3] == 80:
101                    port = ''
102                else:
103                    port = ':%i' % v[3]
104
105                path = self.find_path(v[4])
106                t += '<li><a href="%s://%s%s%s">%s</a></li>' % (urlproto[k[3]], v[2], port, path, k[2])
107                
108            t += '</ul>'
109        
110        t += '<hr noshade/><p style="font-size: 8; font-family: sans-serif">Served by %s</p></body></html>' % self.version_string
111
112        return str(t)
113
114
115    def new_service(self, interface, protocol, name, type, domain, flags):
116
117        interface, protocol, name, type, domain, host, aprotocol, address, port, txt, flags = self.server.ResolveService(interface, protocol, name, type, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0))
118
119        if self.use_host_names:
120            h = host
121        else:
122            if aprotocol == avahi.PROTO_INET6:
123                h = "[" + address + "]"
124            else:
125                h = address
126
127        self.services[(interface, protocol, name, type, domain)] = (host, aprotocol, h, port, txt)
128
129    def remove_service(self, interface, protocol, name, type, domain):
130
131        del self.services[(interface, protocol, name, type, domain)]
132
133
134    # Only reachable with use_CGI
135    def all_for_now(self):
136
137        mainloop.quit()
138
139def usage(retval = 0):
140
141    print "%s [options]\n" % sys.argv[0]
142    print "   -h --help             Show this help"
143    print "   -c --cgi              Run as a CGI instead of as a server (default to server"
144    print "                         unless environment variable GATEWAY_INTERFACE is set)"
145    print "   -t --timeout MS       Specify the max time for CGI browsing (default %u)" % timeout
146    print "   -p --port PORT        Specify the port to use (default %u)" % port
147    print "   -a --address ADDRESS  Specify the address to bind to (default %s)" % address
148    print "   -H --host-names       Show links with real hostnames"
149    print "   -A --addresses        Show links with numeric IP addresses"
150    print "   -d --domain DOMAIN    Specify the domain to browse" 
151    sys.exit(retval)
152
153try:
154    opts, args = getopt.getopt(sys.argv[1:], "hct:p:a:HAd:", ["help", "cgi", "port=", "timeout=", "address=", "host-names", "addresses", "domain="])
155except getopt.GetoptError:
156    usage(2)
157
158for o, a in opts:
159    if o in ("-h", "--help"):
160        usage()
161
162    if o in ("-c", "--cgi"):
163        use_CGI = True
164
165    if o in ("-t", "--timeout"):
166        timeout = int(a)
167
168    if o in ("-p", "--port"):
169        port = int(a)
170
171    if o in ("-a", "--address"):
172        address = a
173
174    if o in ("-H", "--host-names"):
175        use_host_names = True
176
177    if o in ("-A", "--addresses"):
178        use_host_names = False
179
180    if o in ("-d", "--domain"):
181        domain = a
182
183if use_CGI is None:
184    use_CGI = os.environ.has_key("GATEWAY_INTERFACE")
185
186if use_CGI:
187    cgi = AvahiBookmarks(use_host_names)
188
189    mainloop = gobject.MainLoop()
190    gobject.timeout_add(timeout, mainloop.quit)
191
192    try:
193        mainloop.run()
194    except KeyboardInterrupt:
195        pass
196        
197    print 'Content-type: text/html\n\n' + cgi.render_html()
198
199else:
200    try:
201        from twisted.internet import glib2reactor
202        glib2reactor.install()
203        from twisted.internet import reactor
204        from twisted.web import server, resource
205    except ImportError:
206        print "Sorry, to use this tool as a server you need to install twisted and twisted.web.\n"
207	sys.exit(1)
208
209    class AvahiBookmarksServer(AvahiBookmarks, resource.Resource):
210        isLeaf = True
211
212        def __init__(self, use_host_names):
213            resource.Resource.__init__(self)
214            AvahiBookmarks.__init__(self, use_host_names)
215
216        def render_GET(self, request):
217            return self.render_html()
218
219    site = server.Site(AvahiBookmarksServer(use_host_names))
220    reactor.listenTCP(port, site, interface=address)
221
222    print "Now point your web browser to http://%s:%u/!" % (address, port)
223
224    try:
225        reactor.run()
226    except KeyboardInterrupt:
227        pass
228