| 1 | class protoerr(Exception): |
| 2 | pass |
| 3 | |
| 4 | def readns(sk): |
| 5 | hln = 0 |
| 6 | while True: |
| 7 | c = sk.read(1) |
| 8 | if c == ':': |
| 9 | break |
| 10 | elif c >= '0' or c <= '9': |
| 11 | hln = (hln * 10) + (ord(c) - ord('0')) |
| 12 | else: |
| 13 | raise protoerr, "Invalid netstring length byte: " + c |
| 14 | ret = sk.read(hln) |
| 15 | if sk.read(1) != ',': |
| 16 | raise protoerr, "Non-terminated netstring" |
| 17 | return ret |
| 18 | |
| 19 | def readhead(sk): |
| 20 | parts = readns(sk).split('\0')[:-1] |
| 21 | if len(parts) % 2 != 0: |
| 22 | raise protoerr, "Malformed headers" |
| 23 | ret = {} |
| 24 | i = 0 |
| 25 | while i < len(parts): |
| 26 | ret[parts[i]] = parts[i + 1] |
| 27 | i += 2 |
| 28 | return ret |