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)
42 (self.host, self.dir) = (host, dir)
43 self.cachedir = git.repo('index-cache/%s'
44 % re.sub(r'[^@\w]', '_',
45 "%s:%s" % (host, dir)))
47 self.p = p = Popen(argv, stdin=PIPE, stdout=PIPE, preexec_fn=fixenv)
49 raise ClientError, 'exec %r: %s' % (argv[0], e), sys.exc_info()[2]
50 self.conn = conn = Conn(p.stdout, p.stdin)
52 dir = re.sub(r'[\r\n]', ' ', dir)
54 conn.write('init-dir %s\n' % dir)
56 conn.write('set-dir %s\n' % dir)
58 self.sync_indexes_del()
64 if e.errno == errno.EPIPE:
70 if self.conn and not self._busy:
71 self.conn.write('quit\n')
74 while self.p.stdout.read(65536):
80 raise ClientError('server tunnel returned exit code %d' % rv)
87 raise ClientError('server exited unexpectedly with code %r' % rv)
89 return self.conn.check_ok()
91 raise ClientError, e, sys.exc_info()[2]
95 raise ClientError('already busy with command %r' % self._busy)
100 def sync_indexes_del(self):
103 conn.write('list-indexes\n')
104 packdir = git.repo('objects/pack')
107 for line in linereader(conn):
111 assert(line.find('/') < 0)
112 if not os.path.exists(os.path.join(self.cachedir, line)):
116 mkdirp(self.cachedir)
117 for f in os.listdir(self.cachedir):
118 if f.endswith('.idx') and not f in all:
119 log('pruning old index: %r\n' % f)
120 os.unlink(os.path.join(self.cachedir, f))
122 def sync_index(self, name):
123 #log('requesting %r\n' % name)
124 mkdirp(self.cachedir)
125 self.conn.write('send-index %s\n' % name)
126 n = struct.unpack('!I', self.conn.read(4))[0]
128 fn = os.path.join(self.cachedir, name)
129 f = open(fn + '.tmp', 'w')
131 progress('Receiving index: %d/%d\r' % (count, n))
132 for b in chunkyreader(self.conn, n):
135 progress('Receiving index: %d/%d\r' % (count, n))
136 progress('Receiving index: %d/%d, done.\n' % (count, n))
139 os.rename(fn + '.tmp', fn)
141 def _make_objcache(self):
146 return git.PackIdxList(self.cachedir)
148 def _suggest_pack(self, indexname):
149 log('received index suggestion: %s\n' % indexname)
152 assert(ob == 'receive-objects')
154 self.conn.write('\xff\xff\xff\xff') # suspend receive-objects
155 self.conn.drain_and_check_ok()
156 self.sync_index(indexname)
158 self.conn.write('receive-objects\n')
161 def new_packwriter(self):
163 self._busy = 'receive-objects'
164 return PackWriter_Remote(self.conn,
165 objcache_maker = self._make_objcache,
166 suggest_pack = self._suggest_pack,
167 onclose = self._not_busy)
169 def read_ref(self, refname):
171 self.conn.write('read-ref %s\n' % refname)
172 r = self.conn.readline().strip()
175 assert(len(r) == 40) # hexified sha
176 return r.decode('hex')
178 return None # nonexistent ref
180 def update_ref(self, refname, newval, oldval):
182 self.conn.write('update-ref %s\n%s\n%s\n'
183 % (refname, newval.encode('hex'),
184 (oldval or '').encode('hex')))
190 self.conn.write('cat %s\n' % re.sub(r'[\n\r]', '_', id))
192 sz = struct.unpack('!I', self.conn.read(4))[0]
194 yield self.conn.read(sz)
198 raise KeyError(str(e))
201 class PackWriter_Remote(git.PackWriter):
202 def __init__(self, conn, objcache_maker, suggest_pack, onclose):
203 git.PackWriter.__init__(self, objcache_maker)
205 self.filename = 'remote socket'
206 self.suggest_pack = suggest_pack
207 self.onclose = onclose
208 self._packopen = False
211 if not self._packopen:
212 self._make_objcache()
213 self.file.write('receive-objects\n')
214 self._packopen = True
217 if self._packopen and self.file:
218 self.file.write('\0\0\0\0')
219 self._packopen = False
221 line = self.file.readline().strip()
222 if line.startswith('index '):
231 if self.suggest_pack:
232 self.suggest_pack(id)
241 raise GitError("don't know how to abort remote pack writing")
243 def _raw_write(self, datalist):
245 if not self._packopen:
247 data = ''.join(datalist)
249 self.file.write(struct.pack('!I', len(data)) + data)
250 self.outbytes += len(data)
253 if self.file.has_input():
254 line = self.file.readline().strip()
255 assert(line.startswith('index '))
257 if self.suggest_pack:
258 self.suggest_pack(idxname)
259 self.objcache.refresh()