open62541 1.3.12
Open source implementation of OPC UA
Loading...
Searching...
No Matches
openssl_sockets.h
Go to the documentation of this file.
1#if !defined(__OPENSSL_SOCKET_TEMPLATE_H__)
2#define __OPENSSL_SOCKET_TEMPLATE_H__
3
4#include <openssl/bio.h>
5#include <openssl/ssl.h>
6#include <openssl/err.h>
7
8#include <string.h>
9
10/*
11 A template for opening a non-blocking OpenSSL connection.
12*/
13void open_nb_socket(BIO** bio,
14 SSL_CTX** ssl_ctx,
15 const char* addr,
16 const char* port,
17 const char* ca_file,
18 const char* ca_path,
19 const char* cert_file,
20 const char* key_file);
21
22void open_nb_socket(BIO** bio,
23 SSL_CTX** ssl_ctx,
24 const char* addr,
25 const char* port,
26 const char* ca_file,
27 const char* ca_path,
28 const char* cert_file,
29 const char* key_file)
30{
31 *ssl_ctx = SSL_CTX_new(SSLv23_client_method());
32 SSL* ssl;
33
34 /* load certificate */
35 if (!SSL_CTX_load_verify_locations(*ssl_ctx, ca_file, ca_path)) {
36 printf("error: failed to load ca certificate\n");
37 exit(1);
38 }
39
40 if (cert_file && key_file)
41 {
42 if (!SSL_CTX_use_certificate_file(*ssl_ctx, cert_file, SSL_FILETYPE_PEM))
43 {
44 printf("error: failed to load client certificate\n");
45 exit(1);
46 }
47
48 if (!SSL_CTX_use_PrivateKey_file(*ssl_ctx, key_file, SSL_FILETYPE_PEM))
49 {
50 printf("error: failed to load client key\n");
51 exit(1);
52 }
53 }
54
55 /* open BIO socket */
56 char * addr_copy = (char*)malloc(strlen(addr) + 1);
57 strcpy(addr_copy,addr);
58 char * port_copy = (char*)malloc(strlen(port) + 1);
59 strcpy(port_copy,port);
60
61 *bio = BIO_new_ssl_connect(*ssl_ctx);
62 BIO_get_ssl(*bio, &ssl);
63 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
64 BIO_set_conn_hostname(*bio, addr_copy);
65 BIO_set_nbio(*bio, 1);
66 BIO_set_conn_port(*bio, port_copy);
67
68 free(addr_copy);
69 free(port_copy);
70
71 /* wait for connect with 10 second timeout */
72 int start_time = (int)time(NULL);
73 int do_connect_rv = (int)BIO_do_connect(*bio);
74 while(do_connect_rv <= 0 && BIO_should_retry(*bio) && (int)time(NULL) - start_time < 10) {
75 do_connect_rv = (int)BIO_do_connect(*bio);
76 }
77 if (do_connect_rv <= 0) {
78 printf("error: %s\n", ERR_reason_error_string(ERR_get_error()));
79 BIO_free_all(*bio);
80 SSL_CTX_free(*ssl_ctx);
81 *bio = NULL;
82 *ssl_ctx=NULL;
83 return;
84 }
85
86 /* verify certificate */
87 if (SSL_get_verify_result(ssl) != X509_V_OK) {
88 /* Handle the failed verification */
89 printf("error: x509 certificate verification failed\n");
90 exit(1);
91 }
92}
93
94#endif
void open_nb_socket(BIO **bio, SSL_CTX **ssl_ctx, const char *addr, const char *port, const char *ca_file, const char *ca_path, const char *cert_file, const char *key_file)