1#!/usr/bin/env python3
2# NBD server - fault injection utility
3#
4# Configuration file syntax:
5#   [inject-error "disconnect-neg1"]
6#   event=neg1
7#   io=readwrite
8#   when=before
9#
10# Note that Python's ConfigParser squashes together all sections with the same
11# name, so give each [inject-error] a unique name.
12#
13# inject-error options:
14#   event - name of the trigger event
15#           "neg1" - first part of negotiation struct
16#           "export" - export struct
17#           "neg2" - second part of negotiation struct
18#           "request" - NBD request struct
19#           "reply" - NBD reply struct
20#           "data" - request/reply data
21#   io    - I/O direction that triggers this rule:
22#           "read", "write", or "readwrite"
23#           default: readwrite
24#   when  - after how many bytes to inject the fault
25#           -1 - inject error after I/O
26#           0 - inject error before I/O
27#           integer - inject error after integer bytes
28#           "before" - alias for 0
29#           "after" - alias for -1
30#           default: before
31#
32# Currently the only error injection action is to terminate the server process.
33# This resets the TCP connection and thus forces the client to handle
34# unexpected connection termination.
35#
36# Other error injection actions could be added in the future.
37#
38# Copyright Red Hat, Inc. 2014
39#
40# Authors:
41#   Stefan Hajnoczi <stefanha@redhat.com>
42#
43# This work is licensed under the terms of the GNU GPL, version 2 or later.
44# See the COPYING file in the top-level directory.
45
46import sys
47import socket
48import struct
49import collections
50if sys.version_info.major >= 3:
51    import configparser
52else:
53    import ConfigParser as configparser
54
55FAKE_DISK_SIZE = 8 * 1024 * 1024 * 1024 # 8 GB
56
57# Protocol constants
58NBD_CMD_READ = 0
59NBD_CMD_WRITE = 1
60NBD_CMD_DISC = 2
61NBD_REQUEST_MAGIC = 0x25609513
62NBD_SIMPLE_REPLY_MAGIC = 0x67446698
63NBD_PASSWD = 0x4e42444d41474943
64NBD_OPTS_MAGIC = 0x49484156454F5054
65NBD_CLIENT_MAGIC = 0x0000420281861253
66NBD_OPT_EXPORT_NAME = 1 << 0
67
68# Protocol structs
69neg_classic_struct = struct.Struct('>QQQI124x')
70neg1_struct = struct.Struct('>QQH')
71export_tuple = collections.namedtuple('Export', 'reserved magic opt len')
72export_struct = struct.Struct('>IQII')
73neg2_struct = struct.Struct('>QH124x')
74request_tuple = collections.namedtuple('Request', 'magic type handle from_ len')
75request_struct = struct.Struct('>IIQQI')
76reply_struct = struct.Struct('>IIQ')
77
78def err(msg):
79    sys.stderr.write(msg + '\n')
80    sys.exit(1)
81
82def recvall(sock, bufsize):
83    received = 0
84    chunks = []
85    while received < bufsize:
86        chunk = sock.recv(bufsize - received)
87        if len(chunk) == 0:
88            raise Exception('unexpected disconnect')
89        chunks.append(chunk)
90        received += len(chunk)
91    return b''.join(chunks)
92
93class Rule(object):
94    def __init__(self, name, event, io, when):
95        self.name = name
96        self.event = event
97        self.io = io
98        self.when = when
99
100    def match(self, event, io):
101        if event != self.event:
102            return False
103        if io != self.io and self.io != 'readwrite':
104            return False
105        return True
106
107class FaultInjectionSocket(object):
108    def __init__(self, sock, rules):
109        self.sock = sock
110        self.rules = rules
111
112    def check(self, event, io, bufsize=None):
113        for rule in self.rules:
114            if rule.match(event, io):
115                if rule.when == 0 or bufsize is None:
116                    print('Closing connection on rule match %s' % rule.name)
117                    self.sock.close()
118                    sys.stdout.flush()
119                    sys.exit(0)
120                if rule.when != -1:
121                    return rule.when
122        return bufsize
123
124    def send(self, buf, event):
125        bufsize = self.check(event, 'write', bufsize=len(buf))
126        self.sock.sendall(buf[:bufsize])
127        self.check(event, 'write')
128
129    def recv(self, bufsize, event):
130        bufsize = self.check(event, 'read', bufsize=bufsize)
131        data = recvall(self.sock, bufsize)
132        self.check(event, 'read')
133        return data
134
135    def close(self):
136        self.sock.close()
137
138def negotiate_classic(conn):
139    buf = neg_classic_struct.pack(NBD_PASSWD, NBD_CLIENT_MAGIC,
140                                  FAKE_DISK_SIZE, 0)
141    conn.send(buf, event='neg-classic')
142
143def negotiate_export(conn):
144    # Send negotiation part 1
145    buf = neg1_struct.pack(NBD_PASSWD, NBD_OPTS_MAGIC, 0)
146    conn.send(buf, event='neg1')
147
148    # Receive export option
149    buf = conn.recv(export_struct.size, event='export')
150    export = export_tuple._make(export_struct.unpack(buf))
151    assert export.magic == NBD_OPTS_MAGIC
152    assert export.opt == NBD_OPT_EXPORT_NAME
153    name = conn.recv(export.len, event='export-name')
154
155    # Send negotiation part 2
156    buf = neg2_struct.pack(FAKE_DISK_SIZE, 0)
157    conn.send(buf, event='neg2')
158
159def negotiate(conn, use_export):
160    '''Negotiate export with client'''
161    if use_export:
162        negotiate_export(conn)
163    else:
164        negotiate_classic(conn)
165
166def read_request(conn):
167    '''Parse NBD request from client'''
168    buf = conn.recv(request_struct.size, event='request')
169    req = request_tuple._make(request_struct.unpack(buf))
170    assert req.magic == NBD_REQUEST_MAGIC
171    return req
172
173def write_reply(conn, error, handle):
174    buf = reply_struct.pack(NBD_SIMPLE_REPLY_MAGIC, error, handle)
175    conn.send(buf, event='reply')
176
177def handle_connection(conn, use_export):
178    negotiate(conn, use_export)
179    while True:
180        req = read_request(conn)
181        if req.type == NBD_CMD_READ:
182            write_reply(conn, 0, req.handle)
183            conn.send(b'\0' * req.len, event='data')
184        elif req.type == NBD_CMD_WRITE:
185            _ = conn.recv(req.len, event='data')
186            write_reply(conn, 0, req.handle)
187        elif req.type == NBD_CMD_DISC:
188            break
189        else:
190            print('unrecognized command type %#02x' % req.type)
191            break
192    conn.close()
193
194def run_server(sock, rules, use_export):
195    while True:
196        conn, _ = sock.accept()
197        handle_connection(FaultInjectionSocket(conn, rules), use_export)
198
199def parse_inject_error(name, options):
200    if 'event' not in options:
201        err('missing \"event\" option in %s' % name)
202    event = options['event']
203    if event not in ('neg-classic', 'neg1', 'export', 'neg2', 'request', 'reply', 'data'):
204        err('invalid \"event\" option value \"%s\" in %s' % (event, name))
205    io = options.get('io', 'readwrite')
206    if io not in ('read', 'write', 'readwrite'):
207        err('invalid \"io\" option value \"%s\" in %s' % (io, name))
208    when = options.get('when', 'before')
209    try:
210        when = int(when)
211    except ValueError:
212        if when == 'before':
213            when = 0
214        elif when == 'after':
215            when = -1
216        else:
217            err('invalid \"when\" option value \"%s\" in %s' % (when, name))
218    return Rule(name, event, io, when)
219
220def parse_config(config):
221    rules = []
222    for name in config.sections():
223        if name.startswith('inject-error'):
224            options = dict(config.items(name))
225            rules.append(parse_inject_error(name, options))
226        else:
227            err('invalid config section name: %s' % name)
228    return rules
229
230def load_rules(filename):
231    config = configparser.RawConfigParser()
232    with open(filename, 'rt') as f:
233        config.readfp(f, filename)
234    return parse_config(config)
235
236def open_socket(path):
237    '''Open a TCP or UNIX domain listen socket'''
238    if ':' in path:
239        host, port = path.split(':', 1)
240        sock = socket.socket()
241        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
242        sock.bind((host, int(port)))
243
244        # If given port was 0 the final port number is now available
245        path = '%s:%d' % sock.getsockname()
246    else:
247        sock = socket.socket(socket.AF_UNIX)
248        sock.bind(path)
249    sock.listen(0)
250    print('Listening on %s' % path)
251    sys.stdout.flush() # another process may be waiting, show message now
252    return sock
253
254def usage(args):
255    sys.stderr.write('usage: %s [--classic-negotiation] <tcp-port>|<unix-path> <config-file>\n' % args[0])
256    sys.stderr.write('Run an fault injector NBD server with rules defined in a config file.\n')
257    sys.exit(1)
258
259def main(args):
260    if len(args) != 3 and len(args) != 4:
261        usage(args)
262    use_export = True
263    if args[1] == '--classic-negotiation':
264        use_export = False
265    elif len(args) == 4:
266        usage(args)
267    sock = open_socket(args[1 if use_export else 2])
268    rules = load_rules(args[2 if use_export else 3])
269    run_server(sock, rules, use_export)
270    return 0
271
272if __name__ == '__main__':
273    sys.exit(main(sys.argv))
274