summaryrefslogtreecommitdiffstats
path: root/libkmime/kmime_codec_base64.cpp
blob: e1c4d499ad7db36b2dfdc43f0d4851b4279c189f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*  -*- c++ -*-
    kmime_codec_base64.cpp

    This file is part of KMime, the KDE internet mail/usenet news message library.
    Copyright (c) 2001 Marc Mutz <mutz@kde.org>

    KMime is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMime is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this library with any edition of
    the TQt library by Trolltech AS, Norway (or with modified versions
    of TQt that use the same license as TQt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    TQt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "kmime_codec_base64.h"

#include <kdebug.h>

#include <cassert>

using namespace KMime;

namespace KMime {

// codec for base64 as specified in RFC 2045
  //class Base64Codec;
  //class Base64Decoder;
  //class Base64Encoder;

// codec for the B encoding as specified in RFC 2047
  //class Rfc2047BEncodingCodec;
  //class Rfc2047BEncodingEncoder;
  //class Rfc2047BEncodingDecoder;


static const uchar base64DecodeMap[128] = {
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
  
  64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 62, 64, 64, 64, 63,
  52, 53, 54, 55, 56, 57, 58, 59,  60, 61, 64, 64, 64, 64, 64, 64,
  
  64,  0,  1,  2,  3,  4,  5,  6,   7,  8,  9, 10, 11, 12, 13, 14,
  15, 16, 17, 18, 19, 20, 21, 22,  23, 24, 25, 64, 64, 64, 64, 64,
  
  64, 26, 27, 28, 29, 30, 31, 32,  33, 34, 35, 36, 37, 38, 39, 40,
  41, 42, 43, 44, 45, 46, 47, 48,  49, 50, 51, 64, 64, 64, 64, 64
};

static const char base64EncodeMap[64] = {
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  'w', 'x', 'y', 'z', '0', '1', '2', '3',
  '4', '5', '6', '7', '8', '9', '+', '/'
};


class Base64Decoder : public Decoder {
  uint mStepNo;
  uchar mOutbits;
  bool mSawPadding : 1;

protected:
  friend class Base64Codec;
  Base64Decoder( bool withCRLF=false )
    : Decoder( withCRLF ), mStepNo(0), mOutbits(0),
      mSawPadding(false) {}

public:
  virtual ~Base64Decoder() {}

  bool decode( const char* & scursor, const char * const send,
	       char* & dcursor, const char * const dend );
  // ### really needs no finishing???
  bool finish( char* & /*dcursor*/, const char * const /*dend*/ ) { return true; }
};



class Base64Encoder : public Encoder {
  uint mStepNo;
  /** number of already written base64-quartets on current line */
  uint mWrittenPacketsOnThisLine;
  uchar mNextbits;
  bool mInsideFinishing : 1;

protected:
  friend class Rfc2047BEncodingCodec;
  friend class Rfc2047BEncodingEncoder;
  friend class Base64Codec;
  Base64Encoder( bool withCRLF=false )
    : Encoder( withCRLF ), mStepNo(0), mWrittenPacketsOnThisLine(0),
      mNextbits(0), mInsideFinishing(false) {}

  bool generic_finish( char* & dcursor, const char * const dend,
		       bool withLFatEnd );

public:
  virtual ~Base64Encoder() {}

  bool encode( const char* & scursor, const char * const send,
	       char* & dcursor, const char * const dend );

  bool finish( char* & dcursor, const char * const dend );

protected:
  bool writeBase64( uchar ch, char* & dcursor, const char * const dend ) {
    return write( base64EncodeMap[ ch ], dcursor, dend );
  }
};



class Rfc2047BEncodingEncoder : public Base64Encoder {
protected:
  friend class Rfc2047BEncodingCodec;
  Rfc2047BEncodingEncoder( bool withCRLF=false )
    : Base64Encoder( withCRLF ) {};
public:
  bool encode( const char* & scursor, const char * const send,
	       char* & dcursor, const char * const dend );
  bool finish( char* & dcursor, const char * const dend );
};


Encoder * Base64Codec::makeEncoder( bool withCRLF ) const {
  return new Base64Encoder( withCRLF );
}

Decoder * Base64Codec::makeDecoder( bool withCRLF ) const {
  return new Base64Decoder( withCRLF );
}

Encoder * Rfc2047BEncodingCodec::makeEncoder( bool withCRLF ) const {
  return new Rfc2047BEncodingEncoder( withCRLF );
}

  /********************************************************/
  /********************************************************/
  /********************************************************/


bool Base64Decoder::decode( const char* & scursor, const char * const send,
			    char* & dcursor, const char * const dend )
{
  while ( dcursor != dend && scursor != send ) {
    uchar ch = *scursor++;
    uchar value;

    // try converting ch to a 6-bit value:
    if ( ch < 128 )
      value = base64DecodeMap[ ch ];
    else
      value = 64;

    // ch isn't of the base64 alphabet, check for other significant chars:
    if ( value >= 64 ) {
      if ( ch == '=' ) {
	// padding:
	if ( mStepNo == 0 || mStepNo == 1) {
	  if (!mSawPadding) {
	    // malformed
	    kdWarning() << "Base64Decoder: unexpected padding "
	      "character in input stream" << endl;
	  }
	  mSawPadding = true;
	  break;
	} else if ( mStepNo == 2 ) {
	  // ok, there should be another one
	} else if ( mStepNo == 3 ) {
	  // ok, end of encoded stream
	  mSawPadding = true;
	  break;
	}
	mSawPadding = true;
	mStepNo = (mStepNo + 1) % 4;
	continue;
      } else {
	// non-base64 alphabet
	continue;
      }
    }

    if ( mSawPadding ) {
      kdWarning() << "Base64Decoder: Embedded padding character "
	"encountered!" << endl;
      return true;
    }

    // add the new bits to the output stream and flush full octets:    
    switch ( mStepNo ) {
    case 0:
      mOutbits = value << 2;
      break;
    case 1:
      *dcursor++ = (char)(mOutbits | value >> 4);
      mOutbits = value << 4;
      break;
    case 2:
      *dcursor++ = (char)(mOutbits | value >> 2);
      mOutbits = value << 6;
      break;
    case 3:
      *dcursor++ = (char)(mOutbits | value);
      mOutbits = 0;
      break;
    default:
      assert( 0 );
    }
    mStepNo = (mStepNo + 1) % 4;
  }

  // return false when caller should call us again:
  return (scursor == send);
} // Base64Decoder::decode()



bool Base64Encoder::encode( const char* & scursor, const char * const send,
			    char* & dcursor, const char * const dend ) {
  const uint maxPacketsPerLine = 76 / 4;

  // detect when the caller doesn't adhere to our rules:
  if ( mInsideFinishing ) return true;

  while ( scursor != send && dcursor != dend ) {
    // properly empty the output buffer before starting something new:
    // ### fixme: we can optimize this away, since the buffer isn't
    // written to anyway (most of the time)
    if ( mOutputBufferCursor && !flushOutputBuffer( dcursor, dend ) )
      return (scursor == send);

    uchar ch = *scursor++;
    // mNextbits   // (part of) value of next sextet

    // check for line length;
    if ( mStepNo == 0 && mWrittenPacketsOnThisLine >= maxPacketsPerLine ) {
      writeCRLF( dcursor, dend );
      mWrittenPacketsOnThisLine = 0;
    }

    // depending on mStepNo, extract value and mNextbits from the
    // octet stream:
    switch ( mStepNo ) {
    case 0:
      assert( mNextbits == 0 );
      writeBase64( ch >> 2, dcursor, dend ); // top-most 6 bits -> output
      mNextbits = (ch & 0x3) << 4; // 0..1 bits -> 4..5 in mNextbits
      break;
    case 1:
      assert( (mNextbits & ~0x30) == 0 );
      writeBase64( mNextbits | ch >> 4, dcursor, dend ); // 4..7 bits -> 0..3 in value
      mNextbits = (ch & 0xf) << 2; // 0..3 bits -> 2..5 in mNextbits
      break;
    case 2:
      assert( (mNextbits & ~0x3C) == 0 );
      writeBase64( mNextbits | ch >> 6, dcursor, dend ); // 6..7 bits -> 0..1 in value
      writeBase64( ch & 0x3F, dcursor, dend ); // 0..5 bits -> output
      mNextbits = 0;
      mWrittenPacketsOnThisLine++;
      break;
    default:
      assert( 0 );
    }
    mStepNo = ( mStepNo + 1 ) % 3;
  }

  if ( mOutputBufferCursor ) flushOutputBuffer( dcursor, dend );

  return (scursor == send);
}


bool Rfc2047BEncodingEncoder::encode( const char* & scursor,
				      const char * const send,
				      char* & dcursor,
				      const char * const dend )
{
  // detect when the caller doesn't adhere to our rules:
  if ( mInsideFinishing ) return true;

  while ( scursor != send && dcursor != dend ) {
    // properly empty the output buffer before starting something new:
    // ### fixme: we can optimize this away, since the buffer isn't
    // written to anyway (most of the time)
    if ( mOutputBufferCursor && !flushOutputBuffer( dcursor, dend ) )
      return (scursor == send);

    uchar ch = *scursor++;
    // mNextbits   // (part of) value of next sextet

    // depending on mStepNo, extract value and mNextbits from the
    // octet stream:
    switch ( mStepNo ) {
    case 0:
      assert( mNextbits == 0 );
      writeBase64( ch >> 2, dcursor, dend ); // top-most 6 bits -> output
      mNextbits = (ch & 0x3) << 4; // 0..1 bits -> 4..5 in mNextbits
      break;
    case 1:
      assert( (mNextbits & ~0x30) == 0 );
      writeBase64( mNextbits | ch >> 4, dcursor, dend ); // 4..7 bits -> 0..3 in value
      mNextbits = (ch & 0xf) << 2; // 0..3 bits -> 2..5 in mNextbits
      break;
    case 2:
      assert( (mNextbits & ~0x3C) == 0 );
      writeBase64( mNextbits | ch >> 6, dcursor, dend ); // 6..7 bits -> 0..1 in value
      writeBase64( ch & 0x3F, dcursor, dend ); // 0..5 bits -> output
      mNextbits = 0;
      break;
    default:
      assert( 0 );
    }
    mStepNo = ( mStepNo + 1 ) % 3;
  }

  if ( mOutputBufferCursor ) flushOutputBuffer( dcursor, dend );

  return (scursor == send);
}


bool Base64Encoder::finish( char* & dcursor, const char * const dend ) {
  return generic_finish( dcursor, dend, true );
}

bool Rfc2047BEncodingEncoder::finish( char* & dcursor,
				      const char * const dend ) {
  return generic_finish( dcursor, dend, false );
}

bool Base64Encoder::generic_finish( char* & dcursor, const char * const dend,
				    bool withLFatEnd )
{
  if ( mInsideFinishing )
    return flushOutputBuffer( dcursor, dend );

  if ( mOutputBufferCursor && !flushOutputBuffer( dcursor, dend ) )
    return false;

  mInsideFinishing = true;

  //
  // writing out the last mNextbits...
  //
  switch ( mStepNo ) {
  case 1: // 2 mNextbits waiting to be written. Needs two padding chars:
  case 2: // 4 or 6 mNextbits waiting to be written. Completes a block
    writeBase64( mNextbits, dcursor, dend );
    mNextbits = 0;
    break;
  case 0: // no padding, nothing to be written, except possibly the CRLF
    assert( mNextbits == 0 );
    break;
  default:
    assert( 0 );
  }

  //
  // adding padding...
  //
  switch( mStepNo ) {
  case 1:
    write( '=', dcursor, dend );
    // fall through:
  case 2:
    write( '=', dcursor, dend );
    // fall through:
  case 0: // completed an quartet - add CRLF
    if ( withLFatEnd )
      writeCRLF( dcursor, dend );
    return flushOutputBuffer( dcursor, dend );
  default:
    assert( 0 );
  }
return true; // asserts get compiled out
}






} // namespace KMime