Decode uuencoded file
(in_file, out_file=None, mode=None, quiet=False)
| 101 | |
| 102 | |
| 103 | def decode(in_file, out_file=None, mode=None, quiet=False): |
| 104 | """Decode uuencoded file""" |
| 105 | # |
| 106 | # Open the input file, if needed. |
| 107 | # |
| 108 | opened_files = [] |
| 109 | if in_file == '-': |
| 110 | in_file = sys.stdin.buffer |
| 111 | elif isinstance(in_file, str): |
| 112 | in_file = open(in_file, 'rb') |
| 113 | opened_files.append(in_file) |
| 114 | |
| 115 | try: |
| 116 | # |
| 117 | # Read until a begin is encountered or we've exhausted the file |
| 118 | # |
| 119 | while True: |
| 120 | hdr = in_file.readline() |
| 121 | if not hdr: |
| 122 | raise Error('No valid begin line found in input file') |
| 123 | if not hdr.startswith(b'begin'): |
| 124 | continue |
| 125 | hdrfields = hdr.split(b' ', 2) |
| 126 | if len(hdrfields) == 3 and hdrfields[0] == b'begin': |
| 127 | try: |
| 128 | int(hdrfields[1], 8) |
| 129 | break |
| 130 | except ValueError: |
| 131 | pass |
| 132 | if out_file is None: |
| 133 | # If the filename isn't ASCII, what's up with that?!? |
| 134 | out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii") |
| 135 | if os.path.exists(out_file): |
| 136 | raise Error(f'Cannot overwrite existing file: {out_file}') |
| 137 | if (out_file.startswith(os.sep) or |
| 138 | f'..{os.sep}' in out_file or ( |
| 139 | os.altsep and |
| 140 | (out_file.startswith(os.altsep) or |
| 141 | f'..{os.altsep}' in out_file)) |
| 142 | ): |
| 143 | raise Error(f'Refusing to write to {out_file} due to directory traversal') |
| 144 | if mode is None: |
| 145 | mode = int(hdrfields[1], 8) |
| 146 | # |
| 147 | # Open the output file |
| 148 | # |
| 149 | if out_file == '-': |
| 150 | out_file = sys.stdout.buffer |
| 151 | elif isinstance(out_file, str): |
| 152 | fp = open(out_file, 'wb') |
| 153 | os.chmod(out_file, mode) |
| 154 | out_file = fp |
| 155 | opened_files.append(out_file) |
| 156 | # |
| 157 | # Main decoding loop |
| 158 | # |
| 159 | s = in_file.readline() |
| 160 | while s and s.strip(b' \t\r\n\f') != b'end': |
no test coverage detected