• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/uhttpd/tests/ubus_list_encoding.py

  1 #!/usr/bin/env python3
  2 """
  3 Regression tests for the ubus JSON-RPC "list" response encoding.
  4 
  5 Covers GHSA-788h-w5m4-j5xv: uhttpd's list callback opened one nesting level
  6 per signature method of every object returned by a lookup and closed the
  7 returned cookie without checking it. A JSON-RPC "list" request naming enough
  8 object paths made the accumulated response blob approach the 24 bit length
  9 limit of libubox blobs (BLOB_ATTR_LEN_MASK). Appending more data then fails,
 10 blobmsg_open_nested() returns NULL and blobmsg_close_table(buf, NULL) treats
 11 that cookie as an offset into the buffer ((char *)buf->buf - BLOB_COOKIE),
 12 corrupting the blob header and eventually arbitrary heap. On the reported
 13 target this was shaped into unauthenticated remote code execution.
 14 
 15 The tests run uhttpd against a throwaway ubusd holding synthetic objects with
 16 large signatures and check that:
 17 
 18   1. an unauthenticated verbose list still works,
 19   2. a single wildcard lookup over JSON-RPC still works,
 20   3. a request repeating the same lookup path is encoded once instead of
 21      once per repetition (the request from the advisory),
 22   4. a request whose result would outgrow the response budget is answered
 23      with a bounded JSON-RPC error and uhttpd survives it,
 24   5. more object paths than allowed are rejected as invalid params,
 25   6. the "call" and batched request paths still produce well formed answers,
 26   7. normal list requests are still served after all of the above,
 27   8. an unparameterized GET list which no longer fits is refused with a
 28      bounded HTTP 500 instead of being truncated.
 29 
 30 Usage: ubus_list_encoding.py /path/to/uhttpd [-v] [--keep] [--objects N]
 31        [--oversize-objects N]
 32 
 33 Needs ubusd plus a C compiler with libubus/libubox headers to build the fake
 34 object provider. The test is skipped (exit code 0) when those are missing.
 35 """
 36 
 37 import argparse
 38 import json
 39 import os
 40 import shutil
 41 import socket
 42 import subprocess
 43 import sys
 44 import tempfile
 45 import time
 46 
 47 PROVIDER_SRC = r"""
 48 /* Registers synthetic ubus objects with large signatures, so that a single
 49  * wildcard lookup already returns a sizeable verbose list blob. */
 50 #include <stdio.h>
 51 #include <stdlib.h>
 52 #include <string.h>
 53 
 54 #include <libubox/blobmsg.h>
 55 #include <libubox/uloop.h>
 56 #include <libubus.h>
 57 
 58 static struct ubus_context *ctx;
 59 
 60 int main(int argc, char **argv)
 61 {
 62         const char *sock = argc > 1 ? argv[1] : NULL;
 63         int nobj = argc > 2 ? atoi(argv[2]) : 60;
 64         int nmeth = argc > 3 ? atoi(argv[3]) : 30;
 65         int nargs = argc > 4 ? atoi(argv[4]) : 15;
 66         struct ubus_object *objs;
 67         struct ubus_object_type *types;
 68         struct ubus_method *meths;
 69         struct blobmsg_policy *pols;
 70         char name[64], meth[64], arg[32];
 71         int i, m, a;
 72 
 73         if (!sock) {
 74                 fprintf(stderr, "usage: %s <ubus-socket> [objects] [methods] [args]\n", argv[0]);
 75                 return 1;
 76         }
 77 
 78         objs = calloc(nobj, sizeof(*objs));
 79         types = calloc(nobj, sizeof(*types));
 80         meths = calloc(nobj * nmeth, sizeof(*meths));
 81         pols = calloc(nobj * nmeth * nargs, sizeof(*pols));
 82         if (!objs || !types || !meths || !pols)
 83                 return 1;
 84 
 85         uloop_init();
 86 
 87         ctx = ubus_connect(sock);
 88         if (!ctx) {
 89                 fprintf(stderr, "ubus_connect(%s) failed\n", sock);
 90                 return 1;
 91         }
 92 
 93         for (i = 0; i < nobj; i++) {
 94                 struct ubus_object_type *t = &types[i];
 95 
 96                 snprintf(name, sizeof(name), "probe%03d", i);
 97 
 98                 t->name = strdup(name);
 99                 t->methods = &meths[i * nmeth];
100                 t->n_methods = nmeth;
101 
102                 for (m = 0; m < nmeth; m++) {
103                         struct ubus_method *mm = &meths[i * nmeth + m];
104                         struct blobmsg_policy *pp = &pols[(i * nmeth + m) * nargs];
105 
106                         snprintf(meth, sizeof(meth), "method%02d", m);
107 
108                         mm->name = strdup(meth);
109                         mm->mask = 0;
110                         mm->policy = pp;
111                         mm->n_policy = nargs;
112 
113                         for (a = 0; a < nargs; a++) {
114                                 snprintf(arg, sizeof(arg), "arg%02d", a);
115                                 pp[a].name = strdup(arg);
116                                 pp[a].type = BLOBMSG_TYPE_STRING;
117                         }
118                 }
119 
120                 objs[i].name = t->name;
121                 objs[i].type = t;
122 
123                 if (ubus_add_object(ctx, &objs[i])) {
124                         fprintf(stderr, "ubus_add_object(%s) failed\n", name);
125                         return 1;
126                 }
127         }
128 
129         ubus_add_uloop(ctx);
130         uloop_run();
131 
132         uloop_done();
133         return 0;
134 }
135 """
136 
137 # libubox bounds blob lengths with BLOB_ATTR_LEN_MASK (0x00ffffff == 16 MiB)
138 BLOB_LIMIT = 0x00ffffff
139 
140 # uhttpd's UH_UBUS_MAX_POST_SIZE
141 UH_UBUS_MAX_POST_SIZE = 65536
142 
143 # how many lookup paths the fixed build accepts in one "list" request
144 UH_UBUS_MAX_LIST_PATHS = 512
145 
146 # how many lookup paths the fixed build rejects as invalid params
147 OVER_MANY_PATHS = UH_UBUS_MAX_LIST_PATHS + 200
148 
149 
150 class HttpError(Exception):
151     pass
152 
153 
154 def free_port():
155     s = socket.socket()
156     s.bind(("127.0.0.1", 0))
157     port = s.getsockname()[1]
158     s.close()
159     return port
160 
161 
162 def find_ubusd():
163     env = os.environ.get("UBUSD")
164     if env and os.path.exists(env):
165         return env
166     for name in ("ubusd", "/usr/sbin/ubusd", "/usr/local/sbin/ubusd", "/sbin/ubusd"):
167         path = shutil.which(name) or (name if os.path.exists(name) else None)
168         if path:
169             return path
170     return None
171 
172 
173 def build_provider(tmpdir, verbose):
174     src = os.path.join(tmpdir, "provider.c")
175     exe = os.path.join(tmpdir, "provider")
176 
177     with open(src, "w") as f:
178         f.write(PROVIDER_SRC)
179 
180     compilers = [c for c in (os.environ.get("CC"), "cc", "gcc", "clang") if c]
181     flagsets = [os.environ.get("UBUS_CFLAGS", "").split(), [], ["-I/usr/local/include"]]
182     ldflags = [os.environ.get("UBUS_LDFLAGS", "").split(), [], ["-L/usr/local/lib"]]
183 
184     for cc in dict.fromkeys(compilers):
185         for cflags in flagsets:
186             for ldfs in ldflags:
187                 cmd = [cc, "-std=gnu99", "-o", exe, src] + cflags + ["-lubus", "-lubox"] + ldfs
188                 if verbose:
189                     print("  try: %s" % " ".join(cmd))
190                 try:
191                     p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
192                 except (FileNotFoundError, PermissionError):
193                     continue
194                 if p.returncode == 0:
195                     return exe
196                 if verbose:
197                     print("  %s" % p.stderr.decode(errors="replace").strip())
198 
199     return None
200 
201 
202 def decode_chunked(body):
203     out = bytearray()
204     while True:
205         nl = body.find(b"\r\n")
206         if nl < 0:
207             break
208         try:
209             size = int(body[:nl].split(b";")[0], 16)
210         except ValueError:
211             break
212         if size == 0:
213             break
214         out += body[nl + 2:nl + 2 + size]
215         body = body[nl + 2 + size + 2:]
216     return bytes(out)
217 
218 
219 class Client:
220     def __init__(self, port):
221         self.port = port
222 
223     def request(self, method, path, body=None):
224         raw = ("%s %s HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n" % (method, path)).encode()
225 
226         if body is not None:
227             body = body.encode()
228             raw += b"Content-Type: application/json\r\nContent-Length: %d\r\n" % len(body)
229 
230         raw += b"\r\n"
231 
232         sock = socket.create_connection(("127.0.0.1", self.port), timeout=10)
233         try:
234             sock.sendall(raw + (body or b""))
235             sock.settimeout(120)
236             data = b""
237             while True:
238                 try:
239                     chunk = sock.recv(65536)
240                 except socket.timeout:
241                     raise HttpError("timed out reading response")
242                 if not chunk:
243                     break
244                 data += chunk
245                 if data.endswith(b"\r\n0\r\n\r\n"):
246                     break
247         finally:
248             sock.close()
249 
250         head, _, rest = data.partition(b"\r\n\r\n")
251         status = head.split(b"\r\n", 1)[0].decode(errors="replace")
252 
253         headers = {}
254         for line in head.split(b"\r\n")[1:]:
255             key, _, val = line.partition(b":")
256             headers[key.decode().lower()] = val.decode().strip()
257 
258         payload = decode_chunked(rest) if headers.get("transfer-encoding", "").lower() == "chunked" else rest
259 
260         return status, payload
261 
262 
263 class Server:
264     def __init__(self, uhttpd, tmpdir):
265         self.uhttpd = uhttpd
266         self.tmpdir = tmpdir
267         self.sock = os.path.join(tmpdir, "ubus.sock")
268         self.port = free_port()
269         self.log = open(os.path.join(tmpdir, "uhttpd.log"), "wb")
270         self.procs = []
271 
272     def start(self, ubusd, provider, objects):
273         self.procs.append(subprocess.Popen([ubusd, "-s", self.sock], cwd=self.tmpdir))
274 
275         for _ in range(200):
276             if os.path.exists(self.sock):
277                 break
278             time.sleep(0.05)
279         else:
280             raise RuntimeError("ubusd did not create its socket")
281 
282         self.procs.append(subprocess.Popen([provider, self.sock, str(objects)], cwd=self.tmpdir))
283 
284         env = dict(os.environ)
285         env["LD_LIBRARY_PATH"] = os.path.dirname(os.path.abspath(self.uhttpd)) + os.pathsep + env.get("LD_LIBRARY_PATH", "")
286 
287         self.procs.append(subprocess.Popen(
288             [self.uhttpd, "-f", "-p", "127.0.0.1:%d" % self.port, "-h", self.tmpdir,
289              "-u", "/ubus", "-U", self.sock, "-t", "10", "-T", "10"],
290             cwd=self.tmpdir, env=env, stdout=self.log, stderr=self.log))
291 
292     def alive(self):
293         return all(p.poll() is None for p in self.procs)
294 
295     def dead_with(self):
296         return [(i, p.returncode) for i, p in enumerate(self.procs) if p.returncode is not None]
297 
298     def uhttpd_output(self, limit=8):
299         try:
300             self.log.flush()
301             with open(self.log.name, "rb") as f:
302                 lines = f.read().splitlines()[-limit:]
303             return b" / ".join(lines).decode(errors="replace")
304         except Exception:
305             return ""
306 
307     def stop(self):
308         for proc in reversed(self.procs):
309             if proc.poll() is None:
310                 proc.terminate()
311         for proc in self.procs:
312             try:
313                 proc.wait(timeout=5)
314             except subprocess.TimeoutExpired:
315                 proc.kill()
316                 proc.wait()
317         self.log.close()
318 
319     def wait_for_objects(self, client, wanted, timeout=60):
320         deadline = time.time() + timeout
321         while time.time() < deadline:
322             try:
323                 _, body = client.request("GET", "/ubus/list")
324                 names = json.loads(body.decode(errors="replace"))
325                 if isinstance(names, dict) and all(w in names for w in wanted):
326                     return sorted(names)
327             except Exception:
328                 pass
329             time.sleep(0.2)
330         return None
331 
332 
333 def list_body(paths):
334     return json.dumps({"jsonrpc": "2.0", "id": 1, "method": "list", "params": list(paths)})
335 
336 
337 def describe(body, paths):
338     if paths is not None:
339         return "list with %d paths" % len(paths)
340     return body[:120]
341 
342 
343 def jsonrpc_error_code(payload):
344     try:
345         obj = json.loads(payload.decode(errors="replace"))
346     except Exception:
347         return None
348 
349     if isinstance(obj, dict):
350         err = obj.get("error")
351         if isinstance(err, dict):
352             return err.get("code")
353     return None
354 
355 
356 def overflow_paths(names, per_object, budget=2 * 1024 * 1024, max_paths=UH_UBUS_MAX_LIST_PATHS):
357     """A set of distinct lookup paths whose combined result exceeds budget.
358 
359     Every entry is a different string, so none of them can be collapsed as a
360     duplicate, and the broadest wildcards come first because they contribute
361     the most response bytes per request byte.
362     """
363     candidates = []
364     seen = set()
365 
366     for name in names:
367         for i in range(1, len(name) + 1):
368             path = name[:i] + "*"
369             if path not in seen:
370                 seen.add(path)
371                 candidates.append(path)
372 
373     candidates.sort(key=lambda path: -sum(1 for n in names if n.startswith(path[:-1])))
374 
375     paths = []
376     total = 0
377 
378     for path in candidates:
379         if total > budget or len(paths) >= max_paths:
380             break
381         paths.append(path)
382         total += per_object * sum(1 for n in names if n.startswith(path[:-1]))
383 
384     return paths, total
385 
386 
387 def run_oversize_get_case(uhttpd, ubusd, provider, tmpdir, objects, failures):
388     """An unparameterized list which no longer fits has to be refused.
389 
390     Runs a second, independent uhttpd instance against an ubusd holding enough
391     objects to push a single full list past the response budget.
392     """
393     sub = os.path.join(tmpdir, "oversize")
394     os.makedirs(sub, exist_ok=True)
395 
396     server = Server(uhttpd, sub)
397     try:
398         server.start(ubusd, provider, objects)
399         client = Client(server.port)
400         last = "probe%03d" % (objects - 1)
401 
402         deadline = time.time() + 60
403         while time.time() < deadline:
404             try:
405                 status, _ = client.request("GET", "/ubus/list/" + last)
406                 if "200" in status:
407                     break
408             except (OSError, HttpError):
409                 pass
410             time.sleep(0.2)
411         else:
412             failures.append("case9: ubus objects never showed up (%s)" % server.uhttpd_output())
413             return
414 
415         status, body = client.request("GET", "/ubus/list")
416         try:
417             code = json.loads(body.decode(errors="replace")).get("code")
418         except Exception:
419             code = None
420 
421         if "500" in status and code == -EFBIG and server.alive():
422             print("ok   case9: GET /ubus/list over %d objects -> %s, code %s, %d bytes"
423                   % (objects, status, code, len(body)))
424         else:
425             failures.append("case9: GET /ubus/list over %d objects -> %s, code %s, "
426                             "%d bytes (alive=%s)" % (objects, status, code, len(body), server.alive()))
427 
428         status, body = client.request("GET", "/ubus/list/probe000")
429         if "200" in status and b"method00" in body and server.alive():
430             print("ok   case10: GET /ubus/list/probe000 -> %s after the refused list" % status)
431         else:
432             failures.append("case10: GET /ubus/list/probe000 -> %s (%d bytes)" % (status, len(body)))
433     finally:
434         server.stop()
435 
436 
437 EFBIG = 27
438 
439 
440 def run_oversize_get_case(uhttpd, ubusd, provider, tmpdir, objects, failures):
441     """An unparameterized list which no longer fits has to be refused.
442 
443     Runs a second, independent uhttpd instance against a throwaway ubusd
444     holding enough objects to push a single full list past the response budget.
445     """
446     sub = os.path.join(tmpdir, "oversize")
447     os.makedirs(sub, exist_ok=True)
448 
449     server = Server(uhttpd, sub)
450     try:
451         server.start(ubusd, provider, objects)
452         client = Client(server.port)
453         last = "probe%03d" % (objects - 1)
454 
455         deadline = time.time() + 60
456         while time.time() < deadline:
457             try:
458                 status, _ = client.request("GET", "/ubus/list/" + last)
459                 if "200" in status:
460                     break
461             except (OSError, HttpError):
462                 pass
463             time.sleep(0.2)
464         else:
465             failures.append("case9: ubus objects never showed up (%s)" % server.uhttpd_output())
466             return
467 
468         try:
469             status, body = client.request("GET", "/ubus/list")
470         except (OSError, HttpError) as e:
471             status, body = "no response (%s)" % e, b""
472 
473         try:
474             code = json.loads(body.decode(errors="replace")).get("code")
475         except Exception:
476             code = None
477 
478         if "500" in status and code == -EFBIG and server.alive():
479             print("ok   case9: GET /ubus/list of %d objects -> %s, code %s, %d bytes"
480                   % (objects, status, code, len(body)))
481         else:
482             failures.append("case9: GET /ubus/list of %d objects -> %s, code %s, "
483                             "%d bytes (alive=%s)" % (objects, status, code, len(body), server.alive()))
484 
485         status, body = client.request("GET", "/ubus/list/probe000")
486         if "200" in status and b"method00" in body and server.alive():
487             print("ok   case10: GET /ubus/list/probe000 -> %s after the refused list" % status)
488         else:
489             failures.append("case10: GET /ubus/list/probe000 -> %s (%d bytes)" % (status, len(body)))
490     finally:
491         server.stop()
492 
493 
494 def main():
495     ap = argparse.ArgumentParser()
496     ap.add_argument("uhttpd", help="path to the uhttpd binary")
497     ap.add_argument("-v", "--verbose", action="store_true")
498     ap.add_argument("--keep", action="store_true", help="keep the scratch directory")
499     ap.add_argument("--objects", type=int, default=60, help="number of fake ubus objects")
500     ap.add_argument("--oversize-objects", type=int, default=300,
501                     help="object count of the oversize GET list case, 0 to skip")
502     args = ap.parse_args()
503 
504     uhttpd = os.path.abspath(args.uhttpd)
505     if not os.path.isfile(uhttpd):
506         print("FAIL: no such binary: %s" % uhttpd)
507         return 2
508 
509     ubusd = find_ubusd()
510     if not ubusd:
511         print("SKIP: no ubusd binary found (set UBUSD=/path/to/ubusd)")
512         return 0
513 
514     tmpdir = tempfile.mkdtemp(prefix="uhttpd-ubus-list-")
515 
516     provider = build_provider(tmpdir, args.verbose)
517     if not provider:
518         print("SKIP: could not build the ubus object provider (needs libubus + libubox headers)")
519         if not args.keep:
520             shutil.rmtree(tmpdir, ignore_errors=True)
521         return 0
522 
523     objects = ["probe%03d" % i for i in range(args.objects)]
524     failures = []
525     server = Server(uhttpd, tmpdir)
526 
527     def call(name, body, expect_codes, paths=None):
528         """POST a JSON-RPC list request and check that the answer stays bounded."""
529         if isinstance(expect_codes, int):
530             expect_codes = (expect_codes,)
531         try:
532             status, payload = client.request("POST", "/ubus", body)
533             code = jsonrpc_error_code(payload)
534         except (OSError, HttpError) as e:
535             status, payload, code = "no response (%s)" % e, b"", None
536 
537         if not server.alive():
538             failures.append("%s: %s killed uhttpd (%s, exited with %s)"
539                             % (name, body[:120], status, server.dead_with()))
540             return status, payload, code
541 
542         if code in expect_codes:
543             print("ok   %s: %s -> %s, server alive" % (name, describe(body, paths), code))
544         elif code is not None:
545             failures.append("%s: %s -> unexpected error %s" % (name, describe(body, paths), code))
546         else:
547             failures.append("%s: %s -> %s, %d bytes, no bounded error (alive=%s)"
548                             % (name, describe(body, paths), status, len(payload), server.alive()))
549 
550         return status, payload, code
551 
552     try:
553         server.start(ubusd, provider, args.objects)
554         client = Client(server.port)
555 
556         names = server.wait_for_objects(client, objects)
557         if names is None:
558             print("FAIL: fake ubus objects never showed up (%s)" % server.uhttpd_output())
559             return 2
560 
561         # 1. unauthenticated verbose list
562         status, body = client.request("GET", "/ubus/list")
563         if "200" in status and b"probe000" in body and server.alive():
564             print("ok   case1: GET /ubus/list -> %s, %d bytes" % (status, len(body)))
565         else:
566             failures.append("case1: GET /ubus/list -> %s (%d bytes)" % (status, len(body)))
567 
568         # 2. a single wildcard lookup over JSON-RPC, without any session id
569         status, body = client.request("POST", "/ubus", list_body(["*"]))
570         result = None
571         try:
572             result = json.loads(body.decode(errors="replace")).get("result")
573         except Exception:
574             pass
575 
576         if isinstance(result, dict) and all(w in result for w in objects) and server.alive():
577             single = len(body)
578             print("ok   case2: list(['*']) -> %s, %d objects, %d bytes" % (status, len(result), single))
579         else:
580             single = 1
581             failures.append("case2: list(['*']) -> %s, incomplete result (%s)"
582                             % (status, body[:120].decode(errors="replace")))
583 
584         # 3. the request from the advisory: the same path over and over again.
585         #    Repeating it must not encode the same objects over and over.
586         reps = (BLOB_LIMIT + 4 * 1024 * 1024) // max(single, 1) + 10
587         reps = min(reps, (UH_UBUS_MAX_POST_SIZE - 64) // 4)
588 
589         status, body = client.request("POST", "/ubus", list_body(["*"] * reps))
590         duplicates = body.count(b'"probe000"')
591         if not server.alive():
592             failures.append("case3: list(['*']*%d) killed uhttpd (exited with %s)"
593                             % (reps, server.dead_with()))
594         elif duplicates > 1:
595             failures.append("case3: list(['*']*%d) encoded 'probe000' %d times" % (reps, duplicates))
596         else:
597             print("ok   case3: list(['*']*%d) -> %s, each object encoded once, %d bytes"
598                   % (reps, status, len(body)))
599 
600         # 4. distinct paths whose combined result exceeds the response budget
601         per_object = max(single // max(len(objects), 1), 1)
602         paths, expected = overflow_paths(names, per_object, budget=3 * 1024 * 1024)
603         body = list_body(paths)
604 
605         if len(paths) < 2 or expected <= 3 * 1024 * 1024:
606             failures.append("case4: cannot build an over-large result from %d lookup paths "
607                             "(estimated %d bytes)" % (len(paths), expected))
608         elif len(body) > UH_UBUS_MAX_POST_SIZE:
609             failures.append("case4: request would be %d bytes, above the post limit" % len(body))
610         else:
611             print("     case4: %d distinct paths, result should be about %d bytes" % (len(paths), expected))
612             call("case4", body, (-32603, -32602), paths)
613 
614         # 5. more lookup paths than a single request may name
615         paths = [objects[i % len(objects)] for i in range(OVER_MANY_PATHS)]
616         call("case5", list_body(paths), -32602, paths)
617 
618         # 6. error responses of the "call" path are still well formed
619         call_body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "call",
620                                "params": ["0" * 32, "nosuchobject", "test", {}]})
621         try:
622             status, body = client.request("POST", "/ubus", call_body)
623             code = jsonrpc_error_code(body)
624         except (OSError, HttpError) as e:
625             status, body, code = "no response (%s)" % e, b"", None
626 
627         if code in (-32000, -32001, -32002) and server.alive():
628             print("ok   case6: call() on a missing object -> %s" % code)
629         else:
630             failures.append("case6: call() on a missing object -> %s (%s)"
631                             % (status, body[:120].decode(errors="replace")))
632 
633         # 7. batched requests are still answered with a JSON array
634         batch = json.dumps([
635             {"jsonrpc": "2.0", "id": 1, "method": "list", "params": [objects[2]]},
636             {"jsonrpc": "2.0", "id": 2, "method": "call",
637              "params": ["0" * 32, "nosuchobject", "test", {}]},
638         ])
639         try:
640             status, body = client.request("POST", "/ubus", batch)
641             parsed = json.loads(body.decode(errors="replace"))
642             ok = isinstance(parsed, list) and len(parsed) == 2 and server.alive()
643         except (OSError, HttpError, ValueError) as e:
644             status, body, ok = "no response (%s)" % e, b"", False
645 
646         if ok:
647             print("ok   case7: batched list+call -> %s, 2 results" % status)
648         else:
649             failures.append("case7: batched list+call -> %s (%s)"
650                             % (status, body[:120].decode(errors="replace")))
651 
652         # 8. normal list requests are still served after the abuse above
653         try:
654             status, body = client.request("POST", "/ubus", list_body([objects[1]]))
655             ok = "200" in status and b"method00" in body and server.alive()
656         except (OSError, HttpError) as e:
657             status, body, ok = "no response (%s)" % e, b"", False
658 
659         if ok:
660             print("ok   case8: list(['%s']) -> %s after the abuse cases" % (objects[1], status))
661         else:
662             failures.append("case8: normal list after abuse -> %s (%d bytes), alive=%s"
663                             % (status, len(body), server.alive()))
664     finally:
665         server.stop()
666 
667     if args.oversize_objects:
668         run_oversize_get_case(uhttpd, ubusd, provider, tmpdir, args.oversize_objects, failures)
669 
670     if not args.keep:
671         shutil.rmtree(tmpdir, ignore_errors=True)
672     else:
673         print("\nscratch directory kept: %s" % tmpdir)
674 
675     if failures:
676         print()
677         for f in failures:
678             print("FAIL: %s" % f)
679         return 1
680 
681     print("all ubus list encoding cases passed")
682     return 0
683 
684 
685 if __name__ == "__main__":
686     sys.exit(main())

This page was automatically generated by LXR 0.3.1.  •  OpenWrt