2 from __future__ import absolute_import
3 from binascii import hexlify, unhexlify
4 import os, struct, subprocess, sys
6 from bup import options, git, vfs, vint
7 from bup.compat import environ, hexstr
8 from bup.git import MissingObject
9 from bup.helpers import (Conn, debug1, debug2, linereader, lines_until_sentinel,
11 from bup.io import byte_stream, path_msg
12 from bup.repo import LocalRepo
16 dumb_server_mode = False
20 def do_help(conn, junk):
21 conn.write(b'Commands:\n %s\n' % b'\n '.join(sorted(commands)))
26 global dumb_server_mode
27 dumb_server_mode = os.path.exists(git.repo(b'bup-dumb-server'))
28 debug1('bup server: serving in %s mode\n'
29 % (dumb_server_mode and 'dumb' or 'smart'))
32 def _init_session(reinit_with_new_repopath=None):
34 if reinit_with_new_repopath is None and git.repodir:
38 git.check_repo_or_die(reinit_with_new_repopath)
42 # OK. we now know the path is a proper repository. Record this path in the
43 # environment so that subprocesses inherit it and know where to operate.
44 environ[b'BUP_DIR'] = git.repodir
45 debug1('bup server: bupdir is %s\n' % path_msg(git.repodir))
49 def init_dir(conn, arg):
51 debug1('bup server: bupdir initialized: %s\n' % path_msg(git.repodir))
56 def set_dir(conn, arg):
61 def list_indexes(conn, junk):
66 for f in os.listdir(git.repo(b'objects/pack')):
67 if f.endswith(b'.idx'):
68 conn.write(b'%s%s\n' % (f, suffix))
72 def send_index(conn, name):
74 assert name.find(b'/') < 0
75 assert name.endswith(b'.idx')
76 idx = git.open_idx(git.repo(b'objects/pack/%s' % name))
77 conn.write(struct.pack('!I', len(idx.map)))
82 def receive_objects_v2(conn, junk):
91 w = git.PackWriter(objcache_maker=None)
98 raise Exception('object read: expected length header, got EOF\n')
99 n = struct.unpack('!I', ns)[0]
100 #debug2('expecting %d bytes\n' % n)
102 debug1('bup server: received %d object%s.\n'
103 % (w.count, w.count!=1 and "s" or ''))
104 fullpath = w.close(run_midx=not dumb_server_mode)
106 (dir, name) = os.path.split(fullpath)
107 conn.write(b'%s.idx\n' % name)
110 elif n == 0xffffffff:
111 debug2('bup server: receive-objects suspended.\n')
117 crcr = struct.unpack('!I', conn.read(4))[0]
119 buf = conn.read(n) # object sizes in bup are reasonably small
120 #debug2('read %d bytes\n' % n)
121 _check(w, n, len(buf), 'object read: expected %d bytes, got %d\n')
122 if not dumb_server_mode:
123 oldpack = w.exists(shar, want_source=True)
125 assert(not oldpack == True)
126 assert(oldpack.endswith(b'.idx'))
127 (dir,name) = os.path.split(oldpack)
128 if not (name in suggested):
129 debug1("bup server: suggesting index %s\n"
130 % git.shorten_hash(name).decode('ascii'))
131 debug1("bup server: because of object %s\n"
133 conn.write(b'index %s\n' % name)
136 nw, crc = w._raw_write((buf,), sha=shar)
137 _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
141 def _check(w, expected, actual, msg):
142 if expected != actual:
144 raise Exception(msg % (expected, actual))
147 def read_ref(conn, refname):
149 r = git.read_ref(refname)
150 conn.write(b'%s\n' % hexlify(r) if r else b'')
154 def update_ref(conn, refname):
156 newval = conn.readline().strip()
157 oldval = conn.readline().strip()
158 git.update_ref(refname, unhexlify(newval), unhexlify(oldval))
164 for blob in git.cp().join(id):
165 conn.write(struct.pack('!I', len(blob)))
167 except KeyError as e:
168 log('server: error: %s\n' % e)
169 conn.write(b'\0\0\0\0')
172 conn.write(b'\0\0\0\0')
175 def cat_batch(conn, dummy):
178 # For now, avoid potential deadlock by just reading them all
179 for ref in tuple(lines_until_sentinel(conn, b'\n', Exception)):
181 it = cat_pipe.get(ref)
184 conn.write(b'missing\n')
186 conn.write(b'%s %s %d\n' % info)
191 def refs(conn, args):
192 limit_to_heads, limit_to_tags = args.split()
193 assert limit_to_heads in (b'0', b'1')
194 assert limit_to_tags in (b'0', b'1')
195 limit_to_heads = int(limit_to_heads)
196 limit_to_tags = int(limit_to_tags)
198 patterns = tuple(x[:-1] for x in lines_until_sentinel(conn, b'\n', Exception))
199 for name, oid in git.list_refs(patterns=patterns,
200 limit_to_heads=limit_to_heads,
201 limit_to_tags=limit_to_tags):
202 assert b'\n' not in name
203 conn.write(b'%s %s\n' % (hexlify(oid), name))
207 def rev_list(conn, _):
209 count = conn.readline()
211 raise Exception('Unexpected EOF while reading rev-list count')
212 assert count == b'\n'
214 fmt = conn.readline()
216 raise Exception('Unexpected EOF while reading rev-list format')
217 fmt = None if fmt == b'\n' else fmt[:-1]
218 refs = tuple(x[:-1] for x in lines_until_sentinel(conn, b'\n', Exception))
219 args = git.rev_list_invocation(refs, format=fmt)
220 p = subprocess.Popen(args, env=git._gitenv(git.repodir),
221 stdout=subprocess.PIPE)
223 out = p.stdout.read(64 * 1024)
228 rv = p.wait() # not fatal
230 msg = 'git rev-list returned error %d' % rv
235 def resolve(conn, args):
237 (flags,) = args.split()
239 want_meta = bool(flags & 1)
240 follow = bool(flags & 2)
241 have_parent = bool(flags & 4)
242 parent = vfs.read_resolution(conn) if have_parent else None
243 path = vint.read_bvec(conn)
245 raise Exception('Empty resolve path')
247 res = list(vfs.resolve(repo, path, parent=parent, want_meta=want_meta,
249 except vfs.IOError as ex:
251 if isinstance(res, vfs.IOError):
252 conn.write(b'\x00') # error
253 vfs.write_ioerror(conn, res)
255 conn.write(b'\x01') # success
256 vfs.write_resolution(conn, res)
266 b'init-dir': init_dir,
268 b'list-indexes': list_indexes,
269 b'send-index': send_index,
270 b'receive-objects-v2': receive_objects_v2,
271 b'read-ref': read_ref,
272 b'update-ref': update_ref,
274 b'cat': join, # apocryphal alias
275 b'cat-batch' : cat_batch,
277 b'rev-list': rev_list,
282 o = options.Options(optspec)
283 opt, flags, extra = o.parse_bytes(argv[1:])
286 o.fatal('no arguments expected')
288 debug2('bup server: reading from stdin.\n')
290 # FIXME: this protocol is totally lame and not at all future-proof.
291 # (Especially since we abort completely as soon as *anything* bad happens)
293 conn = Conn(byte_stream(sys.stdin), byte_stream(sys.stdout))
294 lr = linereader(conn)
299 debug1('bup server: command: %r\n' % line)
300 words = line.split(b' ', 1)
302 rest = len(words)>1 and words[1] or b''
306 cmd = commands.get(cmd)
310 raise Exception('unknown server command: %r\n' % line)
312 debug1('bup server: done\n')