Back to index

lightning-sunbird  0.9+nobinonly
nssb64d.c
Go to the documentation of this file.
00001 /* ***** BEGIN LICENSE BLOCK *****
00002  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00003  *
00004  * The contents of this file are subject to the Mozilla Public License Version
00005  * 1.1 (the "License"); you may not use this file except in compliance with
00006  * the License. You may obtain a copy of the License at
00007  * http://www.mozilla.org/MPL/
00008  *
00009  * Software distributed under the License is distributed on an "AS IS" basis,
00010  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00011  * for the specific language governing rights and limitations under the
00012  * License.
00013  *
00014  * The Original Code is the Netscape security libraries.
00015  *
00016  * The Initial Developer of the Original Code is
00017  * Netscape Communications Corporation.
00018  * Portions created by the Initial Developer are Copyright (C) 1994-2000
00019  * the Initial Developer. All Rights Reserved.
00020  *
00021  * Contributor(s):
00022  *
00023  * Alternatively, the contents of this file may be used under the terms of
00024  * either the GNU General Public License Version 2 or later (the "GPL"), or
00025  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00026  * in which case the provisions of the GPL or the LGPL are applicable instead
00027  * of those above. If you wish to allow use of your version of this file only
00028  * under the terms of either the GPL or the LGPL, and not to allow others to
00029  * use your version of this file under the terms of the MPL, indicate your
00030  * decision by deleting the provisions above and replace them with the notice
00031  * and other provisions required by the GPL or the LGPL. If you do not delete
00032  * the provisions above, a recipient may use your version of this file under
00033  * the terms of any one of the MPL, the GPL or the LGPL.
00034  *
00035  * ***** END LICENSE BLOCK ***** */
00036 
00037 /*
00038  * Base64 decoding (ascii to binary).
00039  *
00040  * $Id: nssb64d.c,v 1.6 2004/04/25 15:03:17 gerv%gerv.net Exp $
00041  */
00042 
00043 #include "nssb64.h"
00044 #include "nspr.h"
00045 #include "secitem.h"
00046 #include "secerr.h"
00047 
00048 /*
00049  * XXX We want this basic support to go into NSPR (the PL part).
00050  * Until that can happen, the PL interface is going to be kept entirely
00051  * internal here -- all static functions and opaque data structures.
00052  * When someone can get it moved over into NSPR, that should be done:
00053  *    - giving everything names that are accepted by the NSPR module owners
00054  *     (though I tried to choose ones that would work without modification)
00055  *    - exporting the functions (remove static declarations and add
00056  *     PR_IMPLEMENT as necessary)
00057  *    - put prototypes into appropriate header file (probably replacing
00058  *     the entire current lib/libc/include/plbase64.h in NSPR)
00059  *     along with a typedef for the context structure (which should be
00060  *     kept opaque -- definition in the source file only, but typedef
00061  *     ala "typedef struct PLBase64FooStr PLBase64Foo;" in header file)
00062  *    - modify anything else as necessary to conform to NSPR required style
00063  *     (I looked but found no formatting guide to follow)
00064  *
00065  * You will want to move over everything from here down to the comment
00066  * which says "XXX End of base64 decoding code to be moved into NSPR",
00067  * into a new file in NSPR.
00068  */
00069 
00070 /*
00071  **************************************************************
00072  * XXX Beginning of base64 decoding code to be moved into NSPR.
00073  */
00074 
00075 /*
00076  * This typedef would belong in the NSPR header file (i.e. plbase64.h).
00077  */
00078 typedef struct PLBase64DecoderStr PLBase64Decoder;
00079 
00080 /*
00081  * The following implementation of base64 decoding was based on code
00082  * found in libmime (specifically, in mimeenc.c).  It has been adapted to
00083  * use PR types and naming as well as to provide other necessary semantics
00084  * (like buffer-in/buffer-out in addition to "streaming" without undue
00085  * performance hit of extra copying if you made the buffer versions
00086  * use the output_fn).  It also incorporates some aspects of the current
00087  * NSPR base64 decoding code.  As such, you may find similarities to
00088  * both of those implementations.  I tried to use names that reflected
00089  * the original code when possible.  For this reason you may find some
00090  * inconsistencies -- libmime used lots of "in" and "out" whereas the
00091  * NSPR version uses "src" and "dest"; sometimes I changed one to the other
00092  * and sometimes I left them when I thought the subroutines were at least
00093  * self-consistent.
00094  */
00095 
00096 PR_BEGIN_EXTERN_C
00097 
00098 /*
00099  * Opaque object used by the decoder to store state.
00100  */
00101 struct PLBase64DecoderStr {
00102     /* Current token (or portion, if token_size < 4) being decoded. */
00103     unsigned char token[4];
00104     int token_size;
00105 
00106     /*
00107      * Where to write the decoded data (used when streaming, not when
00108      * doing all in-memory (buffer) operations).
00109      *
00110      * Note that this definition is chosen to be compatible with PR_Write.
00111      */
00112     PRInt32 (*output_fn) (void *output_arg, const unsigned char *buf,
00113                        PRInt32 size);
00114     void *output_arg;
00115 
00116     /*
00117      * Where the decoded output goes -- either temporarily (in the streaming
00118      * case, staged here before it goes to the output function) or what will
00119      * be the entire buffered result for users of the buffer version.
00120      */
00121     unsigned char *output_buffer;
00122     PRUint32 output_buflen; /* the total length of allocated buffer */
00123     PRUint32 output_length; /* the length that is currently populated */
00124 };
00125 
00126 PR_END_EXTERN_C
00127 
00128 
00129 /*
00130  * Table to convert an ascii "code" to its corresponding binary value.
00131  * For ease of use, the binary values in the table are the actual values
00132  * PLUS ONE.  This is so that the special value of zero can denote an
00133  * invalid mapping; that was much easier than trying to fill in the other
00134  * values with some value other than zero, and to check for it.
00135  * Just remember to SUBTRACT ONE when using the value retrieved.
00136  */
00137 static unsigned char base64_codetovaluep1[256] = {
00138 /*   0: */      0,     0,     0,     0,     0,     0,     0,     0,
00139 /*   8: */      0,     0,     0,     0,     0,     0,     0,     0,
00140 /*  16: */      0,     0,     0,     0,     0,     0,     0,     0,
00141 /*  24: */      0,     0,     0,     0,     0,     0,     0,     0,
00142 /*  32: */      0,     0,     0,     0,     0,     0,     0,     0,
00143 /*  40: */      0,     0,     0,    63,     0,     0,     0,    64,
00144 /*  48: */     53,    54,    55,    56,    57,    58,    59,    60,
00145 /*  56: */     61,    62,     0,     0,     0,     0,     0,     0,
00146 /*  64: */      0,     1,     2,     3,     4,     5,     6,     7,
00147 /*  72: */      8,     9,    10,    11,    12,    13,    14,    15,
00148 /*  80: */     16,    17,    18,    19,    20,    21,    22,    23,
00149 /*  88: */     24,    25,    26,     0,     0,     0,     0,     0,
00150 /*  96: */      0,    27,    28,    29,    30,    31,    32,    33,
00151 /* 104: */     34,    35,    36,    37,    38,    39,    40,    41,
00152 /* 112: */     42,    43,    44,    45,    46,    47,    48,    49,
00153 /* 120: */     50,    51,    52,     0,     0,     0,     0,     0,
00154 /* 128: */      0,     0,     0,     0,     0,     0,     0,     0
00155 /* and rest are all zero as well */
00156 };
00157 
00158 #define B64_PAD      '='
00159 
00160 
00161 /*
00162  * Reads 4; writes 3 (known, or expected, to have no trailing padding).
00163  * Returns bytes written; -1 on error (unexpected character).
00164  */
00165 static int
00166 pl_base64_decode_4to3 (const unsigned char *in, unsigned char *out)
00167 {
00168     int j;
00169     PRUint32 num = 0;
00170     unsigned char bits;
00171 
00172     for (j = 0; j < 4; j++) {
00173        bits = base64_codetovaluep1[in[j]];
00174        if (bits == 0)
00175            return -1;
00176        num = (num << 6) | (bits - 1);
00177     }
00178 
00179     out[0] = (unsigned char) (num >> 16);
00180     out[1] = (unsigned char) ((num >> 8) & 0xFF);
00181     out[2] = (unsigned char) (num & 0xFF);
00182 
00183     return 3;
00184 }
00185 
00186 /*
00187  * Reads 3; writes 2 (caller already confirmed EOF or trailing padding).
00188  * Returns bytes written; -1 on error (unexpected character).
00189  */
00190 static int
00191 pl_base64_decode_3to2 (const unsigned char *in, unsigned char *out)
00192 {
00193     PRUint32 num = 0;
00194     unsigned char bits1, bits2, bits3;
00195 
00196     bits1 = base64_codetovaluep1[in[0]];
00197     bits2 = base64_codetovaluep1[in[1]];
00198     bits3 = base64_codetovaluep1[in[2]];
00199 
00200     if ((bits1 == 0) || (bits2 == 0) || (bits3 == 0))
00201        return -1;
00202 
00203     num = ((PRUint32)(bits1 - 1)) << 10;
00204     num |= ((PRUint32)(bits2 - 1)) << 4;
00205     num |= ((PRUint32)(bits3 - 1)) >> 2;
00206 
00207     out[0] = (unsigned char) (num >> 8);
00208     out[1] = (unsigned char) (num & 0xFF);
00209 
00210     return 2;
00211 }
00212 
00213 /*
00214  * Reads 2; writes 1 (caller already confirmed EOF or trailing padding).
00215  * Returns bytes written; -1 on error (unexpected character).
00216  */
00217 static int
00218 pl_base64_decode_2to1 (const unsigned char *in, unsigned char *out)
00219 {
00220     PRUint32 num = 0;
00221     unsigned char bits1, bits2;
00222 
00223     bits1 = base64_codetovaluep1[in[0]];
00224     bits2 = base64_codetovaluep1[in[1]];
00225 
00226     if ((bits1 == 0) || (bits2 == 0))
00227        return -1;
00228 
00229     num = ((PRUint32)(bits1 - 1)) << 2;
00230     num |= ((PRUint32)(bits2 - 1)) >> 4;
00231 
00232     out[0] = (unsigned char) num;
00233 
00234     return 1;
00235 }
00236 
00237 /*
00238  * Reads 4; writes 0-3.  Returns bytes written or -1 on error.
00239  * (Writes less than 3 only at (presumed) EOF.)
00240  */
00241 static int
00242 pl_base64_decode_token (const unsigned char *in, unsigned char *out)
00243 {
00244     if (in[3] != B64_PAD)
00245        return pl_base64_decode_4to3 (in, out);
00246 
00247     if (in[2] == B64_PAD)
00248        return pl_base64_decode_2to1 (in, out);
00249 
00250     return pl_base64_decode_3to2 (in, out);
00251 }
00252 
00253 static PRStatus
00254 pl_base64_decode_buffer (PLBase64Decoder *data, const unsigned char *in,
00255                       PRUint32 length)
00256 {
00257     unsigned char *out = data->output_buffer;
00258     unsigned char *token = data->token;
00259     int i, n = 0;
00260 
00261     i = data->token_size;
00262     data->token_size = 0;
00263 
00264     while (length > 0) {
00265        while (i < 4 && length > 0) {
00266            /*
00267             * XXX Note that the following simply ignores any unexpected
00268             * characters.  This is exactly what the original code in
00269             * libmime did, and I am leaving it.  We certainly want to skip
00270             * over whitespace (we must); this does much more than that.
00271             * I am not confident changing it, and I don't want to slow
00272             * the processing down doing more complicated checking, but
00273             * someone else might have different ideas in the future.
00274             */
00275            if (base64_codetovaluep1[*in] > 0 || *in == B64_PAD)
00276               token[i++] = *in;
00277            in++;
00278            length--;
00279        }
00280 
00281        if (i < 4) {
00282            /* Didn't get enough for a complete token. */
00283            data->token_size = i;
00284            break;
00285        }
00286        i = 0;
00287 
00288        PR_ASSERT((out - data->output_buffer + 3) <= data->output_buflen);
00289 
00290        /*
00291         * Assume we are not at the end; the following function only works
00292         * for an internal token (no trailing padding characters) but is
00293         * faster that way.  If it hits an invalid character (padding) it
00294         * will return an error; we break out of the loop and try again
00295         * calling the routine that will handle a final token.
00296         * Note that we intentionally do it this way rather than explicitly
00297         * add a check for padding here (because that would just slow down
00298         * the normal case) nor do we rely on checking whether we have more
00299         * input to process (because that would also slow it down but also
00300         * because we want to allow trailing garbage, especially white space
00301         * and cannot tell that without read-ahead, also a slow proposition).
00302         * Whew.  Understand?
00303         */
00304        n = pl_base64_decode_4to3 (token, out);
00305        if (n < 0)
00306            break;
00307 
00308        /* Advance "out" by the number of bytes just written to it. */
00309        out += n;
00310        n = 0;
00311     }
00312 
00313     /*
00314      * See big comment above, before call to pl_base64_decode_4to3.
00315      * Here we check if we error'd out of loop, and allow for the case
00316      * that we are processing the last interesting token.  If the routine
00317      * which should handle padding characters also fails, then we just
00318      * have bad input and give up.
00319      */
00320     if (n < 0) {
00321        n = pl_base64_decode_token (token, out);
00322        if (n < 0)
00323            return PR_FAILURE;
00324 
00325        out += n;
00326     }
00327 
00328     /*
00329      * As explained above, we can get here with more input remaining, but
00330      * it should be all characters we do not care about (i.e. would be
00331      * ignored when transferring from "in" to "token" in loop above,
00332      * except here we choose to ignore extraneous pad characters, too).
00333      * Swallow it, performing that check.  If we find more characters that
00334      * we would expect to decode, something is wrong.
00335      */
00336     while (length > 0) {
00337        if (base64_codetovaluep1[*in] > 0)
00338            return PR_FAILURE;
00339        in++;
00340        length--;
00341     }
00342 
00343     /* Record the length of decoded data we have left in output_buffer. */
00344     data->output_length = (PRUint32) (out - data->output_buffer);
00345     return PR_SUCCESS;
00346 }
00347 
00348 /*
00349  * Flush any remaining buffered characters.  Given well-formed input,
00350  * this will have nothing to do.  If the input was missing the padding
00351  * characters at the end, though, there could be 1-3 characters left
00352  * behind -- we will tolerate that by adding the padding for them.
00353  */
00354 static PRStatus
00355 pl_base64_decode_flush (PLBase64Decoder *data)
00356 {
00357     int count;
00358 
00359     /*
00360      * If no remaining characters, or all are padding (also not well-formed
00361      * input, but again, be tolerant), then nothing more to do.  (And, that
00362      * is considered successful.)
00363      */
00364     if (data->token_size == 0 || data->token[0] == B64_PAD)
00365        return PR_SUCCESS;
00366 
00367     /*
00368      * Assume we have all the interesting input except for some expected
00369      * padding characters.  Add them and decode the resulting token.
00370      */
00371     while (data->token_size < 4)
00372        data->token[data->token_size++] = B64_PAD;
00373 
00374     data->token_size = 0;   /* so a subsequent flush call is a no-op */
00375 
00376     count = pl_base64_decode_token (data->token,
00377                                 data->output_buffer + data->output_length);
00378     if (count < 0)
00379        return PR_FAILURE;
00380 
00381     /*
00382      * If there is an output function, call it with this last bit of data.
00383      * Otherwise we are doing all buffered output, and the decoded bytes
00384      * are now there, we just need to reflect that in the length.
00385      */
00386     if (data->output_fn != NULL) {
00387        PRInt32 output_result;
00388 
00389        PR_ASSERT(data->output_length == 0);
00390        output_result = data->output_fn (data->output_arg,
00391                                     data->output_buffer,
00392                                     (PRInt32) count);
00393        if (output_result < 0)
00394            return  PR_FAILURE;
00395     } else {
00396        data->output_length += count;
00397     }
00398 
00399     return PR_SUCCESS;
00400 }
00401 
00402 
00403 /*
00404  * The maximum space needed to hold the output of the decoder given
00405  * input data of length "size".
00406  */
00407 static PRUint32
00408 PL_Base64MaxDecodedLength (PRUint32 size)
00409 {
00410     return ((size * 3) / 4);
00411 }
00412 
00413 
00414 /*
00415  * A distinct internal creation function for the buffer version to use.
00416  * (It does not want to specify an output_fn, and we want the normal
00417  * Create function to require that.)  If more common initialization
00418  * of the decoding context needs to be done, it should be done *here*.
00419  */
00420 static PLBase64Decoder *
00421 pl_base64_create_decoder (void)
00422 {
00423     return PR_NEWZAP(PLBase64Decoder);
00424 }
00425 
00426 /*
00427  * Function to start a base64 decoding context.
00428  * An "output_fn" is required; the "output_arg" parameter to that is optional.
00429  */
00430 static PLBase64Decoder *
00431 PL_CreateBase64Decoder (PRInt32 (*output_fn) (void *, const unsigned char *,
00432                                          PRInt32),
00433                      void *output_arg)
00434 {
00435     PLBase64Decoder *data;
00436 
00437     if (output_fn == NULL) {
00438        PR_SetError (PR_INVALID_ARGUMENT_ERROR, 0);
00439        return NULL;
00440     }
00441 
00442     data = pl_base64_create_decoder ();
00443     if (data != NULL) {
00444        data->output_fn = output_fn;
00445        data->output_arg = output_arg;
00446     }
00447     return data;
00448 }
00449 
00450 
00451 /*
00452  * Push data through the decoder, causing the output_fn (provided to Create)
00453  * to be called with the decoded data.
00454  */
00455 static PRStatus
00456 PL_UpdateBase64Decoder (PLBase64Decoder *data, const char *buffer,
00457                      PRUint32 size)
00458 {
00459     PRUint32 need_length;
00460     PRStatus status;
00461 
00462     /* XXX Should we do argument checking only in debug build? */
00463     if (data == NULL || buffer == NULL || size == 0) {
00464        PR_SetError (PR_INVALID_ARGUMENT_ERROR, 0);
00465        return PR_FAILURE;
00466     }
00467 
00468     /*
00469      * How much space could this update need for decoding?
00470      */
00471     need_length = PL_Base64MaxDecodedLength (size + data->token_size);
00472 
00473     /*
00474      * Make sure we have at least that much.  If not, (re-)allocate.
00475      */
00476     if (need_length > data->output_buflen) {
00477        unsigned char *output_buffer = data->output_buffer;
00478 
00479        if (output_buffer != NULL)
00480            output_buffer = (unsigned char *) PR_Realloc(output_buffer,
00481                                                   need_length);
00482        else
00483            output_buffer = (unsigned char *) PR_Malloc(need_length);
00484 
00485        if (output_buffer == NULL)
00486            return PR_FAILURE;
00487 
00488        data->output_buffer = output_buffer;
00489        data->output_buflen = need_length;
00490     }
00491 
00492     /* There should not have been any leftover output data in the buffer. */
00493     PR_ASSERT(data->output_length == 0);
00494     data->output_length = 0;
00495 
00496     status = pl_base64_decode_buffer (data, (const unsigned char *) buffer,
00497                                   size);
00498 
00499     /* Now that we have some decoded data, write it. */
00500     if (status == PR_SUCCESS && data->output_length > 0) {
00501        PRInt32 output_result;
00502 
00503        PR_ASSERT(data->output_fn != NULL);
00504        output_result = data->output_fn (data->output_arg,
00505                                     data->output_buffer,
00506                                     (PRInt32) data->output_length);
00507        if (output_result < 0)
00508            status = PR_FAILURE;
00509     }
00510 
00511     data->output_length = 0;
00512     return status;
00513 }
00514 
00515 
00516 /*
00517  * When you're done decoding, call this to free the data.  If "abort_p"
00518  * is false, then calling this may cause the output_fn to be called
00519  * one last time (as the last buffered data is flushed out).
00520  */
00521 static PRStatus
00522 PL_DestroyBase64Decoder (PLBase64Decoder *data, PRBool abort_p)
00523 {
00524     PRStatus status = PR_SUCCESS;
00525 
00526     /* XXX Should we do argument checking only in debug build? */
00527     if (data == NULL) {
00528        PR_SetError (PR_INVALID_ARGUMENT_ERROR, 0);
00529        return PR_FAILURE;
00530     }
00531 
00532     /* Flush out the last few buffered characters. */
00533     if (!abort_p)
00534        status = pl_base64_decode_flush (data);
00535 
00536     if (data->output_buffer != NULL)
00537        PR_Free(data->output_buffer);
00538     PR_Free(data);
00539 
00540     return status;
00541 }
00542 
00543 
00544 /*
00545  * Perform base64 decoding from an input buffer to an output buffer.
00546  * The output buffer can be provided (as "dest"); you can also pass in
00547  * a NULL and this function will allocate a buffer large enough for you,
00548  * and return it.  If you do provide the output buffer, you must also
00549  * provide the maximum length of that buffer (as "maxdestlen").
00550  * The actual decoded length of output will be returned to you in
00551  * "output_destlen".
00552  *
00553  * Return value is NULL on error, the output buffer (allocated or provided)
00554  * otherwise.
00555  */
00556 static unsigned char *
00557 PL_Base64DecodeBuffer (const char *src, PRUint32 srclen, unsigned char *dest,
00558                      PRUint32 maxdestlen, PRUint32 *output_destlen)
00559 {
00560     PRUint32 need_length;
00561     unsigned char *output_buffer = NULL;
00562     PLBase64Decoder *data = NULL;
00563     PRStatus status;
00564 
00565     PR_ASSERT(srclen > 0);
00566     if (srclen == 0)
00567        return dest;
00568 
00569     /*
00570      * How much space could we possibly need for decoding this input?
00571      */
00572     need_length = PL_Base64MaxDecodedLength (srclen);
00573 
00574     /*
00575      * Make sure we have at least that much, if output buffer provided.
00576      * If no output buffer provided, then we allocate that much.
00577      */
00578     if (dest != NULL) {
00579        PR_ASSERT(maxdestlen >= need_length);
00580        if (maxdestlen < need_length) {
00581            PR_SetError(PR_BUFFER_OVERFLOW_ERROR, 0);
00582            goto loser;
00583        }
00584        output_buffer = dest;
00585     } else {
00586        output_buffer = (unsigned char *) PR_Malloc(need_length);
00587        if (output_buffer == NULL)
00588            goto loser;
00589        maxdestlen = need_length;
00590     }
00591 
00592     data = pl_base64_create_decoder();
00593     if (data == NULL)
00594        goto loser;
00595 
00596     data->output_buflen = maxdestlen;
00597     data->output_buffer = output_buffer;
00598 
00599     status = pl_base64_decode_buffer (data, (const unsigned char *) src,
00600                                   srclen);
00601 
00602     /*
00603      * We do not wait for Destroy to flush, because Destroy will also
00604      * get rid of our decoder context, which we need to look at first!
00605      */
00606     if (status == PR_SUCCESS)
00607        status = pl_base64_decode_flush (data);
00608 
00609     /* Must clear this or Destroy will free it. */
00610     data->output_buffer = NULL;
00611 
00612     if (status == PR_SUCCESS) {
00613        *output_destlen = data->output_length;
00614        status = PL_DestroyBase64Decoder (data, PR_FALSE);
00615        data = NULL;
00616        if (status == PR_FAILURE)
00617            goto loser;
00618        return output_buffer;
00619     }
00620 
00621 loser:
00622     if (dest == NULL && output_buffer != NULL)
00623        PR_Free(output_buffer);
00624     if (data != NULL)
00625        (void) PL_DestroyBase64Decoder (data, PR_TRUE);
00626     return NULL;
00627 }
00628 
00629 
00630 /*
00631  * XXX End of base64 decoding code to be moved into NSPR.
00632  ********************************************************
00633  */
00634 
00635 /*
00636  * This is the beginning of the NSS cover functions.  These will
00637  * provide the interface we want to expose as NSS-ish.  For example,
00638  * they will operate on our Items, do any special handling or checking
00639  * we want to do, etc.
00640  */
00641 
00642 
00643 PR_BEGIN_EXTERN_C
00644 
00645 /*
00646  * A boring cover structure for now.  Perhaps someday it will include
00647  * some more interesting fields.
00648  */
00649 struct NSSBase64DecoderStr {
00650     PLBase64Decoder *pl_data;
00651 };
00652 
00653 PR_END_EXTERN_C
00654 
00655 
00656 /*
00657  * Function to start a base64 decoding context.
00658  */
00659 NSSBase64Decoder *
00660 NSSBase64Decoder_Create (PRInt32 (*output_fn) (void *, const unsigned char *,
00661                                           PRInt32),
00662                       void *output_arg)
00663 {
00664     PLBase64Decoder *pl_data;
00665     NSSBase64Decoder *nss_data;
00666 
00667     nss_data = PORT_ZNew(NSSBase64Decoder);
00668     if (nss_data == NULL)
00669        return NULL;
00670 
00671     pl_data = PL_CreateBase64Decoder (output_fn, output_arg);
00672     if (pl_data == NULL) {
00673        PORT_Free(nss_data);
00674        return NULL;
00675     }
00676 
00677     nss_data->pl_data = pl_data;
00678     return nss_data;
00679 }
00680 
00681 
00682 /*
00683  * Push data through the decoder, causing the output_fn (provided to Create)
00684  * to be called with the decoded data.
00685  */
00686 SECStatus
00687 NSSBase64Decoder_Update (NSSBase64Decoder *data, const char *buffer,
00688                       PRUint32 size)
00689 {
00690     PRStatus pr_status;
00691 
00692     /* XXX Should we do argument checking only in debug build? */
00693     if (data == NULL) {
00694        PORT_SetError (SEC_ERROR_INVALID_ARGS);
00695        return SECFailure;
00696     }
00697 
00698     pr_status = PL_UpdateBase64Decoder (data->pl_data, buffer, size);
00699     if (pr_status == PR_FAILURE)
00700        return SECFailure;
00701 
00702     return SECSuccess;
00703 }
00704 
00705 
00706 /*
00707  * When you're done decoding, call this to free the data.  If "abort_p"
00708  * is false, then calling this may cause the output_fn to be called
00709  * one last time (as the last buffered data is flushed out).
00710  */
00711 SECStatus
00712 NSSBase64Decoder_Destroy (NSSBase64Decoder *data, PRBool abort_p)
00713 {
00714     PRStatus pr_status;
00715 
00716     /* XXX Should we do argument checking only in debug build? */
00717     if (data == NULL) {
00718        PORT_SetError (SEC_ERROR_INVALID_ARGS);
00719        return SECFailure;
00720     }
00721 
00722     pr_status = PL_DestroyBase64Decoder (data->pl_data, abort_p);
00723 
00724     PORT_Free(data);
00725 
00726     if (pr_status == PR_FAILURE)
00727        return SECFailure;
00728 
00729     return SECSuccess;
00730 }
00731 
00732 
00733 /*
00734  * Perform base64 decoding from an ascii string "inStr" to an Item.
00735  * The length of the input must be provided as "inLen".  The Item
00736  * may be provided (as "outItemOpt"); you can also pass in a NULL
00737  * and the Item will be allocated for you.
00738  *
00739  * In any case, the data within the Item will be allocated for you.
00740  * All allocation will happen out of the passed-in "arenaOpt", if non-NULL.
00741  * If "arenaOpt" is NULL, standard allocation (heap) will be used and
00742  * you will want to free the result via SECITEM_FreeItem.
00743  *
00744  * Return value is NULL on error, the Item (allocated or provided) otherwise.
00745  */
00746 SECItem *
00747 NSSBase64_DecodeBuffer (PRArenaPool *arenaOpt, SECItem *outItemOpt,
00748                      const char *inStr, unsigned int inLen)
00749 {
00750     SECItem *out_item = outItemOpt;
00751     PRUint32 max_out_len = PL_Base64MaxDecodedLength (inLen);
00752     PRUint32 out_len;
00753     void *mark = NULL;
00754     unsigned char *dummy;
00755 
00756     PORT_Assert(outItemOpt == NULL || outItemOpt->data == NULL);
00757 
00758     if (arenaOpt != NULL)
00759        mark = PORT_ArenaMark (arenaOpt);
00760 
00761     out_item = SECITEM_AllocItem (arenaOpt, outItemOpt, max_out_len);
00762     if (out_item == NULL) {
00763        if (arenaOpt != NULL)
00764            PORT_ArenaRelease (arenaOpt, mark);
00765        return NULL;
00766     }
00767 
00768     dummy = PL_Base64DecodeBuffer (inStr, inLen, out_item->data,
00769                                max_out_len, &out_len);
00770     if (dummy == NULL) {
00771        if (arenaOpt != NULL) {
00772            PORT_ArenaRelease (arenaOpt, mark);
00773            if (outItemOpt != NULL) {
00774               outItemOpt->data = NULL;
00775               outItemOpt->len = 0;
00776            }
00777        } else {
00778            SECITEM_FreeItem (out_item,
00779                            (outItemOpt == NULL) ? PR_TRUE : PR_FALSE);
00780        }
00781        return NULL;
00782     }
00783 
00784     if (arenaOpt != NULL)
00785        PORT_ArenaUnmark (arenaOpt, mark);
00786     out_item->len = out_len;
00787     return out_item;
00788 }
00789 
00790 
00791 /*
00792  * XXX Everything below is deprecated.  If you add new stuff, put it
00793  * *above*, not below.
00794  */
00795 
00796 /*
00797  * XXX The following "ATOB" functions are provided for backward compatibility
00798  * with current code.  They should be considered strongly deprecated.
00799  * When we can convert all our code over to using the new NSSBase64Decoder_
00800  * functions defined above, we should get rid of these altogether.  (Remove
00801  * protoypes from base64.h as well -- actually, remove that file completely).
00802  * If someone thinks either of these functions provides such a very useful
00803  * interface (though, as shown, the same functionality can already be
00804  * obtained by calling NSSBase64_DecodeBuffer directly), fine -- but then
00805  * that API should be provided with a nice new NSSFoo name and using
00806  * appropriate types, etc.
00807  */
00808 
00809 #include "base64.h"
00810 
00811 /*
00812 ** Return an PORT_Alloc'd string which is the base64 decoded version
00813 ** of the input string; set *lenp to the length of the returned data.
00814 */
00815 unsigned char *
00816 ATOB_AsciiToData(const char *string, unsigned int *lenp)
00817 {
00818     SECItem binary_item, *dummy;
00819 
00820     binary_item.data = NULL;
00821     binary_item.len = 0;
00822 
00823     dummy = NSSBase64_DecodeBuffer (NULL, &binary_item, string,
00824                                 (PRUint32) PORT_Strlen(string));
00825     if (dummy == NULL)
00826        return NULL;
00827 
00828     PORT_Assert(dummy == &binary_item);
00829 
00830     *lenp = dummy->len;
00831     return dummy->data;
00832 }
00833  
00834 /*
00835 ** Convert from ascii to binary encoding of an item.
00836 */
00837 SECStatus
00838 ATOB_ConvertAsciiToItem(SECItem *binary_item, char *ascii)
00839 {
00840     SECItem *dummy;
00841 
00842     if (binary_item == NULL) {
00843        PORT_SetError (SEC_ERROR_INVALID_ARGS);
00844        return SECFailure;
00845     }
00846 
00847     /*
00848      * XXX Would prefer to assert here if data is non-null (actually,
00849      * don't need to, just let NSSBase64_DecodeBuffer do it), so as to
00850      * to catch unintended memory leaks, but callers are not clean in
00851      * this respect so we need to explicitly clear here to avoid the
00852      * assert in NSSBase64_DecodeBuffer.
00853      */
00854     binary_item->data = NULL;
00855     binary_item->len = 0;
00856 
00857     dummy = NSSBase64_DecodeBuffer (NULL, binary_item, ascii,
00858                                 (PRUint32) PORT_Strlen(ascii));
00859 
00860     if (dummy == NULL)
00861        return SECFailure;
00862 
00863     return SECSuccess;
00864 }