/* kc3
* Copyright from 2022 to 2025 kmx.io <contact@kmx.io>
*
* Permission is hereby granted to use this software granted the above
* copyright notice and this permission paragraph are included in all
* copies and substantial portions of this software.
*
* THIS SOFTWARE IS PROVIDED "AS-IS" WITHOUT ANY GUARANTEE OF
* PURPOSE AND PERFORMANCE. IN NO EVENT WHATSOEVER SHALL THE
* AUTHOR BE CONSIDERED LIABLE FOR THE USE AND PERFORMANCE OF
* THIS SOFTWARE.
*/
#include "libkc3/io.h"
#include "libkc3/types.h"
#include "tls/types.h"
#if defined(WIN32) || defined(WIN64)
# include <windows.h>
# include <wincrypt.h>
#else
# include <unistd.h>
# include <stdlib.h>
#endif
#include <tls.h>
#include "../libkc3/kc3.h"
#include "tls.h"
bool kc3_tls_configure(p_tls ctx, p_tls_config cfg)
{
if (tls_configure(ctx, cfg)) {
err_puts("kc3_tls_configure: tls_configure: ");
err_puts(tls_error(ctx));
assert(! "kc3_tls_configure: tls_configure");
return false;
}
return true;
}
s_str * kc3_tls_ca_cert_path (s_str *dest)
{
uw i;
static const s_str paths[] = {
STR("/etc/certs/ca-certificates.crt"),
STR("/etc/pki/tls/certs/ca-bundle.crt"),
STR("/etc/ssl/cert.pem"),
STR("/etc/ssl/certs/ca-certificates.crt"),
STR("/usr/local/share/certs/ca-root-nss.crt"),
STR("/usr/ssl/certs/ca-bundle.crt"),
};
const char *ssl_cert_file = getenv("SSL_CERT_FILE");
if (ssl_cert_file && access(ssl_cert_file, R_OK) == 0)
return str_init_1_alloc(dest, ssl_cert_file);
const char *default_path = tls_default_ca_cert_file();
if (default_path && access(default_path, R_OK) == 0)
return str_init_1_alloc(dest, default_path);
i = 0;
while (i < sizeof(paths) / sizeof(*paths)) {
if (access(paths[i].ptr.pchar, R_OK) == 0) {
*dest = paths[i];
return dest;
}
i++;
}
#if defined(WIN32) || defined(WIN64)
err_puts("kc3_tls_get_ca_cert_path: not implemented");
assert(! "kc3_tls_get_ca_cert_path: not implemented");
#else
err_puts("kc3_tls_get_ca_cert_path: not found");
assert(! "kc3_tls_get_ca_cert_path: not found");
#endif
return NULL;
}
bool kc3_tls_init (void)
{
if (tls_init()) {
err_puts("kc3_tls_init: tls_init");
assert(! "kc3_tls_init: tls_init");
return false;
}
return true;
}
p_tls * kc3_tls_client (p_tls *result)
{
p_tls tmp = NULL;
if (! (tmp = tls_client())) {
err_puts("kc3_tls_client: tls_client");
assert(! "kc3_tls_client: tls_client");
return NULL;
}
*result = tmp;
return result;
}
bool kc3_tls_connect_socket (p_tls ctx, t_socket sockfd,
const s_str *hostname)
{
if (tls_connect_socket(ctx, sockfd, hostname->ptr.pchar)) {
err_write_1("kc3_tls_connect_socket: tls_connect_socket: ");
err_puts(tls_error(ctx));
assert(! "kc3_tls_connect_socket: tls_connect_socket");
return false;
}
return true;
}