Coverage Report

Created: 2026-03-29 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mosquitto/libcommon/random_common.c
Line
Count
Source
1
/*
2
Copyright (c) 2009-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
#include <stdlib.h> /* Keep this here to allow glibc detection */
21
22
#ifdef WIN32
23
#  include <winsock2.h>
24
#  include <aclapi.h>
25
#  include <io.h>
26
#  include <lmcons.h>
27
#endif
28
29
#if !defined(WITH_TLS) && defined(__linux__) && defined(__GLIBC__)
30
#  if __GLIBC_PREREQ(2, 25)
31
#    include <sys/random.h>
32
#    define HAVE_GETRANDOM 1
33
#  endif
34
#endif
35
36
#ifdef WITH_TLS
37
#  include <openssl/bn.h>
38
#  include <openssl/rand.h>
39
#endif
40
41
#include "mosquitto.h"
42
43
44
int mosquitto_getrandom(void *bytes, int count)
45
0
{
46
0
  int rc = MOSQ_ERR_UNKNOWN;
47
48
0
#ifdef WITH_TLS
49
0
  if(RAND_bytes(bytes, count) == 1){
50
0
    rc = MOSQ_ERR_SUCCESS;
51
0
  }
52
#elif defined(HAVE_GETRANDOM)
53
  if(getrandom(bytes, (size_t)count, 0) == count){
54
    rc = MOSQ_ERR_SUCCESS;
55
  }
56
#elif defined(WIN32)
57
  HCRYPTPROV provider;
58
59
  if(!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)){
60
    return MOSQ_ERR_UNKNOWN;
61
  }
62
63
  if(CryptGenRandom(provider, count, bytes)){
64
    rc = MOSQ_ERR_SUCCESS;
65
  }
66
67
  CryptReleaseContext(provider, 0);
68
#else
69
#  error "No suitable random function found."
70
#endif
71
0
  return rc;
72
0
}