Helpers from subvertpy for talking to a remote SSH process
[jelmer/dulwich-libgit2.git] / dulwich / protocol.py
1 # protocol.py -- Shared parts of the git protocols
2 # Copryight (C) 2008 John Carr <john.carr@unrouted.co.uk>
3 # Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; version 2
8 # or (at your option) any later version of the License.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 # MA  02110-1301, USA.
19
20 from errors import HangupException
21
22 TCP_GIT_PORT = 9418
23
24 class ProtocolFile(object):
25     """
26     Some network ops are like file ops. The file ops expect to operate on
27     file objects, so provide them with a dummy file.
28     """
29
30     def __init__(self, read, write):
31         self.read = read
32         self.write = write
33
34     def tell(self):
35         pass
36
37     def close(self):
38         pass
39
40
41 class Protocol(object):
42
43     def __init__(self, read, write):
44         self.read = read
45         self.write = write
46
47     def read_pkt_line(self):
48         """
49         Reads a 'pkt line' from the remote git process
50
51         :return: The next string from the stream
52         """
53         sizestr = self.read(4)
54         if not sizestr:
55             raise HangupException()
56         size = int(sizestr, 16)
57         if size == 0:
58             return None
59         return self.read(size-4)
60
61     def read_pkt_seq(self):
62         pkt = self.read_pkt_line()
63         while pkt:
64             yield pkt
65             pkt = self.read_pkt_line()
66
67     def write_pkt_line(self, line):
68         """
69         Sends a 'pkt line' to the remote git process
70
71         :param line: A string containing the data to send
72         """
73         if line is None:
74             self.write("0000")
75         else:
76             self.write("%04x%s" % (len(line)+4, line))
77
78     def write_sideband(self, channel, blob):
79         """
80         Write data to the sideband (a git multiplexing method)
81
82         :param channel: int specifying which channel to write to
83         :param blob: a blob of data (as a string) to send on this channel
84         """
85         # a pktline can be a max of 65520. a sideband line can therefore be
86         # 65520-5 = 65515
87         # WTF: Why have the len in ASCII, but the channel in binary.
88         while blob:
89             self.write_pkt_line("%s%s" % (chr(channel), blob[:65515]))
90             blob = blob[65515:]
91
92     def send_cmd(self, cmd, *args):
93         """
94         Send a command and some arguments to a git server
95
96         Only used for git://
97
98         :param cmd: The remote service to access
99         :param args: List of arguments to send to remove service
100         """
101         self.write_pkt_line("%s %s" % (cmd, "".join(["%s\0" % a for a in args])))
102
103     def read_cmd(self):
104         """
105         Read a command and some arguments from the git client
106
107         Only used for git://
108
109         :return: A tuple of (command, [list of arguments])
110         """
111         line = self.read_pkt_line()
112         splice_at = line.find(" ")
113         cmd, args = line[:splice_at], line[splice_at+1:]
114         return cmd, args.split(chr(0))
115
116
117 def extract_capabilities(text):
118     if not "\0" in text:
119         return text, None
120     capabilities = text.split("\0")
121     return (capabilities[0], capabilities[1:])
122
123
124 class SSHSubprocess(object):
125     """A socket-like object that talks to an ssh subprocess via pipes."""
126
127     def __init__(self, proc):
128         self.proc = proc
129
130     def send(self, data):
131         return os.write(self.proc.stdin.fileno(), data)
132
133     def recv(self, count):
134         return os.read(self.proc.stdout.fileno(), count)
135
136     def close(self):
137         self.proc.stdin.close()
138         self.proc.stdout.close()
139         self.proc.wait()
140
141
142 class SSHVendor(object):
143
144     def connect_ssh(self, host, command, username=None, port=None):
145         #FIXME: This has no way to deal with passwords..
146         args = ['ssh', '-x']
147         if port is not None:
148             args.extend(['-p', str(port)])
149         if username is not None:
150             host = "%s@%s" % (username, host)
151             args.append(host)
152         else:
153             args.append(host)
154         proc = subprocess.Popen(args + command,
155                                 stdin=subprocess.PIPE,
156                                 stdout=subprocess.PIPE)
157         return SSHSubprocess(proc)
158
159 # Can be overridden by users
160 get_ssh_vendor = SSHVendor
161