1 import re, struct, errno, select
3 from bup.helpers import *
4 from subprocess import Popen, PIPE
7 class ClientError(Exception):
12 def __init__(self, remote, create=False):
16 rs = remote.split(':', 1)
17 main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
18 nicedir = os.path.split(os.path.abspath(main_exe))[0]
19 nicedir = re.sub(r':', "_", nicedir)
21 (host, dir) = ('NONE', remote)
23 os.environ['PATH'] = ':'.join([nicedir,
24 os.environ.get('PATH', '')])
25 argv = ['bup', 'server']
29 # WARNING: shell quoting security holes are possible here, so we
30 # have to be super careful. We have to use 'sh -c' because
31 # csh-derived shells can't handle PATH= notation. We can't
32 # set PATH in advance, because ssh probably replaces it. We
33 # can't exec *safely* using argv, because *both* ssh and 'sh -c'
34 # allow shellquoting. So we end up having to double-shellquote
36 escapedir = re.sub(r'([^\w/])', r'\\\\\\\1', nicedir)
38 sh -c PATH=%s:'$PATH bup server'
40 argv = ['ssh', host, '--', cmd.strip()]
41 #log('argv is: %r\n' % argv)
46 (self.host, self.dir) = (host, dir)
47 self.cachedir = git.repo('index-cache/%s'
48 % re.sub(r'[^@\w]', '_',
49 "%s:%s" % (host, dir)))
51 self.p = p = Popen(argv, stdin=PIPE, stdout=PIPE, preexec_fn=setup)
53 raise ClientError, 'exec %r: %s' % (argv[0], e), sys.exc_info()[2]
54 self.conn = conn = Conn(p.stdout, p.stdin)
56 dir = re.sub(r'[\r\n]', ' ', dir)
58 conn.write('init-dir %s\n' % dir)
60 conn.write('set-dir %s\n' % dir)
62 self.sync_indexes_del()
68 if e.errno == errno.EPIPE:
74 if self.conn and not self._busy:
75 self.conn.write('quit\n')
78 while self.p.stdout.read(65536):
84 raise ClientError('server tunnel returned exit code %d' % rv)
91 raise ClientError('server exited unexpectedly with code %r' % rv)
93 return self.conn.check_ok()
95 raise ClientError, e, sys.exc_info()[2]
99 raise ClientError('already busy with command %r' % self._busy)
104 def sync_indexes_del(self):
107 conn.write('list-indexes\n')
108 packdir = git.repo('objects/pack')
111 for line in linereader(conn):
115 assert(line.find('/') < 0)
116 if not os.path.exists(os.path.join(self.cachedir, line)):
120 mkdirp(self.cachedir)
121 for f in os.listdir(self.cachedir):
122 if f.endswith('.idx') and not f in all:
123 log('pruning old index: %r\n' % f)
124 os.unlink(os.path.join(self.cachedir, f))
126 def sync_index(self, name):
127 #log('requesting %r\n' % name)
128 mkdirp(self.cachedir)
129 self.conn.write('send-index %s\n' % name)
130 n = struct.unpack('!I', self.conn.read(4))[0]
132 fn = os.path.join(self.cachedir, name)
133 f = open(fn + '.tmp', 'w')
135 progress('Receiving index: %d/%d\r' % (count, n))
136 for b in chunkyreader(self.conn, n):
139 progress('Receiving index: %d/%d\r' % (count, n))
140 progress('Receiving index: %d/%d, done.\n' % (count, n))
143 os.rename(fn + '.tmp', fn)
145 def _make_objcache(self):
150 return git.PackIdxList(self.cachedir)
152 def _suggest_pack(self, indexname):
153 log('received index suggestion: %s\n' % indexname)
156 assert(ob == 'receive-objects')
158 self.conn.write('\xff\xff\xff\xff') # suspend receive-objects
159 self.conn.drain_and_check_ok()
160 self.sync_index(indexname)
162 self.conn.write('receive-objects\n')
165 def new_packwriter(self):
167 self._busy = 'receive-objects'
168 return PackWriter_Remote(self.conn,
169 objcache_maker = self._make_objcache,
170 suggest_pack = self._suggest_pack,
171 onclose = self._not_busy)
173 def read_ref(self, refname):
175 self.conn.write('read-ref %s\n' % refname)
176 r = self.conn.readline().strip()
179 assert(len(r) == 40) # hexified sha
180 return r.decode('hex')
182 return None # nonexistent ref
184 def update_ref(self, refname, newval, oldval):
186 self.conn.write('update-ref %s\n%s\n%s\n'
187 % (refname, newval.encode('hex'),
188 (oldval or '').encode('hex')))
194 self.conn.write('cat %s\n' % re.sub(r'[\n\r]', '_', id))
196 sz = struct.unpack('!I', self.conn.read(4))[0]
198 yield self.conn.read(sz)
202 raise KeyError(str(e))
205 class PackWriter_Remote(git.PackWriter):
206 def __init__(self, conn, objcache_maker, suggest_pack, onclose):
207 git.PackWriter.__init__(self, objcache_maker)
209 self.filename = 'remote socket'
210 self.suggest_pack = suggest_pack
211 self.onclose = onclose
212 self._packopen = False
215 if not self._packopen:
216 self._make_objcache()
217 self.file.write('receive-objects\n')
218 self._packopen = True
221 if self._packopen and self.file:
222 self.file.write('\0\0\0\0')
223 self._packopen = False
225 line = self.file.readline().strip()
226 if line.startswith('index '):
235 if self.suggest_pack:
236 self.suggest_pack(id)
245 raise GitError("don't know how to abort remote pack writing")
247 def _raw_write(self, datalist):
249 if not self._packopen:
251 data = ''.join(datalist)
253 self.file.write(struct.pack('!I', len(data)) + data)
254 self.outbytes += len(data)
257 if self.file.has_input():
258 line = self.file.readline().strip()
259 assert(line.startswith('index '))
261 if self.suggest_pack:
262 self.suggest_pack(idxname)
263 self.objcache.refresh()