]> git.sur5r.net Git - bacula/bacula/blobdiff - bacula/src/lib/base64.c
19July06
[bacula/bacula] / bacula / src / lib / base64.c
index dbfcbd60bf46ed99e0ce3e669881a0b89dd809ae..4b1a505a83f3a23d6dde150709aa86bf83960be1 100644 (file)
@@ -6,7 +6,7 @@
  *   Version $Id$
  */
 /*
-   Copyright (C) 2000-2005 Kern Sibbald
+   Copyright (C) 2000-2006 Kern Sibbald
 
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
@@ -23,6 +23,7 @@
 
 #include "bacula.h"
 
+
 #ifdef TEST_MODE
 #include <glob.h>
 #endif
@@ -126,11 +127,14 @@ from_base64(intmax_t *value, char *where)
  * Encode binary data in bin of len bytes into
  * buf as base64 characters.
  *
+ * If compatible is true, the bin_to_base64 routine will be compatible
+ * with what the rest of the world uses.
+ *
  *  Returns: the number of characters stored not
  *           including the EOS
  */
 int
-bin_to_base64(char *buf, char *bin, int len)
+bin_to_base64(char *buf, int buflen, char *bin, int binlen, int compatible)
 {
    uint32_t reg, save, mask;
    int rem, i;
@@ -138,24 +142,32 @@ bin_to_base64(char *buf, char *bin, int len)
 
    reg = 0;
    rem = 0;
-   for (i=0; i<len; ) {
+   buflen--;                       /* allow for storing EOS */
+   for (i=0; i < binlen; ) {
       if (rem < 6) {
          reg <<= 8;
-         reg |= (int8_t)bin[i++];
+         if (compatible) {
+            reg |= (uint8_t)bin[i++];
+         } else {
+            reg |= (int8_t)bin[i++];
+         }
          rem += 8;
       }
       save = reg;
       reg >>= (rem - 6);
-      buf[j++] = base64_digits[reg & (uint32_t)0x3F];
+      if (j < buflen) {
+         buf[j++] = base64_digits[reg & 0x3F];
+      }
       reg = save;
       rem -= 6;
    }
-   if (rem) {
-      mask = 1;
-      for (i=1; i<rem; i++) {
-         mask = (mask << 1) | 1;
+   if (rem && j < buflen) {
+      mask = (1 << rem) - 1;
+      if (compatible) {
+         buf[j++] = base64_digits[(reg & mask) << 6 - rem];
+      } else {
+         buf[j++] = base64_digits[reg & mask];
       }
-      buf[j++] = base64_digits[reg & mask];
    }
    buf[j] = 0;
    return j;
@@ -172,7 +184,7 @@ int main(int argc, char *argv[])
 
 #ifdef xxxx
    for (i=0; i < 1000; i++) {
-      bin_to_base64(buf, (char *)&xx, 4);
+      bin_to_base64(buf, sizeof(buf), (char *)&xx, 4, true);
       printf("xx=%s\n", buf);
       xx++;
    }
@@ -181,7 +193,7 @@ int main(int argc, char *argv[])
    for (i=1; i<100; i++) {
       junk[i] = junk[i-1]-1;
    }
-   len = bin_to_base64(buf, junk, 16);
+   len = bin_to_base64(buf, sizeof(buf) junk, 16, true);
    printf("len=%d junk=%s\n", len, buf);
    return 0;
 }