Coverage Report

Created: 2025-11-24 06:45

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
0
{
35
0
  BIO *bmem, *b64;
36
0
  BUF_MEM *bptr = NULL;
37
0
  int rc = 1;
38
39
0
  b64 = BIO_new(BIO_f_base64());
40
0
  if(b64 == NULL){
41
0
    return 1;
42
0
  }
43
44
0
  BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
45
0
  bmem = BIO_new(BIO_s_mem());
46
0
  if(bmem){
47
0
    b64 = BIO_push(b64, bmem);
48
0
    BIO_write(b64, in, (int)in_len);
49
50
0
    if(BIO_flush(b64) == 1){
51
0
      BIO_get_mem_ptr(b64, &bptr);
52
0
      *encoded = mosquitto_malloc(bptr->length+1);
53
0
      if(*encoded){
54
0
        memcpy(*encoded, bptr->data, bptr->length);
55
0
        (*encoded)[bptr->length] = '\0';
56
0
        rc = 0;
57
0
      }
58
0
    }
59
0
  }
60
0
  BIO_free_all(b64);
61
62
0
  return rc;
63
0
}
64
65
66
int mosquitto_base64_decode(const char *in, unsigned char **decoded, unsigned int *decoded_len)
67
957
{
68
957
  BIO *bmem, *b64;
69
957
  size_t slen;
70
957
  int len;
71
957
  int rc = 1;
72
73
957
  slen = strlen(in);
74
75
957
  b64 = BIO_new(BIO_f_base64());
76
957
  if(!b64){
77
0
    return 1;
78
0
  }
79
80
957
  BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
81
957
  bmem = BIO_new(BIO_s_mem());
82
957
  if(bmem){
83
957
    b64 = BIO_push(b64, bmem);
84
957
    BIO_write(bmem, in, (int)slen);
85
86
957
    if(BIO_flush(bmem) == 1){
87
957
      *decoded = mosquitto_calloc(slen, 1);
88
89
957
      if(*decoded){
90
957
        len = BIO_read(b64, *decoded, (int)slen);
91
957
        if(len > 0){
92
715
          *decoded_len = (unsigned int)len;
93
715
          rc = 0;
94
715
        }else{
95
242
          mosquitto_free(*decoded);
96
242
          *decoded = NULL;
97
242
        }
98
957
      }
99
957
    }
100
957
  }
101
957
  BIO_free_all(b64);
102
103
957
  return rc;
104
957
}
105
#endif