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, pending_raise
9 import (Conn, debug1, debug2, finalized, 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 with git.open_idx(git.repo(b'objects/pack/%s' % name)) as idx:
77 conn.write(struct.pack('!I', len(idx.map)))
82 def receive_objects_v2(conn, junk):
88 elif dumb_server_mode:
89 w = git.PackWriter(objcache_maker=None)
98 raise Exception('object read: expected length header, got EOF')
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)
107 dir, name = os.path.split(fullpath)
108 conn.write(b'%s.idx\n' % name)
111 elif n == 0xffffffff:
112 debug2('bup server: receive-objects suspending\n')
119 crcr = struct.unpack('!I', conn.read(4))[0]
121 buf = conn.read(n) # object sizes in bup are reasonably small
122 #debug2('read %d bytes\n' % n)
123 _check(w, n, len(buf), 'object read: expected %d bytes, got %d\n')
124 if not dumb_server_mode:
125 oldpack = w.exists(shar, want_source=True)
127 assert(not oldpack == True)
128 assert(oldpack.endswith(b'.idx'))
129 (dir,name) = os.path.split(oldpack)
130 if not (name in suggested):
131 debug1("bup server: suggesting index %s\n"
132 % git.shorten_hash(name).decode('ascii'))
133 debug1("bup server: because of object %s\n"
135 conn.write(b'index %s\n' % name)
138 nw, crc = w._raw_write((buf,), sha=shar)
139 _check(w, crcr, crc, 'object read: expected crc %d, got %d\n')
140 # py2: this clause is unneeded with py3
141 except BaseException as ex:
142 with pending_raise(ex):
148 assert False # should be unreachable
151 def _check(w, expected, actual, msg):
152 if expected != actual:
154 raise Exception(msg % (expected, actual))
157 def read_ref(conn, refname):
159 r = git.read_ref(refname)
160 conn.write(b'%s\n' % hexlify(r) if r else b'')
164 def update_ref(conn, refname):
166 newval = conn.readline().strip()
167 oldval = conn.readline().strip()
168 git.update_ref(refname, unhexlify(newval), unhexlify(oldval))
174 for blob in git.cp().join(id):
175 conn.write(struct.pack('!I', len(blob)))
177 except KeyError as e:
178 log('server: error: %s\n' % e)
179 conn.write(b'\0\0\0\0')
182 conn.write(b'\0\0\0\0')
185 def cat_batch(conn, dummy):
188 # For now, avoid potential deadlock by just reading them all
189 for ref in tuple(lines_until_sentinel(conn, b'\n', Exception)):
191 it = cat_pipe.get(ref)
194 conn.write(b'missing\n')
196 conn.write(b'%s %s %d\n' % info)
201 def refs(conn, args):
202 limit_to_heads, limit_to_tags = args.split()
203 assert limit_to_heads in (b'0', b'1')
204 assert limit_to_tags in (b'0', b'1')
205 limit_to_heads = int(limit_to_heads)
206 limit_to_tags = int(limit_to_tags)
208 patterns = tuple(x[:-1] for x in lines_until_sentinel(conn, b'\n', Exception))
209 for name, oid in git.list_refs(patterns=patterns,
210 limit_to_heads=limit_to_heads,
211 limit_to_tags=limit_to_tags):
212 assert b'\n' not in name
213 conn.write(b'%s %s\n' % (hexlify(oid), name))
217 def rev_list(conn, _):
219 count = conn.readline()
221 raise Exception('Unexpected EOF while reading rev-list count')
222 assert count == b'\n'
224 fmt = conn.readline()
226 raise Exception('Unexpected EOF while reading rev-list format')
227 fmt = None if fmt == b'\n' else fmt[:-1]
228 refs = tuple(x[:-1] for x in lines_until_sentinel(conn, b'\n', Exception))
229 args = git.rev_list_invocation(refs, format=fmt)
230 p = subprocess.Popen(args, env=git._gitenv(git.repodir),
231 stdout=subprocess.PIPE)
233 out = p.stdout.read(64 * 1024)
238 rv = p.wait() # not fatal
240 msg = 'git rev-list returned error %d' % rv
242 raise git.GitError(msg)
245 def resolve(conn, args):
247 (flags,) = args.split()
249 want_meta = bool(flags & 1)
250 follow = bool(flags & 2)
251 have_parent = bool(flags & 4)
252 parent = vfs.read_resolution(conn) if have_parent else None
253 path = vint.read_bvec(conn)
255 raise Exception('Empty resolve path')
257 res = list(vfs.resolve(repo, path, parent=parent, want_meta=want_meta,
259 except vfs.IOError as ex:
261 if isinstance(res, vfs.IOError):
262 conn.write(b'\x00') # error
263 vfs.write_ioerror(conn, res)
265 conn.write(b'\x01') # success
266 vfs.write_resolution(conn, res)
276 b'init-dir': init_dir,
278 b'list-indexes': list_indexes,
279 b'send-index': send_index,
280 b'receive-objects-v2': receive_objects_v2,
281 b'read-ref': read_ref,
282 b'update-ref': update_ref,
284 b'cat': join, # apocryphal alias
285 b'cat-batch' : cat_batch,
287 b'rev-list': rev_list,
292 global repo, suspended_w
294 o = options.Options(optspec)
295 opt, flags, extra = o.parse_bytes(argv[1:])
297 o.fatal('no arguments expected')
299 debug2('bup server: reading from stdin.\n')
301 # FIXME: this protocol is totally lame and not at all future-proof.
302 # (Especially since we abort completely as soon as *anything* bad happens)
304 with Conn(byte_stream(sys.stdin), byte_stream(sys.stdout)) as conn, \
305 finalized(None, lambda _: repo and repo.close()), \
306 finalized(None, lambda _: suspended_w and suspended_w.close()):
307 lr = linereader(conn)
312 debug1('bup server: command: %r\n' % line)
313 words = line.split(b' ', 1)
315 rest = len(words)>1 and words[1] or b''
319 cmd = commands.get(cmd)
323 raise Exception('unknown server command: %r\n' % line)
324 debug1('bup server: done\n')