unbanked

b64.c

Apr 20th, 2017
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 20.62 KB | None | 0 0
  1. /*********************************************************************\
  2.  
  3. MODULE NAME:    b64.c
  4.  
  5. AUTHOR:         Bob Trower 2001/08/04
  6.  
  7. PROJECT:        Crypt Data Packaging
  8.  
  9. COPYRIGHT:      Copyright (c) Trantor Standard Systems Inc., 2001
  10.  
  11. NOTES:          This source code may be used as you wish, subject to
  12.                 the MIT license.  See the LICENCE section below.
  13.  
  14.                 Canonical source should be at:
  15.                     http://base64.sourceforge.net
  16.  
  17. DESCRIPTION:
  18.                 This little utility implements the Base64
  19.                 Content-Transfer-Encoding standard described in
  20.                 RFC1113 (http://www.faqs.org/rfcs/rfc1113.html).
  21.  
  22.                 This is the coding scheme used by MIME to allow
  23.                 binary data to be transferred by SMTP mail.
  24.  
  25.                 Groups of 3 bytes from a binary stream are coded as
  26.                 groups of 4 bytes in a text stream.
  27.  
  28.                 The input stream is 'padded' with zeros to create
  29.                 an input that is an even multiple of 3.
  30.  
  31.                 A special character ('=') is used to denote padding so
  32.                 that the stream can be decoded back to its exact size.
  33.  
  34.                 Encoded output is formatted in lines which should
  35.                 be a maximum of 72 characters to conform to the
  36.                 specification.  This program defaults to 72 characters,
  37.                 but will allow more or less through the use of a
  38.                 switch.  The program enforces a minimum line size
  39.                 of 4 characters.
  40.  
  41.                 Example encoding:
  42.  
  43.                 The stream 'ABCD' is 32 bits long.  It is mapped as
  44.                 follows:
  45.  
  46.                 ABCD
  47.  
  48.                  A (65)     B (66)     C (67)     D (68)   (None) (None)
  49.                 01000001   01000010   01000011   01000100
  50.  
  51.                 16 (Q)  20 (U)  9 (J)   3 (D)    17 (R) 0 (A)  NA (=) NA (=)
  52.                 010000  010100  001001  000011   010001 000000 000000 000000
  53.  
  54.  
  55.                 QUJDRA==
  56.  
  57.                 Decoding is the process in reverse.  A 'decode' lookup
  58.                 table has been created to avoid string scans.
  59.  
  60. DESIGN GOALS:   Specifically:
  61.         Code is a stand-alone utility to perform base64
  62.         encoding/decoding. It should be genuinely useful
  63.         when the need arises and it meets a need that is
  64.         likely to occur for some users.  
  65.         Code acts as sample code to show the author's
  66.         design and coding style.  
  67.  
  68.         Generally:
  69.         This program is designed to survive:
  70.         Everything you need is in a single source file.
  71.         It compiles cleanly using a vanilla ANSI C compiler.
  72.         It does its job correctly with a minimum of fuss.  
  73.         The code is not overly clever, not overly simplistic
  74.         and not overly verbose.
  75.         Access is 'cut and paste' from a web page.  
  76.         Terms of use are reasonable.  
  77.  
  78. VALIDATION:     Non-trivial code is never without errors.  This
  79.                 file likely has some problems, since it has only
  80.                 been tested by the author.  It is expected with most
  81.                 source code that there is a period of 'burn-in' when
  82.                 problems are identified and corrected.  That being
  83.                 said, it is possible to have 'reasonably correct'
  84.                 code by following a regime of unit test that covers
  85.                 the most likely cases and regression testing prior
  86.                 to release.  This has been done with this code and
  87.                 it has a good probability of performing as expected.
  88.  
  89.                 Unit Test Cases:
  90.  
  91.                 case 0:empty file:
  92.                     CASE0.DAT  ->  ->
  93.                     (Zero length target file created
  94.                     on both encode and decode.)
  95.  
  96.                 case 1:One input character:
  97.                     CASE1.DAT A -> QQ== -> A
  98.  
  99.                 case 2:Two input characters:
  100.                     CASE2.DAT AB -> QUI= -> AB
  101.  
  102.                 case 3:Three input characters:
  103.                     CASE3.DAT ABC -> QUJD -> ABC
  104.  
  105.                 case 4:Four input characters:
  106.                     case4.dat ABCD -> QUJDRA== -> ABCD
  107.  
  108.                 case 5:All chars from 0 to ff, linesize set to 50:
  109.  
  110.                     AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIj
  111.                     JCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZH
  112.                     SElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr
  113.                     bG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P
  114.                     kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKz
  115.                     tLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX
  116.                     2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7
  117.                     /P3+/w==
  118.  
  119.                 case 6:Mime Block from e-mail:
  120.                     (Data same as test case 5)
  121.  
  122.                 case 7: Large files:
  123.                     Tested 28 MB file in/out.
  124.  
  125.                 case 8: Random Binary Integrity:
  126.                     This binary program (b64.exe) was encoded to base64,
  127.                     back to binary and then executed.
  128.  
  129.                 case 9 Stress:
  130.                     All files in a working directory encoded/decoded
  131.                     and compared with file comparison utility to
  132.                     ensure that multiple runs do not cause problems
  133.                     such as exhausting file handles, tmp storage, etc.
  134.  
  135.                 -------------
  136.  
  137.                 Syntax, operation and failure:
  138.                     All options/switches tested.  Performs as
  139.                     expected.
  140.  
  141.                 case 10:
  142.                     No Args -- Shows Usage Screen
  143.                     Return Code 1 (Invalid Syntax)
  144.                 case 11:
  145.                     One Arg (invalid) -- Shows Usage Screen
  146.                     Return Code 1 (Invalid Syntax)
  147.                 case 12:
  148.                     One Arg Help (-?) -- Shows detailed Usage Screen.
  149.                     Return Code 0 (Success -- help request is valid).
  150.                 case 13:
  151.                     One Arg Help (-h) -- Shows detailed Usage Screen.
  152.                     Return Code 0 (Success -- help request is valid).
  153.                 case 14:
  154.                     One Arg (valid) -- Uses stdin/stdout (filter)
  155.                     Return Code 0 (Sucess)
  156.                 case 15:
  157.                     Two Args (invalid file) -- shows system error.
  158.                     Return Code 2 (File Error)
  159.                 case 16:
  160.                     Encode non-existent file -- shows system error.
  161.                     Return Code 2 (File Error)
  162.                 case 17:
  163.                     Out of disk space -- shows system error.
  164.                     Return Code 3 (File I/O Error)
  165.                 case 18:
  166.                     Too many args -- shows system error.
  167.                     Return Code 1 (Invalid Syntax)
  168.  
  169.                 -------------
  170.  
  171.                 Compile/Regression test:
  172.                     gcc compiled binary under Cygwin
  173.                     Microsoft Visual Studio under Windows 2000
  174.                     Microsoft Version 6.0 C under Windows 2000
  175.  
  176. DEPENDENCIES:   None
  177.  
  178. LICENCE:        Copyright (c) 2001 Bob Trower, Trantor Standard Systems Inc.
  179.  
  180.                 Permission is hereby granted, free of charge, to any person
  181.                 obtaining a copy of this software and associated
  182.                 documentation files (the "Software"), to deal in the
  183.                 Software without restriction, including without limitation
  184.                 the rights to use, copy, modify, merge, publish, distribute,
  185.                 sublicense, and/or sell copies of the Software, and to
  186.                 permit persons to whom the Software is furnished to do so,
  187.                 subject to the following conditions:
  188.  
  189.                 The above copyright notice and this permission notice shall
  190.                 be included in all copies or substantial portions of the
  191.                 Software.
  192.  
  193.                 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  194.                 KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  195.                 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  196.                 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  197.                 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  198.                 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  199.                 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  200.                 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  201.  
  202. VERSION HISTORY:
  203.                 Bob Trower 2001/08/04 -- Create Version 0.00.00B
  204.                 Bob Trower 2001/08/17 -- Correct documentation, messages.
  205.                                       -- Correct help for linesize syntax.
  206.                                       -- Force error on too many arguments.
  207.                 Bob Trower 2001/08/19 -- Add sourceforge.net reference to
  208.                                          help screen prior to release.
  209.                 Bob Trower 2004/10/22 -- Cosmetics for package/release.
  210.                 Bob Trower 2008/02/28 -- More Cosmetics for package/release.
  211.                 Bob Trower 2011/02/14 -- Cast altered to fix warning in VS6.
  212.                 Bob Trower 2015/10/29 -- Change *bug* from 0 to EOF in putc
  213.                                          invocation. BIG shout out to people
  214.                                          reviewing on sourceforge,
  215.                                          particularly rachidc, jorgeventura
  216.                                          and zeroxia.
  217.                                       -- Change date format to conform with
  218.                                          latest convention.
  219.  
  220. \******************************************************************* */
  221.  
  222. #include <stdio.h>
  223. #include <stdlib.h>
  224.  
  225. /*
  226. ** Translation Table as described in RFC1113
  227. */
  228. static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  229.  
  230. /*
  231. ** Translation Table to decode (created by author)
  232. */
  233. static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
  234.  
  235. /*
  236. ** returnable errors
  237. **
  238. ** Error codes returned to the operating system.
  239. **
  240. */
  241. #define B64_SYNTAX_ERROR        1
  242. #define B64_FILE_ERROR          2
  243. #define B64_FILE_IO_ERROR       3
  244. #define B64_ERROR_OUT_CLOSE     4
  245. #define B64_LINE_SIZE_TO_MIN    5
  246. #define B64_SYNTAX_TOOMANYARGS  6
  247.  
  248. /*
  249. ** b64_message
  250. **
  251. ** Gather text messages in one place.
  252. **
  253. */
  254. #define B64_MAX_MESSAGES 7
  255. static char *b64_msgs[ B64_MAX_MESSAGES ] = {
  256.             "b64:000:Invalid Message Code.",
  257.             "b64:001:Syntax Error -- check help (-h) for usage.",
  258.             "b64:002:File Error Opening/Creating Files.",
  259.             "b64:003:File I/O Error -- Note: output file not removed.",
  260.             "b64:004:Error on output file close.",
  261.             "b64:005:linesize set to minimum.",
  262.             "b64:006:Syntax: Too many arguments."
  263. };
  264.  
  265. #define b64_message( ec ) ((ec > 0 && ec < B64_MAX_MESSAGES ) ? b64_msgs[ ec ] : b64_msgs[ 0 ])
  266.  
  267. /*
  268. ** encodeblock
  269. **
  270. ** encode 3 8-bit binary bytes as 4 '6-bit' characters
  271. */
  272. static void encodeblock( unsigned char *in, unsigned char *out, int len )
  273. {
  274.     out[0] = (unsigned char) cb64[ (int)(in[0] >> 2) ];
  275.     out[1] = (unsigned char) cb64[ (int)(((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)) ];
  276.     out[2] = (unsigned char) (len > 1 ? cb64[ (int)(((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)) ] : '=');
  277.     out[3] = (unsigned char) (len > 2 ? cb64[ (int)(in[2] & 0x3f) ] : '=');
  278. }
  279.  
  280. /*
  281. ** encode
  282. **
  283. ** base64 encode a stream adding padding and line breaks as per spec.
  284. */
  285. static int encode( FILE *infile, FILE *outfile, int linesize )
  286. {
  287.     unsigned char in[3];
  288.     unsigned char out[4];
  289.     int i, len, blocksout = 0;
  290.     int retcode = 0;
  291.  
  292.     *in = (unsigned char) 0;
  293.     *out = (unsigned char) 0;
  294.     while( feof( infile ) == 0 ) {
  295.         len = 0;
  296.         for( i = 0; i < 3; i++ ) {
  297.             in[i] = (unsigned char) getc( infile );
  298.  
  299.             if( feof( infile ) == 0 ) {
  300.                 len++;
  301.             }
  302.             else {
  303.                 in[i] = (unsigned char) 0;
  304.             }
  305.         }
  306.         if( len > 0 ) {
  307.             encodeblock( in, out, len );
  308.             for( i = 0; i < 4; i++ ) {
  309.                 if( putc( (int)(out[i]), outfile ) == EOF ){
  310.                     if( ferror( outfile ) != 0 )      {
  311.                         perror( b64_message( B64_FILE_IO_ERROR ) );
  312.                         retcode = B64_FILE_IO_ERROR;
  313.                     }
  314.                     break;
  315.                 }
  316.             }
  317.             blocksout++;
  318.         }
  319.         if( blocksout >= (linesize/4) || feof( infile ) != 0 ) {
  320.             if( blocksout > 0 ) {
  321.                 fprintf( outfile, "\n" );
  322.             }
  323.             blocksout = 0;
  324.         }
  325.     }
  326.     return( retcode );
  327. }
  328.  
  329. /*
  330. ** decodeblock
  331. **
  332. ** decode 4 '6-bit' characters into 3 8-bit binary bytes
  333. */
  334. static void decodeblock( unsigned char *in, unsigned char *out )
  335. {  
  336.     out[ 0 ] = (unsigned char ) (in[0] << 2 | in[1] >> 4);
  337.     out[ 1 ] = (unsigned char ) (in[1] << 4 | in[2] >> 2);
  338.     out[ 2 ] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]);
  339. }
  340.  
  341. /*
  342. ** decode
  343. **
  344. ** decode a base64 encoded stream discarding padding, line breaks and noise
  345. */
  346. static int decode( FILE *infile, FILE *outfile )
  347. {
  348.     int retcode = 0;
  349.     unsigned char in[4];
  350.     unsigned char out[3];
  351.     int v;
  352.     int i, len;
  353.  
  354.     *in = (unsigned char) 0;
  355.     *out = (unsigned char) 0;
  356.     while( feof( infile ) == 0 ) {
  357.         for( len = 0, i = 0; i < 4 && feof( infile ) == 0; i++ ) {
  358.             v = 0;
  359.             while( feof( infile ) == 0 && v == 0 ) {
  360.                 v = getc( infile );
  361.                 if( feof( infile ) == 0 ) {
  362.                     v = ((v < 43 || v > 122) ? 0 : (int) cd64[ v - 43 ]);
  363.                     if( v != 0 ) {
  364.                         v = ((v == (int)'$') ? 0 : v - 61);
  365.                     }
  366.                 }
  367.             }
  368.             if( feof( infile ) == 0 ) {
  369.                 len++;
  370.                 if( v != 0 ) {
  371.                     in[ i ] = (unsigned char) (v - 1);
  372.                 }
  373.             }
  374.             else {
  375.                 in[i] = (unsigned char) 0;
  376.             }
  377.         }
  378.         if( len > 0 ) {
  379.             decodeblock( in, out );
  380.             for( i = 0; i < len - 1; i++ ) {
  381.                 if( putc( (int) out[i], outfile ) == EOF ){
  382.                     if( ferror( outfile ) != 0 )      {
  383.                         perror( b64_message( B64_FILE_IO_ERROR ) );
  384.                         retcode = B64_FILE_IO_ERROR;
  385.                     }
  386.                     break;
  387.                 }
  388.             }
  389.         }
  390.     }
  391.     return( retcode );
  392. }
  393.  
  394. /*
  395. ** b64
  396. **
  397. ** 'engine' that opens streams and calls encode/decode
  398. */
  399.  
  400. static int b64( char opt, char *infilename, char *outfilename, int linesize )
  401. {
  402.     FILE *infile;
  403.     int retcode = B64_FILE_ERROR;
  404.  
  405.     if( !infilename ) {
  406.         infile = stdin;
  407.     }
  408.     else {
  409.         infile = fopen( infilename, "rb" );
  410.     }
  411.     if( !infile ) {
  412.         perror( infilename );
  413.     }
  414.     else {
  415.         FILE *outfile;
  416.         if( !outfilename ) {
  417.             outfile = stdout;
  418.         }
  419.         else {
  420.             outfile = fopen( outfilename, "wb" );
  421.         }
  422.         if( !outfile ) {
  423.             perror( outfilename );
  424.         }
  425.         else {
  426.             if( opt == 'e' ) {
  427.                 retcode = encode( infile, outfile, linesize );
  428.             }
  429.             else {
  430.                 retcode = decode( infile, outfile );
  431.             }
  432.             if( retcode == 0 ) {
  433.                 if (ferror( infile ) != 0 || ferror( outfile ) != 0) {
  434.                     perror( b64_message( B64_FILE_IO_ERROR ) );
  435.                     retcode = B64_FILE_IO_ERROR;
  436.                 }
  437.             }
  438.             if( outfile != stdout ) {
  439.                 if( fclose( outfile ) != 0 ) {
  440.                     perror( b64_message( B64_ERROR_OUT_CLOSE ) );
  441.                     retcode = B64_FILE_IO_ERROR;
  442.                 }
  443.             }
  444.         }
  445.         if( infile != stdin ) {
  446.             if( fclose( infile ) != 0 ) {
  447.                 perror( b64_message( B64_ERROR_OUT_CLOSE ) );
  448.                 retcode = B64_FILE_IO_ERROR;
  449.             }
  450.         }
  451.     }
  452.  
  453.     return( retcode );
  454. }
  455.  
  456. /*
  457. ** showuse
  458. **
  459. ** display usage information, help, version info
  460. */
  461. static void showuse( int morehelp )
  462. {
  463.     {
  464.         printf( "\n" );
  465.         printf( "  b64      (Base64 Encode/Decode)    Bob Trower 2001/08/03 \n" );
  466.         printf( "           (C) Copr Bob Trower 1986-2015     Version 0.94R \n" );
  467.         printf( "  Usage:   b64 -option [-l<num>] [<FileIn> [<FileOut>]]\n" );
  468.         printf( "  Purpose: This program is a simple utility that implements\n" );
  469.         printf( "           Base64 Content-Transfer-Encoding (RFC1113).\n" );
  470.     }
  471.     if( morehelp == 0 ) {
  472.         printf( "           Use -h option for additional help.\n" );
  473.     }
  474.     else {
  475.         printf( "  Options: -e  encode to Base64   -h  This help text.\n" );
  476.         printf( "           -d  decode from Base64 -?  This help text.\n" );
  477.         printf( "           -t  Show test instructions. Under Windows the\n" );
  478.         printf( "               following command line will pipe the help\n" );
  479.         printf( "               text to run a test:\n" );
  480.         printf( "                   b64 -t | cmd\n" );
  481.         printf( "  Note:    -l  use to change line size (from 72 characters)\n" );
  482.         printf( "  Returns: 0 = success.  Non-zero is an error code.\n" );
  483.         printf( "  ErrCode: 1 = Bad Syntax, 2 = File Open, 3 = File I/O\n" );
  484.         printf( "  Example: b64 -e binfile b64file     <- Encode to b64\n" );
  485.         printf( "           b64 -d b64file binfile     <- Decode from b64\n" );
  486.         printf( "           b64 -e -l40 infile outfile <- Line Length of 40\n" );
  487.         printf( "  Note:    Will act as a filter, but this should only be\n" );
  488.         printf( "           used on text files due to translations made by\n" );
  489.         printf( "           operating systems.\n" );
  490.         printf( "  Source:  Source code and latest releases can be found at:\n" );
  491.         printf( "           http://base64.sourceforge.net\n" );
  492.         printf( "  Release: 0.94.00, Thu Oct 29 01:36:00 2015, ANSI-SOURCE C\n" );
  493.     }
  494. }
  495.  
  496. void dotest(void)
  497. {
  498.     printf(":See source code at sourceforge.net for\n");
  499.     printf(":Unit test information.\n");
  500.     printf(":\n");
  501.     printf(":Under Windows the following batch file will\n");
  502.     printf(":do a quick reality check:\n");
  503.     printf("\n");
  504.     printf("@echo off&cls\n");
  505.     printf("copy /b /y b64.exe b64.bin 1>>nul 2>>nul\n");
  506.     printf("b64 -e b64.bin b64.b64\n");
  507.     printf("b64 -d b64.b64 b64.bin.exe\n");
  508.     printf("fc /b b64.exe b64.bin.exe\n");
  509.     printf(":/\\ Should say no differences enountered /\\\n");
  510.     printf("\n");
  511. }
  512.  
  513. #define B64_DEF_LINE_SIZE   72
  514. #define B64_MIN_LINE_SIZE    4
  515.  
  516. #define THIS_OPT(ac, av) ((char)(ac > 1 ? av[1][0] == '-' ? av[1][1] : 0 : 0))
  517.  
  518. /*
  519. ** main
  520. **
  521. ** parse and validate arguments and call b64 engine or help
  522. */
  523. int main( int argc, char **argv )
  524. {
  525.     char opt = (char) 0;
  526.     int retcode = 0;
  527.     int linesize = B64_DEF_LINE_SIZE;
  528.     char *infilename = NULL, *outfilename = NULL;
  529.  
  530.     while( THIS_OPT( argc, argv ) != (char) 0 ) {
  531.         switch( THIS_OPT(argc, argv) ) {
  532.             case 'l':
  533.                     linesize = atoi( &(argv[1][2]) );
  534.                     if( linesize < B64_MIN_LINE_SIZE ) {
  535.                         linesize = B64_MIN_LINE_SIZE;
  536.                         printf( "%s\n", b64_message( B64_LINE_SIZE_TO_MIN ) );
  537.                     }
  538.                     break;
  539.             case '?':
  540.             case 'h':
  541.                     opt = 'h';
  542.                     break;
  543.             case 'e':
  544.             case 'd':
  545.                     opt = THIS_OPT(argc, argv);
  546.                     break;
  547.             case 't':
  548.                     opt = THIS_OPT(argc, argv);
  549.                     break;
  550.              default:
  551.                     opt = (char) 0;
  552.                     break;
  553.         }
  554.         argv++;
  555.         argc--;
  556.     }
  557.     if( argc > 3 ) {
  558.         printf( "%s\n", b64_message( B64_SYNTAX_TOOMANYARGS ) );
  559.         opt = (char) 0;
  560.     }
  561.     switch( opt ) {
  562.         case 'e':
  563.         case 'd':
  564.             infilename = argc > 1 ? argv[1] : NULL;
  565.             outfilename = argc > 2 ? argv[2] : NULL;
  566.             retcode = b64( opt, infilename, outfilename, linesize );
  567.             break;
  568.         case 0:
  569.             if( argv[1] == NULL ) {
  570.                 showuse( 0 );
  571.             }
  572.             else {
  573.                 retcode = B64_SYNTAX_ERROR;
  574.             }
  575.             break;
  576.         case 'h':
  577.             showuse( (int) opt );
  578.             break;
  579.         case 't':
  580.             dotest();
  581.             break;
  582.  
  583.     }
  584.     if( retcode != 0 ) {
  585.         printf( "%s\n", b64_message( retcode ) );
  586.     }
  587.  
  588.     return( retcode );
  589. }
Add Comment
Please, Sign In to add comment