-
Notifications
You must be signed in to change notification settings - Fork 286
/
smtp.c
3533 lines (3153 loc) · 94.1 KB
/
smtp.c
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file
* @brief SMTP client library.
* @author James Humphrey ([email protected])
* @version 1.00
*
* This SMTP client library allows the user to send emails to an SMTP server.
* The user can include custom headers and MIME attachments.
*
* This software has been placed into the public domain using CC0.
*/
/**
* @mainpage smtp-client
*
* This section contains documentation generated directly from the source
* code.
*
* To view the repository details, visit the main smtp-client page at
* <a href='https://www.somnisoft.com/smtp-client'>
* www.somnisoft.com/smtp-client
* </a>.
*/
#if defined(ARDUINO)
#else
#if defined(_WIN32) || defined(WIN32)
# define SMTP_IS_WINDOWS
#endif /* SMTP_IS_WINDOWS */
#ifdef SMTP_IS_WINDOWS
# include <winsock2.h>
# include <ws2tcpip.h>
#else /* POSIX */
# include <netinet/in.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <netdb.h>
# include <unistd.h>
#endif /* SMTP_IS_WINDOWS */
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifdef SMTP_OPENSSL
# include <openssl/bio.h>
# include <openssl/err.h>
# include <openssl/ssl.h>
# include <openssl/x509.h>
# include <openssl/x509v3.h>
#endif /* SMTP_OPENSSL */
/**
* Get access to the @ref smtp_result_code and @ref smtp_command definitions.
*/
#define SMTP_INTERNAL_DEFINE
#include "smtp.h"
/*
* The SMTP_TEST converts some library routines into special test seams which
* allows the test program to control whether they fail. For example, we can
* control when malloc() fails under certain conditions with an out of
* memory condition.
*/
#ifdef SMTP_TEST
/**
* Declare extern linkage on some functions so we can redefine their behavior
* in the external test suite.
*/
# define SMTP_LINKAGE extern
# include "../test/seams.h"
#else /* !(SMTP_TEST) */
/**
* When not testing, all functions should have static linkage except for those
* in the header.
*/
# define SMTP_LINKAGE static
#endif /* SMTP_TEST */
/**
* Increment the read buffer size by this amount if the delimiter
* has not been found.
*/
#define SMTP_GETDELIM_READ_SZ 1000
/**
* Stores source and destination email addresses.
*/
struct smtp_address{
/**
* Email address without any special formatting.
*
* For example: [email protected]
*/
char *email;
/**
* Description of the email address.
*/
char *name;
/**
* Specify from, to, cc, bcc.
*/
enum smtp_address_type type;
/**
* Padding structure to align.
*/
char pad[4];
};
/**
* Attachment data which gets placed in the MIME email section.
*/
struct smtp_attachment{
/**
* File name of the attachment.
*/
char *name;
/**
* Base64-encoded file data.
*/
char *b64_data;
};
/**
* List of email headers to send before the mail body.
*/
struct smtp_header{
/**
* Header name which will get sorted alphabetically in the header list.
*/
char *key;
/**
* Content of the corresponding header key.
*/
char *value;
};
/**
* Main data structure that holds the SMTP client context.
*/
struct smtp{
/**
* Bitwise list of flags controlling the behavior of this SMTP client.
*/
enum smtp_flag flags;
/**
* Standard network socket connection.
*/
int sock;
/**
* Read buffer and line parsing structure.
*/
struct str_getdelimfd gdfd;
/**
* List of headers to print before the mail body.
*/
struct smtp_header *header_list;
/**
* Number of headers in header_list.
*/
size_t num_headers;
/**
* List of from, to, cc, and bcc email addresses.
*/
struct smtp_address *address_list;
/**
* Number of addresses in address_list.
*/
size_t num_address;
/**
* List of attachments to send.
*/
struct smtp_attachment *attachment_list;
/**
* Number of attachments in attachment_list.
*/
size_t num_attachment;
/**
* Timeout in seconds to wait before returning with an error.
*
* This applies to both writing to and reading from a network socket.
*/
long timeout_sec;
/**
* Status code indicating success/failure.
*
* This code gets returned by most of the header functions.
*/
enum smtp_status_code status_code;
/**
* Indicates if this context has an active TLS connection.
* - Set to 0 if TLS connection inactive.
* - Set to 1 if TLS connection currently active.
*/
int tls_on;
/**
* Path to certificate file if using self-signed or untrusted certificate
* not in the default key store.
*/
const char *cafile;
#ifdef SMTP_OPENSSL
/**
* OpenSSL TLS object.
*/
SSL *tls;
/**
* OpenSSL TLS context.
*/
SSL_CTX *tls_ctx;
/**
* OpenSSL TLS I/O abstraction.
*/
BIO *tls_bio;
#endif /* SMTP_OPENSSL */
};
/**
* Check if adding a size_t value will cause a wrap.
*
* @param[in] a Add this value with @p b.
* @param[in] b Add this value with @p a.
* @param[out] result Save the addition to this buffer. Does not
* perform the addition if set to NULL.
* @retval 1 Value wrapped.
* @retval 0 Value did not wrap.
*/
SMTP_LINKAGE int
smtp_si_add_size_t(const size_t a,
const size_t b,
size_t *const result){
int wraps;
#ifdef SMTP_TEST
if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_add_size_t_ctr)){
return 1;
}
#endif /* SMTP_TEST */
if(SIZE_MAX - a < b){
wraps = 1;
}
else{
wraps = 0;
}
if(result){
*result = a + b;
}
return wraps;
}
/**
* Check if subtracting a size_t value will cause wrap.
*
* @param[in] a Subtract this value by @p b.
* @param[in] b Subtract this value from @p a.
* @param[out] result Save the subtraction to this buffer. Does not
* perform the subtraction if set to NULL.
* @retval 1 Value wrapped.
* @retval 0 Value did not wrap.
*/
SMTP_LINKAGE int
smtp_si_sub_size_t(const size_t a,
const size_t b,
size_t *const result){
int wraps;
#ifdef SMTP_TEST
if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_sub_size_t_ctr)){
return 1;
}
#endif /* SMTP_TEST */
if(a < b){
wraps = 1;
}
else{
wraps = 0;
}
if(result){
*result = a - b;
}
return wraps;
}
/**
* Check if multiplying a size_t value will cause a wrap.
*
* @param[in] a Multiply this value with @p b.
* @param[in] b Multiply this value with @p a.
* @param[out] result Save the multiplication to this buffer. Does not
* perform the multiplication if set to NULL.
* @retval 1 Value wrapped.
* @retval 0 Value did not wrap.
*/
SMTP_LINKAGE int
smtp_si_mul_size_t(const size_t a,
const size_t b,
size_t *const result){
int wraps;
#ifdef SMTP_TEST
if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_mul_size_t_ctr)){
return 1;
}
#endif /* SMTP_TEST */
if(b != 0 && a > SIZE_MAX / b){
wraps = 1;
}
else{
wraps = 0;
}
if(result){
*result = a * b;
}
return wraps;
}
/**
* Wait until more data has been made available on the socket read end.
*
* @param[in] smtp SMTP client context.
* @retval SMTP_STATUS_OK If data available to read on the socket.
* @retval SMTP_STATUS_RECV If the connection times out before any data
* appears on the socket.
*/
static enum smtp_status_code
smtp_str_getdelimfd_read_timeout(struct smtp *const smtp){
fd_set readfds;
struct timeval timeout;
int sel_rc;
FD_ZERO(&readfds);
FD_SET(smtp->sock, &readfds);
timeout.tv_sec = smtp->timeout_sec;
timeout.tv_usec = 0;
sel_rc = select(smtp->sock + 1, &readfds, NULL, NULL, &timeout);
if(sel_rc < 1){
return smtp_status_code_set(smtp, SMTP_STATUS_RECV);
}
return SMTP_STATUS_OK;
}
/**
* This function gets called by the @ref smtp_str_getdelimfd interface when it
* needs to read in more data.
*
* It reads using either the plain socket connection if encryption not
* enabled, or it reads using OpenSSL if it has an active TLS connection.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @param[out] buf Pointer to buffer for storing bytes read.
* @param[in] count Maximum number of bytes to try reading.
* @retval >=0 Number of bytes read.
* @retval -1 Failed to read from the socket.
*/
static long
smtp_str_getdelimfd_read(struct str_getdelimfd *const gdfd,
void *buf,
size_t count){
struct smtp *smtp;
long bytes_read;
smtp = (struct smtp*)(gdfd->user_data);
if(smtp_str_getdelimfd_read_timeout(smtp) != SMTP_STATUS_OK){
return -1;
}
bytes_read = 0;
if(smtp->tls_on){
#ifdef SMTP_OPENSSL
do{
/*
* Count will never have a value greater than SMTP_GETDELIM_READ_SZ,
* so we can safely convert this to an int.
*/
bytes_read = SSL_read(smtp->tls, buf, (int)count);
} while(bytes_read <= 0 && BIO_should_retry(smtp->tls_bio));
#endif /* SMTP_OPENSSL */
}
else{
bytes_read = recv(smtp->sock, buf, count, 0);
}
return bytes_read;
}
/**
* Find and return the location of the delimiter character in the
* search buffer.
*
* This function gets used by the main socket parsing function which
* continually reads from the socket and expands the buffer until it
* encounters the expected delimiter. This function provides the logic
* to check for the delimiter character in order to simplify the code
* in the main parse function.
*
* @param[in] buf Search buffer used to find the delimiter.
* @param[in] buf_len Number of bytes to search for in buf.
* @param[in] delim The delimiter to search for in buf.
* @param[out] delim_pos If delimiter found in buf, return the delimiter
* position in this parameter.
* @retval 1 If the delimiter character found.
* @retval 0 If the delimiter character not found.
*/
static int
smtp_str_getdelimfd_search_delim(const char *const buf,
size_t buf_len,
int delim,
size_t *const delim_pos){
size_t i;
*delim_pos = 0;
for(i = 0; i < buf_len; i++){
if(buf[i] == delim){
*delim_pos = i;
return 1;
}
}
return 0;
}
/**
* Set the internal line buffer to the number of bytes specified.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @param[in] copy_len Number of bytes to copy to the internal line buffer.
* @retval 0 Successfully allocated and copied data over to the new
* line buffer.
* @retval -1 Failed to allocate memory for the new line buffer.
*/
SMTP_LINKAGE int
smtp_str_getdelimfd_set_line_and_buf(struct str_getdelimfd *const gdfd,
size_t copy_len){
size_t copy_len_inc;
size_t nbytes_to_shift;
size_t new_buf_len;
if(gdfd->line){
free(gdfd->line);
gdfd->line = NULL;
}
if(smtp_si_add_size_t(copy_len, 1, ©_len_inc) ||
smtp_si_add_size_t((size_t)gdfd->_buf, copy_len_inc, NULL) ||
smtp_si_sub_size_t(gdfd->_buf_len, copy_len, &nbytes_to_shift) ||
(gdfd->line = (char*)(calloc(1, copy_len_inc))) == NULL){
return -1;
}
memcpy(gdfd->line, gdfd->_buf, copy_len);
gdfd->line_len = copy_len;
memmove(gdfd->_buf, gdfd->_buf + copy_len_inc, nbytes_to_shift);
if(smtp_si_sub_size_t(nbytes_to_shift, 1, &new_buf_len) == 0){
gdfd->_buf_len = new_buf_len;
}
return 0;
}
/**
* Free memory in the @ref str_getdelimfd data structure.
*
* @param[in] gdfd Frees memory stored in this socket parsing structure.
*/
SMTP_LINKAGE void
smtp_str_getdelimfd_free(struct str_getdelimfd *const gdfd){
free(gdfd->_buf);
free(gdfd->line);
gdfd->_buf = NULL;
gdfd->_bufsz = 0;
gdfd->_buf_len = 0;
gdfd->line = NULL;
gdfd->line_len = 0;
}
/**
* Free the @ref str_getdelimfd and return the @ref STRING_GETDELIMFD_ERROR
* error code.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @return See @ref str_getdelim_retcode.
*/
static enum str_getdelim_retcode
smtp_str_getdelimfd_throw_error(struct str_getdelimfd *const gdfd){
smtp_str_getdelimfd_free(gdfd);
return STRING_GETDELIMFD_ERROR;
}
/**
* Read and parse a delimited string using a custom socket read function.
*
* This interface handles all of the logic for expanding the buffer,
* parsing the delimiter in the buffer, and returning each "line"
* to the caller for handling.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @return See @ref str_getdelim_retcode.
*/
SMTP_LINKAGE enum str_getdelim_retcode
smtp_str_getdelimfd(struct str_getdelimfd *const gdfd){
size_t delim_pos;
long bytes_read;
void *read_buf_ptr;
char *buf_new;
size_t buf_sz_remaining;
size_t buf_sz_new;
if(gdfd->getdelimfd_read == NULL){
return STRING_GETDELIMFD_ERROR;
}
bytes_read = -1;
while(1){
if(smtp_str_getdelimfd_search_delim(gdfd->_buf,
gdfd->_buf_len,
gdfd->delim,
&delim_pos)){
if(smtp_str_getdelimfd_set_line_and_buf(gdfd, delim_pos) < 0){
return smtp_str_getdelimfd_throw_error(gdfd);
}
return STRING_GETDELIMFD_NEXT;
}else if(bytes_read == 0){
if(smtp_str_getdelimfd_set_line_and_buf(gdfd, gdfd->_buf_len) < 0){
return smtp_str_getdelimfd_throw_error(gdfd);
}
return STRING_GETDELIMFD_DONE;
}
if(smtp_si_sub_size_t(gdfd->_bufsz, gdfd->_buf_len, &buf_sz_remaining)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
if(buf_sz_remaining < SMTP_GETDELIM_READ_SZ){
if(smtp_si_add_size_t(buf_sz_remaining,
SMTP_GETDELIM_READ_SZ,
&buf_sz_new)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
buf_new = (char*)(realloc(gdfd->_buf, buf_sz_new));
if(buf_new == NULL){
return smtp_str_getdelimfd_throw_error(gdfd);
}
gdfd->_buf = buf_new;
gdfd->_bufsz = buf_sz_new;
}
if(smtp_si_add_size_t((size_t)gdfd->_buf, gdfd->_buf_len, NULL)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
read_buf_ptr = gdfd->_buf + gdfd->_buf_len;
bytes_read = (*gdfd->getdelimfd_read)(gdfd,
read_buf_ptr,
SMTP_GETDELIM_READ_SZ);
if(bytes_read < 0 ||
smtp_si_add_size_t(gdfd->_buf_len,
(size_t)bytes_read,
&gdfd->_buf_len)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
}
}
/**
* Copy a string and get the pointer to the end of the copied buffer.
*
* This function behaves similar to POSIX stpcpy(), useful for
* concatenating multiple strings onto a buffer. It always adds a
* null-terminated byte at the end of the string.
*
* @param[in] s1 Destination buffer.
* @param[in] s2 Null-terminated source string to copy to @p s1.
* @return Pointer to location in @p s1 after the last copied byte.
*/
SMTP_LINKAGE char *
smtp_stpcpy(char *s1,
const char *s2){
size_t i;
i = 0;
do{
s1[i] = s2[i];
} while(s2[i++] != '\0');
return &s1[i-1];
}
/**
* Reallocate memory with unsigned wrapping checks.
*
* @param[in] ptr Existing allocation buffer, or NULL when allocating a
* new buffer.
* @param[in] nmemb Number of elements to allocate.
* @param[in] size Size of each element in @p nmemb.
* @retval void* Pointer to a reallocated buffer containing
* @p nmemb * @p size bytes.
* @retval NULL Failed to reallocate memory.
*/
SMTP_LINKAGE void *
smtp_reallocarray(void *ptr,
size_t nmemb,
size_t size){
void *alloc;
size_t size_mul;
if(smtp_si_mul_size_t(nmemb, size, &size_mul)){
alloc = NULL;
errno = ENOMEM;
}
else{
alloc = realloc(ptr, size_mul);
}
return alloc;
}
/**
* Copy a string into a new dynamically allocated buffer.
*
* Returns a dynamically allocated string, with the same contents as the
* input string. The caller must free the returned string when finished.
*
* @param[in] s String to duplicate.
* @retval char* Pointer to a new dynamically allocated string duplicated
* from @p s.
* @retval NULL Failed to allocate memory for the new duplicate string.
*/
SMTP_LINKAGE char *
smtp_strdup(const char *s){
char *dup;
size_t dup_len;
size_t slen;
slen = strlen(s);
if(smtp_si_add_size_t(slen, 1, &dup_len)){
dup = NULL;
errno = ENOMEM;
}
else if((dup = (char*)(malloc(dup_len))) != NULL){
memcpy(dup, s, dup_len);
}
return dup;
}
/**
* Search for all substrings in a string and replace each instance with a
* replacement string.
*
* @param[in] search Substring to search for in @p s.
* @param[in] replace Replace each instance of the search string with this.
* @param[in] s Null-terminated string to search and replace.
* @retval char* A dynamically allocated string with the replaced instances
* as described above. The caller must free the allocated
* memory when finished.
* @retval NULL Memory allocation failure.
*/
SMTP_LINKAGE char *
smtp_str_replace(const char *const search,
const char *const replace,
const char *const s){
size_t search_len;
size_t replace_len;
size_t replace_len_inc;
size_t slen;
size_t slen_inc;
size_t s_idx;
size_t snew_len;
size_t snew_len_inc;
size_t snew_sz;
size_t snew_sz_dup;
size_t snew_sz_plus_slen;
size_t snew_replace_len_inc;
char *snew;
char *stmp;
search_len = strlen(search);
replace_len = strlen(replace);
slen = strlen(s);
s_idx = 0;
snew = NULL;
snew_len = 0;
snew_sz = 0;
if(smtp_si_add_size_t(replace_len, 1, &replace_len_inc) ||
smtp_si_add_size_t(slen, 1, &slen_inc)){
return NULL;
}
if(s[0] == '\0'){
return smtp_strdup("");
}
else if(search_len < 1){
return smtp_strdup(s);
}
while(s[s_idx]){
if(smtp_si_add_size_t(snew_len, 1, &snew_len_inc) ||
smtp_si_add_size_t(snew_sz, snew_sz, &snew_sz_dup) ||
smtp_si_add_size_t(snew_sz, slen, &snew_sz_plus_slen)){
free(snew);
return NULL;
}
if(strncmp(&s[s_idx], search, search_len) == 0){
if(smtp_si_add_size_t(snew_len, replace_len_inc, &snew_replace_len_inc)){
free(snew);
return NULL;
}
if(snew_replace_len_inc >= snew_sz){
/* snew_sz += snew_sz + slen + replace_len + 1 */
if(smtp_si_add_size_t(snew_sz_dup, slen_inc, &snew_sz) ||
smtp_si_add_size_t(snew_sz, replace_len, &snew_sz) ||
(stmp = (char*)(realloc(snew, snew_sz))) == NULL){
free(snew);
return NULL;
}
snew = stmp;
}
memcpy(&snew[snew_len], replace, replace_len);
snew_len += replace_len;
s_idx += search_len;
}
else{
if(snew_len_inc >= snew_sz){
/* snew_sz += snew_sz + slen + snew_len + 1 */
if(smtp_si_add_size_t(snew_sz_dup, slen, &snew_sz) ||
smtp_si_add_size_t(snew_sz, snew_len_inc, &snew_sz) ||
(stmp = (char*)(realloc(snew, snew_sz))) == NULL){
free(snew);
return NULL;
}
snew = stmp;
}
snew[snew_len] = s[s_idx];
s_idx += 1;
snew_len = snew_len_inc;
}
}
snew[snew_len] = '\0';
return snew;
}
/**
* Lookup table used to encode data into base64.
*
* Base64 encoding takes six bits of data and encodes those bits using this
* table. Since 2^6 = 64, this array has 64 entries which maps directly from
* the 6 bit value into the corresponding array value.
*/
static char g_base64_encode_table[] = {
'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',
'+','/'
};
/**
* Encode a single block of binary data into base64.
*
* @param[in] buf Buffer with data to encode.
* @param[in] buf_block_sz Number of bytes in buf to encode (min 1, max 3).
* @param[out] b64 Pointer to buffer with at least 4 bytes for
* storing the base64 encoded result.
*/
static void
smtp_base64_encode_block(const char *const buf,
size_t buf_block_sz,
char *const b64){
unsigned char inb[3] = {0};
unsigned char in_idx[4] = {0};
char outb[5] = {'=', '=', '=', '=', '\0'};
size_t i;
memcpy(inb, buf, buf_block_sz);
in_idx[0] = ((inb[0] >> 2)) & 0x3F;
in_idx[1] = ((inb[0] << 4) | ((inb[1] >> 4) & 0xF)) & 0x3F;
in_idx[2] = ((inb[1] << 2) | ((inb[2] >> 6) & 0x3)) & 0x3F;
in_idx[3] = ((inb[2] )) & 0x3F;
for(i = 0; i < 4; i++){
if(i < buf_block_sz + 1){
outb[i] = g_base64_encode_table[in_idx[i]];
}
b64[i] = outb[i];
}
}
/**
* Encode binary data into a base64 string.
*
* @param[in] buf Binary data to encode in base64.
* @param[in] buflen Number of bytes in the @p buf parameter, or -1 if
* null-terminated.
* @retval char* Dynamically allocated base64 encoded string. The caller
* must free this string when finished.
* @retval NULL Memory allocation failure.
*/
SMTP_LINKAGE char *
smtp_base64_encode(const char *const buf,
size_t buflen){
char *b64;
size_t b64_sz;
size_t buf_i;
size_t b64_i;
size_t remaining_block_sz;
size_t buf_block_sz;
if(buflen == SIZE_MAX){
buflen = strlen(buf);
}
/*
* base64 size expands by 33%
* +1 to round integer division up
* +2 for '=' padding
* +1 null terminator
*/
if(smtp_si_mul_size_t(buflen, 4, NULL)){
return NULL;
}
b64_sz = (4 * buflen / 3) + 1 + 2 + 1;
if((b64 = (char*)(calloc(1, b64_sz))) == NULL){
return NULL;
}
if(buflen == 0){
return b64;
}
buf_i = 0;
b64_i = 0;
remaining_block_sz = buflen;
while(remaining_block_sz > 0){
if(remaining_block_sz >= 3){
buf_block_sz = 3;
}
else{
buf_block_sz = remaining_block_sz;
}
smtp_base64_encode_block(&buf[buf_i], buf_block_sz, &b64[b64_i]);
/*
* Do not need to check for wrapping because these values restricted to
* range of b64_sz, which has already been checked for wrapping above.
*/
buf_i += 3;
b64_i += 4;
remaining_block_sz -= buf_block_sz;
}
return b64;
}
#ifdef SMTP_OPENSSL
/**
* Lookup table used to decode base64 data.
*
* For base64 encoding, every six bits have been encoded using only the ASCII
* characters from @ref g_base64_encode_table. This table has entries which
* allow the reversal of that process. It has 128 entries which map over to
* the index value from the encoding table. If an indexing result ends up
* with -1 during the decoding process, then that indicates an invalid base64
* character in the encoded data.
*/
static signed char
g_base64_decode_table[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1,
62, /* + */
-1, -1, -1,
63, /* / */
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /* 0 - 9 */
-1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* A - J */
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, /* K - T */
20, 21, 22, 23, 24, 25, /* U - Z */
-1, -1, -1, -1, -1, -1,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, /* a - j */
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, /* k - t */
46, 47, 48, 49, 50, 51, /* u - z */
-1, -1, -1, -1, -1
};
/**
* Decodes a base64 block of up to four bytes at a time.
*
* @param[in] buf Buffer containing bytes to decode.
* @param[out] decode Buffer for storing base64 decoded bytes.
* @retval >0 Length of the decoded block.
* @retval 0 If the block contains invalid base64 data.
*/
static size_t
smtp_base64_decode_block(const unsigned char *const buf,
unsigned char *const decode){
size_t decode_block_len;
size_t i;
signed char decode_table[4];
unsigned char outb[3];
decode_block_len = 0;
for(i = 0; i < 4; i++){
if(buf[i] == '='){
decode_table[i] = 0;
continue;
}
decode_table[i] = g_base64_decode_table[buf[i]];
if(decode_table[i] < 0){
return 0;
}
}
outb[0] = ((decode_table[0] << 2) & 0xFC) | ((decode_table[1] >> 4) & 0x03);
outb[1] = ((decode_table[1] << 4) & 0xF0) | ((decode_table[2] >> 2) & 0x0F);
outb[2] = ((decode_table[2] << 6) & 0xC0) | ((decode_table[3] ) & 0x3F);
decode[0] = outb[0];
decode_block_len += 1;
if(buf[2] == '='){
decode[1] = '\0';
}
else{
decode[1] = outb[1];
decode_block_len += 1;
}
if(buf[3] == '='){
decode[2] = '\0';
}
else{
decode[2] = outb[2];
decode_block_len += 1;
}
return decode_block_len;
}
/**
* Decode a base64 string.
*
* The decode parameter will get dynamically allocated by this function
* if it successfully completes. Therefore, the caller must free the decode
* parameter after use.
*
* @param[in] buf Null-terminated base64 string.
* @param[out] decode Pointer to buffer which will get dynamically allocated
* and will contain the decoded binary data. This parameter
* will get set to NULL if the memory allocation fails.
* @retval >=0 Length of the data stored in the decode parameter.
* @retval -1 Memory allocation failure or invalid base64 byte sequences.
*/
SMTP_LINKAGE size_t
smtp_base64_decode(const char *const buf,
unsigned char **decode){
size_t buf_len;
size_t buf_len_inc;
size_t buf_i;
unsigned char *b64_decode;
size_t decode_len;
size_t decode_block_len;
*decode = NULL;
buf_len = strlen(buf);
if(buf_len % 4 != 0){