Coverage Report

Created: 2025-11-14 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mosquitto/libcommon/base64_common.c
Line
Count
Source
1
/*
2
Copyright (c) 2012-2021 Roger Light <roger@atchoo.org>
3
4
All rights reserved. This program and the accompanying materials
5
are made available under the terms of the Eclipse Public License 2.0
6
and Eclipse Distribution License v1.0 which accompany this distribution.
7
8
The Eclipse Public License is available at
9
   https://www.eclipse.org/legal/epl-2.0/
10
and the Eclipse Distribution License is available at
11
  http://www.eclipse.org/org/documents/edl-v10.php.
12
13
SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
14
15
Contributors:
16
   Roger Light - initial implementation and documentation.
17
*/
18
19
#include "config.h"
20
21
#ifdef WITH_TLS
22
#  include <openssl/opensslv.h>
23
#  include <openssl/evp.h>
24
#  include <openssl/buffer.h>
25
#endif
26
#include <string.h>
27
28
#include "mosquitto.h"
29
30
#ifdef WITH_TLS
31
32
33
int mosquitto_base64_encode(const unsigned char *in, size_t in_len, char **encoded)
34
448
{
35
448
  BIO *bmem, *b64;
36
448
  BUF_MEM *bptr = NULL;
37
448
  int rc = 1;
38
39
448
  b64 = BIO_new(BIO_f_base64());
40
448
  if(b64 == NULL){
41
0
    return 1;
42
0
  }
43
44
448
  BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
45
448
  bmem = BIO_new(BIO_s_mem());
46
448
  if(bmem){
47
448
    b64 = BIO_push(b64, bmem);
48
448
    BIO_write(b64, in, (int)in_len);
49
50
448
    if(BIO_flush(b64) == 1){
51
448
      BIO_get_mem_ptr(b64, &bptr);
52
448
      *encoded = mosquitto_malloc(bptr->length+1);
53
448
      if(*encoded){
54
448
        memcpy(*encoded, bptr->data, bptr->length);
55
448
        (*encoded)[bptr->length] = '\0';
56
448
        rc = 0;
57
448
      }
58
448
    }
59
448
  }
60
448
  BIO_free_all(b64);
61
62
448
  return rc;
63
448
}
64
65
66
int mosquitto_base64_decode(const char *in, unsigned char **decoded, unsigned int *decoded_len)
67
24.2k
{
68
24.2k
  BIO *bmem, *b64;
69
24.2k
  size_t slen;
70
24.2k
  int len;
71
24.2k
  int rc = 1;
72
73
24.2k
  slen = strlen(in);
74
75
24.2k
  b64 = BIO_new(BIO_f_base64());
76
24.2k
  if(!b64){
77
0
    return 1;
78
0
  }
79
80
24.2k
  BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
81
24.2k
  bmem = BIO_new(BIO_s_mem());
82
24.2k
  if(bmem){
83
24.2k
    b64 = BIO_push(b64, bmem);
84
24.2k
    BIO_write(bmem, in, (int)slen);
85
86
24.2k
    if(BIO_flush(bmem) == 1){
87
24.2k
      *decoded = mosquitto_calloc(slen, 1);
88
89
24.2k
      if(*decoded){
90
24.2k
        len = BIO_read(b64, *decoded, (int)slen);
91
24.2k
        if(len > 0){
92
24.0k
          *decoded_len = (unsigned int)len;
93
24.0k
          rc = 0;
94
24.0k
        }else{
95
219
          mosquitto_free(*decoded);
96
219
          *decoded = NULL;
97
219
        }
98
24.2k
      }
99
24.2k
    }
100
24.2k
  }
101
24.2k
  BIO_free_all(b64);
102
103
24.2k
  return rc;
104
24.2k
}
105
#endif