Coverage Report

Created: 2025-09-04 06:10

/src/mosquitto/libcommon/random_common.c
Line
Count
Source (jump to first uncovered line)
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
int mosquitto_getrandom(void *bytes, int count)
44
0
{
45
0
  int rc = MOSQ_ERR_UNKNOWN;
46
47
0
#ifdef WITH_TLS
48
0
  if(RAND_bytes(bytes, count) == 1){
49
0
    rc = MOSQ_ERR_SUCCESS;
50
0
  }
51
#elif defined(HAVE_GETRANDOM)
52
  if(getrandom(bytes, (size_t)count, 0) == count){
53
    rc = MOSQ_ERR_SUCCESS;
54
  }
55
#elif defined(WIN32)
56
  HCRYPTPROV provider;
57
58
  if(!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)){
59
    return MOSQ_ERR_UNKNOWN;
60
  }
61
62
  if(CryptGenRandom(provider, count, bytes)){
63
    rc = MOSQ_ERR_SUCCESS;
64
  }
65
66
  CryptReleaseContext(provider, 0);
67
#else
68
#  error "No suitable random function found."
69
#endif
70
0
  return rc;
71
0
}