LCOV - code coverage report
Current view: top level - libreoffice/workdir/unxlngi6.pro/UnpackedTarball/python3/Modules - binascii.c (source / functions) Hit Total Coverage
Test: libreoffice_filtered.info Lines: 0 611 0.0 %
Date: 2012-12-17 Functions: 0 19 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             : ** Routines to represent binary data in ASCII and vice-versa
       3             : **
       4             : ** This module currently supports the following encodings:
       5             : ** uuencode:
       6             : **      each line encodes 45 bytes (except possibly the last)
       7             : **      First char encodes (binary) length, rest data
       8             : **      each char encodes 6 bits, as follows:
       9             : **      binary: 01234567 abcdefgh ijklmnop
      10             : **      ascii:  012345 67abcd efghij klmnop
      11             : **      ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc.
      12             : **      short binary data is zero-extended (so the bits are always in the
      13             : **      right place), this does *not* reflect in the length.
      14             : ** base64:
      15             : **      Line breaks are insignificant, but lines are at most 76 chars
      16             : **      each char encodes 6 bits, in similar order as uucode/hqx. Encoding
      17             : **      is done via a table.
      18             : **      Short binary data is filled (in ASCII) with '='.
      19             : ** hqx:
      20             : **      File starts with introductory text, real data starts and ends
      21             : **      with colons.
      22             : **      Data consists of three similar parts: info, datafork, resourcefork.
      23             : **      Each part is protected (at the end) with a 16-bit crc
      24             : **      The binary data is run-length encoded, and then ascii-fied:
      25             : **      binary: 01234567 abcdefgh ijklmnop
      26             : **      ascii:  012345 67abcd efghij klmnop
      27             : **      ASCII encoding is table-driven, see the code.
      28             : **      Short binary data results in the runt ascii-byte being output with
      29             : **      the bits in the right place.
      30             : **
      31             : ** While I was reading dozens of programs that encode or decode the formats
      32             : ** here (documentation? hihi:-) I have formulated Jansen's Observation:
      33             : **
      34             : **      Programs that encode binary data in ASCII are written in
      35             : **      such a style that they are as unreadable as possible. Devices used
      36             : **      include unnecessary global variables, burying important tables
      37             : **      in unrelated sourcefiles, putting functions in include files,
      38             : **      using seemingly-descriptive variable names for different purposes,
      39             : **      calls to empty subroutines and a host of others.
      40             : **
      41             : ** I have attempted to break with this tradition, but I guess that that
      42             : ** does make the performance sub-optimal. Oh well, too bad...
      43             : **
      44             : ** Jack Jansen, CWI, July 1995.
      45             : **
      46             : ** Added support for quoted-printable encoding, based on rfc 1521 et al
      47             : ** quoted-printable encoding specifies that non printable characters (anything
      48             : ** below 32 and above 126) be encoded as =XX where XX is the hexadecimal value
      49             : ** of the character.  It also specifies some other behavior to enable 8bit data
      50             : ** in a mail message with little difficulty (maximum line sizes, protecting
      51             : ** some cases of whitespace, etc).
      52             : **
      53             : ** Brandon Long, September 2001.
      54             : */
      55             : 
      56             : #define PY_SSIZE_T_CLEAN
      57             : 
      58             : #include "Python.h"
      59             : #ifdef USE_ZLIB_CRC32
      60             : #include "zlib.h"
      61             : #endif
      62             : 
      63             : static PyObject *Error;
      64             : static PyObject *Incomplete;
      65             : 
      66             : /*
      67             : ** hqx lookup table, ascii->binary.
      68             : */
      69             : 
      70             : #define RUNCHAR 0x90
      71             : 
      72             : #define DONE 0x7F
      73             : #define SKIP 0x7E
      74             : #define FAIL 0x7D
      75             : 
      76             : static unsigned char table_a2b_hqx[256] = {
      77             : /*       ^@    ^A    ^B    ^C    ^D    ^E    ^F    ^G   */
      78             : /* 0*/  FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
      79             : /*       \b    \t    \n    ^K    ^L    \r    ^N    ^O   */
      80             : /* 1*/  FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL,
      81             : /*       ^P    ^Q    ^R    ^S    ^T    ^U    ^V    ^W   */
      82             : /* 2*/  FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
      83             : /*       ^X    ^Y    ^Z    ^[    ^\    ^]    ^^    ^_   */
      84             : /* 3*/  FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
      85             : /*              !     "     #     $     %     &     '   */
      86             : /* 4*/  FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
      87             : /*        (     )     *     +     ,     -     .     /   */
      88             : /* 5*/  0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL,
      89             : /*        0     1     2     3     4     5     6     7   */
      90             : /* 6*/  0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL,
      91             : /*        8     9     :     ;     <     =     >     ?   */
      92             : /* 7*/  0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL,
      93             : /*        @     A     B     C     D     E     F     G   */
      94             : /* 8*/  0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
      95             : /*        H     I     J     K     L     M     N     O   */
      96             : /* 9*/  0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL,
      97             : /*        P     Q     R     S     T     U     V     W   */
      98             : /*10*/  0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL,
      99             : /*        X     Y     Z     [     \     ]     ^     _   */
     100             : /*11*/  0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL,
     101             : /*        `     a     b     c     d     e     f     g   */
     102             : /*12*/  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL,
     103             : /*        h     i     j     k     l     m     n     o   */
     104             : /*13*/  0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL,
     105             : /*        p     q     r     s     t     u     v     w   */
     106             : /*14*/  0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL,
     107             : /*        x     y     z     {     |     }     ~    ^?   */
     108             : /*15*/  FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     109             : /*16*/  FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     110             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     111             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     112             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     113             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     114             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     115             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     116             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     117             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     118             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     119             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     120             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     121             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     122             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     123             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     124             :     FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
     125             : };
     126             : 
     127             : static unsigned char table_b2a_hqx[] =
     128             : "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr";
     129             : 
     130             : static char table_a2b_base64[] = {
     131             :     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     132             :     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     133             :     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
     134             :     52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */
     135             :     -1, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
     136             :     15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
     137             :     -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
     138             :     41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
     139             : };
     140             : 
     141             : #define BASE64_PAD '='
     142             : 
     143             : /* Max binary chunk size; limited only by available memory */
     144             : #define BASE64_MAXBIN ((PY_SSIZE_T_MAX - 3) / 2)
     145             : 
     146             : static unsigned char table_b2a_base64[] =
     147             : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
     148             : 
     149             : 
     150             : 
     151             : static unsigned short crctab_hqx[256] = {
     152             :     0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
     153             :     0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
     154             :     0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
     155             :     0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
     156             :     0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
     157             :     0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
     158             :     0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
     159             :     0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
     160             :     0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
     161             :     0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
     162             :     0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
     163             :     0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
     164             :     0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
     165             :     0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
     166             :     0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
     167             :     0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
     168             :     0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
     169             :     0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
     170             :     0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
     171             :     0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
     172             :     0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
     173             :     0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
     174             :     0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
     175             :     0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
     176             :     0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
     177             :     0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
     178             :     0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
     179             :     0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
     180             :     0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
     181             :     0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
     182             :     0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
     183             :     0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
     184             : };
     185             : 
     186             : static int
     187           0 : ascii_buffer_converter(PyObject *arg, Py_buffer *buf)
     188             : {
     189           0 :     if (arg == NULL) {
     190           0 :         PyBuffer_Release(buf);
     191           0 :         return 1;
     192             :     }
     193           0 :     if (PyUnicode_Check(arg)) {
     194           0 :         if (PyUnicode_READY(arg) < 0)
     195           0 :             return 0;
     196           0 :         if (!PyUnicode_IS_ASCII(arg)) {
     197           0 :             PyErr_SetString(PyExc_ValueError,
     198             :                             "string argument should contain only ASCII characters");
     199           0 :             return 0;
     200             :         }
     201             :         assert(PyUnicode_KIND(arg) == PyUnicode_1BYTE_KIND);
     202           0 :         buf->buf = (void *) PyUnicode_1BYTE_DATA(arg);
     203           0 :         buf->len = PyUnicode_GET_LENGTH(arg);
     204           0 :         buf->obj = NULL;
     205           0 :         return 1;
     206             :     }
     207           0 :     if (PyObject_GetBuffer(arg, buf, PyBUF_SIMPLE) != 0) {
     208           0 :         PyErr_Format(PyExc_TypeError,
     209             :                      "argument should be bytes, buffer or ASCII string, "
     210             :                      "not %R", Py_TYPE(arg));
     211           0 :         return 0;
     212             :     }
     213           0 :     if (!PyBuffer_IsContiguous(buf, 'C')) {
     214           0 :         PyErr_Format(PyExc_TypeError,
     215             :                      "argument should be a contiguous buffer, "
     216             :                      "not %R", Py_TYPE(arg));
     217           0 :         PyBuffer_Release(buf);
     218           0 :         return 0;
     219             :     }
     220           0 :     return Py_CLEANUP_SUPPORTED;
     221             : }
     222             : 
     223             : 
     224             : PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data");
     225             : 
     226             : static PyObject *
     227           0 : binascii_a2b_uu(PyObject *self, PyObject *args)
     228             : {
     229             :     Py_buffer pascii;
     230             :     unsigned char *ascii_data, *bin_data;
     231           0 :     int leftbits = 0;
     232             :     unsigned char this_ch;
     233           0 :     unsigned int leftchar = 0;
     234             :     PyObject *rv;
     235             :     Py_ssize_t ascii_len, bin_len;
     236             : 
     237           0 :     if ( !PyArg_ParseTuple(args, "O&:a2b_uu", ascii_buffer_converter, &pascii) )
     238           0 :         return NULL;
     239           0 :     ascii_data = pascii.buf;
     240           0 :     ascii_len = pascii.len;
     241             : 
     242             :     assert(ascii_len >= 0);
     243             : 
     244             :     /* First byte: binary data length (in bytes) */
     245           0 :     bin_len = (*ascii_data++ - ' ') & 077;
     246           0 :     ascii_len--;
     247             : 
     248             :     /* Allocate the buffer */
     249           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) {
     250           0 :         PyBuffer_Release(&pascii);
     251           0 :         return NULL;
     252             :     }
     253           0 :     bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
     254             : 
     255           0 :     for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) {
     256             :         /* XXX is it really best to add NULs if there's no more data */
     257           0 :         this_ch = (ascii_len > 0) ? *ascii_data : 0;
     258           0 :         if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) {
     259             :             /*
     260             :             ** Whitespace. Assume some spaces got eaten at
     261             :             ** end-of-line. (We check this later)
     262             :             */
     263           0 :             this_ch = 0;
     264             :         } else {
     265             :             /* Check the character for legality
     266             :             ** The 64 in stead of the expected 63 is because
     267             :             ** there are a few uuencodes out there that use
     268             :             ** '`' as zero instead of space.
     269             :             */
     270           0 :             if ( this_ch < ' ' || this_ch > (' ' + 64)) {
     271           0 :                 PyErr_SetString(Error, "Illegal char");
     272           0 :                 PyBuffer_Release(&pascii);
     273           0 :                 Py_DECREF(rv);
     274           0 :                 return NULL;
     275             :             }
     276           0 :             this_ch = (this_ch - ' ') & 077;
     277             :         }
     278             :         /*
     279             :         ** Shift it in on the low end, and see if there's
     280             :         ** a byte ready for output.
     281             :         */
     282           0 :         leftchar = (leftchar << 6) | (this_ch);
     283           0 :         leftbits += 6;
     284           0 :         if ( leftbits >= 8 ) {
     285           0 :             leftbits -= 8;
     286           0 :             *bin_data++ = (leftchar >> leftbits) & 0xff;
     287           0 :             leftchar &= ((1 << leftbits) - 1);
     288           0 :             bin_len--;
     289             :         }
     290             :     }
     291             :     /*
     292             :     ** Finally, check that if there's anything left on the line
     293             :     ** that it's whitespace only.
     294             :     */
     295           0 :     while( ascii_len-- > 0 ) {
     296           0 :         this_ch = *ascii_data++;
     297             :         /* Extra '`' may be written as padding in some cases */
     298           0 :         if ( this_ch != ' ' && this_ch != ' '+64 &&
     299           0 :              this_ch != '\n' && this_ch != '\r' ) {
     300           0 :             PyErr_SetString(Error, "Trailing garbage");
     301           0 :             PyBuffer_Release(&pascii);
     302           0 :             Py_DECREF(rv);
     303           0 :             return NULL;
     304             :         }
     305             :     }
     306           0 :     PyBuffer_Release(&pascii);
     307           0 :     return rv;
     308             : }
     309             : 
     310             : PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
     311             : 
     312             : static PyObject *
     313           0 : binascii_b2a_uu(PyObject *self, PyObject *args)
     314             : {
     315             :     Py_buffer pbin;
     316             :     unsigned char *ascii_data, *bin_data;
     317           0 :     int leftbits = 0;
     318             :     unsigned char this_ch;
     319           0 :     unsigned int leftchar = 0;
     320             :     PyObject *rv;
     321             :     Py_ssize_t bin_len;
     322             : 
     323           0 :     if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) )
     324           0 :         return NULL;
     325           0 :     bin_data = pbin.buf;
     326           0 :     bin_len = pbin.len;
     327           0 :     if ( bin_len > 45 ) {
     328             :         /* The 45 is a limit that appears in all uuencode's */
     329           0 :         PyErr_SetString(Error, "At most 45 bytes at once");
     330           0 :         PyBuffer_Release(&pbin);
     331           0 :         return NULL;
     332             :     }
     333             : 
     334             :     /* We're lazy and allocate to much (fixed up later) */
     335           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) {
     336           0 :         PyBuffer_Release(&pbin);
     337           0 :         return NULL;
     338             :     }
     339           0 :     ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
     340             : 
     341             :     /* Store the length */
     342           0 :     *ascii_data++ = ' ' + (bin_len & 077);
     343             : 
     344           0 :     for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) {
     345             :         /* Shift the data (or padding) into our buffer */
     346           0 :         if ( bin_len > 0 )              /* Data */
     347           0 :             leftchar = (leftchar << 8) | *bin_data;
     348             :         else                            /* Padding */
     349           0 :             leftchar <<= 8;
     350           0 :         leftbits += 8;
     351             : 
     352             :         /* See if there are 6-bit groups ready */
     353           0 :         while ( leftbits >= 6 ) {
     354           0 :             this_ch = (leftchar >> (leftbits-6)) & 0x3f;
     355           0 :             leftbits -= 6;
     356           0 :             *ascii_data++ = this_ch + ' ';
     357             :         }
     358             :     }
     359           0 :     *ascii_data++ = '\n';       /* Append a courtesy newline */
     360             : 
     361           0 :     if (_PyBytes_Resize(&rv,
     362             :                        (ascii_data -
     363           0 :                         (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
     364           0 :         Py_DECREF(rv);
     365           0 :         rv = NULL;
     366             :     }
     367           0 :     PyBuffer_Release(&pbin);
     368           0 :     return rv;
     369             : }
     370             : 
     371             : 
     372             : static int
     373           0 : binascii_find_valid(unsigned char *s, Py_ssize_t slen, int num)
     374             : {
     375             :     /* Finds & returns the (num+1)th
     376             :     ** valid character for base64, or -1 if none.
     377             :     */
     378             : 
     379           0 :     int ret = -1;
     380             :     unsigned char c, b64val;
     381             : 
     382           0 :     while ((slen > 0) && (ret == -1)) {
     383           0 :         c = *s;
     384           0 :         b64val = table_a2b_base64[c & 0x7f];
     385           0 :         if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) {
     386           0 :             if (num == 0)
     387           0 :                 ret = *s;
     388           0 :             num--;
     389             :         }
     390             : 
     391           0 :         s++;
     392           0 :         slen--;
     393             :     }
     394           0 :     return ret;
     395             : }
     396             : 
     397             : PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data");
     398             : 
     399             : static PyObject *
     400           0 : binascii_a2b_base64(PyObject *self, PyObject *args)
     401             : {
     402             :     Py_buffer pascii;
     403             :     unsigned char *ascii_data, *bin_data;
     404           0 :     int leftbits = 0;
     405             :     unsigned char this_ch;
     406           0 :     unsigned int leftchar = 0;
     407             :     PyObject *rv;
     408             :     Py_ssize_t ascii_len, bin_len;
     409           0 :     int quad_pos = 0;
     410             : 
     411           0 :     if ( !PyArg_ParseTuple(args, "O&:a2b_base64", ascii_buffer_converter, &pascii) )
     412           0 :         return NULL;
     413           0 :     ascii_data = pascii.buf;
     414           0 :     ascii_len = pascii.len;
     415             : 
     416             :     assert(ascii_len >= 0);
     417             : 
     418           0 :     if (ascii_len > PY_SSIZE_T_MAX - 3) {
     419           0 :         PyBuffer_Release(&pascii);
     420           0 :         return PyErr_NoMemory();
     421             :     }
     422             : 
     423           0 :     bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
     424             : 
     425             :     /* Allocate the buffer */
     426           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) {
     427           0 :         PyBuffer_Release(&pascii);
     428           0 :         return NULL;
     429             :     }
     430           0 :     bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
     431           0 :     bin_len = 0;
     432             : 
     433           0 :     for( ; ascii_len > 0; ascii_len--, ascii_data++) {
     434           0 :         this_ch = *ascii_data;
     435             : 
     436           0 :         if (this_ch > 0x7f ||
     437           0 :             this_ch == '\r' || this_ch == '\n' || this_ch == ' ')
     438           0 :             continue;
     439             : 
     440             :         /* Check for pad sequences and ignore
     441             :         ** the invalid ones.
     442             :         */
     443           0 :         if (this_ch == BASE64_PAD) {
     444           0 :             if ( (quad_pos < 2) ||
     445           0 :                  ((quad_pos == 2) &&
     446           0 :                   (binascii_find_valid(ascii_data, ascii_len, 1)
     447             :                    != BASE64_PAD)) )
     448             :             {
     449           0 :                 continue;
     450             :             }
     451             :             else {
     452             :                 /* A pad sequence means no more input.
     453             :                 ** We've already interpreted the data
     454             :                 ** from the quad at this point.
     455             :                 */
     456           0 :                 leftbits = 0;
     457           0 :                 break;
     458             :             }
     459             :         }
     460             : 
     461           0 :         this_ch = table_a2b_base64[*ascii_data];
     462           0 :         if ( this_ch == (unsigned char) -1 )
     463           0 :             continue;
     464             : 
     465             :         /*
     466             :         ** Shift it in on the low end, and see if there's
     467             :         ** a byte ready for output.
     468             :         */
     469           0 :         quad_pos = (quad_pos + 1) & 0x03;
     470           0 :         leftchar = (leftchar << 6) | (this_ch);
     471           0 :         leftbits += 6;
     472             : 
     473           0 :         if ( leftbits >= 8 ) {
     474           0 :             leftbits -= 8;
     475           0 :             *bin_data++ = (leftchar >> leftbits) & 0xff;
     476           0 :             bin_len++;
     477           0 :             leftchar &= ((1 << leftbits) - 1);
     478             :         }
     479             :     }
     480             : 
     481           0 :     if (leftbits != 0) {
     482           0 :         PyBuffer_Release(&pascii);
     483           0 :         PyErr_SetString(Error, "Incorrect padding");
     484           0 :         Py_DECREF(rv);
     485           0 :         return NULL;
     486             :     }
     487             : 
     488             :     /* And set string size correctly. If the result string is empty
     489             :     ** (because the input was all invalid) return the shared empty
     490             :     ** string instead; _PyBytes_Resize() won't do this for us.
     491             :     */
     492           0 :     if (bin_len > 0) {
     493           0 :         if (_PyBytes_Resize(&rv, bin_len) < 0) {
     494           0 :             Py_DECREF(rv);
     495           0 :             rv = NULL;
     496             :         }
     497             :     }
     498             :     else {
     499           0 :         Py_DECREF(rv);
     500           0 :         rv = PyBytes_FromStringAndSize("", 0);
     501             :     }
     502           0 :     PyBuffer_Release(&pascii);
     503           0 :     return rv;
     504             : }
     505             : 
     506             : PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
     507             : 
     508             : static PyObject *
     509           0 : binascii_b2a_base64(PyObject *self, PyObject *args)
     510             : {
     511             :     Py_buffer pbuf;
     512             :     unsigned char *ascii_data, *bin_data;
     513           0 :     int leftbits = 0;
     514             :     unsigned char this_ch;
     515           0 :     unsigned int leftchar = 0;
     516             :     PyObject *rv;
     517             :     Py_ssize_t bin_len;
     518             : 
     519           0 :     if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) )
     520           0 :         return NULL;
     521           0 :     bin_data = pbuf.buf;
     522           0 :     bin_len = pbuf.len;
     523             : 
     524             :     assert(bin_len >= 0);
     525             : 
     526           0 :     if ( bin_len > BASE64_MAXBIN ) {
     527           0 :         PyErr_SetString(Error, "Too much data for base64 line");
     528           0 :         PyBuffer_Release(&pbuf);
     529           0 :         return NULL;
     530             :     }
     531             : 
     532             :     /* We're lazy and allocate too much (fixed up later).
     533             :        "+3" leaves room for up to two pad characters and a trailing
     534             :        newline.  Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */
     535           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) {
     536           0 :         PyBuffer_Release(&pbuf);
     537           0 :         return NULL;
     538             :     }
     539           0 :     ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
     540             : 
     541           0 :     for( ; bin_len > 0 ; bin_len--, bin_data++ ) {
     542             :         /* Shift the data into our buffer */
     543           0 :         leftchar = (leftchar << 8) | *bin_data;
     544           0 :         leftbits += 8;
     545             : 
     546             :         /* See if there are 6-bit groups ready */
     547           0 :         while ( leftbits >= 6 ) {
     548           0 :             this_ch = (leftchar >> (leftbits-6)) & 0x3f;
     549           0 :             leftbits -= 6;
     550           0 :             *ascii_data++ = table_b2a_base64[this_ch];
     551             :         }
     552             :     }
     553           0 :     if ( leftbits == 2 ) {
     554           0 :         *ascii_data++ = table_b2a_base64[(leftchar&3) << 4];
     555           0 :         *ascii_data++ = BASE64_PAD;
     556           0 :         *ascii_data++ = BASE64_PAD;
     557           0 :     } else if ( leftbits == 4 ) {
     558           0 :         *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2];
     559           0 :         *ascii_data++ = BASE64_PAD;
     560             :     }
     561           0 :     *ascii_data++ = '\n';       /* Append a courtesy newline */
     562             : 
     563           0 :     if (_PyBytes_Resize(&rv,
     564             :                        (ascii_data -
     565           0 :                         (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
     566           0 :         Py_DECREF(rv);
     567           0 :         rv = NULL;
     568             :     }
     569           0 :     PyBuffer_Release(&pbuf);
     570           0 :     return rv;
     571             : }
     572             : 
     573             : PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
     574             : 
     575             : static PyObject *
     576           0 : binascii_a2b_hqx(PyObject *self, PyObject *args)
     577             : {
     578             :     Py_buffer pascii;
     579             :     unsigned char *ascii_data, *bin_data;
     580           0 :     int leftbits = 0;
     581             :     unsigned char this_ch;
     582           0 :     unsigned int leftchar = 0;
     583             :     PyObject *rv;
     584             :     Py_ssize_t len;
     585           0 :     int done = 0;
     586             : 
     587           0 :     if ( !PyArg_ParseTuple(args, "O&:a2b_hqx", ascii_buffer_converter, &pascii) )
     588           0 :         return NULL;
     589           0 :     ascii_data = pascii.buf;
     590           0 :     len = pascii.len;
     591             : 
     592             :     assert(len >= 0);
     593             : 
     594           0 :     if (len > PY_SSIZE_T_MAX - 2) {
     595           0 :         PyBuffer_Release(&pascii);
     596           0 :         return PyErr_NoMemory();
     597             :     }
     598             : 
     599             :     /* Allocate a string that is too big (fixed later)
     600             :        Add two to the initial length to prevent interning which
     601             :        would preclude subsequent resizing.  */
     602           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) {
     603           0 :         PyBuffer_Release(&pascii);
     604           0 :         return NULL;
     605             :     }
     606           0 :     bin_data = (unsigned char *)PyBytes_AS_STRING(rv);
     607             : 
     608           0 :     for( ; len > 0 ; len--, ascii_data++ ) {
     609             :         /* Get the byte and look it up */
     610           0 :         this_ch = table_a2b_hqx[*ascii_data];
     611           0 :         if ( this_ch == SKIP )
     612           0 :             continue;
     613           0 :         if ( this_ch == FAIL ) {
     614           0 :             PyErr_SetString(Error, "Illegal char");
     615           0 :             PyBuffer_Release(&pascii);
     616           0 :             Py_DECREF(rv);
     617           0 :             return NULL;
     618             :         }
     619           0 :         if ( this_ch == DONE ) {
     620             :             /* The terminating colon */
     621           0 :             done = 1;
     622           0 :             break;
     623             :         }
     624             : 
     625             :         /* Shift it into the buffer and see if any bytes are ready */
     626           0 :         leftchar = (leftchar << 6) | (this_ch);
     627           0 :         leftbits += 6;
     628           0 :         if ( leftbits >= 8 ) {
     629           0 :             leftbits -= 8;
     630           0 :             *bin_data++ = (leftchar >> leftbits) & 0xff;
     631           0 :             leftchar &= ((1 << leftbits) - 1);
     632             :         }
     633             :     }
     634             : 
     635           0 :     if ( leftbits && !done ) {
     636           0 :         PyErr_SetString(Incomplete,
     637             :                         "String has incomplete number of bytes");
     638           0 :         PyBuffer_Release(&pascii);
     639           0 :         Py_DECREF(rv);
     640           0 :         return NULL;
     641             :     }
     642           0 :     if (_PyBytes_Resize(&rv,
     643             :                        (bin_data -
     644           0 :                         (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
     645           0 :         Py_DECREF(rv);
     646           0 :         rv = NULL;
     647             :     }
     648           0 :     if (rv) {
     649           0 :         PyObject *rrv = Py_BuildValue("Oi", rv, done);
     650           0 :         PyBuffer_Release(&pascii);
     651           0 :         Py_DECREF(rv);
     652           0 :         return rrv;
     653             :     }
     654             : 
     655           0 :     PyBuffer_Release(&pascii);
     656           0 :     return NULL;
     657             : }
     658             : 
     659             : PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
     660             : 
     661             : static PyObject *
     662           0 : binascii_rlecode_hqx(PyObject *self, PyObject *args)
     663             : {
     664             :     Py_buffer pbuf;
     665             :     unsigned char *in_data, *out_data;
     666             :     PyObject *rv;
     667             :     unsigned char ch;
     668             :     Py_ssize_t in, inend, len;
     669             : 
     670           0 :     if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) )
     671           0 :         return NULL;
     672           0 :     in_data = pbuf.buf;
     673           0 :     len = pbuf.len;
     674             : 
     675             :     assert(len >= 0);
     676             : 
     677           0 :     if (len > PY_SSIZE_T_MAX / 2 - 2) {
     678           0 :         PyBuffer_Release(&pbuf);
     679           0 :         return PyErr_NoMemory();
     680             :     }
     681             : 
     682             :     /* Worst case: output is twice as big as input (fixed later) */
     683           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) {
     684           0 :         PyBuffer_Release(&pbuf);
     685           0 :         return NULL;
     686             :     }
     687           0 :     out_data = (unsigned char *)PyBytes_AS_STRING(rv);
     688             : 
     689           0 :     for( in=0; in<len; in++) {
     690           0 :         ch = in_data[in];
     691           0 :         if ( ch == RUNCHAR ) {
     692             :             /* RUNCHAR. Escape it. */
     693           0 :             *out_data++ = RUNCHAR;
     694           0 :             *out_data++ = 0;
     695             :         } else {
     696             :             /* Check how many following are the same */
     697           0 :             for(inend=in+1;
     698           0 :                 inend<len && in_data[inend] == ch &&
     699           0 :                     inend < in+255;
     700           0 :                 inend++) ;
     701           0 :             if ( inend - in > 3 ) {
     702             :                 /* More than 3 in a row. Output RLE. */
     703           0 :                 *out_data++ = ch;
     704           0 :                 *out_data++ = RUNCHAR;
     705           0 :                 *out_data++ = (unsigned char) (inend-in);
     706           0 :                 in = inend-1;
     707             :             } else {
     708             :                 /* Less than 3. Output the byte itself */
     709           0 :                 *out_data++ = ch;
     710             :             }
     711             :         }
     712             :     }
     713           0 :     if (_PyBytes_Resize(&rv,
     714             :                        (out_data -
     715           0 :                         (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
     716           0 :         Py_DECREF(rv);
     717           0 :         rv = NULL;
     718             :     }
     719           0 :     PyBuffer_Release(&pbuf);
     720           0 :     return rv;
     721             : }
     722             : 
     723             : PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
     724             : 
     725             : static PyObject *
     726           0 : binascii_b2a_hqx(PyObject *self, PyObject *args)
     727             : {
     728             :     Py_buffer pbin;
     729             :     unsigned char *ascii_data, *bin_data;
     730           0 :     int leftbits = 0;
     731             :     unsigned char this_ch;
     732           0 :     unsigned int leftchar = 0;
     733             :     PyObject *rv;
     734             :     Py_ssize_t len;
     735             : 
     736           0 :     if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) )
     737           0 :         return NULL;
     738           0 :     bin_data = pbin.buf;
     739           0 :     len = pbin.len;
     740             : 
     741             :     assert(len >= 0);
     742             : 
     743           0 :     if (len > PY_SSIZE_T_MAX / 2 - 2) {
     744           0 :         PyBuffer_Release(&pbin);
     745           0 :         return PyErr_NoMemory();
     746             :     }
     747             : 
     748             :     /* Allocate a buffer that is at least large enough */
     749           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) {
     750           0 :         PyBuffer_Release(&pbin);
     751           0 :         return NULL;
     752             :     }
     753           0 :     ascii_data = (unsigned char *)PyBytes_AS_STRING(rv);
     754             : 
     755           0 :     for( ; len > 0 ; len--, bin_data++ ) {
     756             :         /* Shift into our buffer, and output any 6bits ready */
     757           0 :         leftchar = (leftchar << 8) | *bin_data;
     758           0 :         leftbits += 8;
     759           0 :         while ( leftbits >= 6 ) {
     760           0 :             this_ch = (leftchar >> (leftbits-6)) & 0x3f;
     761           0 :             leftbits -= 6;
     762           0 :             *ascii_data++ = table_b2a_hqx[this_ch];
     763             :         }
     764             :     }
     765             :     /* Output a possible runt byte */
     766           0 :     if ( leftbits ) {
     767           0 :         leftchar <<= (6-leftbits);
     768           0 :         *ascii_data++ = table_b2a_hqx[leftchar & 0x3f];
     769             :     }
     770           0 :     if (_PyBytes_Resize(&rv,
     771             :                        (ascii_data -
     772           0 :                         (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
     773           0 :         Py_DECREF(rv);
     774           0 :         rv = NULL;
     775             :     }
     776           0 :     PyBuffer_Release(&pbin);
     777           0 :     return rv;
     778             : }
     779             : 
     780             : PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
     781             : 
     782             : static PyObject *
     783           0 : binascii_rledecode_hqx(PyObject *self, PyObject *args)
     784             : {
     785             :     Py_buffer pin;
     786             :     unsigned char *in_data, *out_data;
     787             :     unsigned char in_byte, in_repeat;
     788             :     PyObject *rv;
     789             :     Py_ssize_t in_len, out_len, out_len_left;
     790             : 
     791           0 :     if ( !PyArg_ParseTuple(args, "y*:rledecode_hqx", &pin) )
     792           0 :         return NULL;
     793           0 :     in_data = pin.buf;
     794           0 :     in_len = pin.len;
     795             : 
     796             :     assert(in_len >= 0);
     797             : 
     798             :     /* Empty string is a special case */
     799           0 :     if ( in_len == 0 ) {
     800           0 :         PyBuffer_Release(&pin);
     801           0 :         return PyBytes_FromStringAndSize("", 0);
     802             :     }
     803           0 :     else if (in_len > PY_SSIZE_T_MAX / 2) {
     804           0 :         PyBuffer_Release(&pin);
     805           0 :         return PyErr_NoMemory();
     806             :     }
     807             : 
     808             :     /* Allocate a buffer of reasonable size. Resized when needed */
     809           0 :     out_len = in_len*2;
     810           0 :     if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) {
     811           0 :         PyBuffer_Release(&pin);
     812           0 :         return NULL;
     813             :     }
     814           0 :     out_len_left = out_len;
     815           0 :     out_data = (unsigned char *)PyBytes_AS_STRING(rv);
     816             : 
     817             :     /*
     818             :     ** We need two macros here to get/put bytes and handle
     819             :     ** end-of-buffer for input and output strings.
     820             :     */
     821             : #define INBYTE(b) \
     822             :     do { \
     823             :              if ( --in_len < 0 ) { \
     824             :                        PyErr_SetString(Incomplete, ""); \
     825             :                        Py_DECREF(rv); \
     826             :                        PyBuffer_Release(&pin); \
     827             :                        return NULL; \
     828             :              } \
     829             :              b = *in_data++; \
     830             :     } while(0)
     831             : 
     832             : #define OUTBYTE(b) \
     833             :     do { \
     834             :              if ( --out_len_left < 0 ) { \
     835             :                       if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \
     836             :                       if (_PyBytes_Resize(&rv, 2*out_len) < 0) \
     837             :                         { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \
     838             :                       out_data = (unsigned char *)PyBytes_AS_STRING(rv) \
     839             :                                                              + out_len; \
     840             :                       out_len_left = out_len-1; \
     841             :                       out_len = out_len * 2; \
     842             :              } \
     843             :              *out_data++ = b; \
     844             :     } while(0)
     845             : 
     846             :         /*
     847             :         ** Handle first byte separately (since we have to get angry
     848             :         ** in case of an orphaned RLE code).
     849             :         */
     850           0 :         INBYTE(in_byte);
     851             : 
     852           0 :     if (in_byte == RUNCHAR) {
     853           0 :         INBYTE(in_repeat);
     854           0 :         if (in_repeat != 0) {
     855             :             /* Note Error, not Incomplete (which is at the end
     856             :             ** of the string only). This is a programmer error.
     857             :             */
     858           0 :             PyErr_SetString(Error, "Orphaned RLE code at start");
     859           0 :             PyBuffer_Release(&pin);
     860           0 :             Py_DECREF(rv);
     861           0 :             return NULL;
     862             :         }
     863           0 :         OUTBYTE(RUNCHAR);
     864             :     } else {
     865           0 :         OUTBYTE(in_byte);
     866             :     }
     867             : 
     868           0 :     while( in_len > 0 ) {
     869           0 :         INBYTE(in_byte);
     870             : 
     871           0 :         if (in_byte == RUNCHAR) {
     872           0 :             INBYTE(in_repeat);
     873           0 :             if ( in_repeat == 0 ) {
     874             :                 /* Just an escaped RUNCHAR value */
     875           0 :                 OUTBYTE(RUNCHAR);
     876             :             } else {
     877             :                 /* Pick up value and output a sequence of it */
     878           0 :                 in_byte = out_data[-1];
     879           0 :                 while ( --in_repeat > 0 )
     880           0 :                     OUTBYTE(in_byte);
     881             :             }
     882             :         } else {
     883             :             /* Normal byte */
     884           0 :             OUTBYTE(in_byte);
     885             :         }
     886             :     }
     887           0 :     if (_PyBytes_Resize(&rv,
     888             :                        (out_data -
     889           0 :                         (unsigned char *)PyBytes_AS_STRING(rv))) < 0) {
     890           0 :         Py_DECREF(rv);
     891           0 :         rv = NULL;
     892             :     }
     893           0 :     PyBuffer_Release(&pin);
     894           0 :     return rv;
     895             : }
     896             : 
     897             : PyDoc_STRVAR(doc_crc_hqx,
     898             : "(data, oldcrc) -> newcrc. Compute hqx CRC incrementally");
     899             : 
     900             : static PyObject *
     901           0 : binascii_crc_hqx(PyObject *self, PyObject *args)
     902             : {
     903             :     Py_buffer pin;
     904             :     unsigned char *bin_data;
     905             :     unsigned int crc;
     906             :     Py_ssize_t len;
     907             : 
     908           0 :     if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) )
     909           0 :         return NULL;
     910           0 :     bin_data = pin.buf;
     911           0 :     len = pin.len;
     912             : 
     913           0 :     while(len-- > 0) {
     914           0 :         crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
     915             :     }
     916             : 
     917           0 :     PyBuffer_Release(&pin);
     918           0 :     return Py_BuildValue("i", crc);
     919             : }
     920             : 
     921             : PyDoc_STRVAR(doc_crc32,
     922             : "(data, oldcrc = 0) -> newcrc. Compute CRC-32 incrementally");
     923             : 
     924             : #ifdef USE_ZLIB_CRC32
     925             : /* This was taken from zlibmodule.c PyZlib_crc32 (but is PY_SSIZE_T_CLEAN) */
     926             : static PyObject *
     927           0 : binascii_crc32(PyObject *self, PyObject *args)
     928             : {
     929           0 :     unsigned int crc32val = 0;  /* crc32(0L, Z_NULL, 0) */
     930             :     Py_buffer pbuf;
     931             :     Byte *buf;
     932             :     Py_ssize_t len;
     933             :     int signed_val;
     934             : 
     935           0 :     if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val))
     936           0 :     return NULL;
     937           0 :     buf = (Byte*)pbuf.buf;
     938           0 :     len = pbuf.len;
     939           0 :     signed_val = crc32(crc32val, buf, len);
     940           0 :     PyBuffer_Release(&pbuf);
     941           0 :     return PyLong_FromUnsignedLong(signed_val & 0xffffffffU);
     942             : }
     943             : #else  /* USE_ZLIB_CRC32 */
     944             : /*  Crc - 32 BIT ANSI X3.66 CRC checksum files
     945             :     Also known as: ISO 3307
     946             : **********************************************************************|
     947             : *                                                                    *|
     948             : * Demonstration program to compute the 32-bit CRC used as the frame  *|
     949             : * check sequence in ADCCP (ANSI X3.66, also known as FIPS PUB 71     *|
     950             : * and FED-STD-1003, the U.S. versions of CCITT's X.25 link-level     *|
     951             : * protocol).  The 32-bit FCS was added via the Federal Register,     *|
     952             : * 1 June 1982, p.23798.  I presume but don't know for certain that   *|
     953             : * this polynomial is or will be included in CCITT V.41, which        *|
     954             : * defines the 16-bit CRC (often called CRC-CCITT) polynomial.  FIPS  *|
     955             : * PUB 78 says that the 32-bit FCS reduces otherwise undetected       *|
     956             : * errors by a factor of 10^-5 over 16-bit FCS.                       *|
     957             : *                                                                    *|
     958             : **********************************************************************|
     959             : 
     960             :  Copyright (C) 1986 Gary S. Brown.  You may use this program, or
     961             :  code or tables extracted from it, as desired without restriction.
     962             : 
     963             :  First, the polynomial itself and its table of feedback terms.  The
     964             :  polynomial is
     965             :  X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0
     966             :  Note that we take it "backwards" and put the highest-order term in
     967             :  the lowest-order bit.  The X^32 term is "implied"; the LSB is the
     968             :  X^31 term, etc.  The X^0 term (usually shown as "+1") results in
     969             :  the MSB being 1.
     970             : 
     971             :  Note that the usual hardware shift register implementation, which
     972             :  is what we're using (we're merely optimizing it by doing eight-bit
     973             :  chunks at a time) shifts bits into the lowest-order term.  In our
     974             :  implementation, that means shifting towards the right.  Why do we
     975             :  do it this way?  Because the calculated CRC must be transmitted in
     976             :  order from highest-order term to lowest-order term.  UARTs transmit
     977             :  characters in order from LSB to MSB.  By storing the CRC this way,
     978             :  we hand it to the UART in the order low-byte to high-byte; the UART
     979             :  sends each low-bit to hight-bit; and the result is transmission bit
     980             :  by bit from highest- to lowest-order term without requiring any bit
     981             :  shuffling on our part.  Reception works similarly.
     982             : 
     983             :  The feedback terms table consists of 256, 32-bit entries.  Notes:
     984             : 
     985             :   1. The table can be generated at runtime if desired; code to do so
     986             :      is shown later.  It might not be obvious, but the feedback
     987             :      terms simply represent the results of eight shift/xor opera-
     988             :      tions for all combinations of data and CRC register values.
     989             : 
     990             :   2. The CRC accumulation logic is the same for all CRC polynomials,
     991             :      be they sixteen or thirty-two bits wide.  You simply choose the
     992             :      appropriate table.  Alternatively, because the table can be
     993             :      generated at runtime, you can start by generating the table for
     994             :      the polynomial in question and use exactly the same "updcrc",
     995             :      if your application needn't simultaneously handle two CRC
     996             :      polynomials.  (Note, however, that XMODEM is strange.)
     997             : 
     998             :   3. For 16-bit CRCs, the table entries need be only 16 bits wide;
     999             :      of course, 32-bit entries work OK if the high 16 bits are zero.
    1000             : 
    1001             :   4. The values must be right-shifted by eight bits by the "updcrc"
    1002             :      logic; the shift must be unsigned (bring in zeroes).  On some
    1003             :      hardware you could probably optimize the shift in assembler by
    1004             :      using byte-swap instructions.
    1005             : ********************************************************************/
    1006             : 
    1007             : static unsigned int crc_32_tab[256] = {
    1008             : 0x00000000U, 0x77073096U, 0xee0e612cU, 0x990951baU, 0x076dc419U,
    1009             : 0x706af48fU, 0xe963a535U, 0x9e6495a3U, 0x0edb8832U, 0x79dcb8a4U,
    1010             : 0xe0d5e91eU, 0x97d2d988U, 0x09b64c2bU, 0x7eb17cbdU, 0xe7b82d07U,
    1011             : 0x90bf1d91U, 0x1db71064U, 0x6ab020f2U, 0xf3b97148U, 0x84be41deU,
    1012             : 0x1adad47dU, 0x6ddde4ebU, 0xf4d4b551U, 0x83d385c7U, 0x136c9856U,
    1013             : 0x646ba8c0U, 0xfd62f97aU, 0x8a65c9ecU, 0x14015c4fU, 0x63066cd9U,
    1014             : 0xfa0f3d63U, 0x8d080df5U, 0x3b6e20c8U, 0x4c69105eU, 0xd56041e4U,
    1015             : 0xa2677172U, 0x3c03e4d1U, 0x4b04d447U, 0xd20d85fdU, 0xa50ab56bU,
    1016             : 0x35b5a8faU, 0x42b2986cU, 0xdbbbc9d6U, 0xacbcf940U, 0x32d86ce3U,
    1017             : 0x45df5c75U, 0xdcd60dcfU, 0xabd13d59U, 0x26d930acU, 0x51de003aU,
    1018             : 0xc8d75180U, 0xbfd06116U, 0x21b4f4b5U, 0x56b3c423U, 0xcfba9599U,
    1019             : 0xb8bda50fU, 0x2802b89eU, 0x5f058808U, 0xc60cd9b2U, 0xb10be924U,
    1020             : 0x2f6f7c87U, 0x58684c11U, 0xc1611dabU, 0xb6662d3dU, 0x76dc4190U,
    1021             : 0x01db7106U, 0x98d220bcU, 0xefd5102aU, 0x71b18589U, 0x06b6b51fU,
    1022             : 0x9fbfe4a5U, 0xe8b8d433U, 0x7807c9a2U, 0x0f00f934U, 0x9609a88eU,
    1023             : 0xe10e9818U, 0x7f6a0dbbU, 0x086d3d2dU, 0x91646c97U, 0xe6635c01U,
    1024             : 0x6b6b51f4U, 0x1c6c6162U, 0x856530d8U, 0xf262004eU, 0x6c0695edU,
    1025             : 0x1b01a57bU, 0x8208f4c1U, 0xf50fc457U, 0x65b0d9c6U, 0x12b7e950U,
    1026             : 0x8bbeb8eaU, 0xfcb9887cU, 0x62dd1ddfU, 0x15da2d49U, 0x8cd37cf3U,
    1027             : 0xfbd44c65U, 0x4db26158U, 0x3ab551ceU, 0xa3bc0074U, 0xd4bb30e2U,
    1028             : 0x4adfa541U, 0x3dd895d7U, 0xa4d1c46dU, 0xd3d6f4fbU, 0x4369e96aU,
    1029             : 0x346ed9fcU, 0xad678846U, 0xda60b8d0U, 0x44042d73U, 0x33031de5U,
    1030             : 0xaa0a4c5fU, 0xdd0d7cc9U, 0x5005713cU, 0x270241aaU, 0xbe0b1010U,
    1031             : 0xc90c2086U, 0x5768b525U, 0x206f85b3U, 0xb966d409U, 0xce61e49fU,
    1032             : 0x5edef90eU, 0x29d9c998U, 0xb0d09822U, 0xc7d7a8b4U, 0x59b33d17U,
    1033             : 0x2eb40d81U, 0xb7bd5c3bU, 0xc0ba6cadU, 0xedb88320U, 0x9abfb3b6U,
    1034             : 0x03b6e20cU, 0x74b1d29aU, 0xead54739U, 0x9dd277afU, 0x04db2615U,
    1035             : 0x73dc1683U, 0xe3630b12U, 0x94643b84U, 0x0d6d6a3eU, 0x7a6a5aa8U,
    1036             : 0xe40ecf0bU, 0x9309ff9dU, 0x0a00ae27U, 0x7d079eb1U, 0xf00f9344U,
    1037             : 0x8708a3d2U, 0x1e01f268U, 0x6906c2feU, 0xf762575dU, 0x806567cbU,
    1038             : 0x196c3671U, 0x6e6b06e7U, 0xfed41b76U, 0x89d32be0U, 0x10da7a5aU,
    1039             : 0x67dd4accU, 0xf9b9df6fU, 0x8ebeeff9U, 0x17b7be43U, 0x60b08ed5U,
    1040             : 0xd6d6a3e8U, 0xa1d1937eU, 0x38d8c2c4U, 0x4fdff252U, 0xd1bb67f1U,
    1041             : 0xa6bc5767U, 0x3fb506ddU, 0x48b2364bU, 0xd80d2bdaU, 0xaf0a1b4cU,
    1042             : 0x36034af6U, 0x41047a60U, 0xdf60efc3U, 0xa867df55U, 0x316e8eefU,
    1043             : 0x4669be79U, 0xcb61b38cU, 0xbc66831aU, 0x256fd2a0U, 0x5268e236U,
    1044             : 0xcc0c7795U, 0xbb0b4703U, 0x220216b9U, 0x5505262fU, 0xc5ba3bbeU,
    1045             : 0xb2bd0b28U, 0x2bb45a92U, 0x5cb36a04U, 0xc2d7ffa7U, 0xb5d0cf31U,
    1046             : 0x2cd99e8bU, 0x5bdeae1dU, 0x9b64c2b0U, 0xec63f226U, 0x756aa39cU,
    1047             : 0x026d930aU, 0x9c0906a9U, 0xeb0e363fU, 0x72076785U, 0x05005713U,
    1048             : 0x95bf4a82U, 0xe2b87a14U, 0x7bb12baeU, 0x0cb61b38U, 0x92d28e9bU,
    1049             : 0xe5d5be0dU, 0x7cdcefb7U, 0x0bdbdf21U, 0x86d3d2d4U, 0xf1d4e242U,
    1050             : 0x68ddb3f8U, 0x1fda836eU, 0x81be16cdU, 0xf6b9265bU, 0x6fb077e1U,
    1051             : 0x18b74777U, 0x88085ae6U, 0xff0f6a70U, 0x66063bcaU, 0x11010b5cU,
    1052             : 0x8f659effU, 0xf862ae69U, 0x616bffd3U, 0x166ccf45U, 0xa00ae278U,
    1053             : 0xd70dd2eeU, 0x4e048354U, 0x3903b3c2U, 0xa7672661U, 0xd06016f7U,
    1054             : 0x4969474dU, 0x3e6e77dbU, 0xaed16a4aU, 0xd9d65adcU, 0x40df0b66U,
    1055             : 0x37d83bf0U, 0xa9bcae53U, 0xdebb9ec5U, 0x47b2cf7fU, 0x30b5ffe9U,
    1056             : 0xbdbdf21cU, 0xcabac28aU, 0x53b39330U, 0x24b4a3a6U, 0xbad03605U,
    1057             : 0xcdd70693U, 0x54de5729U, 0x23d967bfU, 0xb3667a2eU, 0xc4614ab8U,
    1058             : 0x5d681b02U, 0x2a6f2b94U, 0xb40bbe37U, 0xc30c8ea1U, 0x5a05df1bU,
    1059             : 0x2d02ef8dU
    1060             : };
    1061             : 
    1062             : static PyObject *
    1063             : binascii_crc32(PyObject *self, PyObject *args)
    1064             : { /* By Jim Ahlstrom; All rights transferred to CNRI */
    1065             :     Py_buffer pbin;
    1066             :     unsigned char *bin_data;
    1067             :     unsigned int crc = 0;       /* initial value of CRC */
    1068             :     Py_ssize_t len;
    1069             :     unsigned int result;
    1070             : 
    1071             :     if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) )
    1072             :         return NULL;
    1073             :     bin_data = pbin.buf;
    1074             :     len = pbin.len;
    1075             : 
    1076             :     crc = ~ crc;
    1077             :     while (len-- > 0) {
    1078             :         crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8);
    1079             :         /* Note:  (crc >> 8) MUST zero fill on left */
    1080             :     }
    1081             : 
    1082             :     result = (crc ^ 0xFFFFFFFF);
    1083             :     PyBuffer_Release(&pbin);
    1084             :     return PyLong_FromUnsignedLong(result & 0xffffffff);
    1085             : }
    1086             : #endif  /* USE_ZLIB_CRC32 */
    1087             : 
    1088             : 
    1089             : static PyObject *
    1090           0 : binascii_hexlify(PyObject *self, PyObject *args)
    1091             : {
    1092             :     Py_buffer parg;
    1093             :     char* argbuf;
    1094             :     Py_ssize_t arglen;
    1095             :     PyObject *retval;
    1096             :     char* retbuf;
    1097             :     Py_ssize_t i, j;
    1098             : 
    1099           0 :     if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg))
    1100           0 :         return NULL;
    1101           0 :     argbuf = parg.buf;
    1102           0 :     arglen = parg.len;
    1103             : 
    1104             :     assert(arglen >= 0);
    1105           0 :     if (arglen > PY_SSIZE_T_MAX / 2) {
    1106           0 :         PyBuffer_Release(&parg);
    1107           0 :         return PyErr_NoMemory();
    1108             :     }
    1109             : 
    1110           0 :     retval = PyBytes_FromStringAndSize(NULL, arglen*2);
    1111           0 :     if (!retval) {
    1112           0 :         PyBuffer_Release(&parg);
    1113           0 :         return NULL;
    1114             :     }
    1115           0 :     retbuf = PyBytes_AS_STRING(retval);
    1116             : 
    1117             :     /* make hex version of string, taken from shamodule.c */
    1118           0 :     for (i=j=0; i < arglen; i++) {
    1119             :         unsigned char c;
    1120           0 :         c = (argbuf[i] >> 4) & 0xf;
    1121           0 :         retbuf[j++] = Py_hexdigits[c];
    1122           0 :         c = argbuf[i] & 0xf;
    1123           0 :         retbuf[j++] = Py_hexdigits[c];
    1124             :     }
    1125           0 :     PyBuffer_Release(&parg);
    1126           0 :     return retval;
    1127             : }
    1128             : 
    1129             : PyDoc_STRVAR(doc_hexlify,
    1130             : "b2a_hex(data) -> s; Hexadecimal representation of binary data.\n\
    1131             : \n\
    1132             : This function is also available as \"hexlify()\".");
    1133             : 
    1134             : 
    1135             : static int
    1136           0 : to_int(int c)
    1137             : {
    1138           0 :     if (isdigit(c))
    1139           0 :         return c - '0';
    1140             :     else {
    1141           0 :         if (Py_ISUPPER(c))
    1142           0 :             c = Py_TOLOWER(c);
    1143           0 :         if (c >= 'a' && c <= 'f')
    1144           0 :             return c - 'a' + 10;
    1145             :     }
    1146           0 :     return -1;
    1147             : }
    1148             : 
    1149             : 
    1150             : static PyObject *
    1151           0 : binascii_unhexlify(PyObject *self, PyObject *args)
    1152             : {
    1153             :     Py_buffer parg;
    1154             :     char* argbuf;
    1155             :     Py_ssize_t arglen;
    1156             :     PyObject *retval;
    1157             :     char* retbuf;
    1158             :     Py_ssize_t i, j;
    1159             : 
    1160           0 :     if (!PyArg_ParseTuple(args, "O&:a2b_hex", ascii_buffer_converter, &parg))
    1161           0 :         return NULL;
    1162           0 :     argbuf = parg.buf;
    1163           0 :     arglen = parg.len;
    1164             : 
    1165             :     assert(arglen >= 0);
    1166             : 
    1167             :     /* XXX What should we do about strings with an odd length?  Should
    1168             :      * we add an implicit leading zero, or a trailing zero?  For now,
    1169             :      * raise an exception.
    1170             :      */
    1171           0 :     if (arglen % 2) {
    1172           0 :         PyBuffer_Release(&parg);
    1173           0 :         PyErr_SetString(Error, "Odd-length string");
    1174           0 :         return NULL;
    1175             :     }
    1176             : 
    1177           0 :     retval = PyBytes_FromStringAndSize(NULL, (arglen/2));
    1178           0 :     if (!retval) {
    1179           0 :         PyBuffer_Release(&parg);
    1180           0 :         return NULL;
    1181             :     }
    1182           0 :     retbuf = PyBytes_AS_STRING(retval);
    1183             : 
    1184           0 :     for (i=j=0; i < arglen; i += 2) {
    1185           0 :         int top = to_int(Py_CHARMASK(argbuf[i]));
    1186           0 :         int bot = to_int(Py_CHARMASK(argbuf[i+1]));
    1187           0 :         if (top == -1 || bot == -1) {
    1188           0 :             PyErr_SetString(Error,
    1189             :                             "Non-hexadecimal digit found");
    1190           0 :             goto finally;
    1191             :         }
    1192           0 :         retbuf[j++] = (top << 4) + bot;
    1193             :     }
    1194           0 :     PyBuffer_Release(&parg);
    1195           0 :     return retval;
    1196             : 
    1197             :   finally:
    1198           0 :     PyBuffer_Release(&parg);
    1199           0 :     Py_DECREF(retval);
    1200           0 :     return NULL;
    1201             : }
    1202             : 
    1203             : PyDoc_STRVAR(doc_unhexlify,
    1204             : "a2b_hex(hexstr) -> s; Binary data of hexadecimal representation.\n\
    1205             : \n\
    1206             : hexstr must contain an even number of hex digits (upper or lower case).\n\
    1207             : This function is also available as \"unhexlify()\"");
    1208             : 
    1209             : static int table_hex[128] = {
    1210             :   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
    1211             :   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
    1212             :   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
    1213             :    0, 1, 2, 3,  4, 5, 6, 7,  8, 9,-1,-1, -1,-1,-1,-1,
    1214             :   -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
    1215             :   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
    1216             :   -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
    1217             :   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
    1218             : };
    1219             : 
    1220             : #define hexval(c) table_hex[(unsigned int)(c)]
    1221             : 
    1222             : #define MAXLINESIZE 76
    1223             : 
    1224             : PyDoc_STRVAR(doc_a2b_qp, "Decode a string of qp-encoded data");
    1225             : 
    1226             : static PyObject*
    1227           0 : binascii_a2b_qp(PyObject *self, PyObject *args, PyObject *kwargs)
    1228             : {
    1229             :     Py_ssize_t in, out;
    1230             :     char ch;
    1231             :     Py_buffer pdata;
    1232             :     unsigned char *data, *odata;
    1233           0 :     Py_ssize_t datalen = 0;
    1234             :     PyObject *rv;
    1235             :     static char *kwlist[] = {"data", "header", NULL};
    1236           0 :     int header = 0;
    1237             : 
    1238           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|i:a2b_qp", kwlist,
    1239             :                                      ascii_buffer_converter, &pdata, &header))
    1240           0 :         return NULL;
    1241           0 :     data = pdata.buf;
    1242           0 :     datalen = pdata.len;
    1243             : 
    1244             :     /* We allocate the output same size as input, this is overkill.
    1245             :      * The previous implementation used calloc() so we'll zero out the
    1246             :      * memory here too, since PyMem_Malloc() does not guarantee that.
    1247             :      */
    1248           0 :     odata = (unsigned char *) PyMem_Malloc(datalen);
    1249           0 :     if (odata == NULL) {
    1250           0 :         PyBuffer_Release(&pdata);
    1251           0 :         PyErr_NoMemory();
    1252           0 :         return NULL;
    1253             :     }
    1254           0 :     memset(odata, 0, datalen);
    1255             : 
    1256           0 :     in = out = 0;
    1257           0 :     while (in < datalen) {
    1258           0 :         if (data[in] == '=') {
    1259           0 :             in++;
    1260           0 :             if (in >= datalen) break;
    1261             :             /* Soft line breaks */
    1262           0 :             if ((data[in] == '\n') || (data[in] == '\r')) {
    1263           0 :                 if (data[in] != '\n') {
    1264           0 :                     while (in < datalen && data[in] != '\n') in++;
    1265             :                 }
    1266           0 :                 if (in < datalen) in++;
    1267             :             }
    1268           0 :             else if (data[in] == '=') {
    1269             :                 /* broken case from broken python qp */
    1270           0 :                 odata[out++] = '=';
    1271           0 :                 in++;
    1272             :             }
    1273           0 :             else if (((data[in] >= 'A' && data[in] <= 'F') ||
    1274           0 :                       (data[in] >= 'a' && data[in] <= 'f') ||
    1275           0 :                       (data[in] >= '0' && data[in] <= '9')) &&
    1276           0 :                      ((data[in+1] >= 'A' && data[in+1] <= 'F') ||
    1277           0 :                       (data[in+1] >= 'a' && data[in+1] <= 'f') ||
    1278           0 :                       (data[in+1] >= '0' && data[in+1] <= '9'))) {
    1279             :                 /* hexval */
    1280           0 :                 ch = hexval(data[in]) << 4;
    1281           0 :                 in++;
    1282           0 :                 ch |= hexval(data[in]);
    1283           0 :                 in++;
    1284           0 :                 odata[out++] = ch;
    1285             :             }
    1286             :             else {
    1287           0 :               odata[out++] = '=';
    1288             :             }
    1289             :         }
    1290           0 :         else if (header && data[in] == '_') {
    1291           0 :             odata[out++] = ' ';
    1292           0 :             in++;
    1293             :         }
    1294             :         else {
    1295           0 :             odata[out] = data[in];
    1296           0 :             in++;
    1297           0 :             out++;
    1298             :         }
    1299             :     }
    1300           0 :     if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
    1301           0 :         PyBuffer_Release(&pdata);
    1302           0 :         PyMem_Free(odata);
    1303           0 :         return NULL;
    1304             :     }
    1305           0 :     PyBuffer_Release(&pdata);
    1306           0 :     PyMem_Free(odata);
    1307           0 :     return rv;
    1308             : }
    1309             : 
    1310             : static int
    1311           0 : to_hex (unsigned char ch, unsigned char *s)
    1312             : {
    1313           0 :     unsigned int uvalue = ch;
    1314             : 
    1315           0 :     s[1] = "0123456789ABCDEF"[uvalue % 16];
    1316           0 :     uvalue = (uvalue / 16);
    1317           0 :     s[0] = "0123456789ABCDEF"[uvalue % 16];
    1318           0 :     return 0;
    1319             : }
    1320             : 
    1321             : PyDoc_STRVAR(doc_b2a_qp,
    1322             : "b2a_qp(data, quotetabs=0, istext=1, header=0) -> s; \n\
    1323             :  Encode a string using quoted-printable encoding. \n\
    1324             : \n\
    1325             : On encoding, when istext is set, newlines are not encoded, and white \n\
    1326             : space at end of lines is.  When istext is not set, \\r and \\n (CR/LF) are \n\
    1327             : both encoded.  When quotetabs is set, space and tabs are encoded.");
    1328             : 
    1329             : /* XXX: This is ridiculously complicated to be backward compatible
    1330             :  * (mostly) with the quopri module.  It doesn't re-create the quopri
    1331             :  * module bug where text ending in CRLF has the CR encoded */
    1332             : static PyObject*
    1333           0 : binascii_b2a_qp (PyObject *self, PyObject *args, PyObject *kwargs)
    1334             : {
    1335             :     Py_ssize_t in, out;
    1336             :     Py_buffer pdata;
    1337             :     unsigned char *data, *odata;
    1338           0 :     Py_ssize_t datalen = 0, odatalen = 0;
    1339             :     PyObject *rv;
    1340           0 :     unsigned int linelen = 0;
    1341             :     static char *kwlist[] = {"data", "quotetabs", "istext",
    1342             :                                    "header", NULL};
    1343           0 :     int istext = 1;
    1344           0 :     int quotetabs = 0;
    1345           0 :     int header = 0;
    1346             :     unsigned char ch;
    1347           0 :     int crlf = 0;
    1348             :     unsigned char *p;
    1349             : 
    1350           0 :     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata,
    1351             :           &quotetabs, &istext, &header))
    1352           0 :         return NULL;
    1353           0 :     data = pdata.buf;
    1354           0 :     datalen = pdata.len;
    1355             : 
    1356             :     /* See if this string is using CRLF line ends */
    1357             :     /* XXX: this function has the side effect of converting all of
    1358             :      * the end of lines to be the same depending on this detection
    1359             :      * here */
    1360           0 :     p = (unsigned char *) memchr(data, '\n', datalen);
    1361           0 :     if ((p != NULL) && (p > data) && (*(p-1) == '\r'))
    1362           0 :         crlf = 1;
    1363             : 
    1364             :     /* First, scan to see how many characters need to be encoded */
    1365           0 :     in = 0;
    1366           0 :     while (in < datalen) {
    1367           0 :         if ((data[in] > 126) ||
    1368           0 :             (data[in] == '=') ||
    1369           0 :             (header && data[in] == '_') ||
    1370           0 :             ((data[in] == '.') && (linelen == 0) &&
    1371           0 :              (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
    1372           0 :             (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
    1373           0 :             ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
    1374           0 :             ((data[in] < 33) &&
    1375           0 :              (data[in] != '\r') && (data[in] != '\n') &&
    1376           0 :              (quotetabs || ((data[in] != '\t') && (data[in] != ' ')))))
    1377             :         {
    1378           0 :             if ((linelen + 3) >= MAXLINESIZE) {
    1379           0 :                 linelen = 0;
    1380           0 :                 if (crlf)
    1381           0 :                     odatalen += 3;
    1382             :                 else
    1383           0 :                     odatalen += 2;
    1384             :             }
    1385           0 :             linelen += 3;
    1386           0 :             odatalen += 3;
    1387           0 :             in++;
    1388             :         }
    1389             :         else {
    1390           0 :             if (istext &&
    1391           0 :                 ((data[in] == '\n') ||
    1392           0 :                  ((in+1 < datalen) && (data[in] == '\r') &&
    1393           0 :                  (data[in+1] == '\n'))))
    1394             :             {
    1395           0 :                 linelen = 0;
    1396             :                 /* Protect against whitespace on end of line */
    1397           0 :                 if (in && ((data[in-1] == ' ') || (data[in-1] == '\t')))
    1398           0 :                     odatalen += 2;
    1399           0 :                 if (crlf)
    1400           0 :                     odatalen += 2;
    1401             :                 else
    1402           0 :                     odatalen += 1;
    1403           0 :                 if (data[in] == '\r')
    1404           0 :                     in += 2;
    1405             :                 else
    1406           0 :                     in++;
    1407             :             }
    1408             :             else {
    1409           0 :                 if ((in + 1 != datalen) &&
    1410           0 :                     (data[in+1] != '\n') &&
    1411           0 :                     (linelen + 1) >= MAXLINESIZE) {
    1412           0 :                     linelen = 0;
    1413           0 :                     if (crlf)
    1414           0 :                         odatalen += 3;
    1415             :                     else
    1416           0 :                         odatalen += 2;
    1417             :                 }
    1418           0 :                 linelen++;
    1419           0 :                 odatalen++;
    1420           0 :                 in++;
    1421             :             }
    1422             :         }
    1423             :     }
    1424             : 
    1425             :     /* We allocate the output same size as input, this is overkill.
    1426             :      * The previous implementation used calloc() so we'll zero out the
    1427             :      * memory here too, since PyMem_Malloc() does not guarantee that.
    1428             :      */
    1429           0 :     odata = (unsigned char *) PyMem_Malloc(odatalen);
    1430           0 :     if (odata == NULL) {
    1431           0 :         PyBuffer_Release(&pdata);
    1432           0 :         PyErr_NoMemory();
    1433           0 :         return NULL;
    1434             :     }
    1435           0 :     memset(odata, 0, odatalen);
    1436             : 
    1437           0 :     in = out = linelen = 0;
    1438           0 :     while (in < datalen) {
    1439           0 :         if ((data[in] > 126) ||
    1440           0 :             (data[in] == '=') ||
    1441           0 :             (header && data[in] == '_') ||
    1442           0 :             ((data[in] == '.') && (linelen == 0) &&
    1443           0 :              (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
    1444           0 :             (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
    1445           0 :             ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
    1446           0 :             ((data[in] < 33) &&
    1447           0 :              (data[in] != '\r') && (data[in] != '\n') &&
    1448           0 :              (quotetabs ||
    1449           0 :             (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
    1450             :         {
    1451           0 :             if ((linelen + 3 )>= MAXLINESIZE) {
    1452           0 :                 odata[out++] = '=';
    1453           0 :                 if (crlf) odata[out++] = '\r';
    1454           0 :                 odata[out++] = '\n';
    1455           0 :                 linelen = 0;
    1456             :             }
    1457           0 :             odata[out++] = '=';
    1458           0 :             to_hex(data[in], &odata[out]);
    1459           0 :             out += 2;
    1460           0 :             in++;
    1461           0 :             linelen += 3;
    1462             :         }
    1463             :         else {
    1464           0 :             if (istext &&
    1465           0 :                 ((data[in] == '\n') ||
    1466           0 :                  ((in+1 < datalen) && (data[in] == '\r') &&
    1467           0 :                  (data[in+1] == '\n'))))
    1468             :             {
    1469           0 :                 linelen = 0;
    1470             :                 /* Protect against whitespace on end of line */
    1471           0 :                 if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) {
    1472           0 :                     ch = odata[out-1];
    1473           0 :                     odata[out-1] = '=';
    1474           0 :                     to_hex(ch, &odata[out]);
    1475           0 :                     out += 2;
    1476             :                 }
    1477             : 
    1478           0 :                 if (crlf) odata[out++] = '\r';
    1479           0 :                 odata[out++] = '\n';
    1480           0 :                 if (data[in] == '\r')
    1481           0 :                     in += 2;
    1482             :                 else
    1483           0 :                     in++;
    1484             :             }
    1485             :             else {
    1486           0 :                 if ((in + 1 != datalen) &&
    1487           0 :                     (data[in+1] != '\n') &&
    1488           0 :                     (linelen + 1) >= MAXLINESIZE) {
    1489           0 :                     odata[out++] = '=';
    1490           0 :                     if (crlf) odata[out++] = '\r';
    1491           0 :                     odata[out++] = '\n';
    1492           0 :                     linelen = 0;
    1493             :                 }
    1494           0 :                 linelen++;
    1495           0 :                 if (header && data[in] == ' ') {
    1496           0 :                     odata[out++] = '_';
    1497           0 :                     in++;
    1498             :                 }
    1499             :                 else {
    1500           0 :                     odata[out++] = data[in++];
    1501             :                 }
    1502             :             }
    1503             :         }
    1504             :     }
    1505           0 :     if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) {
    1506           0 :         PyBuffer_Release(&pdata);
    1507           0 :         PyMem_Free(odata);
    1508           0 :         return NULL;
    1509             :     }
    1510           0 :     PyBuffer_Release(&pdata);
    1511           0 :     PyMem_Free(odata);
    1512           0 :     return rv;
    1513             : }
    1514             : 
    1515             : /* List of functions defined in the module */
    1516             : 
    1517             : static struct PyMethodDef binascii_module_methods[] = {
    1518             :     {"a2b_uu",     binascii_a2b_uu,     METH_VARARGS, doc_a2b_uu},
    1519             :     {"b2a_uu",     binascii_b2a_uu,     METH_VARARGS, doc_b2a_uu},
    1520             :     {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64},
    1521             :     {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64},
    1522             :     {"a2b_hqx",    binascii_a2b_hqx,    METH_VARARGS, doc_a2b_hqx},
    1523             :     {"b2a_hqx",    binascii_b2a_hqx,    METH_VARARGS, doc_b2a_hqx},
    1524             :     {"b2a_hex",    binascii_hexlify,    METH_VARARGS, doc_hexlify},
    1525             :     {"a2b_hex",    binascii_unhexlify,  METH_VARARGS, doc_unhexlify},
    1526             :     {"hexlify",    binascii_hexlify,    METH_VARARGS, doc_hexlify},
    1527             :     {"unhexlify",  binascii_unhexlify,  METH_VARARGS, doc_unhexlify},
    1528             :     {"rlecode_hqx",   binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx},
    1529             :     {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS,
    1530             :      doc_rledecode_hqx},
    1531             :     {"crc_hqx",    binascii_crc_hqx,    METH_VARARGS, doc_crc_hqx},
    1532             :     {"crc32",      binascii_crc32,      METH_VARARGS, doc_crc32},
    1533             :     {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS,
    1534             :       doc_a2b_qp},
    1535             :     {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS,
    1536             :       doc_b2a_qp},
    1537             :     {NULL, NULL}                             /* sentinel */
    1538             : };
    1539             : 
    1540             : 
    1541             : /* Initialization function for the module (*must* be called PyInit_binascii) */
    1542             : PyDoc_STRVAR(doc_binascii, "Conversion between binary data and ASCII");
    1543             : 
    1544             : 
    1545             : static struct PyModuleDef binasciimodule = {
    1546             :     PyModuleDef_HEAD_INIT,
    1547             :     "binascii",
    1548             :     doc_binascii,
    1549             :     -1,
    1550             :     binascii_module_methods,
    1551             :     NULL,
    1552             :     NULL,
    1553             :     NULL,
    1554             :     NULL
    1555             : };
    1556             : 
    1557             : PyMODINIT_FUNC
    1558           0 : PyInit_binascii(void)
    1559             : {
    1560             :     PyObject *m, *d;
    1561             : 
    1562             :     /* Create the module and add the functions */
    1563           0 :     m = PyModule_Create(&binasciimodule);
    1564           0 :     if (m == NULL)
    1565           0 :         return NULL;
    1566             : 
    1567           0 :     d = PyModule_GetDict(m);
    1568             : 
    1569           0 :     Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL);
    1570           0 :     PyDict_SetItemString(d, "Error", Error);
    1571           0 :     Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
    1572           0 :     PyDict_SetItemString(d, "Incomplete", Incomplete);
    1573           0 :     if (PyErr_Occurred()) {
    1574           0 :         Py_DECREF(m);
    1575           0 :         m = NULL;
    1576             :     }
    1577           0 :     return m;
    1578             : }

Generated by: LCOV version 1.10