Better response message
[0share.git] / 0share
blobb2f211f65229797c3fe6e708eb0bdbc4fe2b27cf
1 #!/usr/bin/env python
2 # Copyright (C) 2008, Thomas Leonard
3 # See the README file for details, or visit http://0install.net.
5 from optparse import OptionParser
6 from logging import info, debug
7 import socket
9 from zeroinstall.zerostore import Stores, BadDigest, NotStored
11 version = '0.1'
12 port = 308339
14 parser = OptionParser(usage="usage: %prog\n"
15 "usage: %prog --fetch DIGEST...")
17 parser.add_option("-f", "--fetch", help="act as a client", action='store_true')
18 parser.add_option("-q", "--quiet", help="less verbose output", action='store_true')
19 parser.add_option("-v", "--verbose", help="more verbose output", action='store_true')
20 parser.add_option("-V", "--version", help="display version information", action='store_true')
22 (options, args) = parser.parse_args()
24 if options.version:
25 print "0share (zero-install) " + version
26 print "Copyright (C) 2008 Thomas Leonard"
27 print "This program comes with ABSOLUTELY NO WARRANTY,"
28 print "to the extent permitted by law."
29 print "You may redistribute copies of this program"
30 print "under the terms of the GNU General Public License."
31 print "For more information about these matters, see the file named COPYING."
32 sys.exit(0)
34 import logging
35 logger = logging.getLogger()
36 if options.verbose:
37 logger.setLevel(logging.DEBUG)
38 elif not options.quiet:
39 logger.setLevel(logging.INFO)
41 if options.fetch:
42 # Client mode
43 import client
44 client.fetch(args)
45 else:
46 # Server mode
47 if args:
48 parser.print_help()
49 sys.exit(1)
51 stores = Stores()
53 ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
54 ss.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
55 #ss.bind(('<broadcast>', 308339))
56 ss.bind(('', 308339))
58 info("0share started and listening for requests...")
59 while True:
60 data, addr = ss.recvfrom(128)
61 info("Request from %s: %s", addr, repr(data))
62 if not data.startswith('0share\n'):
63 info("Not our format. Ignoring.")
64 continue
65 digests = data.split('\n')[1:]
66 got = []
67 try:
68 for d in digests:
69 if not d: raise BadDigest("Empty digest!")
70 try:
71 stores.lookup(d)
72 info("Yes, we have %s", d)
73 got.append(d)
74 except NotStored:
75 info("No, we don't have %s", d)
76 except BadDigest, ex:
77 info("Bad request: %s", str(ex))
78 continue
79 if got:
80 info("Sending reply...")
81 ss.sendto('0share-reply\n' + '\n'.join(got), addr)