mirror of
https://github.com/openziti/ziti-sdk-c.git
synced 2026-11-07 03:00:42 +00:00
initial import
This commit is contained in:
+17
@@ -0,0 +1,17 @@
|
||||
.DS_Store
|
||||
|
||||
build-*/
|
||||
build/
|
||||
cmake-build-debug/
|
||||
|
||||
# visual studio files
|
||||
.vs
|
||||
**/obj/
|
||||
**/bin/
|
||||
**/Debug/
|
||||
*.user
|
||||
ziti_libs/
|
||||
|
||||
#docfx related
|
||||
docfx_site
|
||||
windows/packages
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
[submodule "deps/mjson"]
|
||||
path = deps/mjson
|
||||
url = https://github.com/cesanta/mjson
|
||||
branch = master
|
||||
[submodule "deps/http-parser"]
|
||||
path = deps/http-parser
|
||||
url = https://github.com/ekoby/http-parser
|
||||
branch = support-opaque-urls
|
||||
[submodule "deps/uv-mbed"]
|
||||
path = deps/uv-mbed
|
||||
url = https://github.com/ekoby/uv-mbed.git
|
||||
branch = master
|
||||
[submodule "deps/subcommand"]
|
||||
path = deps/subcommand
|
||||
url = https://github.com/dimitri/subcommands.c.git
|
||||
branch = master
|
||||
[submodule "deps/Catch2"]
|
||||
path = deps/Catch2
|
||||
url = https://github.com/catchorg/Catch2.git
|
||||
branch = master
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
cmake_minimum_required (VERSION 3.12)
|
||||
file(READ version ver)
|
||||
|
||||
project (ziti-sdk
|
||||
VERSION ${ver}
|
||||
LANGUAGES C CXX
|
||||
)
|
||||
|
||||
message("project version: ${PROJECT_VERSION}")
|
||||
|
||||
if (WIN32)
|
||||
message("WIN32 build. Creating: ${CMAKE_BINARY_DIR}/cmake_install")
|
||||
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/cmake_install)
|
||||
message("WIN32 build. Creating: ${CMAKE_BINARY_DIR}/cmake_install/ziti-sdk-${PROJECT_VERSION}")
|
||||
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/cmake_install/ziti-sdk-${PROJECT_VERSION})
|
||||
set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/cmake_install/ziti-sdk-${PROJECT_VERSION})
|
||||
else()
|
||||
set(CMAKE_INSTALL_PREFIX /opt/netfoundry/ziti-sdk-${PROJECT_VERSION})
|
||||
endif()
|
||||
|
||||
message("cross-compiling ${CMAKE_CROSSCOMPILING}")
|
||||
|
||||
enable_testing()
|
||||
|
||||
# Get the current working branch
|
||||
execute_process(
|
||||
COMMAND git rev-parse --abbrev-ref HEAD
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||
OUTPUT_VARIABLE GIT_BRANCH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
|
||||
# Get the latest abbreviated commit hash of the working branch
|
||||
execute_process(
|
||||
COMMAND git log -1 --format=%h
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||
OUTPUT_VARIABLE GIT_COMMIT_HASH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
|
||||
# capture build date
|
||||
execute_process(
|
||||
COMMAND date +%a-%m/%d/%Y-%H:%M:%S-%Z
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||
OUTPUT_VARIABLE BUILD_DATE
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
|
||||
message("git info:")
|
||||
message(" branch : ${GIT_BRANCH}")
|
||||
message(" hash : ${GIT_COMMIT_HASH}")
|
||||
message(" date : ${BUILD_DATE}")
|
||||
|
||||
if (DEFINED ENV{BITBUCKET_BUILD_NUMBER})
|
||||
set(ZITI_BUILDNUM $ENV{BITBUCKET_BUILD_NUMBER})
|
||||
else ()
|
||||
set(ZITI_BUILDNUM local)
|
||||
endif ()
|
||||
|
||||
set(ZITI_VERSION ${PROJECT_VERSION}-${ZITI_BUILDNUM})
|
||||
|
||||
link_directories(${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
add_subdirectory(deps)
|
||||
|
||||
if(WIN32)
|
||||
add_subdirectory(windows)
|
||||
endif()
|
||||
|
||||
set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 0)
|
||||
set(CPACK_PACKAGE_VERSION ${ZITI_VERSION})
|
||||
set(CPACK_OUTPUT_FILE_PREFIX ${CMAKE_CURRENT_BINARY_DIR})
|
||||
if (UNIX)
|
||||
set(CPACK_GENERATOR "TGZ")
|
||||
elseif (WIN32)
|
||||
set(CPACK_GENERATOR "ZIP")
|
||||
endif ()
|
||||
|
||||
include(CPack)
|
||||
add_custom_target(publish)
|
||||
|
||||
if(${GIT_BRANCH} STREQUAL master)
|
||||
set(PUB_PFX ziti-staging)
|
||||
else()
|
||||
set(PUB_PFX ziti-snapshot/${GIT_BRANCH})
|
||||
endif()
|
||||
|
||||
set(PUB_OPTS --apikey=$ENV{JFROG_API_KEY} --url https://netfoundry.jfrog.io/netfoundry --build-name=ziti --build-number=${ZITI_VERSION})
|
||||
string(TOLOWER ${CMAKE_SYSTEM_NAME} PUB_OS)
|
||||
string(TOLOWER ${CMAKE_SYSTEM_PROCESSOR} PUB_ARCH)
|
||||
|
||||
if(${PUB_ARCH} STREQUAL "x86_64" )
|
||||
set(PUB_ARCH "amd64")
|
||||
endif()
|
||||
|
||||
macro(PUBCOMP comp)
|
||||
if(NOT WIN32)
|
||||
set(${comp}_PUB_PATH ${PUB_PFX}/${comp}/${PUB_ARCH}/${PUB_OS}/${ZITI_VERSION}/${comp}.tar.gz)
|
||||
set(${comp}_PUB_PROPS "version=${ZITI_VERSION}\;name=${comp}\;arch=${PUB_ARCH}\;os=${PUB_OS}\;branch=${GIT_BRANCH}")
|
||||
|
||||
add_custom_target(${comp}-pub
|
||||
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${comp}-${ZITI_VERSION}-${CMAKE_SYSTEM_NAME}.tar.gz
|
||||
COMMAND jfrog rt u ${PUB_OPTS} --props='${${comp}_PUB_PROPS}' ${comp}-${ZITI_VERSION}-${CMAKE_SYSTEM_NAME}.tar.gz ${${comp}_PUB_PATH}
|
||||
)
|
||||
|
||||
add_dependencies(publish ${comp}-pub)
|
||||
endif()
|
||||
endmacro(PUBCOMP)
|
||||
|
||||
# use prefix length to trim path for logging, see inc_internal/utils.h __FILENAME__
|
||||
string(LENGTH "${CMAKE_SOURCE_DIR}/" SOURCE_PATH_SIZE)
|
||||
add_definitions("-DSOURCE_PATH_SIZE=${SOURCE_PATH_SIZE}")
|
||||
|
||||
add_subdirectory(library)
|
||||
|
||||
if(NOT ${PUB_OS} STREQUAL "ios" )
|
||||
add_subdirectory(programs)
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
PUBCOMP(ziti-sdk)
|
||||
|
||||
@@ -1 +1,67 @@
|
||||
# ziti-sdk-c
|
||||
# Ziti C SDK - Setup for Development
|
||||
|
||||
The following steps should get your C SDK for Ziti building. C development is specific to your operating system and tool chain used. These steps should work properly for you but if your OS has variations you may need to adapt these steps accordingly.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Build
|
||||
|
||||
* [Cmake (3.12+)](https://cmake.org/install/)
|
||||
* protobuf-c - only needed when you change `.proto` files, see [below](#working-with-protobuf)
|
||||
|
||||
### Test
|
||||
|
||||
* ubuntu: `softhsm2`, `opensc`
|
||||
* fedora: `softhsm`, `opensc`
|
||||
* macOS (brew): `softhsm (cask)`, `opensc`
|
||||
|
||||
## Init
|
||||
|
||||
The C SDK requires additional dependencies to be retreived. This is accomplished via the `git submodule` command. Fetch third party libs using:
|
||||
|
||||
```bash
|
||||
$ git submodule update --init --recursive
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
### Linux/MacOS
|
||||
|
||||
Building the SDK on linux/mac can be accomplished with:
|
||||
|
||||
```bash
|
||||
$ mkdir build
|
||||
$ cd build
|
||||
$ cmake .. && make
|
||||
```
|
||||
|
||||
If you are cross compiling, you _must_ name the build directory as `build-$(uname -s)-$(uname -m)`
|
||||
|
||||
### Windows
|
||||
|
||||
The easiest method to build on windows is to open a "Developer Command Prompt for VS 2019" and execute `msvc-build.bat`. Open that file to see the individual steps needed to build the C SDK on Windows. The steps the script will do are:
|
||||
|
||||
```
|
||||
mkdir build
|
||||
cd build
|
||||
cmake .. -DCMAKE_INSTALL_INCLUDEDIR=include -DCMAKE_INSTALL_LIBDIR=lib
|
||||
cmake --build . --config Debug [Release]
|
||||
```
|
||||
|
||||
## Working with protobuf
|
||||
Required version of protobuf-c compiler (get it for your specific environment)
|
||||
|
||||
```bash
|
||||
$ protoc-c --version
|
||||
protobuf-c 1.3.1
|
||||
libprotoc 3.6.1
|
||||
|
||||
Generate source files from protocol definitions and check them in
|
||||
```
|
||||
|
||||
$ cd library/proto/
|
||||
$ protoc-c --c_out=. *.proto
|
||||
$ git add *.h *.c
|
||||
...
|
||||
```
|
||||
Copyright© 2018-2019. NetFoundry, Inc.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
Linux-x86_64
|
||||
Linux-arm
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
project(ziti-deps)
|
||||
|
||||
include(ExternalProject)
|
||||
|
||||
add_subdirectory(uv-mbed)
|
||||
|
||||
add_library(subcommand INTERFACE)
|
||||
target_include_directories(subcommand INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/subcommand)
|
||||
|
||||
## Testing library
|
||||
# need to preprocess that to be able to use Cmake integration later
|
||||
execute_process(COMMAND "mkdir" "${CMAKE_CURRENT_BINARY_DIR}/Catch2")
|
||||
execute_process(COMMAND "${CMAKE_COMMAND}" -G "${CMAKE_GENERATOR}"
|
||||
-DCATCH_BUILD_TESTING=OFF
|
||||
-DCATCH_INSTALL_DOCS=OFF
|
||||
-DCMAKE_INSTALL_PREFIX=${PROJECT_BINARY_DIR}/Catch2
|
||||
${PROJECT_SOURCE_DIR}/Catch2
|
||||
WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/Catch2")
|
||||
|
||||
execute_process(COMMAND "${CMAKE_COMMAND}" --build . --target install
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Catch2")
|
||||
+1
Submodule deps/Catch2 added at c8db4e77c4
+1
Submodule deps/http-parser added at 81b9438c80
+1
Submodule deps/mjson added at 18c63620ee
+1
Submodule deps/subcommand added at 1ef677716b
+1
Submodule deps/uv-mbed added at 2a4ce9d2eb
+16
@@ -0,0 +1,16 @@
|
||||
[submodule "deps/mjson"]
|
||||
path = deps/mjson
|
||||
url = https://github.com/cesanta/mjson
|
||||
[submodule "deps/http-parser"]
|
||||
path = deps/http-parser
|
||||
url = https://github.com/ekoby/http-parser
|
||||
branch = support-opaque-urls
|
||||
[submodule "deps/uv-mbed"]
|
||||
path = deps/uv-mbed
|
||||
url = https://github.com/ekoby/uv-mbed.git
|
||||
[submodule "deps/subcommand"]
|
||||
path = deps/subcommand
|
||||
url = https://github.com/dimitri/subcommands.c.git
|
||||
[submodule "deps/Catch2"]
|
||||
path = deps/Catch2
|
||||
url = https://github.com/catchorg/Catch2.git
|
||||
@@ -0,0 +1,39 @@
|
||||
//
|
||||
// Created by eugene on 2/27/19.
|
||||
//
|
||||
|
||||
#ifndef ZT_SDK_TLS_H
|
||||
#define ZT_SDK_TLS_H
|
||||
|
||||
#include <mbedtls/ssl.h>
|
||||
#include <mbedtls/pk.h>
|
||||
#include <mbedtls/entropy.h>
|
||||
#include <mbedtls/ctr_drbg.h>
|
||||
/*
|
||||
* init global TLS stuff
|
||||
*/
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
mbedtls_ssl_config config;
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_x509_crt cert;
|
||||
mbedtls_x509_crt cacert;
|
||||
|
||||
mbedtls_entropy_context entropy;
|
||||
mbedtls_ctr_drbg_context ctr_drbg;
|
||||
} nf_tls_context;
|
||||
|
||||
void tls_debug(void *ctx, int level,
|
||||
const char *file, int line,
|
||||
const char *str);
|
||||
|
||||
int load_key(mbedtls_pk_context *pk, const char *spec);
|
||||
|
||||
#ifdef __cplusplus
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif //ZT_SDK_TLS_H
|
||||
@@ -0,0 +1,110 @@
|
||||
//
|
||||
// Created by eugene on 12/21/17.
|
||||
//
|
||||
|
||||
#ifndef ZITI_TLS_UTILS_H
|
||||
#define ZITI_TLS_UTILS_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <uv.h>
|
||||
#include <http_parser.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
extern const char *ziti_get_version(int verbose);
|
||||
extern const char *ziti_git_branch();
|
||||
extern const char *ziti_git_commit();
|
||||
|
||||
int lt_zero(int v);
|
||||
int non_zero(int v);
|
||||
|
||||
typedef const char *(*fmt_error_t)(int);
|
||||
typedef int *(*cond_error_t)(int);
|
||||
|
||||
#define NEWP(var, type) type *var = calloc(1, sizeof(type))
|
||||
#define VAL_OR_ELSE(v, def) ((v) != NULL ? (v) : (def))
|
||||
#define FREE(v) if ((v) != NULL) { free(v); (v) = NULL; }
|
||||
|
||||
#define __FILENAME__ (__FILE__ + SOURCE_PATH_SIZE)
|
||||
|
||||
|
||||
char *fmt_mbederr(int err);
|
||||
|
||||
#define FMT(ex) _##ex##_fmt
|
||||
#define COND(ex) _##ex##_cond
|
||||
#define ERR(ex) (_##ex##_error)
|
||||
#define ERLINE(ex) (_##ex##_line)
|
||||
#define ERFILE(ex) (_##ex##_file)
|
||||
#define ERLBL(ex) _##ex##_label
|
||||
|
||||
#define PREPCF(ex, cond, fmt) int ERR(ex) = 0, ERLINE(ex) = 0; const char *_##ex##_op = "<unknown>", *ERFILE(ex) = "<unknown>"; \
|
||||
fmt_error_t FMT(ex) = (fmt_error_t)(fmt); cond_error_t COND(ex) = (cond_error_t)cond
|
||||
|
||||
#define PREPF(ex, fmt) PREPCF(ex, lt_zero, fmt)
|
||||
|
||||
#define PREP(ex) PREPF(ex, strerror)
|
||||
|
||||
#define TRY(ex, op) ERR(ex) = (op); do {\
|
||||
if (COND(ex)(ERR(ex))) { ERFILE(ex) = __FILENAME__; ERLINE(ex) = __LINE__; _##ex##_op = #op; goto ERLBL(ex);}\
|
||||
} while(0)
|
||||
|
||||
#define CATCH(ex) { ERLBL(ex):\
|
||||
if (COND(ex)(ERR(ex))) {\
|
||||
ZITI_LOG(ERROR, "%s:%d - %s => %d(%s)", ERFILE(ex), ERLINE(ex), _##ex##_op, ERR(ex), FMT(ex)(ERR(ex)));\
|
||||
}}\
|
||||
for (int _##ex##_count = 0;COND(ex)(ERR(ex)) && _##ex##_count == 0; _##ex##_count++)
|
||||
|
||||
|
||||
#define FOR(idx, arr) for (int (idx) = 0; (idx) < SIZEOF(arr) && (arr)[(idx)] != NULL; (idx)++)
|
||||
|
||||
extern void init_debug();
|
||||
|
||||
extern int ziti_debug_level;
|
||||
extern FILE *ziti_debug_out;
|
||||
|
||||
|
||||
// for windows compilation NOGDI needs to be set:
|
||||
// right click ziti -> properties -> C/C++ -> Preprocessor - ensure NOGDI is in the list of preprocessor definitions
|
||||
// if it's not present check the CMakeLists.txt file
|
||||
#define DEBUG_LEVELS(XX) \
|
||||
XX(NONE) \
|
||||
XX(ERROR) /*WINDOWS - see comment above wrt NOGDI*/ \
|
||||
XX(WARN) \
|
||||
XX(INFO) \
|
||||
XX(DEBUG) \
|
||||
XX(VERBOSE) \
|
||||
XX(TRACE)
|
||||
|
||||
|
||||
enum DebugLevel {
|
||||
#define _level(n) n,
|
||||
DEBUG_LEVELS(_level)
|
||||
#undef _level
|
||||
};
|
||||
|
||||
#define container_of(ptr, type, member) ((type *) ((ptr) - offsetof(type, member)))
|
||||
|
||||
|
||||
#define ZITI_LOG(level, fmt, ...) do { \
|
||||
if (level <= ziti_debug_level) {\
|
||||
long elapsed = get_elapsed();\
|
||||
fprintf(ziti_debug_out, "[%9ld.%03ld] " #level "\t%s:%d %s(): " fmt "\n",\
|
||||
elapsed/1000, elapsed%1000, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__);\
|
||||
}\
|
||||
} while(0)
|
||||
|
||||
long get_elapsed();
|
||||
|
||||
void ziti_alloc_cb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf);
|
||||
|
||||
int get_url_data(const char *url, struct http_parser_url *parser, int uf, char *out, size_t maxout);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif //ZITI_TLS_UTILS_H
|
||||
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// Created by eugene on 2/28/19.
|
||||
//
|
||||
|
||||
#ifndef ZT_SDK_ERRORS_H
|
||||
#define ZT_SDK_ERRORS_H
|
||||
|
||||
#define ZITI_ERRORS(XX) \
|
||||
XX(OK, "OK") \
|
||||
XX(CONFIG_NOT_FOUND, "Configuration not found") \
|
||||
XX(NOT_AUTHORIZED, "Not Authorized") \
|
||||
XX(CONTROLLER_UNAVAILABLE, "Ziti Controller is not available") \
|
||||
XX(GATEWAY_UNAVAILABLE, "Ziti Gateway is not available") \
|
||||
XX(SERVICE_UNAVALABLE, "Service not available") \
|
||||
XX(EOF, "Connection closed") \
|
||||
XX(TIMEOUT, "Operation did not complete in time") \
|
||||
XX(CONNABORT, "Connection to gateway terminated") \
|
||||
XX(KEY_SPEC_UNSUPPORTED, "unsupported key specification") \
|
||||
XX(KEY_INVALID, "invalid key") \
|
||||
XX(WTF, "WTF: programming error")
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define ERR_ID(e, _) extern const int ZITI_##e;
|
||||
ZITI_ERRORS(ERR_ID)
|
||||
#undef ERR_ID
|
||||
|
||||
extern const char *ziti_errorstr(int err);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif //ZT_SDK_ERRORS_H
|
||||
@@ -0,0 +1,66 @@
|
||||
#ifndef NF_ZT_H
|
||||
#define NF_ZT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <inttypes.h>
|
||||
#include <uv.h>
|
||||
#include <uv_mbed/tls_engine.h>
|
||||
#include "errors.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct nf_ctx *nf_context;
|
||||
typedef struct nf_conn *nf_connection;
|
||||
|
||||
typedef void (*nf_init_cb)(nf_context nf_ctx, int status, void* init_ctx);
|
||||
typedef void (*nf_data_cb)(nf_connection conn, uint8_t *data, int length);
|
||||
typedef void (*nf_conn_cb)(nf_connection conn, int status);
|
||||
|
||||
typedef void (*nf_client_cb)(nf_connection serv, nf_connection client, int status);
|
||||
|
||||
typedef nf_conn_cb nf_listen_cb;
|
||||
|
||||
typedef void (*nf_write_cb)(nf_connection conn, ssize_t status, void *write_ctx);
|
||||
|
||||
extern int
|
||||
NF_init_with_tls(const char *ctrl_url, tls_context *tls_context, uv_loop_t *loop, nf_init_cb init_cb, void *init_ctx);
|
||||
extern int NF_init(const char* config, uv_loop_t* loop, nf_init_cb cb, void* init_ctx);
|
||||
|
||||
/*
|
||||
* set connect and write timeouts(in millis) on all connections created in this context.
|
||||
* changing value only affects future connections initialized via NF_conn_init()
|
||||
*/
|
||||
extern int NF_set_timeout(nf_context nf_ctx, int timeout);
|
||||
|
||||
extern int NF_shutdown(nf_context nf_ctx);
|
||||
extern int NF_free(nf_context *nf_ctx);
|
||||
extern void NF_dump(nf_context nf_ctx);
|
||||
|
||||
extern int NF_conn_init(nf_context nf_ctx, nf_connection *conn, void *data);
|
||||
|
||||
extern void *NF_conn_data(nf_connection conn);
|
||||
|
||||
extern int NF_service_available(nf_context nf_ctx, const char *service);
|
||||
|
||||
extern int NF_dial(nf_connection conn, const char *service, nf_conn_cb cb, nf_data_cb data_cb);
|
||||
|
||||
extern int NF_listen(nf_connection serv_conn, const char *service, nf_listen_cb lcb, nf_client_cb cb);
|
||||
|
||||
extern int NF_accept(nf_connection clt, nf_conn_cb cb, nf_data_cb data_cb);
|
||||
|
||||
extern int NF_close(nf_connection *conn);
|
||||
|
||||
/*
|
||||
* data buffer passed into this function should be intact until callback is called. It is only safe to free the buffer in
|
||||
* the write callback.
|
||||
*/
|
||||
extern int NF_write(nf_connection conn, uint8_t *data, size_t length, nf_write_cb, void *write_ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* NF_ZT_H */
|
||||
@@ -0,0 +1,65 @@
|
||||
add_library(ziti STATIC
|
||||
utils.c strutils.h
|
||||
ziti.c
|
||||
zt_auth.c
|
||||
config.c
|
||||
tls.c
|
||||
errors.c
|
||||
controller.c
|
||||
model.c
|
||||
connect.c
|
||||
channel.c
|
||||
message.c
|
||||
buffer.c
|
||||
p11/mbed_p11.c
|
||||
p11/p11_ecdsa.c
|
||||
p11/p11_rsa.c
|
||||
)
|
||||
|
||||
target_sources(ziti
|
||||
PRIVATE ${PROJECT_SOURCE_DIR}/deps/mjson/mjson.c
|
||||
PRIVATE ${PROJECT_SOURCE_DIR}/deps/http-parser/http_parser.c)
|
||||
|
||||
target_link_libraries(ziti
|
||||
PUBLIC uv_mbed
|
||||
)
|
||||
|
||||
target_include_directories(ziti
|
||||
PUBLIC ../includes
|
||||
PRIVATE ../inc_internal
|
||||
PRIVATE ${PROJECT_BINARY_DIR}/include
|
||||
PRIVATE ${PROJECT_SOURCE_DIR}/deps/mjson
|
||||
PUBLIC ${PROJECT_SOURCE_DIR}/deps/http-parser)
|
||||
|
||||
target_compile_definitions(ziti PUBLIC
|
||||
ZITI_BUILDNUM=${ZITI_BUILDNUM}
|
||||
BUILD_DATE=${BUILD_DATE}
|
||||
ZITI_VERSION=${PROJECT_VERSION}
|
||||
ZITI_BRANCH=${GIT_BRANCH}
|
||||
ZITI_COMMIT=${GIT_COMMIT_HASH})
|
||||
|
||||
if (WIN32)
|
||||
# on windows GDI defines ERROR which conflicts with the SDK declaration of DEBUG_LEVELS in utils.h
|
||||
target_compile_definitions(ziti PUBLIC NOGDI)
|
||||
endif()
|
||||
|
||||
set_property(TARGET ziti PROPERTY C_STANDARD 11)
|
||||
|
||||
set(includedir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR})
|
||||
set(libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR})
|
||||
set(prefix ${CMAKE_INSTALL_PREFIX})
|
||||
|
||||
configure_file(${PROJECT_SOURCE_DIR}/ziti.pc.in ${CMAKE_CURRENT_BINARY_DIR}/ziti.pc @ONLY)
|
||||
|
||||
set(CMAKE_INSTALL_DOCDIR share/doc)
|
||||
|
||||
install(TARGETS ziti DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
install(DIRECTORY ${CMAKE_SOURCE_DIR}/includes/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
|
||||
|
||||
install(FILES ${CMAKE_SOURCE_DIR}/deps/http-parser/LICENSE-MIT DESTINATION ${CMAKE_INSTALL_DOCDIR}/http-parser)
|
||||
install(FILES ${CMAKE_SOURCE_DIR}/deps/mjson/LICENSE DESTINATION ${CMAKE_INSTALL_DOCDIR}/mjson)
|
||||
install(FILES ${CMAKE_SOURCE_DIR}/deps/uv-mbed/mbedtls/LICENSE DESTINATION ${CMAKE_INSTALL_DOCDIR}/mbedtls)
|
||||
install(FILES ${CMAKE_SOURCE_DIR}/deps/uv-mbed/LICENSE DESTINATION ${CMAKE_INSTALL_DOCDIR}/uv_mbed)
|
||||
|
||||
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ziti.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//
|
||||
// Created by eugene on 3/22/19.
|
||||
//
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#if _WIN32
|
||||
#define MIN(a,b) min(a,b)
|
||||
#else
|
||||
#include <sys/param.h>
|
||||
#endif
|
||||
#include <sys/queue.h>
|
||||
|
||||
#include "buffer.h"
|
||||
|
||||
|
||||
/** incoming data chunk */
|
||||
typedef struct chunk_s {
|
||||
uint8_t *buf;
|
||||
int len;
|
||||
|
||||
STAILQ_ENTRY(chunk_s) next;
|
||||
} chunk_t;
|
||||
|
||||
struct buffer_s {
|
||||
STAILQ_HEAD(incoming, chunk_s) chunks;
|
||||
int head_offset;
|
||||
size_t available;
|
||||
};
|
||||
|
||||
|
||||
buffer *new_buffer() {
|
||||
buffer *b = malloc(sizeof(buffer));
|
||||
b->head_offset = 0;
|
||||
b->available = 0;
|
||||
STAILQ_INIT(&b->chunks);
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
void free_buffer(buffer* b) {
|
||||
free(b);
|
||||
}
|
||||
|
||||
void buffer_cleanup(buffer *b) {
|
||||
|
||||
if (STAILQ_EMPTY(&b->chunks)) {
|
||||
return;
|
||||
}
|
||||
|
||||
chunk_t *chunk = STAILQ_FIRST(&b->chunks);
|
||||
if (chunk->len == b->head_offset) {
|
||||
STAILQ_REMOVE_HEAD(&b->chunks, next);
|
||||
b->head_offset = 0;
|
||||
free(chunk->buf);
|
||||
free(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
int buffer_get_next(buffer* b, uint32_t want, uint8_t** ptr) {
|
||||
if (STAILQ_EMPTY(&b->chunks)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
chunk_t *chunk = STAILQ_FIRST(&b->chunks);
|
||||
if (chunk->len == b->head_offset) {
|
||||
STAILQ_REMOVE_HEAD(&b->chunks, next);
|
||||
b->head_offset = 0;
|
||||
free(chunk->buf);
|
||||
free(chunk);
|
||||
|
||||
if (STAILQ_EMPTY(&b->chunks)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
chunk = STAILQ_FIRST(&b->chunks);
|
||||
}
|
||||
int len = MIN(chunk->len - b->head_offset, want);
|
||||
*ptr = chunk->buf + b->head_offset;
|
||||
b->head_offset += len;
|
||||
b->available -= len;
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
void buffer_append(buffer* b, uint8_t *buf, uint32_t len) {
|
||||
chunk_t *e = malloc(sizeof(chunk_t));
|
||||
e->buf = buf;
|
||||
e->len = len;
|
||||
b->available += len;
|
||||
|
||||
STAILQ_INSERT_TAIL(&b->chunks, e, next);
|
||||
}
|
||||
|
||||
size_t buffer_available(buffer* b) {
|
||||
return b->available;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// Created by eugene on 3/22/19.
|
||||
//
|
||||
|
||||
#ifndef ZITI_SDK_BUFFER_H
|
||||
#define ZITI_SDK_BUFFER_H
|
||||
|
||||
typedef struct buffer_s buffer;
|
||||
|
||||
buffer *new_buffer();
|
||||
void free_buffer(buffer*);
|
||||
|
||||
void buffer_cleanup(buffer *);
|
||||
int buffer_get_next(buffer*, uint32_t want, uint8_t** ptr);
|
||||
void buffer_append(buffer*, uint8_t *buf, uint32_t len);
|
||||
size_t buffer_available(buffer*);
|
||||
|
||||
|
||||
#endif //ZITI_SDK_BUFFER_H
|
||||
@@ -0,0 +1,599 @@
|
||||
//
|
||||
// Created by eugene on 3/18/19.
|
||||
//
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <http_parser.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include "zt_internal.h"
|
||||
#include "utils.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <WinInet.h>
|
||||
#endif
|
||||
|
||||
#ifndef MAXHOSTNAMELEN
|
||||
#define MAXHOSTNAMELEN INTERNET_MAX_HOST_NAME_LENGTH
|
||||
#endif
|
||||
|
||||
static void on_channel_connect_internal(uv_connect_t *req, int status);
|
||||
|
||||
static void on_write(uv_write_t *req, int status);
|
||||
static void async_write(uv_async_t* ar);
|
||||
|
||||
struct async_write_req {
|
||||
uv_buf_t buf;
|
||||
ziti_channel_t *ch;
|
||||
};
|
||||
|
||||
struct waiter_s {
|
||||
int32_t seq;
|
||||
reply_cb cb;
|
||||
void *reply_ctx;
|
||||
|
||||
SLIST_ENTRY(waiter_s) next;
|
||||
};
|
||||
|
||||
struct ch_conn_req {
|
||||
ch_connect_cb cb;
|
||||
void *ctx;
|
||||
};
|
||||
|
||||
int ziti_channel_init(struct nf_ctx *ctx, ziti_channel_t *ch) {
|
||||
ch->ctx = ctx;
|
||||
ch->id = ctx->ch_counter++;
|
||||
ch->msg_seq = -1;
|
||||
ch->conn_seq = 0;
|
||||
|
||||
char hostname[MAXHOSTNAMELEN];
|
||||
size_t hostlen = sizeof(hostname);
|
||||
uv_os_gethostname(hostname, &hostlen);
|
||||
|
||||
snprintf(ch->token, sizeof(ch->token), "ziti-sdk-c[%d]@%*.*s", ch->id, (int) hostlen, (int) hostlen, hostname);
|
||||
|
||||
ch->state = Initial;
|
||||
// 32 concurrent connect requests for the same channel is probably enough
|
||||
ch->conn_reqs = calloc(32, sizeof(struct ch_conn_req *));
|
||||
ch->conn_reqs_n = 0;
|
||||
|
||||
ch->ingress = NULL;
|
||||
ch->in_next = NULL;
|
||||
ch->in_body_offset = 0;
|
||||
ch->incoming = new_buffer();
|
||||
|
||||
SLIST_INIT(&ch->connections);
|
||||
SLIST_INIT(&ch->waiters);
|
||||
|
||||
uv_mbed_init(ctx->loop, &ch->connection, ctx->tlsCtx);
|
||||
uv_mbed_keepalive(&ch->connection, true, 60);
|
||||
uv_mbed_nodelay(&ch->connection, true);
|
||||
ch->connection._stream.data = ch;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ziti_channel_free(ziti_channel_t* ch) {
|
||||
free(ch->conn_reqs);
|
||||
free_buffer(ch->incoming);
|
||||
free(ch->ingress);
|
||||
}
|
||||
|
||||
int ziti_close_channels(struct nf_ctx *ziti) {
|
||||
ziti_channel_t *ch;
|
||||
SLIST_FOREACH(ch, &ziti->channels, next) {
|
||||
ziti_channel_close(ch);
|
||||
}
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
void ziti_close_cb(uv_handle_t *h) {
|
||||
uv_mbed_t *mbed = (uv_mbed_t *) h;
|
||||
ziti_channel_t *ch = mbed->_stream.data;
|
||||
|
||||
uv_mbed_free(mbed);
|
||||
ziti_channel_free(ch);
|
||||
free(ch);
|
||||
}
|
||||
|
||||
int ziti_channel_close(ziti_channel_t *ch) {
|
||||
return uv_mbed_close(&ch->connection, ziti_close_cb);
|
||||
}
|
||||
|
||||
int ziti_channel_connect(nf_context ziti, const char *url, ch_connect_cb cb, void *cb_ctx) {
|
||||
ziti_channel_t *ch = NULL;
|
||||
SLIST_FOREACH(ch, &ziti->channels, next) {
|
||||
if (strcmp(url, ch->ingress) == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ch != NULL) {
|
||||
ZITI_LOG(DEBUG, "existing channel found for ingress[%s]", url);
|
||||
|
||||
if (ch->state == Connected) {
|
||||
cb(ch, cb_ctx, ZITI_OK);
|
||||
}
|
||||
else if (ch->state == Connecting || ch->state == Initial) {
|
||||
// not connected yet, add to the callbacks
|
||||
if (cb != NULL) {
|
||||
NEWP(r, struct ch_conn_req);
|
||||
r->cb = cb;
|
||||
r->ctx = cb_ctx;
|
||||
ch->conn_reqs[ch->conn_reqs_n++] = r;
|
||||
}
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(ERROR, "should not be here: %s", ziti_errorstr(ZITI_WTF));
|
||||
return ZITI_WTF;
|
||||
}
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
ch = calloc(1, sizeof(ziti_channel_t));
|
||||
ziti_channel_init(ziti, ch);
|
||||
ch->ingress = strdup(url);
|
||||
|
||||
ZITI_LOG(INFO, "opening new channel for ingress[%s] ch[%d]", url, ch->id);
|
||||
|
||||
struct http_parser_url ingress;
|
||||
http_parser_url_init(&ingress);
|
||||
http_parser_parse_url(url, strlen(url), 0, &ingress);
|
||||
|
||||
char host[128];
|
||||
int hostlen = ingress.field_data[UF_HOST].len;
|
||||
int hostoffset = ingress.field_data[UF_HOST].off;
|
||||
snprintf(host, sizeof(host), "%*.*s", hostlen, hostlen, url + hostoffset);
|
||||
|
||||
uv_connect_t *req = calloc(1, sizeof(uv_connect_t));
|
||||
req->data = ch;
|
||||
|
||||
if (cb != NULL) {
|
||||
NEWP(r, struct ch_conn_req);
|
||||
r->cb = cb;
|
||||
r->ctx = cb_ctx;
|
||||
ch->conn_reqs[ch->conn_reqs_n++] = r;
|
||||
}
|
||||
|
||||
ch->state = Connecting;
|
||||
|
||||
SLIST_INSERT_HEAD(&ch->ctx->channels, ch, next);
|
||||
|
||||
uv_mbed_connect(req, &ch->connection, host, ingress.port, on_channel_connect_internal);
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
void on_channel_send(uv_write_t *w, int status) {
|
||||
struct nf_write_req *nf_write = w->data;
|
||||
|
||||
if (nf_write != NULL) {
|
||||
free(nf_write->payload);
|
||||
on_write_completed(nf_write->conn, nf_write, status);
|
||||
}
|
||||
|
||||
free(w);
|
||||
}
|
||||
|
||||
int ziti_channel_send(ziti_channel_t *ch, uint32_t content, const hdr_t *hdrs, int nhdrs, const uint8_t *body,
|
||||
uint32_t body_len,
|
||||
struct nf_write_req *nf_write) {
|
||||
header_t header;
|
||||
header_init(&header, ch->msg_seq++);
|
||||
|
||||
ZITI_LOG(TRACE, "ch[%d]=> ct[%x] seq[%d] len[%d]", ch->id, content, header.seq, body_len);
|
||||
header.content = content;
|
||||
header.body_len = body_len;
|
||||
|
||||
uint32_t hdrs_len = 0;
|
||||
for (int i = 0; i < nhdrs; i++) {
|
||||
hdrs_len += sizeof(uint32_t) * 2 + hdrs[i].length; // header id + val(length) + length
|
||||
}
|
||||
header.headers_len = hdrs_len;
|
||||
|
||||
unsigned int msg_size = body_len + HEADER_SIZE + hdrs_len;
|
||||
uint8_t *msg_buf = malloc(msg_size);
|
||||
header_to_buffer(&header, msg_buf);
|
||||
|
||||
uint8_t *p = msg_buf + HEADER_SIZE;
|
||||
for (int i = 0; i < nhdrs; i++) {
|
||||
p = write_hdr(&hdrs[i], p);
|
||||
}
|
||||
assert(p == msg_buf + HEADER_SIZE + hdrs_len);
|
||||
memcpy(p, body, body_len);
|
||||
|
||||
uv_buf_t buf = uv_buf_init(msg_buf, msg_size);
|
||||
NEWP(req, uv_write_t);
|
||||
req->data = nf_write;
|
||||
nf_write->payload = msg_buf;
|
||||
return uv_mbed_write(req, &ch->connection, &buf, on_channel_send);
|
||||
}
|
||||
|
||||
int ziti_channel_send_for_reply(ziti_channel_t *ch, uint32_t content, const hdr_t *hdrs, int nhdrs, const uint8_t *body,
|
||||
uint32_t body_len,
|
||||
reply_cb rep_cb, void *reply_ctx) {
|
||||
header_t header;
|
||||
header_init(&header, ch->msg_seq++);
|
||||
|
||||
ZITI_LOG(TRACE, "ch[%d]=> ct[%x] seq[%d] len[%d]", ch->id, content, header.seq, body_len);
|
||||
header.content = content;
|
||||
header.body_len = body_len;
|
||||
|
||||
uint32_t hdrs_len = 0;
|
||||
for (int i = 0; i < nhdrs; i++) {
|
||||
hdrs_len += sizeof(uint32_t) * 2 + hdrs[i].length; // header id + val(length) + length
|
||||
}
|
||||
header.headers_len = hdrs_len;
|
||||
unsigned int msg_size = HEADER_SIZE + hdrs_len + body_len;
|
||||
uint8_t *msg_buf = malloc(msg_size);
|
||||
header_to_buffer(&header, msg_buf);
|
||||
|
||||
uint8_t *p = msg_buf + HEADER_SIZE;
|
||||
for (int i = 0; i < nhdrs; i++) {
|
||||
p = write_hdr(&hdrs[i], p);
|
||||
}
|
||||
assert(p == msg_buf + HEADER_SIZE + hdrs_len);
|
||||
|
||||
memcpy(p, body, body_len);
|
||||
|
||||
if (rep_cb != NULL) {
|
||||
NEWP(w, struct waiter_s);
|
||||
w->seq = header.seq;
|
||||
w->cb = rep_cb;
|
||||
w->reply_ctx = reply_ctx;
|
||||
|
||||
SLIST_INSERT_HEAD(&ch->waiters, w, next);
|
||||
}
|
||||
|
||||
NEWP(wr, struct async_write_req);
|
||||
wr->buf = uv_buf_init(msg_buf, msg_size);
|
||||
wr->ch = ch;
|
||||
|
||||
NEWP(async_req, uv_async_t);
|
||||
uv_async_init(ch->ctx->loop, async_req, async_write);
|
||||
async_req->data = wr;
|
||||
|
||||
// Guard against write requests coming on a thread different from our loop
|
||||
if (uv_thread_self() == ch->ctx->loop_thread) {
|
||||
async_write(async_req);
|
||||
}
|
||||
else {
|
||||
uv_async_send(async_req);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static struct nf_conn *find_conn(ziti_channel_t *ch, uint32_t conn_id) {
|
||||
struct nf_conn *c;
|
||||
SLIST_FOREACH(c, &ch->connections, next) {
|
||||
if (c->conn_id == conn_id) {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void process_edge_message(struct nf_conn *conn, message *msg) {
|
||||
int32_t seq;
|
||||
int32_t conn_id;
|
||||
bool has_seq = message_get_int32_header(msg, SeqHeader, &seq);
|
||||
bool has_conn_id = message_get_int32_header(msg, ConnIdHeader, &conn_id);
|
||||
|
||||
switch (msg->header.content) {
|
||||
case ContentTypeStateClosed:
|
||||
ZITI_LOG(TRACE, "conection status[%d] conn_id[%d] seq[%d]", msg->header.content, conn_id, seq);
|
||||
if (conn->state == Bound) {
|
||||
conn->client_cb(conn, NULL, ZITI_EOF);
|
||||
}
|
||||
else if (conn->state == Connected) {
|
||||
conn->data_cb(conn, NULL, ZITI_EOF);
|
||||
}
|
||||
conn->state = Closed;
|
||||
SLIST_REMOVE(&conn->channel->connections, conn, nf_conn, next);
|
||||
break;
|
||||
|
||||
case ContentTypeData:
|
||||
assert(conn->state == Connected);
|
||||
conn->data_cb(conn, msg->body, msg->header.body_len);
|
||||
break;
|
||||
|
||||
case ContentTypeDial:
|
||||
assert(conn->state == Bound);
|
||||
nf_connection clt;
|
||||
NF_conn_init(conn->nf_ctx, &clt, NULL);
|
||||
clt->state = Accepting;
|
||||
clt->parent = conn;
|
||||
clt->dial_req_seq = msg->header.seq;
|
||||
conn->client_cb(conn, clt, ZITI_OK);
|
||||
break;
|
||||
|
||||
default:
|
||||
ZITI_LOG(ERROR, "conection conn_id[%d] received unexpected content_type[%d]", conn_id, msg->header.content);
|
||||
}
|
||||
}
|
||||
|
||||
static bool is_edge(int32_t content) {
|
||||
switch (content) {
|
||||
case ContentTypeConnect:
|
||||
case ContentTypeStateConnected:
|
||||
case ContentTypeStateClosed:
|
||||
case ContentTypeData:
|
||||
case ContentTypeDial:
|
||||
case ContentTypeDialSuccess:
|
||||
case ContentTypeDialFailed:
|
||||
case ContentTypeBind:
|
||||
case ContentTypeUnbind:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
static void dispatch_message(ziti_channel_t *ch, message *m) {
|
||||
struct waiter_s *w = NULL;
|
||||
|
||||
m->nhdrs = parse_hdrs(m->headers, m->header.headers_len, &m->hdrs);
|
||||
|
||||
int32_t reply_to;
|
||||
bool is_reply = message_get_int32_header(m, ReplyForHeader, &reply_to);
|
||||
|
||||
if (is_reply) {
|
||||
SLIST_FOREACH(w, &ch->waiters, next) {
|
||||
if (w->seq == reply_to) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (w) {
|
||||
SLIST_REMOVE(&ch->waiters, w, waiter_s, next);
|
||||
ZITI_LOG(TRACE, "ch[%d] found waiter for [rep_to=%d]", ch->id, w->seq);
|
||||
|
||||
w->cb(w->reply_ctx, m);
|
||||
free(w);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_edge(m->header.content)) {
|
||||
int32_t conn_id;
|
||||
bool has_conn_id = message_get_int32_header(m, ConnIdHeader, &conn_id);
|
||||
|
||||
if (!has_conn_id) {
|
||||
ZITI_LOG(ERROR, "ch[%d] received message without conn_id ct[%d]", ch->id, m->header.content);
|
||||
}
|
||||
else {
|
||||
struct nf_conn *conn = find_conn(ch, conn_id);
|
||||
if (conn == NULL) {
|
||||
ZITI_LOG(ERROR, "ch[%d] received message for unknown connection conn_id[%d] ct[%d]",
|
||||
ch->id, conn_id, m->header.content);
|
||||
}
|
||||
else {
|
||||
process_edge_message(conn, m);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(WARN, "ch[%d] unsupported content type [%d]", ch->id, m->header.content);
|
||||
}
|
||||
}
|
||||
|
||||
static void process_inbound(ziti_channel_t *ch) {
|
||||
uint8_t *ptr;
|
||||
int len;
|
||||
do {
|
||||
if (ch->in_next == NULL) {
|
||||
if (buffer_available(ch->incoming) < HEADER_SIZE) {
|
||||
ZITI_LOG(TRACE, "not enough data in buffer for complete header");
|
||||
break;
|
||||
}
|
||||
|
||||
uint8_t header_buf[HEADER_SIZE];
|
||||
int header_read = 0;
|
||||
|
||||
while(header_read < HEADER_SIZE) {
|
||||
len = buffer_get_next(ch->incoming, HEADER_SIZE - header_read, &ptr);
|
||||
memcpy(header_buf + header_read, ptr, len);
|
||||
header_read += len;
|
||||
}
|
||||
|
||||
assert(header_read == HEADER_SIZE);
|
||||
|
||||
ch->in_next = malloc(sizeof(message));
|
||||
message_init(ch->in_next);
|
||||
|
||||
header_from_buffer(&ch->in_next->header, header_buf);
|
||||
|
||||
// allocate single memory block for both headers and body
|
||||
// body ptr will point to inside the block
|
||||
ch->in_next->headers = malloc(ch->in_next->header.headers_len + ch->in_next->header.body_len);
|
||||
ch->in_next->body = ch->in_next->headers + ch->in_next->header.headers_len;
|
||||
|
||||
ch->in_body_offset = 0;
|
||||
|
||||
ZITI_LOG(TRACE, "ch[%d] <= ct[%x] seq[%d] len[%d] hdrs[%d]", ch->id, ch->in_next->header.content,
|
||||
ch->in_next->header.seq,
|
||||
ch->in_next->header.body_len, ch->in_next->header.headers_len);
|
||||
}
|
||||
|
||||
// to complete the message need to read headers_len + body_len - (whatever was read already)
|
||||
uint32_t total = ch->in_next->header.body_len + ch->in_next->header.headers_len;
|
||||
uint32_t want = total - ch->in_body_offset;
|
||||
len = buffer_get_next(ch->incoming, want, &ptr);
|
||||
ZITI_LOG(TRACE, "ch[%d] completing msg seq[%d] body+hrds=%d+%d, in_offset=%d, want=%d, got=%d",
|
||||
ch->id, ch->in_next->header.seq,
|
||||
ch->in_next->header.body_len, ch->in_next->header.headers_len, ch->in_body_offset, want, len);
|
||||
|
||||
if (len == -1) {
|
||||
break;
|
||||
}
|
||||
if (len > 0) {
|
||||
memcpy(ch->in_next->headers + ch->in_body_offset, ptr, (size_t) len);
|
||||
ch->in_body_offset += len;
|
||||
|
||||
if (ch->in_body_offset == total) {
|
||||
ZITI_LOG(TRACE, "ch[%d] message is complete seq[%d]", ch->id, ch->in_next->header.seq);
|
||||
|
||||
dispatch_message(ch, ch->in_next);
|
||||
|
||||
message_free(ch->in_next);
|
||||
free(ch->in_next);
|
||||
ch->in_next = NULL;
|
||||
}
|
||||
}
|
||||
} while (1);
|
||||
|
||||
buffer_cleanup(ch->incoming);
|
||||
}
|
||||
|
||||
static void hello_reply_cb(void *ctx, message *msg) {
|
||||
|
||||
assert (msg->header.content == ContentTypeResultType);
|
||||
|
||||
bool success;
|
||||
bool found = message_get_bool_header(msg, ResultSuccessHeader, &success);
|
||||
assert(found);
|
||||
|
||||
hdr_t *headers;
|
||||
int nhdrs = parse_hdrs(msg->headers, msg->header.headers_len, &headers);
|
||||
|
||||
for (int i = 0; i < nhdrs; i++) {
|
||||
ZITI_LOG(TRACE, "hdr[%d] id[%d], len[%d]", i, headers[i].header_id, headers[i].length);
|
||||
}
|
||||
ziti_channel_t *ch = ctx;
|
||||
|
||||
int cb_code = ZITI_OK;
|
||||
if (success) {
|
||||
ZITI_LOG(TRACE, "channel[%d] connected: %d", ch->id, success);
|
||||
ch->state = Connected;
|
||||
} else {
|
||||
ZITI_LOG(ERROR, "channel[%d] connect rejected: %d %*s", ch->id, success, msg->header.body_len, msg->body);
|
||||
ch->state = Closed;
|
||||
cb_code = ZITI_GATEWAY_UNAVAILABLE;
|
||||
}
|
||||
|
||||
for (int i = 0; i < ch->conn_reqs_n; i++) {
|
||||
struct ch_conn_req *r = ch->conn_reqs[i];
|
||||
r->cb(ch, r->ctx, cb_code);
|
||||
free(r);
|
||||
}
|
||||
ch->conn_reqs_n = 0;
|
||||
}
|
||||
|
||||
static void send_hello(ziti_channel_t *ch) {
|
||||
hdr_t headers[] = {
|
||||
{
|
||||
.header_id = SessionTokenHeader,
|
||||
.length = strlen(ch->ctx->ziti_session),
|
||||
.value = ch->ctx->ziti_session
|
||||
}
|
||||
};
|
||||
|
||||
ziti_channel_send_for_reply(ch, ContentTypeHelloType, headers, 1, ch->token, strlen(ch->token), hello_reply_cb, ch);
|
||||
}
|
||||
|
||||
static void async_write(uv_async_t* ar) {
|
||||
|
||||
struct async_write_req *wr = ar->data;
|
||||
|
||||
NEWP(req, uv_write_t);
|
||||
req->data = wr;
|
||||
uv_mbed_write(req, &wr->ch->connection, &wr->buf, on_write);
|
||||
|
||||
uv_close((uv_handle_t *) ar, (uv_close_cb) free);
|
||||
}
|
||||
|
||||
static void on_channel_close(ziti_channel_t *ch, ssize_t code) {
|
||||
nf_context nf = ch->ctx;
|
||||
if (!SLIST_EMPTY(&nf->channels)) {
|
||||
SLIST_REMOVE(&nf->channels, ch, ziti_channel, next);
|
||||
}
|
||||
|
||||
nf_connection con;
|
||||
SLIST_FOREACH(con, &ch->connections, next) {
|
||||
if (con->state == Connected) {
|
||||
con->state = Closed;
|
||||
con->data_cb(con, NULL, code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void on_write(uv_write_t *req, int status) {
|
||||
struct async_write_req *wr = req->data;
|
||||
|
||||
if (status < 0) {
|
||||
ZITI_LOG(ERROR, "ch[%d] write failed [status=%d] %s", wr->ch->id, status, uv_strerror(status));
|
||||
uv_mbed_t *mbed = (uv_mbed_t *) req->handle;
|
||||
ziti_channel_t *ch = uv_handle_get_data((const uv_handle_t *) mbed);
|
||||
on_channel_close(ch, status);
|
||||
|
||||
} else {
|
||||
// ZITI_LOG(TRACE, "write completed [status=%d]", status);
|
||||
}
|
||||
|
||||
if (wr != NULL) {
|
||||
FREE(wr->buf.base);
|
||||
FREE(wr);
|
||||
}
|
||||
FREE(req);
|
||||
}
|
||||
|
||||
static void on_channel_data(uv_stream_t *s, ssize_t len, const uv_buf_t *buf) {
|
||||
uv_mbed_t *mbed = (uv_mbed_t *) s;
|
||||
ziti_channel_t *ch = mbed->_stream.data;
|
||||
|
||||
if (len < 0) {
|
||||
free(buf->base);
|
||||
switch (len) {
|
||||
case UV_EOF:
|
||||
case UV_ECONNRESET:
|
||||
case UV_ECONNABORTED:
|
||||
case UV_ECONNREFUSED:
|
||||
case UV_EPIPE:
|
||||
ZITI_LOG(INFO, "channel was closed: %d(%s)", (int) len, uv_strerror((int) len));
|
||||
// propagate close
|
||||
on_channel_close(ch, ZITI_EOF);
|
||||
break;
|
||||
|
||||
case MBEDTLS_ERR_SSL_WANT_READ:
|
||||
ZITI_LOG(DEBUG, "on_channel_data() rc+%zd(%s)", len, fmt_mbederr(len));
|
||||
return;
|
||||
|
||||
default:
|
||||
ZITI_LOG(ERROR, "unhandled error on_data rc=%zd (%s)", len, uv_strerror(len));
|
||||
on_channel_close(ch, len);
|
||||
|
||||
}
|
||||
}
|
||||
else if (len == 0) {
|
||||
// sometimes SSL message has no payload
|
||||
free(buf->base);
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(TRACE, "ch[%d] on_data [len=%zd]", ch->id, len);
|
||||
if (len > 0) {
|
||||
buffer_append(ch->incoming, buf->base, (uint32_t) len);
|
||||
process_inbound(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void on_channel_connect_internal(uv_connect_t *req, int status) {
|
||||
ziti_channel_t *ch = req->data;
|
||||
|
||||
if (status == 0) {
|
||||
ZITI_LOG(DEBUG, "ch[%d] connected", ch->id);
|
||||
uv_mbed_t *mbed = (uv_mbed_t *) req->handle;
|
||||
uv_mbed_read(mbed, ziti_alloc_cb, on_channel_data);
|
||||
send_hello(ch);
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(ERROR, "ch[%d] failed to connect[%s] [status=%d]", ch->id, ch->ingress, status);
|
||||
|
||||
for (int i = 0; i < ch->conn_reqs_n; i++) {
|
||||
struct ch_conn_req *r = ch->conn_reqs[i];
|
||||
r->cb(ch, r->ctx, status);
|
||||
free(r);
|
||||
ch->conn_reqs[i] = NULL;
|
||||
}
|
||||
ch->conn_reqs_n = 0;
|
||||
}
|
||||
free(req);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//
|
||||
// Created by eugene on 2/27/19.
|
||||
//
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/stat.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <utils.h>
|
||||
#include "zt_internal.h"
|
||||
|
||||
const char* ZITI_SDK_CONFIG = "ZITI_SDK_CONFIG";
|
||||
|
||||
int load_config_file(const char *filename, nf_config **cfg) {
|
||||
struct stat stats;
|
||||
int s = stat(filename, &stats);
|
||||
if (s == -1) {
|
||||
ZITI_LOG(ERROR, "%s - %s", filename, strerror(errno));
|
||||
return ZITI_CONFIG_NOT_FOUND;
|
||||
}
|
||||
|
||||
FILE* file = fopen(filename, "r");
|
||||
|
||||
size_t config_len = (size_t) stats.st_size;
|
||||
char * config = malloc(config_len);
|
||||
size_t rc;
|
||||
if ((rc = fread(config, 1, config_len, file)) != config_len) {
|
||||
ZITI_LOG(WARN, "failed to read config in full [%zd/%zd]: %s(%d)", rc, config_len, strerror(errno), errno);
|
||||
}
|
||||
fclose(file);
|
||||
|
||||
*cfg = parse_nf_config(config, config_len);
|
||||
|
||||
free(config);
|
||||
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int load_config(const char *filename, nf_config **cfg) {
|
||||
if (filename != NULL) {
|
||||
return load_config_file(filename, cfg);
|
||||
}
|
||||
|
||||
char *fn = getenv(ZITI_SDK_CONFIG);
|
||||
if (fn != NULL) {
|
||||
return load_config_file(fn, cfg);
|
||||
}
|
||||
|
||||
char def[1024];
|
||||
sprintf(def, "%s/.netfoundry/ziti/id.json", getenv("HOME"));
|
||||
return load_config_file(def, cfg);
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
//
|
||||
// Created by eugene on 3/8/19.
|
||||
//
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include "zt_internal.h"
|
||||
#include "utils.h"
|
||||
#include "endian_internal.h"
|
||||
|
||||
struct nf_conn_req {
|
||||
struct nf_conn *conn;
|
||||
char *service_id;
|
||||
ziti_channel_t *channel;
|
||||
nf_conn_cb cb;
|
||||
|
||||
uv_timer_t *t;
|
||||
};
|
||||
|
||||
int ziti_channel_start_connection(struct nf_conn_req *req);
|
||||
|
||||
static void free_handle(uv_handle_t *h) {
|
||||
free(h);
|
||||
}
|
||||
|
||||
void on_write_completed(struct nf_conn *conn, struct nf_write_req *req, int status) {
|
||||
if (req->conn == NULL) {
|
||||
ZITI_LOG(WARN, "write completed for timed out connection");
|
||||
free(req);
|
||||
return;
|
||||
}
|
||||
conn->write_reqs--;
|
||||
|
||||
if (status < 0) {
|
||||
conn->state = Closed;
|
||||
SLIST_REMOVE(&conn->channel->connections, conn, nf_conn, next);
|
||||
}
|
||||
|
||||
if (req->timeout != NULL) {
|
||||
uv_timer_stop(req->timeout);
|
||||
uv_close((uv_handle_t *) req->timeout, free_handle);
|
||||
}
|
||||
|
||||
if (req->cb != NULL) {
|
||||
if (status == 0) {
|
||||
status = req->len;
|
||||
}
|
||||
req->cb(conn, status, req->ctx);
|
||||
}
|
||||
|
||||
if (conn->state == Closed && conn->write_reqs == 0) {
|
||||
free(conn);
|
||||
}
|
||||
free(req);
|
||||
}
|
||||
|
||||
static int send_message(struct nf_conn *conn, uint32_t content, uint8_t *body, uint32_t body_len, struct nf_write_req *wr) {
|
||||
ziti_channel_t *ch = conn->channel;
|
||||
int32_t conn_id = htole32(conn->conn_id);
|
||||
int32_t msg_seq = htole32(conn->edge_msg_seq++);
|
||||
hdr_t headers[] = {
|
||||
{
|
||||
.header_id = ConnIdHeader,
|
||||
.length = sizeof(conn_id),
|
||||
.value = (uint8_t *) &conn_id
|
||||
},
|
||||
{
|
||||
.header_id = SeqHeader,
|
||||
.length = sizeof(msg_seq),
|
||||
.value = (uint8_t *) &msg_seq
|
||||
}
|
||||
};
|
||||
return ziti_channel_send(ch, content, headers, 2, body, body_len, wr);
|
||||
}
|
||||
|
||||
static void on_channel_connected(ziti_channel_t *ch, void *ctx, int status) {
|
||||
|
||||
struct nf_conn_req * req = ctx;
|
||||
if (status < 0) {
|
||||
ZITI_LOG(ERROR, "ch[%d] failed to connect status[%d](%s)", ch->id, status, uv_strerror(status));
|
||||
req->cb(req->conn, ZITI_GATEWAY_UNAVAILABLE);
|
||||
}
|
||||
else if (req->conn->channel == NULL) { // first channel to connect
|
||||
ZITI_LOG(TRACE, "channel connected status[%d]", status);
|
||||
|
||||
req->conn->edge_msg_seq = 1;
|
||||
|
||||
req->channel = ch;
|
||||
req->conn->channel = ch;
|
||||
ziti_channel_start_connection(req);
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(TRACE, "conn[%d] is already using another channel", req->conn->conn_id);
|
||||
// nothing to do here
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static void connect_timeout(uv_timer_t *timer) {
|
||||
struct nf_conn_req *req = timer->data;
|
||||
struct nf_conn *conn = req->conn;
|
||||
|
||||
if (conn->state == Connecting) {
|
||||
ZITI_LOG(WARN, "ziti connection timed out");
|
||||
conn->state = Closed;
|
||||
req->cb(conn, ZITI_TIMEOUT);
|
||||
}
|
||||
|
||||
uv_timer_stop(timer);
|
||||
uv_close((uv_handle_t *) timer, free_handle);
|
||||
}
|
||||
|
||||
static int ziti_connect(struct nf_ctx *ctx, const ziti_net_session *session, struct nf_conn_req *req) {
|
||||
struct nf_conn *conn = req->conn;
|
||||
conn->token = session->token;
|
||||
|
||||
ziti_gateway **gw;
|
||||
for (gw = session->gateways; *gw != NULL; gw++) {
|
||||
ZITI_LOG(TRACE, "connecting to %s(%s) for session[%s]", (*gw)->name, (*gw)->url_tls, conn->token);
|
||||
ziti_channel_connect(ctx, (*gw)->url_tls, on_channel_connected, req);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ziti_connect_async(uv_async_t *ar) {
|
||||
struct nf_conn_req *req = ar->data;
|
||||
struct nf_ctx *ctx = req->conn->nf_ctx;
|
||||
|
||||
req->t = malloc(sizeof(uv_timer_t));
|
||||
uv_timer_init(ar->loop, req->t);
|
||||
req->t->data = req;
|
||||
uv_timer_start(req->t, connect_timeout, req->conn->timeout, 0);
|
||||
|
||||
uv_close((uv_handle_t *) ar, free_handle);
|
||||
|
||||
// find service
|
||||
const ziti_net_session *net_session = NULL;
|
||||
const char *service_id;
|
||||
for (ziti_service **s = ctx->services; *s != NULL; s++) {
|
||||
if (strcmp(req->service_id, (*s)->name) == 0) {
|
||||
service_id = (*s)->id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for(ziti_net_session **ns = ctx->net_sessions; *ns != NULL; ns++) {
|
||||
if (strcmp(service_id, (*ns)->service_id) == 0) {
|
||||
net_session = (*ns);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//at this point the service_id allocated in ziti_dial is no longer needed - free it
|
||||
free(req->service_id);
|
||||
req->service_id = NULL;
|
||||
|
||||
if (net_session == NULL) {
|
||||
req->cb(req->conn, ZITI_SERVICE_UNAVALABLE);
|
||||
}
|
||||
else {
|
||||
ziti_connect(ctx, net_session, req);
|
||||
}
|
||||
}
|
||||
|
||||
int ziti_dial(nf_connection conn, const char *service, nf_conn_cb conn_cb, nf_data_cb data_cb) {
|
||||
NEWP(req, struct nf_conn_req);
|
||||
|
||||
//duplicate the service name in case the callee reclaims the memory
|
||||
//this string is free'd in ziti_connect_async
|
||||
req->service_id = strdup(service);
|
||||
req->conn = conn;
|
||||
req->cb = conn_cb;
|
||||
|
||||
conn->data_cb = data_cb;
|
||||
conn->state = Connecting;
|
||||
|
||||
NEWP(async_cr, uv_async_t);
|
||||
uv_async_init(conn->nf_ctx->loop, async_cr, ziti_connect_async);
|
||||
|
||||
async_cr->data = req;
|
||||
|
||||
return uv_async_send(async_cr);
|
||||
}
|
||||
|
||||
static void ziti_write_timeout(uv_timer_t *t) {
|
||||
struct nf_write_req *req = t->data;
|
||||
struct nf_conn *conn = req->conn;
|
||||
struct ziti_channel *ch = conn->channel;
|
||||
|
||||
conn->write_reqs--;
|
||||
req->timeout = NULL;
|
||||
req->conn = NULL;
|
||||
|
||||
if (conn->state != Closed) {
|
||||
conn->state = Closed;
|
||||
req->cb(conn, ZITI_TIMEOUT, req->ctx);
|
||||
SLIST_REMOVE(&ch->connections, conn, nf_conn, next);
|
||||
}
|
||||
|
||||
if (conn->write_reqs == 0) {
|
||||
free(conn);
|
||||
}
|
||||
|
||||
uv_close((uv_handle_t *) t, free_handle);
|
||||
}
|
||||
|
||||
static void ziti_write_async(uv_async_t *ar) {
|
||||
struct nf_write_req *req = ar->data;
|
||||
struct nf_conn *conn = req->conn;
|
||||
|
||||
conn->write_reqs++;
|
||||
|
||||
if (req->cb) {
|
||||
req->timeout = calloc(1, sizeof(uv_timer_t));
|
||||
uv_timer_init(ar->loop, req->timeout);
|
||||
req->timeout->data = req;
|
||||
uv_timer_start(req->timeout, ziti_write_timeout, conn->timeout, 0);
|
||||
}
|
||||
|
||||
send_message(conn, ContentTypeData, req->buf, req->len, req);
|
||||
|
||||
uv_close((uv_handle_t *) ar, free_handle);
|
||||
}
|
||||
|
||||
int ziti_write(struct nf_write_req *req) {
|
||||
NEWP(ar, uv_async_t);
|
||||
uv_async_init(req->conn->nf_ctx->loop, ar, ziti_write_async);
|
||||
ar->data = req;
|
||||
return uv_async_send(ar);
|
||||
}
|
||||
|
||||
static void ziti_disconnect_async(uv_async_t *ar) {
|
||||
struct nf_conn *conn = ar->data;
|
||||
|
||||
uv_close((uv_handle_t *) ar, free_handle);
|
||||
|
||||
if (conn->state == Connected) {
|
||||
NEWP(wr, struct nf_write_req);
|
||||
send_message(conn, ContentTypeStateClosed, NULL, 0, wr);
|
||||
}
|
||||
}
|
||||
|
||||
int ziti_disconnect(struct nf_conn *conn) {
|
||||
NEWP(ar, uv_async_t);
|
||||
uv_async_init(conn->channel->ctx->loop, ar, ziti_disconnect_async);
|
||||
ar->data = conn;
|
||||
return uv_async_send(ar);
|
||||
}
|
||||
|
||||
void connect_reply_cb(void *ctx, message *msg) {
|
||||
struct nf_conn_req* req = ctx;
|
||||
struct nf_conn *conn = req->conn;
|
||||
|
||||
if (req->t != NULL) {
|
||||
uv_timer_stop(req->t);
|
||||
uv_close((uv_handle_t *) req->t, free_handle);
|
||||
req->t = NULL;
|
||||
}
|
||||
|
||||
switch (msg->header.content) {
|
||||
case ContentTypeStateClosed:
|
||||
ZITI_LOG(ERROR, "edge conn_id[%d]: failed to %s, reason=%*s",
|
||||
conn->conn_id, conn->state == Binding ? "bind" : "connect",
|
||||
msg->header.body_len, msg->body);
|
||||
conn->state = Closed;
|
||||
req->cb(conn, ZITI_EOF);
|
||||
SLIST_REMOVE(&req->channel->connections, conn, nf_conn, next);
|
||||
break;
|
||||
|
||||
case ContentTypeStateConnected:
|
||||
if (conn->state == Connecting) {
|
||||
ZITI_LOG(TRACE, "edge conn_id[%d]: connected.", conn->conn_id);
|
||||
conn->state = Connected;
|
||||
}
|
||||
else if (conn->state == Binding) {
|
||||
ZITI_LOG(TRACE, "edge conn_id[%d]: bound.", conn->conn_id);
|
||||
conn->state = Bound;
|
||||
}
|
||||
else if (conn->state == Accepting) {
|
||||
ZITI_LOG(TRACE, "edge conn_id[%d]: accepted.", conn->conn_id);
|
||||
conn->state = Connected;
|
||||
}
|
||||
else if (conn->state == Closed) {
|
||||
ZITI_LOG(WARN, "received connect reply for closed connection[%d]. timeout?", conn->conn_id);
|
||||
ziti_disconnect(conn);
|
||||
SLIST_REMOVE(&conn->channel->connections, conn, nf_conn, next);
|
||||
}
|
||||
req->cb(conn, ZITI_OK);
|
||||
break;
|
||||
|
||||
default:
|
||||
ZITI_LOG(WARN, "unexpected content_type[%d] conn_id[%d]", msg->header.content, conn->conn_id);
|
||||
ziti_disconnect(conn);
|
||||
SLIST_REMOVE(&conn->channel->connections, conn, nf_conn, next);
|
||||
}
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
int ziti_channel_start_connection(struct nf_conn_req *req) {
|
||||
ziti_channel_t *ch = req->channel;
|
||||
|
||||
req->conn->channel = ch;
|
||||
req->conn->conn_id = ch->conn_seq++;
|
||||
|
||||
SLIST_INSERT_HEAD(&ch->connections, req->conn, next);
|
||||
|
||||
ZITI_LOG(TRACE, "ch[%d] => Edge Connect request token[%s] conn_id[%d]", ch->id, req->conn->token,
|
||||
req->conn->conn_id);
|
||||
|
||||
uint32_t content_type;
|
||||
switch (req->conn->state) {
|
||||
case Binding:
|
||||
content_type = ContentTypeBind;
|
||||
break;
|
||||
case Connecting:
|
||||
content_type = ContentTypeConnect;
|
||||
break;
|
||||
default:
|
||||
ZITI_LOG(ERROR, "connection[%d] is in unexpected state[%d]", req->conn->conn_id, req->conn->state);
|
||||
return ZITI_WTF;
|
||||
}
|
||||
int32_t conn_id = htole32(req->conn->conn_id);
|
||||
int32_t msg_seq = htole32(0);
|
||||
hdr_t headers[] = {
|
||||
{
|
||||
.header_id = ConnIdHeader,
|
||||
.length = sizeof(conn_id),
|
||||
.value = (uint8_t *) &conn_id
|
||||
},
|
||||
{
|
||||
.header_id = SeqHeader,
|
||||
.length = sizeof(msg_seq),
|
||||
.value = (uint8_t *) &msg_seq
|
||||
}
|
||||
};
|
||||
ziti_channel_send_for_reply(ch, content_type, headers, 2, req->conn->token, strlen(req->conn->token),
|
||||
connect_reply_cb, req);
|
||||
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int ziti_bind(nf_connection conn, const char *service, nf_listen_cb listen_cb, nf_client_cb on_clt_cb) {
|
||||
NEWP(req, struct nf_conn_req);
|
||||
|
||||
//duplicate the service name in case the callee reclaims the memory
|
||||
//this string is free'd in ziti_connect_async
|
||||
req->service_id = strdup(service);
|
||||
req->conn = conn;
|
||||
req->cb = listen_cb;
|
||||
|
||||
conn->client_cb = on_clt_cb;
|
||||
conn->state = Binding;
|
||||
|
||||
NEWP(async_cr, uv_async_t);
|
||||
uv_async_init(conn->nf_ctx->loop, async_cr, ziti_connect_async);
|
||||
async_cr->data = req;
|
||||
return uv_async_send(async_cr);
|
||||
|
||||
}
|
||||
|
||||
int ziti_accept(nf_connection conn, nf_conn_cb cb, nf_data_cb data_cb) {
|
||||
|
||||
ziti_channel_t *ch = conn->parent->channel;
|
||||
|
||||
conn->channel = ch;
|
||||
conn->conn_id = ch->conn_seq++;
|
||||
conn->data_cb = data_cb;
|
||||
|
||||
SLIST_INSERT_HEAD(&ch->connections, conn, next);
|
||||
|
||||
ZITI_LOG(TRACE, "ch[%d] => Edge Accept conn_id[%d] parent_conn_id[%d]", ch->id, conn->conn_id,
|
||||
conn->parent->conn_id);
|
||||
|
||||
uint32_t content_type = ContentTypeDialSuccess;
|
||||
|
||||
int32_t conn_id = htole32(conn->parent->conn_id);
|
||||
int32_t msg_seq = htole32(0);
|
||||
int32_t reply_id = htole32(conn->dial_req_seq);
|
||||
int32_t clt_conn_id = htole32(conn->conn_id);
|
||||
hdr_t headers[] = {
|
||||
{
|
||||
.header_id = ConnIdHeader,
|
||||
.length = sizeof(conn_id),
|
||||
.value = (uint8_t *) &conn_id
|
||||
},
|
||||
{
|
||||
.header_id = SeqHeader,
|
||||
.length = sizeof(msg_seq),
|
||||
.value = (uint8_t *) &msg_seq
|
||||
},
|
||||
{
|
||||
.header_id = ReplyForHeader,
|
||||
.length = sizeof(reply_id),
|
||||
.value = (uint8_t *) &reply_id
|
||||
},
|
||||
};
|
||||
NEWP(req, struct nf_conn_req);
|
||||
req->channel = conn->channel;
|
||||
req->conn = conn;
|
||||
req->cb = cb;
|
||||
ziti_channel_send_for_reply(ch, content_type, headers, 3, (const uint8_t *) &clt_conn_id, sizeof(clt_conn_id),
|
||||
connect_reply_cb, req);
|
||||
|
||||
return ZITI_OK;
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
//
|
||||
// Created by eugene on 3/1/19.
|
||||
//
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <http_parser.h>
|
||||
#include <mjson.h>
|
||||
#include "controller.h"
|
||||
#include "utils.h"
|
||||
#include "zt_internal.h"
|
||||
#include "strutils.h"
|
||||
#include "model.h"
|
||||
|
||||
#if _WIN32
|
||||
#define _WINSOCK_DEPRECATED_NO_WARNINGS
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#define SOCKET int //differences tween windows and posix
|
||||
#endif
|
||||
|
||||
const static char REQ_HTTP[] = "%s %s HTTP/1.1\r\n"
|
||||
"Host: %s\r\n"
|
||||
"Accept: application/json\r\n"
|
||||
"Content-Type: %s\r\n"
|
||||
"Content-Length: %zd\r\n"
|
||||
"%s"
|
||||
"\r\n"
|
||||
;
|
||||
|
||||
struct controller_resp {
|
||||
uint status;
|
||||
char* msg;
|
||||
int complete;
|
||||
size_t body_len;
|
||||
uint8_t *body;
|
||||
};
|
||||
|
||||
void free_resp(struct controller_resp *r) {
|
||||
free(r->msg);
|
||||
free(r->body);
|
||||
}
|
||||
|
||||
int status_cb(http_parser* p, const char* d, size_t len) {
|
||||
struct controller_resp *resp = p->data;
|
||||
resp->status = p->status_code;
|
||||
resp->msg = zitistrndup(d, len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int body_cb(http_parser* p, const char* b, size_t body_len) {
|
||||
struct controller_resp *resp = p->data;
|
||||
if (resp->body == NULL) {
|
||||
resp->body = malloc(body_len);
|
||||
resp->body_len = body_len;
|
||||
memcpy(resp->body, b, resp->body_len);
|
||||
} else {
|
||||
size_t len = resp->body_len;
|
||||
resp->body_len += body_len;
|
||||
resp->body = realloc(resp->body, resp->body_len);
|
||||
memcpy(resp->body + len, b, body_len);
|
||||
}
|
||||
resp->complete = http_body_is_final(p);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int headers_cb(http_parser* p) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int msg_complete(http_parser* p) {
|
||||
struct controller_resp *resp = p->data;
|
||||
resp->complete = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static struct http_parser_settings HTTP_SETTINGS = {
|
||||
NULL, // on_message_begine
|
||||
NULL, // on_url
|
||||
status_cb, // on_status
|
||||
NULL, // on_header_field
|
||||
NULL, // on_header_value
|
||||
headers_cb, // on_headers_complete
|
||||
body_cb, // on_body
|
||||
msg_complete, // on_message_complete
|
||||
// chunk_header_cb,
|
||||
// chunk_complete_cb,
|
||||
|
||||
};
|
||||
|
||||
static int ziti_controller_req(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl,
|
||||
const char *method, const char *path,
|
||||
const char *conttype, const unsigned char *content, size_t content_len,
|
||||
struct controller_resp *resp);
|
||||
|
||||
static bool is_ip(const char* hostname);
|
||||
|
||||
int ziti_ctrl_logout(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl) {
|
||||
if (ssl == NULL) {
|
||||
return ziti_ctrl_process(ctx, ziti_ctrl_logout, NULL);
|
||||
}
|
||||
|
||||
struct controller_resp resp;
|
||||
memset(&resp, 0, sizeof(struct controller_resp));
|
||||
ziti_controller_req(ctx, ctrl, ssl, "DELETE", "/current-session", NULL, NULL, 0, &resp);
|
||||
if (ctx->ziti_session != NULL) {
|
||||
free(ctx->ziti_session);
|
||||
ctx->ziti_session = NULL;
|
||||
}
|
||||
free_resp(&resp);
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int ziti_ctrl_version(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl) {
|
||||
|
||||
if (ssl == NULL) {
|
||||
return ziti_ctrl_process(ctx, ziti_ctrl_login, NULL);
|
||||
}
|
||||
|
||||
struct controller_resp resp;
|
||||
memset(&resp, 0, sizeof(struct controller_resp));
|
||||
ziti_controller_req(ctx, ctrl, ssl, "GET", "/version", "application/json", "", 0, &resp);
|
||||
|
||||
if (resp.status == 200) {
|
||||
const char *s;
|
||||
int len;
|
||||
if (mjson_find(resp.body, (int) resp.body_len, "$.data", &s, &len) == MJSON_TOK_OBJECT) {
|
||||
ctrl_version *v = parse_ctrl_version(s, len);
|
||||
ZITI_LOG(INFO, "connected to controller %s:%d version %s(%s %s)", ctx->controller, ctx->controller_port, v->version, v->revision, v->build_date);
|
||||
free_ctrl_version(v);
|
||||
}
|
||||
else {
|
||||
return ZITI_WTF;
|
||||
}
|
||||
}
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int ziti_ctrl_login(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl) {
|
||||
if (ssl == NULL) {
|
||||
return ziti_ctrl_process(ctx, ziti_ctrl_login, NULL);
|
||||
}
|
||||
|
||||
uv_utsname_t osInfo;
|
||||
uv_os_uname(&osInfo);
|
||||
|
||||
uint8_t *req = NULL;
|
||||
struct mjson_out req_json = MJSON_OUT_DYNAMIC_BUF(&req);
|
||||
int req_len = mjson_printf(&req_json,
|
||||
"{"
|
||||
"%Q:{%Q:%Q, %Q:%Q, %Q:%Q, %Q:%Q}, "
|
||||
"%Q:{%Q:%Q, %Q:%Q, %Q:%Q, %Q:%Q}"
|
||||
"}",
|
||||
"sdkInfo",
|
||||
"type", "ziti-sdk-c",
|
||||
"version", ziti_get_version(0),
|
||||
"revision", ziti_git_commit(),
|
||||
"branch", ziti_git_branch(),
|
||||
"envInfo",
|
||||
"os", osInfo.sysname,
|
||||
"osRelease", osInfo.release,
|
||||
"osVersion", osInfo.version,
|
||||
"arch", osInfo.machine);
|
||||
|
||||
struct controller_resp resp;
|
||||
memset(&resp, 0, sizeof(struct controller_resp));
|
||||
ziti_controller_req(ctx, ctrl, ssl, "POST", "/authenticate?method=cert", "application/json", req, req_len, &resp);
|
||||
|
||||
if (resp.status == 200) {
|
||||
const char *s;
|
||||
int len;
|
||||
if (mjson_find(resp.body, (int) resp.body_len, "$.data.session.token", &s, &len) == MJSON_TOK_STRING) {
|
||||
ctx->ziti_session = malloc(len + 1);
|
||||
mjson_get_string((const char *) resp.body, (int) resp.body_len, "$.data.session.token", ctx->ziti_session, len + 1);
|
||||
}
|
||||
else {
|
||||
return ZITI_WTF;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO handle errors better
|
||||
free(req);
|
||||
free_resp(&resp);
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int ziti_ctrl_get_services(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl) {
|
||||
|
||||
if (ssl == NULL) {
|
||||
return ziti_ctrl_process(ctx, ziti_ctrl_get_services, NULL);
|
||||
}
|
||||
|
||||
struct controller_resp resp;
|
||||
memset(&resp, 0, sizeof(struct controller_resp));
|
||||
ziti_controller_req(ctx, ctrl, ssl, "GET", "/services?limit=100", "", NULL, 0, &resp);
|
||||
|
||||
if (resp.status == 200) {
|
||||
const char* data;
|
||||
int data_len;
|
||||
if (mjson_find(resp.body, resp.body_len, "$.data", &data, &data_len) == MJSON_TOK_ARRAY) {
|
||||
ctx->services = parse_ziti_service_array(data, data_len);
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(ERROR, "unexpected response format, expected array of services");
|
||||
return ZITI_WTF;
|
||||
}
|
||||
}
|
||||
free_resp(&resp);
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int ziti_ctrl_get_network_sessions(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl) {
|
||||
|
||||
if (ssl == NULL) {
|
||||
return ziti_ctrl_process(ctx, ziti_ctrl_get_network_sessions, NULL);
|
||||
}
|
||||
|
||||
PREPF(ziti, ziti_errorstr);
|
||||
const char* method = "POST";
|
||||
const char* path = "/network-sessions";
|
||||
const char* conttype = "application/json";
|
||||
|
||||
int capacity = 10;
|
||||
ctx->net_sessions = calloc(10, sizeof(ziti_net_session*));
|
||||
int ns_idx = 0;
|
||||
|
||||
for (int i = 0; ctx->services[i] != NULL; i++) {
|
||||
if (ns_idx >= capacity) {
|
||||
ctx->net_sessions = realloc(ctx->net_sessions, (capacity + 10) * sizeof(ziti_net_session));
|
||||
memset(ctx->net_sessions + capacity, 0, 10 * sizeof(ziti_net_session));
|
||||
capacity += 10;
|
||||
}
|
||||
struct controller_resp resp;
|
||||
memset(&resp, 0, sizeof(resp));
|
||||
|
||||
uint8_t content[128];
|
||||
size_t len = (size_t) sprintf((char *) content, "{\"serviceId\":\"%s\",\"hosting\":%s}",
|
||||
ctx->services[i]->id, ctx->services[i]->hostable ? "true" : "false");
|
||||
TRY(ziti, ziti_controller_req(ctx, ctrl, ssl, method, path, conttype, content, len, &resp));
|
||||
|
||||
if (resp.status > 299) {
|
||||
ZITI_LOG(WARN, "failed to get network session for [%s]: (%d %s) %*s", ctx->services[i]->name, resp.status,
|
||||
resp.msg, (int) resp.body_len, resp.body);
|
||||
}
|
||||
|
||||
const char* data;
|
||||
int data_len;
|
||||
if (mjson_find(resp.body, resp.body_len, "$.data", &data, &data_len) == MJSON_TOK_OBJECT) {
|
||||
ziti_net_session *ns = parse_ziti_net_session(data, data_len);
|
||||
if (ns != NULL) {
|
||||
ns->service_id = strdup(ctx->services[i]->id);
|
||||
ctx->net_sessions[ns_idx] = ns;
|
||||
|
||||
ns_idx++;
|
||||
}
|
||||
}
|
||||
free_resp(&resp);
|
||||
}
|
||||
|
||||
CATCH(ziti) {
|
||||
return ERR(ziti);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ziti_controller_req(struct nf_ctx *ctx, uv_os_sock_t ctrl, tls_engine *ssl,
|
||||
const char *method, const char *path,
|
||||
const char *conttype, const unsigned char *content, size_t content_len,
|
||||
struct controller_resp *resp) {
|
||||
char sess_hdr[128] = "";
|
||||
if (ctx->ziti_session != NULL) {
|
||||
sprintf(sess_hdr, "zt-session: %s\r\n", ctx->ziti_session);
|
||||
}
|
||||
|
||||
size_t req_size = 1024;
|
||||
uint8_t *req = malloc(req_size);
|
||||
size_t act_size = 0;
|
||||
do {
|
||||
act_size = (size_t) snprintf((char *) req, req_size, REQ_HTTP, method, path, ctx->controller,
|
||||
conttype, content_len, sess_hdr);
|
||||
if (act_size > req_size) {
|
||||
req_size = act_size;
|
||||
req = realloc(req, req_size);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} while(1);
|
||||
|
||||
ZITI_LOG(DEBUG, "%s %s [%zd bytes]", method, path, content_len);
|
||||
ZITI_LOG(TRACE, "===> %*.*s", (uint) content_len, (uint) content_len, content);
|
||||
|
||||
|
||||
char ssl_out[8 * 1024];
|
||||
size_t ssl_bytes;
|
||||
int rc = ssl->api->write(ssl->engine, req, act_size, ssl_out, &ssl_bytes, sizeof(ssl_out));
|
||||
size_t wrote = send(ctrl, ssl_out, ssl_bytes, 0);
|
||||
ZITI_LOG(TRACE, "wrote %zd ssl bytes rc=%d", wrote, rc);
|
||||
while (rc == TLS_MORE_AVAILABLE) {
|
||||
rc = ssl->api->write(ssl->engine, NULL, 0, ssl_out, &ssl_bytes, sizeof(ssl_out));
|
||||
wrote = send(ctrl, ssl_out, ssl_bytes, 0);
|
||||
ZITI_LOG(TRACE, "wrote %zd ssl bytes rc=%d", wrote, rc);
|
||||
}
|
||||
|
||||
rc = ssl->api->write(ssl->engine, content, content_len, ssl_out, &ssl_bytes, sizeof(ssl_out));
|
||||
wrote = send(ctrl, ssl_out, ssl_bytes, 0);
|
||||
ZITI_LOG(TRACE, "wrote %zd ssl bytes rc=%d", wrote, rc);
|
||||
while (rc == TLS_MORE_AVAILABLE) {
|
||||
rc = ssl->api->write(ssl->engine, NULL, 0, ssl_out, &ssl_bytes, sizeof(ssl_out));
|
||||
wrote = send(ctrl, ssl_out, ssl_bytes, 0);
|
||||
ZITI_LOG(TRACE, "wrote %zd ssl bytes rc=%d", wrote, rc);
|
||||
}
|
||||
free(req);
|
||||
|
||||
struct http_parser parser;
|
||||
http_parser_init(&parser, HTTP_RESPONSE);
|
||||
parser.data = resp;
|
||||
|
||||
size_t read = 0;
|
||||
char ssl_in[8 * 1024];
|
||||
size_t ssl_in_bytes;
|
||||
do {
|
||||
char respbuff[8 * 1024];
|
||||
ssl_in_bytes = recv(ctrl, ssl_in, sizeof(ssl_in), 0);
|
||||
ZITI_LOG(TRACE, "read %zd ssl bytes", ssl_in_bytes);
|
||||
if (ssl_in_bytes <= 0)
|
||||
break;
|
||||
rc = ssl->api->read(ssl->engine, ssl_in, ssl_in_bytes, respbuff, &read, sizeof(respbuff));
|
||||
ZITI_LOG(TRACE, "read %zd plain bytes rc=%d ", read, rc);
|
||||
if (rc == TLS_READ_AGAIN) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ssize_t parsed = http_parser_execute(&parser, &HTTP_SETTINGS, (const char *) respbuff, read);
|
||||
ZITI_LOG(TRACE, "body=%zd parsed=%ld", resp->body_len, parsed);
|
||||
while (rc == TLS_MORE_AVAILABLE) {
|
||||
rc = ssl->api->read(ssl->engine, NULL, 0, respbuff, &read, sizeof(respbuff));
|
||||
ZITI_LOG(TRACE, "read %zd plain bytes rc=%d ", read, rc);
|
||||
|
||||
if (rc == TLS_READ_AGAIN) {
|
||||
break;
|
||||
}
|
||||
parsed = http_parser_execute(&parser, &HTTP_SETTINGS, (const char *) respbuff, read);
|
||||
ZITI_LOG(TRACE, "body=%zd parsed=%zd", resp->body_len, parsed);
|
||||
}
|
||||
} while (!resp->complete);
|
||||
|
||||
ZITI_LOG(DEBUG, "%s %s => %d [%zd bytes]", method, path, parser.status_code, resp->body_len);
|
||||
ZITI_LOG(TRACE, ">>> %*.*s\n", resp->body_len, resp->body_len, resp->body);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int sockClose(SOCKET sock)
|
||||
{
|
||||
//a helper to hide the differences between closing a socket in windows vs posix
|
||||
int status = 0;
|
||||
#ifdef _WIN32
|
||||
status = shutdown(sock, SD_BOTH);
|
||||
if (status == 0) { status = closesocket(sock); }
|
||||
#else
|
||||
status = shutdown(sock, SHUT_RDWR);
|
||||
if (status == 0) { status = close(sock); }
|
||||
#endif
|
||||
return status;
|
||||
}
|
||||
|
||||
int ziti_ctrl_process(struct nf_ctx* ctx, ...) {
|
||||
int rc = ZITI_OK;
|
||||
|
||||
PREPF(ziti, ziti_errorstr);
|
||||
|
||||
tls_engine *ssl = ctx->tlsCtx->api->new_engine(ctx->tlsCtx->ctx, ctx->controller);
|
||||
char port[6];
|
||||
sprintf(port, "%d", ctx->controller_port);
|
||||
struct addrinfo hints;
|
||||
memset(&hints, 0, sizeof(hints));
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
|
||||
struct addrinfo *address, *ap;
|
||||
int r = getaddrinfo(ctx->controller, port, &hints, &address);
|
||||
if (r != 0 || address == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to resolve controller(%s): %s", ctx->controller, strerror(errno));
|
||||
return ZITI_CONTROLLER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
uv_os_sock_t sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||
|
||||
// connect
|
||||
for (ap = address; ap != NULL; ap = ap->ai_next) {
|
||||
char a[32], p[6];
|
||||
getnameinfo(ap->ai_addr, ap->ai_addrlen, a, sizeof(a), p, 6, NI_NUMERICHOST | NI_NUMERICSERV);
|
||||
ZITI_LOG(DEBUG, "trying to connect to %s:%s", a, p);
|
||||
r = connect(sock, ap->ai_addr, ap->ai_addrlen);
|
||||
if (r == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
ZITI_LOG(WARN, "failed to connect to %s:%s %s", a, p, strerror(errno));
|
||||
}
|
||||
|
||||
// do handshake
|
||||
char ssl_in[32 * 1024];
|
||||
char ssl_out[32 * 1024];
|
||||
size_t in_bytes = 0;
|
||||
size_t out_bytes = 0;
|
||||
do {
|
||||
tls_handshake_state state = ssl->api->handshake(ssl->engine, ssl_in, in_bytes, ssl_out, &out_bytes,
|
||||
sizeof(ssl_out));
|
||||
if (state == TLS_HS_COMPLETE) {
|
||||
ZITI_LOG(DEBUG, "handshake completed");
|
||||
break;
|
||||
}
|
||||
else if (state == TLS_HS_ERROR) {
|
||||
ZITI_LOG(ERROR, "handshake failed");
|
||||
return ZITI_CONTROLLER_UNAVAILABLE;
|
||||
}
|
||||
|
||||
if (out_bytes > 0) {
|
||||
size_t wrote = send(sock, ssl_out, out_bytes, 0);
|
||||
}
|
||||
|
||||
in_bytes = recv(sock, ssl_in, sizeof(ssl_in), 0);
|
||||
} while (true);
|
||||
|
||||
// execute requests in order
|
||||
va_list argp;
|
||||
va_start(argp, ctx);
|
||||
|
||||
ctrl_req req;
|
||||
while ((req = va_arg(argp, ctrl_req)) != NULL) {
|
||||
TRY(ziti, req(ctx, sock, ssl));
|
||||
}
|
||||
va_end(argp);
|
||||
|
||||
// close SSL and socket
|
||||
ssl->api->close(ssl->engine, ssl_out, &out_bytes, sizeof(ssl_out));
|
||||
send(sock, ssl_out, out_bytes, 0);
|
||||
|
||||
sockClose(sock);
|
||||
|
||||
CATCH(ziti) {
|
||||
rc = ERR(ziti);
|
||||
}
|
||||
|
||||
ctx->tlsCtx->api->free_engine(ssl);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static bool is_ip(const char* hostname) {
|
||||
struct in_addr ipv4;
|
||||
struct in6_addr ipv6;
|
||||
|
||||
if (inet_pton(AF_INET, hostname, &ipv4) == 1) {
|
||||
return true;
|
||||
} else if (inet_pton(AF_INET6, hostname, &ipv6) == 1){
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//
|
||||
// Created by eugene on 3/1/19.
|
||||
//
|
||||
|
||||
#ifndef ZT_SDK_CONTROLLER_H
|
||||
#define ZT_SDK_CONTROLLER_H
|
||||
|
||||
#include <nf/ziti.h>
|
||||
|
||||
typedef int (*ctrl_req)(struct nf_ctx *, uv_os_sock_t sock, tls_engine *ssl);
|
||||
|
||||
int ziti_ctrl_process(nf_context ctx, ...);
|
||||
|
||||
int ziti_ctrl_version(nf_context ctx, uv_os_sock_t, tls_engine *);
|
||||
int ziti_ctrl_login(nf_context ctx, uv_os_sock_t, tls_engine *);
|
||||
|
||||
int ziti_ctrl_logout(nf_context ctx, uv_os_sock_t, tls_engine *);
|
||||
|
||||
int ziti_ctrl_get_services(nf_context ctx, uv_os_sock_t, tls_engine *);
|
||||
|
||||
int ziti_ctrl_get_network_sessions(nf_context ctx, uv_os_sock_t, tls_engine *);
|
||||
|
||||
int ziti_logout(nf_context ctx);
|
||||
#endif //ZT_SDK_CONTROLLER_H
|
||||
@@ -0,0 +1,61 @@
|
||||
#ifndef ZITI_SDK_ENDIAN_INTERNAL_H
|
||||
#define ZITI_SDK_ENDIAN_INTERNAL_H
|
||||
|
||||
#if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__)
|
||||
# define __WINDOWS__
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(__linux__)
|
||||
# include <endian.h>
|
||||
#elif defined (__APPLE__)
|
||||
# include <libkern/OSByteOrder.h>
|
||||
# define htole32(x) OSSwapHostToLittleInt32(x)
|
||||
# define le32toh(x) OSSwapLittleToHostInt32(x)
|
||||
#elif defined(__WINDOWS__)
|
||||
// thanks to https://gist.github.com/PkmX/63dd23f28ba885be53a5
|
||||
# include <windows.h>
|
||||
# if BYTE_ORDER == LITTLE_ENDIAN
|
||||
# if defined(_MSC_VER)
|
||||
# include <stdlib.h>
|
||||
# define htobe16(x) _byteswap_ushort(x)
|
||||
# define htole16(x) (x)
|
||||
# define be16toh(x) _byteswap_ushort(x)
|
||||
# define le16toh(x) (x)
|
||||
# define htobe32(x) _byteswap_ulong(x)
|
||||
# define htole32(x) (x)
|
||||
# define be32toh(x) _byteswap_ulong(x)
|
||||
# define le32toh(x) (x)
|
||||
# define htobe64(x) _byteswap_uint64(x)
|
||||
# define htole64(x) (x)
|
||||
# define be64toh(x) _byteswap_uint64(x)
|
||||
# define le64toh(x) (x)
|
||||
# elif defined(__GNUC__) || defined(__clang__)
|
||||
# define htobe16(x) __builtin_bswap16(x)
|
||||
# define htole16(x) (x)
|
||||
# define be16toh(x) __builtin_bswap16(x)
|
||||
# define le16toh(x) (x)
|
||||
# define htobe32(x) __builtin_bswap32(x)
|
||||
# define htole32(x) (x)
|
||||
# define be32toh(x) __builtin_bswap32(x)
|
||||
# define le32toh(x) (x)
|
||||
# define htobe64(x) __builtin_bswap64(x)
|
||||
# define htole64(x) (x)
|
||||
# define be64toh(x) __builtin_bswap64(x)
|
||||
# define le64toh(x) (x)
|
||||
# else
|
||||
# error platform not supported
|
||||
# endif
|
||||
# else
|
||||
# error byte order not supported
|
||||
# endif
|
||||
# define __BYTE_ORDER BYTE_ORDER
|
||||
# define __BIG_ENDIAN BIG_ENDIAN
|
||||
# define __LITTLE_ENDIAN LITTLE_ENDIAN
|
||||
# define __PDP_ENDIAN PDP_ENDIAN
|
||||
|
||||
#else // other
|
||||
# error Please port endian macros!
|
||||
#endif
|
||||
|
||||
#endif //ZITI_SDK_ENDIAN_INTERNAL_H
|
||||
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// Created by eugene on 2/28/19.
|
||||
//
|
||||
#include "nf/errors.h"
|
||||
|
||||
enum _zt_err {
|
||||
#define _err_enum(e,_) _ziti_##e,
|
||||
ZITI_ERRORS(_err_enum)
|
||||
};
|
||||
|
||||
#define ERR_ID(e,_) const int ZITI_##e = -_ziti_##e;
|
||||
ZITI_ERRORS(ERR_ID)
|
||||
#undef ERR_ID
|
||||
|
||||
|
||||
#define ERR_NAME(e,s) case -_ziti_##e: return s;
|
||||
|
||||
const char* ziti_errorstr(int err) {
|
||||
switch (err) {
|
||||
ZITI_ERRORS(ERR_NAME)
|
||||
|
||||
default:
|
||||
return "unexpected error";
|
||||
}
|
||||
|
||||
}
|
||||
#undef ERR_NAME
|
||||
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// Created by eugene on 3/22/19.
|
||||
//
|
||||
|
||||
#include "message.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "utils.h"
|
||||
#include "endian_internal.h"
|
||||
|
||||
static uint8_t *read_int32(const uint8_t *p, uint32_t *val) {
|
||||
*val = le32toh(*(uint32_t *) p);
|
||||
return p + sizeof(uint32_t);
|
||||
}
|
||||
|
||||
void header_to_buffer(header_t *h, uint8_t *buf) {
|
||||
memcpy(buf, h->magic, sizeof(h->magic));
|
||||
uint8_t *offset = buf + sizeof(h->magic);
|
||||
|
||||
#define write_field(n,t) {\
|
||||
t val = htole32(h->n); \
|
||||
memcpy(offset, &val, sizeof(t)); \
|
||||
offset += sizeof(t);\
|
||||
}
|
||||
HEADER_FIELDS(write_field)
|
||||
#undef write_field
|
||||
};
|
||||
|
||||
void header_from_buffer(header_t *h, uint8_t *buf) {
|
||||
memcpy(h->magic, buf, sizeof(h->magic));
|
||||
uint8_t *offset = buf + sizeof(h->magic);
|
||||
|
||||
#define read_field(n,t) {\
|
||||
t val; \
|
||||
memcpy(&val, offset, sizeof(t)); \
|
||||
offset += sizeof(t);\
|
||||
h->n = le32toh(val);\
|
||||
}
|
||||
HEADER_FIELDS(read_field)
|
||||
#undef read_field
|
||||
};
|
||||
|
||||
|
||||
void header_init(header_t *h, uint32_t seq) {
|
||||
memcpy(h, &EMPTY_HEADER, sizeof(header_t));
|
||||
h->seq = seq;
|
||||
}
|
||||
|
||||
void message_init(message* m) {
|
||||
memset(m, 0, sizeof(message));
|
||||
}
|
||||
void message_free(message* m) {
|
||||
FREE(m->headers);
|
||||
FREE(m->hdrs);
|
||||
}
|
||||
|
||||
uint8_t *write_hdr(const hdr_t *h, uint8_t *buf) {
|
||||
uint32_t v = htole32(h->header_id);
|
||||
memcpy(buf, &v, sizeof(v));
|
||||
buf += sizeof(v);
|
||||
|
||||
v = htole32(h->length);
|
||||
memcpy(buf, &v, sizeof(v));
|
||||
buf += sizeof(v);
|
||||
|
||||
memcpy(buf, h->value, h->length);
|
||||
return buf + h->length;
|
||||
}
|
||||
|
||||
int parse_hdrs(uint8_t *buf, uint32_t len, hdr_t **hp) {
|
||||
uint8_t *p = buf;
|
||||
|
||||
hdr_t *headers = NULL;
|
||||
int count = 0;
|
||||
while (p < buf + len) {
|
||||
if (headers == NULL) {
|
||||
headers = malloc(sizeof(hdr_t));
|
||||
}
|
||||
else {
|
||||
headers = realloc(headers, (count + 1) * sizeof(hdr_t));
|
||||
}
|
||||
|
||||
p = read_int32(p, &headers[count].header_id);
|
||||
p = read_int32(p, &headers[count].length);
|
||||
headers[count].value = p;
|
||||
p += headers[count].length;
|
||||
count++;
|
||||
}
|
||||
|
||||
*hp = headers;
|
||||
return count;
|
||||
}
|
||||
|
||||
static hdr_t *find_header(message *m, int header_id) {
|
||||
for (int i = 0; i < m->nhdrs; i++) {
|
||||
if (m->hdrs[i].header_id == header_id) {
|
||||
return &m->hdrs[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool message_get_bool_header(message *m, int header_id, bool *v) {
|
||||
hdr_t *h = find_header(m, header_id);
|
||||
if (h != NULL) {
|
||||
int8_t val = *h->value;
|
||||
*v = (val != 0);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool message_get_int32_header(message *m, int header_id, int32_t *v) {
|
||||
hdr_t *h = find_header(m, header_id);
|
||||
if (h != NULL) {
|
||||
int32_t val = *(int32_t *) h->value;
|
||||
*v = le32toh(val);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//
|
||||
// Created by eugene on 3/22/19.
|
||||
//
|
||||
|
||||
#ifndef ZITI_SDK_MESSAGE_H
|
||||
#define ZITI_SDK_MESSAGE_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define HEADER_SIZE 20
|
||||
|
||||
#define MAGIC_INIT {0x3, 0x6, 0x9, 0xC}
|
||||
|
||||
typedef char magic_t[4];
|
||||
|
||||
#define HEADER_FIELDS(XX) \
|
||||
XX(content, uint32_t)\
|
||||
XX(seq, int32_t)\
|
||||
XX(headers_len, uint32_t)\
|
||||
XX(body_len, uint32_t)
|
||||
|
||||
typedef struct {
|
||||
magic_t magic;
|
||||
#define field_decl(n, t) t n;
|
||||
|
||||
HEADER_FIELDS(field_decl)
|
||||
|
||||
#undef field_decl
|
||||
|
||||
} header_t;
|
||||
|
||||
static header_t EMPTY_HEADER = {
|
||||
MAGIC_INIT,
|
||||
};
|
||||
|
||||
|
||||
typedef struct {
|
||||
uint32_t header_id;
|
||||
uint32_t length;
|
||||
uint8_t *value;
|
||||
} hdr_t;
|
||||
|
||||
typedef struct {
|
||||
header_t header;
|
||||
uint8_t *headers;
|
||||
uint8_t *body;
|
||||
hdr_t *hdrs;
|
||||
int nhdrs;
|
||||
} message;
|
||||
|
||||
void header_init(header_t *h, uint32_t seq);
|
||||
void header_to_buffer(header_t *h, uint8_t *buf);
|
||||
void header_from_buffer(header_t *h, uint8_t *buf);
|
||||
void message_init(message *m);
|
||||
void message_free(message *m);
|
||||
|
||||
bool message_get_bool_header(message *m, int header_id, bool *v);
|
||||
|
||||
bool message_get_int32_header(message *m, int header_id, int32_t *v);
|
||||
|
||||
uint8_t *write_hdr(const hdr_t *h, uint8_t *buf);
|
||||
|
||||
int parse_hdrs(uint8_t *buf, uint32_t len, hdr_t **hp);
|
||||
|
||||
#endif //ZITI_SDK_MESSAGE_H
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
//
|
||||
// Created by eugene on 3/5/19.
|
||||
//
|
||||
|
||||
#include <mjson.h>
|
||||
#include <stdbool.h>
|
||||
#include "model.h"
|
||||
|
||||
|
||||
//#define free_int(_)
|
||||
//#define free_bool(_)
|
||||
|
||||
typedef int (*dump_func)(void *, int);
|
||||
typedef void *(*parse_func)(const char *, int);
|
||||
typedef void (*free_func)(void *);
|
||||
|
||||
|
||||
void free_int(int i) {}
|
||||
void free_bool(bool i) {}
|
||||
|
||||
void free_string(string s) {
|
||||
if (s != NULL) {
|
||||
free((void *) s);
|
||||
}
|
||||
}
|
||||
|
||||
static string parse_string(const char *json, int json_len, const char *path) {
|
||||
const char *f;
|
||||
int n;
|
||||
string result = NULL;
|
||||
if (path != NULL && mjson_find(json, json_len, path, &f, &n) == MJSON_TOK_STRING) {
|
||||
result = calloc(1, n + 1);
|
||||
mjson_get_string(f, n, "$", result, n);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static int parse_bool(const char *json, int json_len, const char *path) {
|
||||
return mjson_get_bool(json, json_len, path, 0);
|
||||
}
|
||||
|
||||
static int parse_int(const char *json, int json_len, const char *path) {
|
||||
const char *f;
|
||||
int n;
|
||||
int result = 0;
|
||||
if (mjson_find(json, json_len, path, &f, &n) == MJSON_TOK_NUMBER) {
|
||||
result = (int) mjson_get_number(f, n, "$", result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static void *parse_ptr(const char *json, int json_len, char *path, void *(*parse_func)(const char *, int)) {
|
||||
const char *f;
|
||||
int n;
|
||||
if (mjson_find(json, json_len, path, &f, &n) == MJSON_TOK_OBJECT) {
|
||||
return parse_func(f, n);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void **parse_array(const char *json, int json_len, char *path, void *(*parse_func)(const char *, int)) {
|
||||
const char *arrjson;
|
||||
int arrjson_len;
|
||||
int array_len = 1;
|
||||
void **result = NULL;
|
||||
|
||||
if (mjson_find(json, json_len, path, &arrjson, &arrjson_len) == MJSON_TOK_ARRAY) {
|
||||
result = calloc(array_len, sizeof(void *));
|
||||
int idx = 0;
|
||||
do {
|
||||
if (array_len <= idx) {
|
||||
array_len += 2;
|
||||
result = realloc(result, array_len * sizeof(void *));
|
||||
}
|
||||
char elem_path[24];
|
||||
sprintf(elem_path, "$[%d]", idx);
|
||||
const char *el_json;
|
||||
int el_len;
|
||||
enum mjson_tok tok = mjson_find(arrjson, arrjson_len, elem_path, &el_json, &el_len);
|
||||
if (tok != MJSON_TOK_INVALID) {
|
||||
result[idx] = parse_func(el_json, el_len);
|
||||
if (result[idx] == NULL) {
|
||||
break;
|
||||
}
|
||||
idx++;
|
||||
}
|
||||
else {
|
||||
result[idx] = NULL;
|
||||
break;
|
||||
}
|
||||
} while (1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#define free_none(f, func) func(f)
|
||||
|
||||
int dump_string(const char *s, int len) {
|
||||
printf("%s\n", s ? s : "<null>");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int dump_int(int i, int len) {
|
||||
printf("%d\n", i);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int dump_bool(bool v, int len) {
|
||||
printf("%s\n", v ? "true" : "false");
|
||||
return 0;
|
||||
}
|
||||
|
||||
#define parse_none(json, len, path, func) func(json, len, path)
|
||||
|
||||
|
||||
|
||||
int dump_none(void *obj, char *name, dump_func func, int indent) {
|
||||
printf("%*.*s%s: ", indent, indent, "", name);
|
||||
func(obj, indent);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int dump_ptr(void *obj, char *name, int (*dump_func)(void *o, int ind), int ind) {
|
||||
printf("%*.*s%s = ", ind, ind, "", name);
|
||||
if (obj != NULL) {
|
||||
dump_func(obj, ind + 2);
|
||||
}
|
||||
else {
|
||||
printf("null\n");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int dump_array(void **arr, char *name, int (*dump_func)(void *o, int ind), int ind) {
|
||||
printf("%*.*s%s > [\n", ind, ind, "", name);
|
||||
for (int i = 0; arr[i] != NULL; i++) {
|
||||
dump_func(arr[i], ind + 2);
|
||||
}
|
||||
printf("%*.*s]\n", ind, ind, "");
|
||||
return 0;
|
||||
}
|
||||
|
||||
void free_ptr(void *obj, free_func f) {
|
||||
f(obj);
|
||||
}
|
||||
|
||||
void free_array(void **arr, free_func f) {
|
||||
for (int i = 0; arr[i] != NULL; i++) {
|
||||
f(arr[i]);
|
||||
}
|
||||
free(arr);
|
||||
}
|
||||
|
||||
#define cast_array(t) void**
|
||||
#define cast_ptr(t) t*
|
||||
#define cast_none(t) t
|
||||
|
||||
#define parse_field(n, type, mod, path) obj->n = ( mod(type) ) parse_##mod(json, json_len, path, (parse_func)parse_##type);
|
||||
#define free_field(f, type, mod, _) free_##mod((cast_##mod(type))obj->f, free_##type);
|
||||
#define dump_field(f, type, mod, _) dump_##mod((void*)obj->f, #f, (dump_func)dump_##type, ind + 2);
|
||||
|
||||
#define FROM_JSON(type, model) type* parse_##type(const char* json, int json_len){\
|
||||
type *obj = calloc(1, sizeof(type));\
|
||||
model(parse_field)\
|
||||
return obj;\
|
||||
}
|
||||
|
||||
#define FROM_JSON_ARR(type) type** parse_##type##_array(const char* json, int json_len){\
|
||||
return (type**)parse_array(json, json_len, "$", (parse_func)parse_##type); \
|
||||
}
|
||||
|
||||
#define FREE_MODEL(type, model) void free_##type(type *obj) {\
|
||||
model(free_field)\
|
||||
free(obj);\
|
||||
}
|
||||
|
||||
#define FREE_MODEL_ARR(type) void free_##type##_array(type **arr) {\
|
||||
free_array((void**)arr, (free_func)free_##type); \
|
||||
}
|
||||
|
||||
#define DUMP_MODEL(type, model) int dump_##type(type *obj, int ind) {\
|
||||
printf("%*.*s" #type "\n", ind, ind, " ");\
|
||||
model(dump_field)\
|
||||
return 0;\
|
||||
}
|
||||
|
||||
#define MODEL_IMPL(type, model) \
|
||||
FROM_JSON(type, model) \
|
||||
FROM_JSON_ARR(type) \
|
||||
FREE_MODEL(type, model) \
|
||||
FREE_MODEL_ARR(type) \
|
||||
DUMP_MODEL(type, model)
|
||||
|
||||
MODEL_IMPL(ziti_service, ZITI_SERVICE_MODEL)
|
||||
MODEL_IMPL(nf_config, ZITI_CONFIG_MODEL)
|
||||
|
||||
MODEL_IMPL(ziti_gateway, ZITI_GATEWAY_MODEL)
|
||||
MODEL_IMPL(ziti_net_session, ZITI_NET_SESSION_MODEL)
|
||||
|
||||
MODEL_IMPL(ctrl_version, ZITI_CTRL_VERSION)
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
//
|
||||
// Created by eugene on 3/5/19.
|
||||
//
|
||||
|
||||
#ifndef ZT_SDK_MODEL_H
|
||||
#define ZT_SDK_MODEL_H
|
||||
|
||||
/*
|
||||
* set of macros to help generate struct and function for our model;
|
||||
*
|
||||
* - DECLARE_MODEL(type, model_def) :
|
||||
* `type` name of the struct,
|
||||
* `model_def` - marco defining fields for the model
|
||||
*
|
||||
* NOTE: matching MODEL_IMPL macro in model.c is used to generate function implementations
|
||||
*
|
||||
* Fields are defined with name, type, type modifier, and path (for JSON mapping)
|
||||
*
|
||||
* The following functions are generated:
|
||||
* - TYPE* parse_TYPE(json, len) -- parses json into an allocated struct
|
||||
*
|
||||
* - void free_TYPE(TYPE *obj) -- frees struct
|
||||
*
|
||||
* - int dump_TYPE(TYPE *obj, int indent) -- prints the struct to `stdout`,
|
||||
* `indent` is used for printing nested model objects
|
||||
*/
|
||||
|
||||
#define FIELD_DECL(name, type, mod, path) mod(type) name;
|
||||
|
||||
/*
|
||||
* field type macros
|
||||
*
|
||||
* Nested model objects are supported as pointers and NULL-terminated arrays of pointers
|
||||
*/
|
||||
#define none(type) type
|
||||
#define array(type) type**
|
||||
#define ptr(type) type*
|
||||
|
||||
/*
|
||||
* Model declaration: struct type, and functions
|
||||
*/
|
||||
#define DECLARE_MODEL(type, model) \
|
||||
typedef struct {\
|
||||
model(FIELD_DECL) \
|
||||
} type;\
|
||||
type* parse_##type(const char* json, int json_len);\
|
||||
type** parse_##type##_array(const char* json, int json_len);\
|
||||
void free_##type(type* type);\
|
||||
void free_##type##_array(type** arr); \
|
||||
int dump_##type(type* type, int len);
|
||||
|
||||
typedef char* string;
|
||||
|
||||
#define ZITI_CTRL_VERSION(XX) \
|
||||
XX(version, string, none, "$.version") \
|
||||
XX(revision, string, none, "$.revision") \
|
||||
XX(build_date, string, none, "$.buildDate")
|
||||
|
||||
#define ZITI_SERVICE_MODEL(XX) \
|
||||
XX(id, string, none, "$.id") \
|
||||
XX(name, string, none, "$.name") \
|
||||
XX(dns_host, string, none, "$.dns.hostname") \
|
||||
XX(dns_port, int, none, "$.dns.port") \
|
||||
XX(hostable, bool, none, "$.hostable")
|
||||
|
||||
#define ZITI_CONFIG_MODEL(XX) \
|
||||
XX(controller_url, string, none, "$.ztAPI") \
|
||||
XX(cert, string, none, "$.id.cert") \
|
||||
XX(key, string, none, "$.id.key") \
|
||||
XX(ca, string, none, "$.id.ca")
|
||||
|
||||
#define ZITI_GATEWAY_MODEL(XX)\
|
||||
XX(name, string, none, "$.name")\
|
||||
XX(hostname, string, none, "$.hostname") \
|
||||
XX(url_tls, string, none, "$.urls.tls")
|
||||
|
||||
#define ZITI_NET_SESSION_MODEL(XX) \
|
||||
XX(token, string, none, "$.token")\
|
||||
XX(id, string, none, "$.id") \
|
||||
XX(hosting, bool, none, "$.hosting") \
|
||||
XX(gateways, ziti_gateway, array, "$.gateways") \
|
||||
XX(service_id, string, none, NULL)
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
DECLARE_MODEL(ctrl_version, ZITI_CTRL_VERSION)
|
||||
|
||||
DECLARE_MODEL(nf_config, ZITI_CONFIG_MODEL)
|
||||
DECLARE_MODEL(ziti_service, ZITI_SERVICE_MODEL)
|
||||
|
||||
DECLARE_MODEL(ziti_gateway, ZITI_GATEWAY_MODEL)
|
||||
DECLARE_MODEL(ziti_net_session, ZITI_NET_SESSION_MODEL)
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif //ZT_SDK_MODEL_H
|
||||
@@ -0,0 +1,222 @@
|
||||
//
|
||||
// Created by eugene on 7/1/19.
|
||||
//
|
||||
|
||||
#include "mbed_p11.h"
|
||||
#include "p11_errors.h"
|
||||
|
||||
#if _WIN32
|
||||
#define strncasecmp _strnicmp
|
||||
#else
|
||||
#include <dlfcn.h>
|
||||
#endif
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <utils.h>
|
||||
#include <nf/errors.h>
|
||||
|
||||
|
||||
static int p11_getopt(const char *q, const char *opt, char *out, size_t maxout);
|
||||
|
||||
static int mp11_init(mp11_context *p11, const char *lib, const char *slot, const char *pin);
|
||||
|
||||
static int mp11_get_key(mbedtls_pk_context *key, mp11_context *ctx, const char *id, const char *label);
|
||||
|
||||
static mp11_context CTX;
|
||||
|
||||
int mp11_load_key(mbedtls_pk_context *key, const char *path, const char *opts) {
|
||||
PREPF(mbed, fmt_mbederr);
|
||||
|
||||
|
||||
char pin[32];
|
||||
p11_getopt(opts, "pin", pin, sizeof(pin));
|
||||
char slot[32];
|
||||
p11_getopt(opts, "slot", slot, sizeof(slot));
|
||||
|
||||
if (CTX.lib == NULL) {
|
||||
TRY(mbed, mp11_init(&CTX, path, slot, pin));
|
||||
}
|
||||
|
||||
char id[32];
|
||||
p11_getopt(opts, "id", id, sizeof(id));
|
||||
char label[128];
|
||||
p11_getopt(opts, "label", label, sizeof(label));
|
||||
|
||||
TRY(mbed, mp11_get_key(key, &CTX, id, label));
|
||||
CATCH(mbed) {
|
||||
return ERR(mbed);
|
||||
}
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
static int mp11_get_key(mbedtls_pk_context *key, mp11_context *ctx, const char *idstr, const char *label) {
|
||||
PREPCF(p11, non_zero, p11_strerror);
|
||||
|
||||
NEWP(p11_key, mp11_key_ctx);
|
||||
|
||||
CK_ULONG cls = CKO_PRIVATE_KEY;
|
||||
char id[32];
|
||||
CK_ULONG idlen;
|
||||
|
||||
|
||||
CK_ULONG qcount = 1;
|
||||
CK_ATTRIBUTE query[3] = {
|
||||
{CKA_CLASS, &cls, sizeof(cls)}
|
||||
};
|
||||
|
||||
if (idstr != NULL && strcmp(idstr, "") != 0) {
|
||||
idlen = (strlen(idstr) + 1) / 2;
|
||||
for (int idx = 0; idx < idlen; idx++) {
|
||||
sscanf(idstr + 2 * idx, "%2hhx", &id[idx]);
|
||||
}
|
||||
// parse id
|
||||
query[qcount].type = CKA_ID;
|
||||
query[qcount].pValue = id;
|
||||
query[qcount].ulValueLen = idlen;
|
||||
|
||||
qcount++;
|
||||
}
|
||||
|
||||
if (label != NULL && strcmp(label, "") != 0) {
|
||||
query[qcount].type = CKA_LABEL;
|
||||
query[qcount].pValue = label;
|
||||
query[qcount].ulValueLen = strlen(label);
|
||||
|
||||
qcount++;
|
||||
}
|
||||
|
||||
if (qcount < 2) {
|
||||
ZITI_LOG(ERROR, "no id/label specified for key");
|
||||
TRY(p11, CKR_KEY_NEEDED);
|
||||
}
|
||||
|
||||
CK_ULONG objc;
|
||||
TRY(p11, ctx->funcs->C_FindObjectsInit(ctx->session, query, qcount));
|
||||
TRY(p11, ctx->funcs->C_FindObjects(ctx->session, &p11_key->priv_handle, 1, &objc));
|
||||
TRY(p11, ctx->funcs->C_FindObjectsFinal(ctx->session));
|
||||
|
||||
if (objc == 0) {
|
||||
ZITI_LOG(ERROR, "key not found with given id/label");
|
||||
TRY(p11, ("not found", CKR_KEY_NEEDED));
|
||||
}
|
||||
|
||||
cls = CKO_PUBLIC_KEY;
|
||||
TRY(p11, ctx->funcs->C_FindObjectsInit(ctx->session, query, qcount));
|
||||
TRY(p11, ctx->funcs->C_FindObjects(ctx->session, &p11_key->pub_handle, 1, &objc));
|
||||
TRY(p11, ctx->funcs->C_FindObjectsFinal(ctx->session));
|
||||
if (objc == 0) {
|
||||
ZITI_LOG(ERROR, "key not found with given id/label (public)");
|
||||
TRY(p11, ("public key not found", CKR_KEY_NEEDED));
|
||||
}
|
||||
|
||||
CK_ULONG key_type;
|
||||
CK_ATTRIBUTE attr = {CKA_KEY_TYPE, &key_type, sizeof(key_type)};
|
||||
|
||||
TRY(p11, ctx->funcs->C_GetAttributeValue(ctx->session, p11_key->priv_handle, &attr, 1));
|
||||
|
||||
switch (key_type) {
|
||||
case CKK_ECDSA:
|
||||
TRY(p11, p11_load_ecdsa(key, p11_key, &CTX));
|
||||
break;
|
||||
|
||||
case CKK_RSA:
|
||||
TRY(p11, p11_load_rsa(key, p11_key, &CTX));
|
||||
break;
|
||||
|
||||
default: {
|
||||
ZITI_LOG(ERROR, "only RSA and ECDSA keys are supported");
|
||||
TRY(p11, ("unsupported key type", CKR_KEY_HANDLE_INVALID));
|
||||
}
|
||||
}
|
||||
|
||||
CATCH(p11) {
|
||||
free(p11_key);
|
||||
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
static int mp11_init(mp11_context *p11, const char *lib, const char *slot, const char *pin) {
|
||||
PREPCF(P11, non_zero, p11_strerror);
|
||||
memset(p11, 0, sizeof(mp11_context));
|
||||
|
||||
CK_C_GetFunctionList f;
|
||||
|
||||
#if _WIN32
|
||||
//unimplemented in windows at this time
|
||||
ZITI_LOG(ERROR, "p11 not supported on Windows at this time");
|
||||
return 1;
|
||||
|
||||
/*
|
||||
TRY(P11, (p11->lib = LoadLibrary(lib)) != NULL ? CKR_OK : CKR_LIBRARY_LOAD_FAILED);
|
||||
TRY(P11, (f = (CK_C_GetFunctionList)GetProcAddress(p11->lib, "C_GetFunctionList")) != NULL ? CKR_OK : CKR_LIBRARY_LOAD_FAILED);
|
||||
*/
|
||||
#else
|
||||
TRY(P11, (p11->lib = dlopen(lib, RTLD_LAZY)) != NULL ? CKR_OK : CKR_LIBRARY_LOAD_FAILED);
|
||||
TRY(P11, (f = dlsym(p11->lib, "C_GetFunctionList")) != NULL ? CKR_OK : CKR_LIBRARY_LOAD_FAILED);
|
||||
#endif
|
||||
TRY(P11, f(&p11->funcs));
|
||||
TRY(P11, p11->funcs->C_Initialize(NULL));
|
||||
CK_SLOT_ID slot_id;
|
||||
if (slot == NULL || strcmp(slot, "") == 0) {
|
||||
CK_SLOT_ID_PTR slots;
|
||||
CK_ULONG slot_count;
|
||||
TRY(P11, p11->funcs->C_GetSlotList(CK_TRUE, NULL, &slot_count));
|
||||
slots = calloc(slot_count, sizeof(CK_SLOT_ID));
|
||||
TRY(P11, p11->funcs->C_GetSlotList(CK_TRUE, slots, &slot_count));
|
||||
slot_id = slots[0];
|
||||
ZITI_LOG(WARN, "slot id not specified. using the first slot[%lx] reported by driver", slot_id);
|
||||
free(slots);
|
||||
}
|
||||
else {
|
||||
slot_id = strtoul(slot, NULL, 16);
|
||||
}
|
||||
p11->slot_id = slot_id;
|
||||
|
||||
TRY(P11, p11->funcs->C_OpenSession(slot_id, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL, NULL, &p11->session));
|
||||
TRY(P11, p11->funcs->C_Login(p11->session, CKU_USER, (uint8_t *) pin, strlen(pin)));
|
||||
|
||||
CATCH(P11) {
|
||||
return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int p11_getopt(const char *q, const char *opt, char *out, size_t maxout) {
|
||||
int optlen = strlen(opt);
|
||||
do {
|
||||
// found it
|
||||
if (strncasecmp(q, opt, optlen) == 0 && (q[optlen] == '=' || q[optlen] == 0)) {
|
||||
char *val = q + optlen + 1;
|
||||
char *end = strchr(val, '&');
|
||||
int vlen = end == NULL ? strlen(val) : end - val;
|
||||
snprintf(out, maxout, "%*.*s", vlen, vlen, val);
|
||||
return 0;
|
||||
|
||||
}
|
||||
else { // skip to next '&'
|
||||
q = strchr(q, '&');
|
||||
if (q == NULL) {
|
||||
break;
|
||||
}
|
||||
q += 1;
|
||||
}
|
||||
} while (q != NULL);
|
||||
out[0] = '\0';
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
const char *p11_strerror(CK_RV rv) {
|
||||
#define ERR_CASE(e) case e: return #e;
|
||||
switch (rv) {
|
||||
P11_ERRORS(ERR_CASE)
|
||||
|
||||
default:
|
||||
return "Unexpected Error";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//
|
||||
// Created by eugene on 7/1/19.
|
||||
//
|
||||
|
||||
#include <mbedtls/pk.h>
|
||||
|
||||
|
||||
#define CK_PTR *
|
||||
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
|
||||
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
|
||||
#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)
|
||||
|
||||
#ifndef NULL_PTR
|
||||
#define NULL_PTR 0
|
||||
#endif
|
||||
|
||||
#include "pkcs11/pkcs11.h"
|
||||
|
||||
#ifndef ZITI_SDK_MBED_P11_H
|
||||
#define ZITI_SDK_MBED_P11_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct mp11_context_s {
|
||||
void *lib;
|
||||
CK_FUNCTION_LIST *funcs;
|
||||
CK_SESSION_HANDLE session;
|
||||
CK_LONG slot_id;
|
||||
};
|
||||
|
||||
struct mp11_key_ctx_s {
|
||||
CK_OBJECT_HANDLE priv_handle;
|
||||
CK_OBJECT_HANDLE pub_handle;
|
||||
CK_MECHANISM_TYPE sign_mechanism;
|
||||
|
||||
struct mp11_context_s *ctx;
|
||||
void *pub; // mbedtls_rsa_context or mbedtls_ecdsa_context
|
||||
};
|
||||
|
||||
typedef struct mp11_context_s mp11_context;
|
||||
typedef struct mp11_key_ctx_s mp11_key_ctx;
|
||||
|
||||
int mp11_load_key(mbedtls_pk_context *key, const char *path, const char *opts);
|
||||
|
||||
int p11_load_ecdsa(mbedtls_pk_context *pk, struct mp11_key_ctx_s *pCtx, mp11_context *pS);
|
||||
|
||||
int p11_load_rsa(mbedtls_pk_context *pk, struct mp11_key_ctx_s *pCtx, mp11_context *pS);
|
||||
|
||||
|
||||
const char *p11_strerror(CK_RV rv);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif //ZITI_SDK_MBED_P11_H
|
||||
@@ -0,0 +1,214 @@
|
||||
//
|
||||
// Created by eugene on 7/2/19.
|
||||
//
|
||||
|
||||
#include <mbedtls/pk.h>
|
||||
#include <mbedtls/pk_internal.h>
|
||||
#include <utils.h>
|
||||
#include "mbed_p11.h"
|
||||
#include <mbedtls/asn1write.h>
|
||||
#include <mbedtls/oid.h>
|
||||
|
||||
static int p11_ecdsa_can_do(mbedtls_pk_type_t type);
|
||||
|
||||
static int p11_ecdsa_sign(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
unsigned char *sig, size_t *sig_len,
|
||||
int (*f_rng)(void *, unsigned char *, size_t),
|
||||
void *p_rng);
|
||||
|
||||
static int p11_ecdsa_verify(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
const unsigned char *sig, size_t sig_len);
|
||||
|
||||
static size_t p11_ecdsa_bitlen(const void *ctx);
|
||||
static void p11_ecdsa_free(void *ctx);
|
||||
|
||||
static int ecdsa_signature_to_asn1(const mbedtls_mpi *r, const mbedtls_mpi *s,
|
||||
unsigned char *sig, size_t *slen);
|
||||
|
||||
const mbedtls_pk_info_t p11_ecdsa_info = {
|
||||
MBEDTLS_PK_ECDSA,
|
||||
"ECDSA",
|
||||
p11_ecdsa_bitlen,
|
||||
p11_ecdsa_can_do,
|
||||
p11_ecdsa_verify,
|
||||
p11_ecdsa_sign,
|
||||
#if defined(MBEDTLS_ECP_RESTARTABLE)
|
||||
ecdsa_verify_rs_wrap,
|
||||
ecdsa_sign_rs_wrap,
|
||||
#endif
|
||||
NULL,
|
||||
NULL,
|
||||
NULL, //eckey_check_pair, /* Compatible key structures */
|
||||
NULL, //ecdsa_alloc_wrap,
|
||||
p11_ecdsa_free,
|
||||
#if defined(MBEDTLS_ECP_RESTARTABLE)
|
||||
ecdsa_rs_alloc,
|
||||
ecdsa_rs_free,
|
||||
#endif
|
||||
NULL, //eckey_debug, /* Compatible key structures */
|
||||
};
|
||||
|
||||
int p11_load_ecdsa(mbedtls_pk_context *pk, struct mp11_key_ctx_s *p11key, mp11_context *p11) {
|
||||
pk->pk_info = &p11_ecdsa_info;
|
||||
pk->pk_ctx = p11key;
|
||||
p11key->ctx = p11;
|
||||
|
||||
PREPCF(p11, non_zero, p11_strerror);
|
||||
|
||||
// load public key
|
||||
CK_BYTE ec_param[32];
|
||||
memset(ec_param, 0, sizeof(ec_param));
|
||||
CK_BYTE ec_point[MBEDTLS_ECP_MAX_PT_LEN];
|
||||
|
||||
CK_ATTRIBUTE pubattr[] = {
|
||||
{CKA_EC_PARAMS, ec_param, sizeof(ec_param)},
|
||||
{CKA_EC_POINT, ec_point, MBEDTLS_ECP_MAX_PT_LEN},
|
||||
};
|
||||
|
||||
TRY(p11, p11->funcs->C_GetAttributeValue(p11->session, p11key->pub_handle, pubattr, 2));
|
||||
|
||||
mbedtls_asn1_buf oid;
|
||||
unsigned char *p = ec_param;
|
||||
oid.p = ec_param;
|
||||
mbedtls_asn1_get_tag(&oid.p, p + pubattr[0].ulValueLen, &oid.len, MBEDTLS_ASN1_OID);
|
||||
|
||||
mbedtls_ecp_group_id grp_id = 0;
|
||||
mbedtls_oid_get_ec_grp(&oid, &grp_id);
|
||||
|
||||
NEWP(ecdsa, mbedtls_ecdsa_context);
|
||||
mbedtls_ecp_keypair_init(ecdsa);
|
||||
mbedtls_ecp_group_load(&ecdsa->grp, grp_id);
|
||||
|
||||
p = ec_point;
|
||||
size_t point_len;
|
||||
mbedtls_asn1_get_tag(&p, p + pubattr[1].ulValueLen, &point_len, MBEDTLS_ASN1_OCTET_STRING);
|
||||
|
||||
mbedtls_ecp_point_read_binary(&ecdsa->grp, &ecdsa->Q, p, point_len);
|
||||
p11key->pub = ecdsa;
|
||||
|
||||
CK_MECHANISM_TYPE sign_mech;
|
||||
switch (ecdsa->grp.pbits) {
|
||||
case 512:
|
||||
sign_mech = CKM_ECDSA_SHA512;
|
||||
break;
|
||||
case 384:
|
||||
sign_mech = CKM_ECDSA_SHA384;
|
||||
break;
|
||||
case 256:
|
||||
sign_mech = CKM_ECDSA_SHA256;
|
||||
break;
|
||||
case 224:
|
||||
sign_mech = CKM_ECDSA_SHA224;
|
||||
break;
|
||||
default:
|
||||
sign_mech = CKM_ECDSA_SHA1;
|
||||
}
|
||||
|
||||
CK_MECHANISM_INFO mech_info;
|
||||
CK_RV rv = p11->funcs->C_GetMechanismInfo(p11->slot_id, sign_mech, &mech_info);
|
||||
if (rv != CKR_OK) {
|
||||
sign_mech = CKM_ECDSA;
|
||||
rv = p11->funcs->C_GetMechanismInfo(p11->slot_id, sign_mech, &mech_info);
|
||||
}
|
||||
TRY(p11, ("expected signing mechanism not found", rv));
|
||||
p11key->sign_mechanism = sign_mech;
|
||||
|
||||
|
||||
CATCH(p11) {
|
||||
return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int p11_ecdsa_can_do(mbedtls_pk_type_t type) {
|
||||
return (type == MBEDTLS_PK_ECDSA);
|
||||
}
|
||||
|
||||
static int p11_ecdsa_sign(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
unsigned char *sig, size_t *sig_len,
|
||||
int (*f_rng)(void *, unsigned char *, size_t),
|
||||
void *p_rng) {
|
||||
PREPCF(p11, non_zero, p11_strerror);
|
||||
|
||||
mp11_key_ctx *p11key = ctx;
|
||||
mp11_context *p11 = p11key->ctx;
|
||||
|
||||
CK_MECHANISM mech = {
|
||||
p11key->sign_mechanism,
|
||||
};
|
||||
|
||||
CK_BYTE rawsig[MBEDTLS_ECP_MAX_PT_LEN];
|
||||
CK_ULONG rawsig_len = sizeof(rawsig);
|
||||
|
||||
TRY(p11, p11->funcs->C_SignInit(p11->session, &mech, p11key->priv_handle));
|
||||
TRY(p11, p11->funcs->C_Sign(p11->session, hash, hash_len, rawsig, &rawsig_len));
|
||||
|
||||
mbedtls_mpi r, s;
|
||||
mbedtls_mpi_init(&r);
|
||||
mbedtls_mpi_init(&s);
|
||||
|
||||
CK_ULONG coordlen = rawsig_len / 2;
|
||||
mbedtls_mpi_read_binary(&r, rawsig, coordlen);
|
||||
mbedtls_mpi_read_binary(&s, rawsig + coordlen, coordlen);
|
||||
|
||||
CATCH(p11) {
|
||||
return MBEDTLS_ERR_ECP_HW_ACCEL_FAILED;
|
||||
}
|
||||
|
||||
ecdsa_signature_to_asn1(&r, &s, sig, sig_len);
|
||||
|
||||
mbedtls_mpi_free(&r);
|
||||
mbedtls_mpi_free(&s);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ecdsa_signature_to_asn1(const mbedtls_mpi *r, const mbedtls_mpi *s,
|
||||
unsigned char *sig, size_t *slen) {
|
||||
int ret;
|
||||
unsigned char buf[MBEDTLS_ECDSA_MAX_LEN];
|
||||
unsigned char *p = buf + sizeof(buf);
|
||||
size_t len = 0;
|
||||
|
||||
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_mpi(&p, buf, s));
|
||||
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_mpi(&p, buf, r));
|
||||
|
||||
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&p, buf, len));
|
||||
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&p, buf,
|
||||
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
|
||||
|
||||
memcpy(sig, p, len);
|
||||
*slen = len;
|
||||
|
||||
return (0);
|
||||
}
|
||||
|
||||
static int p11_ecdsa_verify(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
const unsigned char *sig, size_t sig_len) {
|
||||
mp11_key_ctx *p11key = ctx;
|
||||
PREPF(mbed, fmt_mbederr);
|
||||
|
||||
|
||||
TRY(mbed, mbedtls_ecdsa_read_signature(p11key->pub, hash, hash_len, sig, sig_len));
|
||||
CATCH(mbed) {
|
||||
return ERR(mbed);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void p11_ecdsa_free(void *ctx) {
|
||||
mp11_key_ctx *p11key = ctx;
|
||||
mbedtls_ecp_keypair_free(p11key->pub);
|
||||
free(p11key->pub);
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
static size_t p11_ecdsa_bitlen(const void *ctx) {
|
||||
mp11_key_ctx *p11key = (mp11_key_ctx *) ctx;
|
||||
return (((mbedtls_ecdsa_context *) p11key->pub)->grp.pbits);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//
|
||||
// Created by eugene on 7/1/19.
|
||||
//
|
||||
|
||||
#ifndef ZITI_SDK_P11_ERRORS_H
|
||||
#define ZITI_SDK_P11_ERRORS_H
|
||||
|
||||
#endif //ZITI_SDK_P11_ERRORS_H
|
||||
|
||||
#define P11_ERRORS(XX) \
|
||||
XX(CKR_OK) \
|
||||
XX(CKR_CANCEL) \
|
||||
XX(CKR_HOST_MEMORY) \
|
||||
XX(CKR_SLOT_ID_INVALID) \
|
||||
XX(CKR_GENERAL_ERROR) \
|
||||
XX(CKR_FUNCTION_FAILED) \
|
||||
XX(CKR_ARGUMENTS_BAD) \
|
||||
XX(CKR_NO_EVENT) \
|
||||
XX(CKR_NEED_TO_CREATE_THREADS) \
|
||||
XX(CKR_CANT_LOCK) \
|
||||
XX(CKR_ATTRIBUTE_READ_ONLY) \
|
||||
XX(CKR_ATTRIBUTE_SENSITIVE) \
|
||||
XX(CKR_ATTRIBUTE_TYPE_INVALID) \
|
||||
XX(CKR_ATTRIBUTE_VALUE_INVALID) \
|
||||
XX(CKR_ACTION_PROHIBITED) \
|
||||
XX(CKR_DATA_INVALID) \
|
||||
XX(CKR_DATA_LEN_RANGE) \
|
||||
XX(CKR_DEVICE_ERROR) \
|
||||
XX(CKR_DEVICE_MEMORY) \
|
||||
XX(CKR_DEVICE_REMOVED) \
|
||||
XX(CKR_ENCRYPTED_DATA_INVALID) \
|
||||
XX(CKR_ENCRYPTED_DATA_LEN_RANGE) \
|
||||
XX(CKR_FUNCTION_CANCELED) \
|
||||
XX(CKR_FUNCTION_NOT_PARALLEL) \
|
||||
XX(CKR_FUNCTION_NOT_SUPPORTED) \
|
||||
XX(CKR_KEY_HANDLE_INVALID) \
|
||||
XX(CKR_KEY_SIZE_RANGE) \
|
||||
XX(CKR_KEY_TYPE_INCONSISTENT) \
|
||||
XX(CKR_KEY_NOT_NEEDED) \
|
||||
XX(CKR_KEY_CHANGED) \
|
||||
XX(CKR_KEY_NEEDED) \
|
||||
XX(CKR_KEY_INDIGESTIBLE) \
|
||||
XX(CKR_KEY_FUNCTION_NOT_PERMITTED) \
|
||||
XX(CKR_KEY_NOT_WRAPPABLE) \
|
||||
XX(CKR_KEY_UNEXTRACTABLE) \
|
||||
XX(CKR_MECHANISM_INVALID) \
|
||||
XX(CKR_MECHANISM_PARAM_INVALID) \
|
||||
XX(CKR_OBJECT_HANDLE_INVALID) \
|
||||
XX(CKR_OPERATION_ACTIVE) \
|
||||
XX(CKR_OPERATION_NOT_INITIALIZED) \
|
||||
XX(CKR_PIN_INCORRECT) \
|
||||
XX(CKR_PIN_INVALID) \
|
||||
XX(CKR_PIN_LEN_RANGE) \
|
||||
XX(CKR_PIN_EXPIRED) \
|
||||
XX(CKR_PIN_LOCKED) \
|
||||
XX(CKR_SESSION_CLOSED) \
|
||||
XX(CKR_SESSION_COUNT) \
|
||||
XX(CKR_SESSION_HANDLE_INVALID) \
|
||||
XX(CKR_SESSION_PARALLEL_NOT_SUPPORTED) \
|
||||
XX(CKR_SESSION_READ_ONLY) \
|
||||
XX(CKR_SESSION_EXISTS) \
|
||||
XX(CKR_SESSION_READ_ONLY_EXISTS) \
|
||||
XX(CKR_SESSION_READ_WRITE_SO_EXISTS) \
|
||||
XX(CKR_SIGNATURE_INVALID) \
|
||||
XX(CKR_SIGNATURE_LEN_RANGE) \
|
||||
XX(CKR_TEMPLATE_INCOMPLETE) \
|
||||
XX(CKR_TEMPLATE_INCONSISTENT) \
|
||||
XX(CKR_TOKEN_NOT_PRESENT) \
|
||||
XX(CKR_TOKEN_NOT_RECOGNIZED) \
|
||||
XX(CKR_TOKEN_WRITE_PROTECTED) \
|
||||
XX(CKR_UNWRAPPING_KEY_HANDLE_INVALID) \
|
||||
XX(CKR_UNWRAPPING_KEY_SIZE_RANGE) \
|
||||
XX(CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT) \
|
||||
XX(CKR_USER_ALREADY_LOGGED_IN) \
|
||||
XX(CKR_USER_NOT_LOGGED_IN) \
|
||||
XX(CKR_USER_PIN_NOT_INITIALIZED) \
|
||||
XX(CKR_USER_TYPE_INVALID) \
|
||||
XX(CKR_USER_ANOTHER_ALREADY_LOGGED_IN) \
|
||||
XX(CKR_USER_TOO_MANY_TYPES) \
|
||||
XX(CKR_WRAPPED_KEY_INVALID) \
|
||||
XX(CKR_WRAPPED_KEY_LEN_RANGE) \
|
||||
XX(CKR_WRAPPING_KEY_HANDLE_INVALID) \
|
||||
XX(CKR_WRAPPING_KEY_SIZE_RANGE) \
|
||||
XX(CKR_WRAPPING_KEY_TYPE_INCONSISTENT) \
|
||||
XX(CKR_RANDOM_SEED_NOT_SUPPORTED) \
|
||||
XX(CKR_RANDOM_NO_RNG) \
|
||||
XX(CKR_DOMAIN_PARAMS_INVALID) \
|
||||
XX(CKR_CURVE_NOT_SUPPORTED) \
|
||||
XX(CKR_BUFFER_TOO_SMALL) \
|
||||
XX(CKR_SAVED_STATE_INVALID) \
|
||||
XX(CKR_INFORMATION_SENSITIVE) \
|
||||
XX(CKR_STATE_UNSAVEABLE) \
|
||||
XX(CKR_CRYPTOKI_NOT_INITIALIZED) \
|
||||
XX(CKR_CRYPTOKI_ALREADY_INITIALIZED) \
|
||||
XX(CKR_MUTEX_BAD) \
|
||||
XX(CKR_MUTEX_NOT_LOCKED) \
|
||||
XX(CKR_NEW_PIN_MODE) \
|
||||
XX(CKR_NEXT_OTP) \
|
||||
XX(CKR_EXCEEDED_MAX_ITERATIONS) \
|
||||
XX(CKR_FIPS_SELF_TEST_FAILED) \
|
||||
XX(CKR_LIBRARY_LOAD_FAILED) \
|
||||
XX(CKR_PIN_TOO_WEAK) \
|
||||
XX(CKR_PUBLIC_KEY_INVALID) \
|
||||
XX(CKR_FUNCTION_REJECTED) \
|
||||
XX(CKR_VENDOR_DEFINED)
|
||||
@@ -0,0 +1,203 @@
|
||||
//
|
||||
// Created by eugene on 7/2/19.
|
||||
//
|
||||
|
||||
#include <mbedtls/pk.h>
|
||||
#include <mbedtls/pk_internal.h>
|
||||
#include <utils.h>
|
||||
#include "mbed_p11.h"
|
||||
#include <mbedtls/asn1write.h>
|
||||
#include <mbedtls/oid.h>
|
||||
|
||||
static int p11_rsa_can_do(mbedtls_pk_type_t type);
|
||||
|
||||
static int p11_rsa_sign(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
unsigned char *sig, size_t *sig_len,
|
||||
int (*f_rng)(void *, unsigned char *, size_t),
|
||||
void *p_rng);
|
||||
|
||||
static int p11_rsa_verify(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
const unsigned char *sig, size_t sig_len);
|
||||
|
||||
static size_t p11_rsa_bitlen(const void *ctx);
|
||||
|
||||
static void p11_rsa_free(void *ctx);
|
||||
|
||||
static int get_md_prefix(mbedtls_md_type_t md, const char **prefix, size_t *len);
|
||||
|
||||
const mbedtls_pk_info_t p11_rsa_info = {
|
||||
MBEDTLS_PK_RSA,
|
||||
"RSA",
|
||||
p11_rsa_bitlen,
|
||||
p11_rsa_can_do,
|
||||
p11_rsa_verify,
|
||||
p11_rsa_sign,
|
||||
#if defined(MBEDTLS_ECP_RESTARTABLE)
|
||||
rsa_verify_rs_wrap,
|
||||
rsa_sign_rs_wrap,
|
||||
#endif
|
||||
NULL,
|
||||
NULL,
|
||||
NULL, //eckey_check_pair, /* Compatible key structures */
|
||||
NULL, //rsa_alloc_wrap,
|
||||
p11_rsa_free,
|
||||
#if defined(MBEDTLS_ECP_RESTARTABLE)
|
||||
rsa_rs_alloc,
|
||||
rsa_rs_free,
|
||||
#endif
|
||||
NULL, //eckey_debug, /* Compatible key structures */
|
||||
};
|
||||
|
||||
int p11_load_rsa(mbedtls_pk_context *pk, struct mp11_key_ctx_s *p11key, mp11_context *p11) {
|
||||
pk->pk_info = &p11_rsa_info;
|
||||
pk->pk_ctx = p11key;
|
||||
p11key->ctx = p11;
|
||||
|
||||
PREPCF(p11, non_zero, p11_strerror);
|
||||
|
||||
// load public key
|
||||
CK_BYTE ec_param[512];
|
||||
memset(ec_param, 0, sizeof(ec_param));
|
||||
CK_BYTE ec_point[MBEDTLS_ECP_MAX_PT_LEN];
|
||||
|
||||
CK_ATTRIBUTE pubattr[] = {
|
||||
{CKA_PUBLIC_EXPONENT, NULL, 0},
|
||||
{CKA_MODULUS, NULL, 0},
|
||||
};
|
||||
|
||||
TRY(p11, p11->funcs->C_GetAttributeValue(p11->session, p11key->pub_handle, pubattr, 2));
|
||||
pubattr[0].pValue = malloc(pubattr[0].ulValueLen);
|
||||
pubattr[1].pValue = malloc(pubattr[1].ulValueLen);
|
||||
TRY(p11, p11->funcs->C_GetAttributeValue(p11->session, p11key->pub_handle, pubattr, 2));
|
||||
|
||||
NEWP(rsa, mbedtls_rsa_context);
|
||||
mbedtls_rsa_init(rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256);
|
||||
mbedtls_mpi_read_binary(&rsa->N, pubattr[1].pValue, pubattr[1].ulValueLen);
|
||||
mbedtls_mpi_read_binary(&rsa->E, pubattr[0].pValue, pubattr[0].ulValueLen);
|
||||
|
||||
rsa->len = mbedtls_mpi_size(&rsa->N);
|
||||
|
||||
CK_MECHANISM_TYPE sign_mech = CKM_RSA_PKCS;
|
||||
CK_MECHANISM_INFO mech_info;
|
||||
CK_RV rv = p11->funcs->C_GetMechanismInfo(p11->slot_id, sign_mech, &mech_info);
|
||||
if (rv != CKR_OK) {
|
||||
sign_mech = CKM_RSA_PKCS;
|
||||
rv = p11->funcs->C_GetMechanismInfo(p11->slot_id, sign_mech, &mech_info);
|
||||
}
|
||||
TRY(p11, ("expected signing mechanism not found", rv));
|
||||
p11key->sign_mechanism = sign_mech;
|
||||
p11key->pub = rsa;
|
||||
|
||||
CATCH(p11) {
|
||||
return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int p11_rsa_can_do(mbedtls_pk_type_t type) {
|
||||
return (type == MBEDTLS_PK_ECDSA);
|
||||
}
|
||||
|
||||
static int p11_rsa_sign(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
unsigned char *sig, size_t *sig_len,
|
||||
int (*f_rng)(void *, unsigned char *, size_t),
|
||||
void *p_rng) {
|
||||
PREPCF(p11, non_zero, p11_strerror);
|
||||
|
||||
mp11_key_ctx *p11key = ctx;
|
||||
mp11_context *p11 = p11key->ctx;
|
||||
|
||||
CK_MECHANISM mech = {
|
||||
p11key->sign_mechanism,
|
||||
};
|
||||
|
||||
CK_BYTE rawsig[4096];
|
||||
CK_ULONG rawsig_len = sizeof(rawsig);
|
||||
|
||||
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
|
||||
if (md_info == NULL) {
|
||||
return (MBEDTLS_ERR_RSA_BAD_INPUT_DATA);
|
||||
}
|
||||
|
||||
|
||||
hash_len = mbedtls_md_get_size(md_info);
|
||||
|
||||
const char *oid = "";
|
||||
size_t oid_len = 0;
|
||||
int rc = get_md_prefix(md_alg, &oid, &oid_len);
|
||||
|
||||
CK_BYTE *msg = malloc(hash_len + oid_len);
|
||||
memcpy(msg, oid, oid_len);
|
||||
memcpy(msg + oid_len, hash, hash_len);
|
||||
|
||||
TRY(p11, p11->funcs->C_SignInit(p11->session, &mech, p11key->priv_handle));
|
||||
TRY(p11, p11->funcs->C_Sign(p11->session, msg, hash_len + oid_len, rawsig, &rawsig_len));
|
||||
|
||||
memcpy(sig, rawsig, rawsig_len);
|
||||
*sig_len = rawsig_len;
|
||||
|
||||
CATCH(p11) {
|
||||
return MBEDTLS_ERR_ECP_HW_ACCEL_FAILED;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int p11_rsa_verify(void *ctx, mbedtls_md_type_t md_alg,
|
||||
const unsigned char *hash, size_t hash_len,
|
||||
const unsigned char *sig, size_t sig_len) {
|
||||
mp11_key_ctx *p11key = ctx;
|
||||
PREPF(mbed, fmt_mbederr);
|
||||
|
||||
TRY(mbed,
|
||||
mbedtls_rsa_rsassa_pkcs1_v15_verify(p11key->pub, NULL, NULL, MBEDTLS_RSA_PUBLIC, md_alg, hash_len, hash, sig));
|
||||
CATCH(mbed) {
|
||||
return ERR(mbed);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void p11_rsa_free(void *ctx) {
|
||||
mp11_key_ctx *p11key = ctx;
|
||||
mbedtls_rsa_free(p11key->pub);
|
||||
free(p11key->pub);
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
static size_t p11_rsa_bitlen(const void *ctx) {
|
||||
mp11_key_ctx *p11key = (mp11_key_ctx *) ctx;
|
||||
return 8 * mbedtls_rsa_get_len(p11key->pub);
|
||||
}
|
||||
|
||||
// pre-computed hash prefixes
|
||||
// copied from golang/crypto/rsa/rsa.go
|
||||
#define HASH_HEADERS(XX) \
|
||||
XX(MBEDTLS_MD_MD5, __bytes(0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10))\
|
||||
XX(MBEDTLS_MD_SHA1, __bytes(0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14))\
|
||||
XX(MBEDTLS_MD_SHA224, __bytes(0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c))\
|
||||
XX(MBEDTLS_MD_SHA256, __bytes(0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20))\
|
||||
XX(MBEDTLS_MD_SHA384, __bytes(0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30))\
|
||||
XX(MBEDTLS_MD_SHA512, __bytes(0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40))\
|
||||
XX(MBEDTLS_MD_RIPEMD160, __bytes(0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14))
|
||||
|
||||
#define MD_PREFIX(id, pfx) static char prefix_##id[] = {pfx};
|
||||
#define __bytes(...) __VA_ARGS__
|
||||
|
||||
HASH_HEADERS(MD_PREFIX)
|
||||
|
||||
static int get_md_prefix(mbedtls_md_type_t md, const char **prefix, size_t *len) {
|
||||
#define MD_CASE(id, _) case id: { *prefix = prefix_##id; *len = sizeof(prefix_##id); } break;
|
||||
switch (md) {
|
||||
HASH_HEADERS(MD_CASE)
|
||||
|
||||
default:
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
PKCS#11 headers
|
||||
===============
|
||||
|
||||
|info| |
|
||||
|----|------|
|
||||
|Current version|2.40.0|
|
||||
|Announcement|https://www.oasis-open.org/news/announcements/pkcs-11-cryptographic-token-interface-base-specification-interface-profiles-curre|
|
||||
|Source| https://github.com/oasis-tcs/pkcs11.git|
|
||||
|
||||
We just copy files here. Update them when necessary.
|
||||
@@ -0,0 +1,265 @@
|
||||
/* Copyright (c) OASIS Open 2016. All Rights Reserved./
|
||||
* /Distributed under the terms of the OASIS IPR Policy,
|
||||
* [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
|
||||
* IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
|
||||
* PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
|
||||
*/
|
||||
|
||||
/* Latest version of the specification:
|
||||
* http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
|
||||
*/
|
||||
|
||||
#ifndef _PKCS11_H_
|
||||
#define _PKCS11_H_ 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Before including this file (pkcs11.h) (or pkcs11t.h by
|
||||
* itself), 5 platform-specific macros must be defined. These
|
||||
* macros are described below, and typical definitions for them
|
||||
* are also given. Be advised that these definitions can depend
|
||||
* on both the platform and the compiler used (and possibly also
|
||||
* on whether a Cryptoki library is linked statically or
|
||||
* dynamically).
|
||||
*
|
||||
* In addition to defining these 5 macros, the packing convention
|
||||
* for Cryptoki structures should be set. The Cryptoki
|
||||
* convention on packing is that structures should be 1-byte
|
||||
* aligned.
|
||||
*
|
||||
* If you're using Microsoft Developer Studio 5.0 to produce
|
||||
* Win32 stuff, this might be done by using the following
|
||||
* preprocessor directive before including pkcs11.h or pkcs11t.h:
|
||||
*
|
||||
* #pragma pack(push, cryptoki, 1)
|
||||
*
|
||||
* and using the following preprocessor directive after including
|
||||
* pkcs11.h or pkcs11t.h:
|
||||
*
|
||||
* #pragma pack(pop, cryptoki)
|
||||
*
|
||||
* If you're using an earlier version of Microsoft Developer
|
||||
* Studio to produce Win16 stuff, this might be done by using
|
||||
* the following preprocessor directive before including
|
||||
* pkcs11.h or pkcs11t.h:
|
||||
*
|
||||
* #pragma pack(1)
|
||||
*
|
||||
* In a UNIX environment, you're on your own for this. You might
|
||||
* not need to do (or be able to do!) anything.
|
||||
*
|
||||
*
|
||||
* Now for the macros:
|
||||
*
|
||||
*
|
||||
* 1. CK_PTR: The indirection string for making a pointer to an
|
||||
* object. It can be used like this:
|
||||
*
|
||||
* typedef CK_BYTE CK_PTR CK_BYTE_PTR;
|
||||
*
|
||||
* If you're using Microsoft Developer Studio 5.0 to produce
|
||||
* Win32 stuff, it might be defined by:
|
||||
*
|
||||
* #define CK_PTR *
|
||||
*
|
||||
* If you're using an earlier version of Microsoft Developer
|
||||
* Studio to produce Win16 stuff, it might be defined by:
|
||||
*
|
||||
* #define CK_PTR far *
|
||||
*
|
||||
* In a typical UNIX environment, it might be defined by:
|
||||
*
|
||||
* #define CK_PTR *
|
||||
*
|
||||
*
|
||||
* 2. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
|
||||
* an importable Cryptoki library function declaration out of a
|
||||
* return type and a function name. It should be used in the
|
||||
* following fashion:
|
||||
*
|
||||
* extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)(
|
||||
* CK_VOID_PTR pReserved
|
||||
* );
|
||||
*
|
||||
* If you're using Microsoft Developer Studio 5.0 to declare a
|
||||
* function in a Win32 Cryptoki .dll, it might be defined by:
|
||||
*
|
||||
* #define CK_DECLARE_FUNCTION(returnType, name) \
|
||||
* returnType __declspec(dllimport) name
|
||||
*
|
||||
* If you're using an earlier version of Microsoft Developer
|
||||
* Studio to declare a function in a Win16 Cryptoki .dll, it
|
||||
* might be defined by:
|
||||
*
|
||||
* #define CK_DECLARE_FUNCTION(returnType, name) \
|
||||
* returnType __export _far _pascal name
|
||||
*
|
||||
* In a UNIX environment, it might be defined by:
|
||||
*
|
||||
* #define CK_DECLARE_FUNCTION(returnType, name) \
|
||||
* returnType name
|
||||
*
|
||||
*
|
||||
* 3. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
|
||||
* which makes a Cryptoki API function pointer declaration or
|
||||
* function pointer type declaration out of a return type and a
|
||||
* function name. It should be used in the following fashion:
|
||||
*
|
||||
* // Define funcPtr to be a pointer to a Cryptoki API function
|
||||
* // taking arguments args and returning CK_RV.
|
||||
* CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args);
|
||||
*
|
||||
* or
|
||||
*
|
||||
* // Define funcPtrType to be the type of a pointer to a
|
||||
* // Cryptoki API function taking arguments args and returning
|
||||
* // CK_RV, and then define funcPtr to be a variable of type
|
||||
* // funcPtrType.
|
||||
* typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args);
|
||||
* funcPtrType funcPtr;
|
||||
*
|
||||
* If you're using Microsoft Developer Studio 5.0 to access
|
||||
* functions in a Win32 Cryptoki .dll, in might be defined by:
|
||||
*
|
||||
* #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
|
||||
* returnType __declspec(dllimport) (* name)
|
||||
*
|
||||
* If you're using an earlier version of Microsoft Developer
|
||||
* Studio to access functions in a Win16 Cryptoki .dll, it might
|
||||
* be defined by:
|
||||
*
|
||||
* #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
|
||||
* returnType __export _far _pascal (* name)
|
||||
*
|
||||
* In a UNIX environment, it might be defined by:
|
||||
*
|
||||
* #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
|
||||
* returnType (* name)
|
||||
*
|
||||
*
|
||||
* 4. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
|
||||
* a function pointer type for an application callback out of
|
||||
* a return type for the callback and a name for the callback.
|
||||
* It should be used in the following fashion:
|
||||
*
|
||||
* CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args);
|
||||
*
|
||||
* to declare a function pointer, myCallback, to a callback
|
||||
* which takes arguments args and returns a CK_RV. It can also
|
||||
* be used like this:
|
||||
*
|
||||
* typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args);
|
||||
* myCallbackType myCallback;
|
||||
*
|
||||
* If you're using Microsoft Developer Studio 5.0 to do Win32
|
||||
* Cryptoki development, it might be defined by:
|
||||
*
|
||||
* #define CK_CALLBACK_FUNCTION(returnType, name) \
|
||||
* returnType (* name)
|
||||
*
|
||||
* If you're using an earlier version of Microsoft Developer
|
||||
* Studio to do Win16 development, it might be defined by:
|
||||
*
|
||||
* #define CK_CALLBACK_FUNCTION(returnType, name) \
|
||||
* returnType _far _pascal (* name)
|
||||
*
|
||||
* In a UNIX environment, it might be defined by:
|
||||
*
|
||||
* #define CK_CALLBACK_FUNCTION(returnType, name) \
|
||||
* returnType (* name)
|
||||
*
|
||||
*
|
||||
* 5. NULL_PTR: This macro is the value of a NULL pointer.
|
||||
*
|
||||
* In any ANSI/ISO C environment (and in many others as well),
|
||||
* this should best be defined by
|
||||
*
|
||||
* #ifndef NULL_PTR
|
||||
* #define NULL_PTR 0
|
||||
* #endif
|
||||
*/
|
||||
|
||||
|
||||
/* All the various Cryptoki types and #define'd values are in the
|
||||
* file pkcs11t.h.
|
||||
*/
|
||||
#include "pkcs11t.h"
|
||||
|
||||
#define __PASTE(x, y) x##y
|
||||
|
||||
|
||||
/* ==============================================================
|
||||
* Define the "extern" form of all the entry points.
|
||||
* ==============================================================
|
||||
*/
|
||||
|
||||
#define CK_NEED_ARG_LIST 1
|
||||
#define CK_PKCS11_FUNCTION_INFO(name) \
|
||||
extern CK_DECLARE_FUNCTION(CK_RV, name)
|
||||
|
||||
/* pkcs11f.h has all the information about the Cryptoki
|
||||
* function prototypes.
|
||||
*/
|
||||
#include "pkcs11f.h"
|
||||
|
||||
#undef CK_NEED_ARG_LIST
|
||||
#undef CK_PKCS11_FUNCTION_INFO
|
||||
|
||||
|
||||
/* ==============================================================
|
||||
* Define the typedef form of all the entry points. That is, for
|
||||
* each Cryptoki function C_XXX, define a type CK_C_XXX which is
|
||||
* a pointer to that kind of function.
|
||||
* ==============================================================
|
||||
*/
|
||||
|
||||
#define CK_NEED_ARG_LIST 1
|
||||
#define CK_PKCS11_FUNCTION_INFO(name) \
|
||||
typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
|
||||
|
||||
/* pkcs11f.h has all the information about the Cryptoki
|
||||
* function prototypes.
|
||||
*/
|
||||
#include "pkcs11f.h"
|
||||
|
||||
#undef CK_NEED_ARG_LIST
|
||||
#undef CK_PKCS11_FUNCTION_INFO
|
||||
|
||||
|
||||
/* ==============================================================
|
||||
* Define structed vector of entry points. A CK_FUNCTION_LIST
|
||||
* contains a CK_VERSION indicating a library's Cryptoki version
|
||||
* and then a whole slew of function pointers to the routines in
|
||||
* the library. This type was declared, but not defined, in
|
||||
* pkcs11t.h.
|
||||
* ==============================================================
|
||||
*/
|
||||
|
||||
#define CK_PKCS11_FUNCTION_INFO(name) \
|
||||
__PASTE(CK_,name) name;
|
||||
|
||||
struct CK_FUNCTION_LIST {
|
||||
|
||||
CK_VERSION version; /* Cryptoki version */
|
||||
|
||||
/* Pile all the function pointers into the CK_FUNCTION_LIST. */
|
||||
/* pkcs11f.h has all the information about the Cryptoki
|
||||
* function prototypes.
|
||||
*/
|
||||
#include "pkcs11f.h"
|
||||
|
||||
};
|
||||
|
||||
#undef CK_PKCS11_FUNCTION_INFO
|
||||
|
||||
|
||||
#undef __PASTE
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _PKCS11_H_ */
|
||||
|
||||
@@ -0,0 +1,939 @@
|
||||
/* Copyright (c) OASIS Open 2016. All Rights Reserved./
|
||||
* /Distributed under the terms of the OASIS IPR Policy,
|
||||
* [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
|
||||
* IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
|
||||
* PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
|
||||
*/
|
||||
|
||||
/* Latest version of the specification:
|
||||
* http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
|
||||
*/
|
||||
|
||||
/* This header file contains pretty much everything about all the
|
||||
* Cryptoki function prototypes. Because this information is
|
||||
* used for more than just declaring function prototypes, the
|
||||
* order of the functions appearing herein is important, and
|
||||
* should not be altered.
|
||||
*/
|
||||
|
||||
/* General-purpose */
|
||||
|
||||
/* C_Initialize initializes the Cryptoki library. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_Initialize)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets
|
||||
* cast to CK_C_INITIALIZE_ARGS_PTR
|
||||
* and dereferenced
|
||||
*/
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Finalize indicates that an application is done with the
|
||||
* Cryptoki library.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_Finalize)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_VOID_PTR pReserved /* reserved. Should be NULL_PTR */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetInfo returns general information about Cryptoki. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetInfo)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_INFO_PTR pInfo /* location that receives information */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetFunctionList returns the function list. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetFunctionList)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to
|
||||
* function list
|
||||
*/
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Slot and token management */
|
||||
|
||||
/* C_GetSlotList obtains a list of slots in the system. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetSlotList)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_BBOOL tokenPresent, /* only slots with tokens */
|
||||
CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */
|
||||
CK_ULONG_PTR pulCount /* receives number of slots */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetSlotInfo obtains information about a particular slot in
|
||||
* the system.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID, /* the ID of the slot */
|
||||
CK_SLOT_INFO_PTR pInfo /* receives the slot information */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetTokenInfo obtains information about a particular token
|
||||
* in the system.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID, /* ID of the token's slot */
|
||||
CK_TOKEN_INFO_PTR pInfo /* receives the token information */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetMechanismList obtains a list of mechanism types
|
||||
* supported by a token.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetMechanismList)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID, /* ID of token's slot */
|
||||
CK_MECHANISM_TYPE_PTR pMechanismList, /* gets mech. array */
|
||||
CK_ULONG_PTR pulCount /* gets # of mechs. */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetMechanismInfo obtains information about a particular
|
||||
* mechanism possibly supported by a token.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID, /* ID of the token's slot */
|
||||
CK_MECHANISM_TYPE type, /* type of mechanism */
|
||||
CK_MECHANISM_INFO_PTR pInfo /* receives mechanism info */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_InitToken initializes a token. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_InitToken)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID, /* ID of the token's slot */
|
||||
CK_UTF8CHAR_PTR pPin, /* the SO's initial PIN */
|
||||
CK_ULONG ulPinLen, /* length in bytes of the PIN */
|
||||
CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_InitPIN initializes the normal user's PIN. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_InitPIN)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_UTF8CHAR_PTR pPin, /* the normal user's PIN */
|
||||
CK_ULONG ulPinLen /* length in bytes of the PIN */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SetPIN modifies the PIN of the user who is logged in. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_SetPIN)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_UTF8CHAR_PTR pOldPin, /* the old PIN */
|
||||
CK_ULONG ulOldLen, /* length of the old PIN */
|
||||
CK_UTF8CHAR_PTR pNewPin, /* the new PIN */
|
||||
CK_ULONG ulNewLen /* length of the new PIN */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Session management */
|
||||
|
||||
/* C_OpenSession opens a session between an application and a
|
||||
* token.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_OpenSession)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID, /* the slot's ID */
|
||||
CK_FLAGS flags, /* from CK_SESSION_INFO */
|
||||
CK_VOID_PTR pApplication, /* passed to callback */
|
||||
CK_NOTIFY Notify, /* callback function */
|
||||
CK_SESSION_HANDLE_PTR phSession /* gets session handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_CloseSession closes a session between an application and a
|
||||
* token.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_CloseSession)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession /* the session's handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_CloseAllSessions closes all sessions with a token. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SLOT_ID slotID /* the token's slot */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetSessionInfo obtains information about the session. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_SESSION_INFO_PTR pInfo /* receives session info */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetOperationState obtains the state of the cryptographic operation
|
||||
* in a session.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetOperationState)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pOperationState, /* gets state */
|
||||
CK_ULONG_PTR pulOperationStateLen /* gets state length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SetOperationState restores the state of the cryptographic
|
||||
* operation in a session.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SetOperationState)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pOperationState, /* holds state */
|
||||
CK_ULONG ulOperationStateLen, /* holds state length */
|
||||
CK_OBJECT_HANDLE hEncryptionKey, /* en/decryption key */
|
||||
CK_OBJECT_HANDLE hAuthenticationKey /* sign/verify key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Login logs a user into a token. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_Login)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_USER_TYPE userType, /* the user type */
|
||||
CK_UTF8CHAR_PTR pPin, /* the user's PIN */
|
||||
CK_ULONG ulPinLen /* the length of the PIN */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Logout logs a user out from a token. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_Logout)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession /* the session's handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Object management */
|
||||
|
||||
/* C_CreateObject creates a new object. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_CreateObject)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* the object's template */
|
||||
CK_ULONG ulCount, /* attributes in template */
|
||||
CK_OBJECT_HANDLE_PTR phObject /* gets new object's handle. */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_CopyObject copies an object, creating a new object for the
|
||||
* copy.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_CopyObject)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_OBJECT_HANDLE hObject, /* the object's handle */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* template for new object */
|
||||
CK_ULONG ulCount, /* attributes in template */
|
||||
CK_OBJECT_HANDLE_PTR phNewObject /* receives handle of copy */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DestroyObject destroys an object. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_DestroyObject)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_OBJECT_HANDLE hObject /* the object's handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetObjectSize gets the size of an object in bytes. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetObjectSize)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_OBJECT_HANDLE hObject, /* the object's handle */
|
||||
CK_ULONG_PTR pulSize /* receives size of object */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GetAttributeValue obtains the value of one or more object
|
||||
* attributes.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_OBJECT_HANDLE hObject, /* the object's handle */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs; gets vals */
|
||||
CK_ULONG ulCount /* attributes in template */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SetAttributeValue modifies the value of one or more object
|
||||
* attributes.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_OBJECT_HANDLE hObject, /* the object's handle */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs and values */
|
||||
CK_ULONG ulCount /* attributes in template */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_FindObjectsInit initializes a search for token and session
|
||||
* objects that match a template.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* attribute values to match */
|
||||
CK_ULONG ulCount /* attrs in search template */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_FindObjects continues a search for token and session
|
||||
* objects that match a template, obtaining additional object
|
||||
* handles.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_FindObjects)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_OBJECT_HANDLE_PTR phObject, /* gets obj. handles */
|
||||
CK_ULONG ulMaxObjectCount, /* max handles to get */
|
||||
CK_ULONG_PTR pulObjectCount /* actual # returned */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_FindObjectsFinal finishes a search for token and session
|
||||
* objects.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession /* the session's handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Encryption and decryption */
|
||||
|
||||
/* C_EncryptInit initializes an encryption operation. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_EncryptInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the encryption mechanism */
|
||||
CK_OBJECT_HANDLE hKey /* handle of encryption key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Encrypt encrypts single-part data. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_Encrypt)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pData, /* the plaintext data */
|
||||
CK_ULONG ulDataLen, /* bytes of plaintext */
|
||||
CK_BYTE_PTR pEncryptedData, /* gets ciphertext */
|
||||
CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_EncryptUpdate continues a multiple-part encryption
|
||||
* operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pPart, /* the plaintext data */
|
||||
CK_ULONG ulPartLen, /* plaintext data len */
|
||||
CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */
|
||||
CK_ULONG_PTR pulEncryptedPartLen /* gets c-text size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_EncryptFinal finishes a multiple-part encryption
|
||||
* operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_EncryptFinal)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session handle */
|
||||
CK_BYTE_PTR pLastEncryptedPart, /* last c-text */
|
||||
CK_ULONG_PTR pulLastEncryptedPartLen /* gets last size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DecryptInit initializes a decryption operation. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_DecryptInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the decryption mechanism */
|
||||
CK_OBJECT_HANDLE hKey /* handle of decryption key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Decrypt decrypts encrypted data in a single part. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_Decrypt)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pEncryptedData, /* ciphertext */
|
||||
CK_ULONG ulEncryptedDataLen, /* ciphertext length */
|
||||
CK_BYTE_PTR pData, /* gets plaintext */
|
||||
CK_ULONG_PTR pulDataLen /* gets p-text size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DecryptUpdate continues a multiple-part decryption
|
||||
* operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pEncryptedPart, /* encrypted data */
|
||||
CK_ULONG ulEncryptedPartLen, /* input length */
|
||||
CK_BYTE_PTR pPart, /* gets plaintext */
|
||||
CK_ULONG_PTR pulPartLen /* p-text size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DecryptFinal finishes a multiple-part decryption
|
||||
* operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DecryptFinal)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pLastPart, /* gets plaintext */
|
||||
CK_ULONG_PTR pulLastPartLen /* p-text size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Message digesting */
|
||||
|
||||
/* C_DigestInit initializes a message-digesting operation. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_DigestInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism /* the digesting mechanism */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Digest digests data in a single part. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_Digest)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pData, /* data to be digested */
|
||||
CK_ULONG ulDataLen, /* bytes of data to digest */
|
||||
CK_BYTE_PTR pDigest, /* gets the message digest */
|
||||
CK_ULONG_PTR pulDigestLen /* gets digest length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DigestUpdate continues a multiple-part message-digesting
|
||||
* operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DigestUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pPart, /* data to be digested */
|
||||
CK_ULONG ulPartLen /* bytes of data to be digested */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DigestKey continues a multi-part message-digesting
|
||||
* operation, by digesting the value of a secret key as part of
|
||||
* the data already digested.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DigestKey)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_OBJECT_HANDLE hKey /* secret key to digest */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DigestFinal finishes a multiple-part message-digesting
|
||||
* operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DigestFinal)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pDigest, /* gets the message digest */
|
||||
CK_ULONG_PTR pulDigestLen /* gets byte count of digest */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Signing and MACing */
|
||||
|
||||
/* C_SignInit initializes a signature (private key encryption)
|
||||
* operation, where the signature is (will be) an appendix to
|
||||
* the data, and plaintext cannot be recovered from the
|
||||
* signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SignInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the signature mechanism */
|
||||
CK_OBJECT_HANDLE hKey /* handle of signature key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Sign signs (encrypts with private key) data in a single
|
||||
* part, where the signature is (will be) an appendix to the
|
||||
* data, and plaintext cannot be recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_Sign)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pData, /* the data to sign */
|
||||
CK_ULONG ulDataLen, /* count of bytes to sign */
|
||||
CK_BYTE_PTR pSignature, /* gets the signature */
|
||||
CK_ULONG_PTR pulSignatureLen /* gets signature length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SignUpdate continues a multiple-part signature operation,
|
||||
* where the signature is (will be) an appendix to the data,
|
||||
* and plaintext cannot be recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SignUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pPart, /* the data to sign */
|
||||
CK_ULONG ulPartLen /* count of bytes to sign */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SignFinal finishes a multiple-part signature operation,
|
||||
* returning the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SignFinal)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pSignature, /* gets the signature */
|
||||
CK_ULONG_PTR pulSignatureLen /* gets signature length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SignRecoverInit initializes a signature operation, where
|
||||
* the data can be recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the signature mechanism */
|
||||
CK_OBJECT_HANDLE hKey /* handle of the signature key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SignRecover signs data in a single operation, where the
|
||||
* data can be recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SignRecover)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pData, /* the data to sign */
|
||||
CK_ULONG ulDataLen, /* count of bytes to sign */
|
||||
CK_BYTE_PTR pSignature, /* gets the signature */
|
||||
CK_ULONG_PTR pulSignatureLen /* gets signature length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Verifying signatures and MACs */
|
||||
|
||||
/* C_VerifyInit initializes a verification operation, where the
|
||||
* signature is an appendix to the data, and plaintext cannot
|
||||
* cannot be recovered from the signature (e.g. DSA).
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the verification mechanism */
|
||||
CK_OBJECT_HANDLE hKey /* verification key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_Verify verifies a signature in a single-part operation,
|
||||
* where the signature is an appendix to the data, and plaintext
|
||||
* cannot be recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_Verify)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pData, /* signed data */
|
||||
CK_ULONG ulDataLen, /* length of signed data */
|
||||
CK_BYTE_PTR pSignature, /* signature */
|
||||
CK_ULONG ulSignatureLen /* signature length*/
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_VerifyUpdate continues a multiple-part verification
|
||||
* operation, where the signature is an appendix to the data,
|
||||
* and plaintext cannot be recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pPart, /* signed data */
|
||||
CK_ULONG ulPartLen /* length of signed data */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_VerifyFinal finishes a multiple-part verification
|
||||
* operation, checking the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_VerifyFinal)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pSignature, /* signature to verify */
|
||||
CK_ULONG ulSignatureLen /* signature length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_VerifyRecoverInit initializes a signature verification
|
||||
* operation, where the data is recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the verification mechanism */
|
||||
CK_OBJECT_HANDLE hKey /* verification key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_VerifyRecover verifies a signature in a single-part
|
||||
* operation, where the data is recovered from the signature.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_VerifyRecover)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pSignature, /* signature to verify */
|
||||
CK_ULONG ulSignatureLen, /* signature length */
|
||||
CK_BYTE_PTR pData, /* gets signed data */
|
||||
CK_ULONG_PTR pulDataLen /* gets signed data len */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Dual-function cryptographic operations */
|
||||
|
||||
/* C_DigestEncryptUpdate continues a multiple-part digesting
|
||||
* and encryption operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pPart, /* the plaintext data */
|
||||
CK_ULONG ulPartLen, /* plaintext length */
|
||||
CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */
|
||||
CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DecryptDigestUpdate continues a multiple-part decryption and
|
||||
* digesting operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pEncryptedPart, /* ciphertext */
|
||||
CK_ULONG ulEncryptedPartLen, /* ciphertext length */
|
||||
CK_BYTE_PTR pPart, /* gets plaintext */
|
||||
CK_ULONG_PTR pulPartLen /* gets plaintext len */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_SignEncryptUpdate continues a multiple-part signing and
|
||||
* encryption operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pPart, /* the plaintext data */
|
||||
CK_ULONG ulPartLen, /* plaintext length */
|
||||
CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */
|
||||
CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DecryptVerifyUpdate continues a multiple-part decryption and
|
||||
* verify operation.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_BYTE_PTR pEncryptedPart, /* ciphertext */
|
||||
CK_ULONG ulEncryptedPartLen, /* ciphertext length */
|
||||
CK_BYTE_PTR pPart, /* gets plaintext */
|
||||
CK_ULONG_PTR pulPartLen /* gets p-text length */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Key management */
|
||||
|
||||
/* C_GenerateKey generates a secret key, creating a new key
|
||||
* object.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GenerateKey)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* key generation mech. */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* template for new key */
|
||||
CK_ULONG ulCount, /* # of attrs in template */
|
||||
CK_OBJECT_HANDLE_PTR phKey /* gets handle of new key */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GenerateKeyPair generates a public-key/private-key pair,
|
||||
* creating new key objects.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* key-gen mech. */
|
||||
CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template for pub. key */
|
||||
CK_ULONG ulPublicKeyAttributeCount, /* # pub. attrs. */
|
||||
CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template for priv. key */
|
||||
CK_ULONG ulPrivateKeyAttributeCount, /* # priv. attrs. */
|
||||
CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub. key handle */
|
||||
CK_OBJECT_HANDLE_PTR phPrivateKey /* gets priv. key handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_WrapKey wraps (i.e., encrypts) a key. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_WrapKey)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* the wrapping mechanism */
|
||||
CK_OBJECT_HANDLE hWrappingKey, /* wrapping key */
|
||||
CK_OBJECT_HANDLE hKey, /* key to be wrapped */
|
||||
CK_BYTE_PTR pWrappedKey, /* gets wrapped key */
|
||||
CK_ULONG_PTR pulWrappedKeyLen /* gets wrapped key size */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
|
||||
* key object.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_UnwrapKey)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* unwrapping mech. */
|
||||
CK_OBJECT_HANDLE hUnwrappingKey, /* unwrapping key */
|
||||
CK_BYTE_PTR pWrappedKey, /* the wrapped key */
|
||||
CK_ULONG ulWrappedKeyLen, /* wrapped key len */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* new key template */
|
||||
CK_ULONG ulAttributeCount, /* template length */
|
||||
CK_OBJECT_HANDLE_PTR phKey /* gets new handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_DeriveKey derives a key from a base key, creating a new key
|
||||
* object.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_DeriveKey)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* session's handle */
|
||||
CK_MECHANISM_PTR pMechanism, /* key deriv. mech. */
|
||||
CK_OBJECT_HANDLE hBaseKey, /* base key */
|
||||
CK_ATTRIBUTE_PTR pTemplate, /* new key template */
|
||||
CK_ULONG ulAttributeCount, /* template length */
|
||||
CK_OBJECT_HANDLE_PTR phKey /* gets new handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Random number generation */
|
||||
|
||||
/* C_SeedRandom mixes additional seed material into the token's
|
||||
* random number generator.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_SeedRandom)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR pSeed, /* the seed material */
|
||||
CK_ULONG ulSeedLen /* length of seed material */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_GenerateRandom generates random data. */
|
||||
CK_PKCS11_FUNCTION_INFO(C_GenerateRandom)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession, /* the session's handle */
|
||||
CK_BYTE_PTR RandomData, /* receives the random data */
|
||||
CK_ULONG ulRandomLen /* # of bytes to generate */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* Parallel function management */
|
||||
|
||||
/* C_GetFunctionStatus is a legacy function; it obtains an
|
||||
* updated status of a function running in parallel with an
|
||||
* application.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession /* the session's handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_CancelFunction is a legacy function; it cancels a function
|
||||
* running in parallel.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_CancelFunction)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_SESSION_HANDLE hSession /* the session's handle */
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/* C_WaitForSlotEvent waits for a slot event (token insertion,
|
||||
* removal, etc.) to occur.
|
||||
*/
|
||||
CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent)
|
||||
#ifdef CK_NEED_ARG_LIST
|
||||
(
|
||||
CK_FLAGS flags, /* blocking/nonblocking flag */
|
||||
CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */
|
||||
CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */
|
||||
);
|
||||
#endif
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
char* zitistrndup(const char* s, int n);
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
//
|
||||
// Created by eugene on 2/27/19.
|
||||
//
|
||||
#include <stdlib.h>
|
||||
#include <mbedtls/base64.h>
|
||||
#include <mbedtls/ssl.h>
|
||||
#include <mbedtls/entropy.h>
|
||||
#include <mbedtls/ctr_drbg.h>
|
||||
#include <http_parser.h>
|
||||
#include "tls.h"
|
||||
#include "utils.h"
|
||||
#include "zt_internal.h"
|
||||
#include "p11/mbed_p11.h"
|
||||
|
||||
#if _WIN32
|
||||
#include <io.h>
|
||||
#include <wincrypt.h>
|
||||
#pragma comment (lib, "crypt32.lib")
|
||||
|
||||
#define strncasecmp _strnicmp
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
// inspired by https://golang.org/src/crypto/x509/root_linux.go
|
||||
// Possible certificate files; stop after finding one.
|
||||
const char * const caFiles[] = {
|
||||
"/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
|
||||
"/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL 6
|
||||
"/etc/ssl/ca-bundle.pem", // OpenSUSE
|
||||
"/etc/pki/tls/cacert.pem", // OpenELEC
|
||||
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7
|
||||
"/etc/ssl/cert.pem" // macOS
|
||||
};
|
||||
#define NUM_CAFILES (sizeof(caFiles) / sizeof(char *))
|
||||
|
||||
void tls_debug(void *ctx, int level,
|
||||
const char *file, int line,
|
||||
const char *str)
|
||||
{
|
||||
((void) level);
|
||||
printf("%s:%04d: %s", file, line, str );
|
||||
fflush( stdout );
|
||||
}
|
||||
|
||||
int load_key(mbedtls_pk_context *pk, const char *spec) {
|
||||
|
||||
PREPF(mbed, fmt_mbederr);
|
||||
|
||||
struct http_parser_url url;
|
||||
http_parser_url_init(&url);
|
||||
http_parser_parse_url(spec, strlen(spec), 0, &url);
|
||||
|
||||
|
||||
if (strncasecmp("pem", spec + url.field_data[UF_SCHEMA].off, url.field_data[UF_SCHEMA].len) == 0) {
|
||||
|
||||
TRY(mbed, mbedtls_pk_parse_key(pk, spec + 4, strlen(spec) - 3, NULL, 0));
|
||||
|
||||
}
|
||||
else if (strncasecmp("der", spec + url.field_data[UF_SCHEMA].off, url.field_data[UF_SCHEMA].len) == 0) {
|
||||
if ((url.field_set & (1 << UF_OPAQ)) == 0) {
|
||||
return ZITI_WTF;
|
||||
}
|
||||
|
||||
size_t len = url.field_data[UF_OPAQ].len;
|
||||
|
||||
size_t derlen;
|
||||
unsigned char *der = malloc(len);
|
||||
TRY(mbed, mbedtls_base64_decode(der, len, &derlen, spec + url.field_data[UF_OPAQ].off, len));
|
||||
TRY(mbed, mbedtls_pk_parse_key(pk, der, derlen, NULL, 0));
|
||||
free(der);
|
||||
|
||||
}
|
||||
else if (strncasecmp("file", spec + url.field_data[UF_SCHEMA].off, url.field_data[UF_SCHEMA].len) == 0) {
|
||||
if ((url.field_set & (1 << UF_PATH)) == 0) {
|
||||
ZITI_LOG(ERROR, "key spec error, file without a path");
|
||||
return ZITI_KEY_INVALID;
|
||||
}
|
||||
|
||||
size_t path_len = url.field_data[UF_PATH].len;
|
||||
|
||||
char *path = malloc(path_len + 1);
|
||||
snprintf(path, path_len + 1, "%*.*s", (int) path_len, (int) path_len, spec + url.field_data[UF_PATH].off);
|
||||
TRY(mbed, mbedtls_pk_parse_keyfile(pk, path, NULL));
|
||||
}
|
||||
else if (strncasecmp("pkcs11", spec + url.field_data[UF_SCHEMA].off, url.field_data[UF_SCHEMA].len) == 0) {
|
||||
char lib[1024];
|
||||
if (!get_url_data(spec, &url, UF_PATH, lib, sizeof(lib)) &&
|
||||
!get_url_data(spec, &url, UF_OPAQ, lib, sizeof(lib))) {
|
||||
ZITI_LOG(ERROR, "key spec error, pkcs11 requires driver library");
|
||||
return ZITI_KEY_INVALID;
|
||||
}
|
||||
|
||||
char opts[1024];
|
||||
get_url_data(spec, &url, UF_QUERY, opts, sizeof(opts));
|
||||
|
||||
TRY(mbed, mp11_load_key(pk, lib, opts));
|
||||
}
|
||||
else {
|
||||
return ZITI_KEY_SPEC_UNSUPPORTED;
|
||||
}
|
||||
|
||||
CATCH(mbed) {
|
||||
return ZITI_KEY_INVALID;
|
||||
}
|
||||
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
#if _WIN32
|
||||
int prep_ca_win(mbedtls_x509_crt* my_ca_chain) {
|
||||
HCERTSTORE hCertStore;
|
||||
PCCERT_CONTEXT pCertContext = NULL;
|
||||
|
||||
if (!(hCertStore = CertOpenSystemStore(0, "ROOT")))
|
||||
{
|
||||
printf("The first system store did not open.");
|
||||
return -1;
|
||||
}
|
||||
while (pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) {
|
||||
mbedtls_x509_crt_parse(my_ca_chain, pCertContext->pbCertEncoded, pCertContext->cbCertEncoded);
|
||||
}
|
||||
CertFreeCertificateContext(pCertContext);
|
||||
CertCloseStore(hCertStore, 0);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
int tls_context_init(nf_config *config, nf_tls_context *tls) {
|
||||
PREPF(mbed, fmt_mbederr);
|
||||
mbedtls_ssl_config_init(&tls->config);
|
||||
mbedtls_ssl_conf_dbg(&tls->config, tls_debug, stdout);
|
||||
mbedtls_ssl_config_defaults( &tls->config,
|
||||
MBEDTLS_SSL_IS_CLIENT,
|
||||
MBEDTLS_SSL_TRANSPORT_STREAM,
|
||||
MBEDTLS_SSL_PRESET_DEFAULT );
|
||||
mbedtls_ssl_conf_authmode( &tls->config, MBEDTLS_SSL_VERIFY_REQUIRED );
|
||||
mbedtls_x509_crt_init( &tls->cacert );
|
||||
mbedtls_x509_crt_init(&tls->cert);
|
||||
mbedtls_pk_init(&tls->key);
|
||||
mbedtls_ctr_drbg_init( &tls->ctr_drbg );
|
||||
mbedtls_entropy_init( &tls->entropy );
|
||||
|
||||
// load key
|
||||
load_key(&tls->key, config->key);
|
||||
|
||||
// load cert
|
||||
if (strncmp("file:", config->key, 5) == 0) {
|
||||
// load file
|
||||
//TRY(mbed, mbedtls_x509_crt_parse_file(&TLS_GLOBAL.cert, config->cert));
|
||||
} else if (strncmp("pem:", config->cert, 4) == 0) {
|
||||
// load inline PEM
|
||||
size_t certlen = strlen(config->cert) - 4;
|
||||
TRY(mbed, mbedtls_x509_crt_parse(&tls->cert, config->cert + 4, certlen + 1));
|
||||
}
|
||||
|
||||
TRY(mbed, mbedtls_ssl_conf_own_cert(&tls->config, &tls->cert, &tls->key));
|
||||
|
||||
#if WIN32
|
||||
prep_ca_win(&tls->cacert);
|
||||
#else
|
||||
// look for default CAs in conventional locations; load first one that is found.
|
||||
int i;
|
||||
for (i = 0; i < NUM_CAFILES; i++) {
|
||||
ZITI_LOG(DEBUG, "checking root CA path %s", caFiles[i]);
|
||||
if (access(caFiles[i], R_OK) != -1) {
|
||||
ZITI_LOG(INFO, "found root CA path %s", caFiles[i]);
|
||||
TRY(mbed, mbedtls_x509_crt_parse_file(&tls->cacert, caFiles[i]));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (i == NUM_CAFILES) {
|
||||
int caFiles_strlen = 0;
|
||||
for (i = 0; i < NUM_CAFILES; i++) {
|
||||
caFiles_strlen += strlen(caFiles[i]) + strlen(", ");
|
||||
}
|
||||
char *caFiles_str = (char *)malloc(caFiles_strlen * sizeof(char));
|
||||
for (i = 0; i < NUM_CAFILES; i++) {
|
||||
(void)strcat(caFiles_str, caFiles[i]);
|
||||
if (i < NUM_CAFILES-1) {
|
||||
(void)strcat(caFiles_str, ", ");
|
||||
}
|
||||
}
|
||||
ZITI_LOG(WARN, "default root CA store not found. looked in %s", caFiles_str);
|
||||
free(caFiles_str);
|
||||
}
|
||||
#endif
|
||||
|
||||
// load ca from nf config if present
|
||||
if (config->ca != NULL) {
|
||||
if (strncmp("file:", config->ca, 5) == 0) {
|
||||
// load file
|
||||
char* path = config->ca + strlen("file://");
|
||||
TRY(mbed, mbedtls_x509_crt_parse_file(&tls->cacert, path));
|
||||
}
|
||||
else if (strncmp("pem:", config->ca, 4) == 0) {
|
||||
// load inline PEM
|
||||
size_t calen = strlen(config->ca) - 4;
|
||||
TRY(mbed, mbedtls_x509_crt_parse(&tls->cacert, config->ca + 4, calen + 1));
|
||||
}
|
||||
}
|
||||
|
||||
mbedtls_ssl_conf_ca_chain(&tls->config, &tls->cacert, NULL);
|
||||
|
||||
unsigned char* seed = (unsigned char *) "this is entropy seed";
|
||||
TRY(mbed, mbedtls_ctr_drbg_seed( &tls->ctr_drbg, mbedtls_entropy_func, &tls->entropy,
|
||||
seed, strlen(seed)));
|
||||
mbedtls_ssl_conf_rng(&tls->config, mbedtls_ctr_drbg_random, &tls->ctr_drbg);
|
||||
|
||||
CATCH(mbed) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int tls_context_free(nf_tls_context *tls) {
|
||||
mbedtls_x509_crt_free(&tls->cacert);
|
||||
mbedtls_x509_crt_free(&tls->cert);
|
||||
mbedtls_pk_free(&tls->key);
|
||||
mbedtls_ctr_drbg_free(&tls->ctr_drbg);
|
||||
mbedtls_entropy_free(&tls->entropy);
|
||||
mbedtls_ssl_config_free(&tls->config);
|
||||
return 0;
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
//
|
||||
// Created by eugene on 12/20/17.
|
||||
//
|
||||
#include <mbedtls/error.h>
|
||||
#include <mjson.h>
|
||||
#include <uv.h>
|
||||
#include "utils.h"
|
||||
|
||||
|
||||
#if !defined(ZITI_VERSION)
|
||||
#define ZITI_VERSION unknown
|
||||
#endif
|
||||
|
||||
#if !defined(ZITI_BUILDNUM)
|
||||
#define ZITI_BUILDNUM <local>
|
||||
#endif
|
||||
|
||||
#if !defined(ZITI_BRANCH)
|
||||
#define ZITI_BRANCH "<no-branch>"
|
||||
#define ZITI_COMMIT "<sha>"
|
||||
#endif
|
||||
|
||||
#define to_str(x) str(x)
|
||||
#define str(x) #x
|
||||
|
||||
const char* ziti_get_version(int verbose) {
|
||||
if (verbose) {
|
||||
return "\n\tVersion:\t" to_str(ZITI_VERSION)
|
||||
"\n\tBuild Date:\t" to_str(BUILD_DATE)
|
||||
"\n\tGit Branch:\t" to_str(ZITI_BRANCH)
|
||||
"\n\tGit SHA:\t" to_str(ZITI_COMMIT)
|
||||
"\n\tOS:\t" // TODO
|
||||
"\n\tArch:\t" // TODO
|
||||
"\n";
|
||||
|
||||
}
|
||||
return to_str(ZITI_VERSION) "-" to_str(ZITI_BUILDNUM);
|
||||
}
|
||||
|
||||
const char* ziti_git_branch() {
|
||||
return to_str(ZITI_BRANCH);
|
||||
}
|
||||
|
||||
const char* ziti_git_commit() {
|
||||
return to_str(ZITI_COMMIT);
|
||||
}
|
||||
|
||||
int ziti_debug_level = INFO;
|
||||
FILE *ziti_debug_out;
|
||||
|
||||
#if _WIN32
|
||||
LARGE_INTEGER frequency;
|
||||
LARGE_INTEGER start;
|
||||
LARGE_INTEGER end;
|
||||
#else
|
||||
struct timespec starttime;
|
||||
#endif
|
||||
|
||||
void init_debug() {
|
||||
char *level = getenv("ZITI_LOG");
|
||||
if (level != NULL) {
|
||||
ziti_debug_level = (int) strtol(level, NULL, 10);
|
||||
}
|
||||
ziti_debug_out = stderr;
|
||||
#if _WIN32
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
QueryPerformanceCounter(&start);
|
||||
#else
|
||||
clock_gettime(CLOCK_MONOTONIC, &starttime);
|
||||
#endif
|
||||
}
|
||||
|
||||
long get_elapsed() {
|
||||
#if _WIN32
|
||||
QueryPerformanceCounter(&end);
|
||||
return end.QuadPart - start.QuadPart;
|
||||
#else
|
||||
struct timespec cur;
|
||||
clock_gettime(CLOCK_MONOTONIC, &cur);
|
||||
return (cur.tv_sec - starttime.tv_sec) * 1000 + ((cur.tv_nsec - starttime.tv_nsec) / ((long)1e6));
|
||||
#endif
|
||||
}
|
||||
|
||||
static char errbuf[1024];
|
||||
char* fmt_mbederr(int err) {
|
||||
mbedtls_strerror(err, errbuf, sizeof(errbuf));
|
||||
return errbuf;
|
||||
}
|
||||
|
||||
void ziti_alloc_cb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
|
||||
buf->base = (char *) malloc(suggested_size);
|
||||
if (buf->base == NULL) {
|
||||
ZITI_LOG(ERROR, "failed to allocate %ld bytes. Prepare for crash", suggested_size);
|
||||
buf->len = 0;
|
||||
}
|
||||
else {
|
||||
buf->len = suggested_size;
|
||||
}
|
||||
}
|
||||
|
||||
char* zitistrndup(const char* s, int n)
|
||||
{
|
||||
size_t len = strnlen(s, n);
|
||||
char* new = (char*)malloc(len + 1);
|
||||
if (new == NULL)
|
||||
return NULL;
|
||||
new[len] = '\0';
|
||||
return (char*)memcpy(new, s, len);
|
||||
}
|
||||
|
||||
int get_url_data(const char *url, struct http_parser_url *parser, int uf, char *out, size_t maxout) {
|
||||
if ((parser->field_set & (1 << uf)) != 0) {
|
||||
snprintf(out, maxout, "%*.*s", parser->field_data[uf].len, parser->field_data[uf].len,
|
||||
url + parser->field_data[uf].off);
|
||||
return 1;
|
||||
}
|
||||
out[0] = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lt_zero(int v) { return v < 0; }
|
||||
|
||||
int non_zero(int v) { return v != 0; }
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <nf/ziti.h>
|
||||
#include <uv.h>
|
||||
#include "utils.h"
|
||||
#include "zt_internal.h"
|
||||
#include <http_parser.h>
|
||||
|
||||
#define DEFAULT_TIMEOUT 5000
|
||||
|
||||
struct nf_init_req {
|
||||
nf_context nf;
|
||||
int init_status;
|
||||
nf_init_cb init_cb;
|
||||
void* init_ctx;
|
||||
};
|
||||
|
||||
static void init_work(uv_work_t *req) {
|
||||
ZITI_LOG(INFO, "initializing ziti");
|
||||
PREPF(ziti, ziti_errorstr);
|
||||
|
||||
struct nf_init_req *init_req = req->data;
|
||||
|
||||
nf_context ctx = init_req->nf;
|
||||
SLIST_INIT(&ctx->channels);
|
||||
|
||||
TRY(ziti, ziti_auth(ctx));
|
||||
|
||||
CATCH(ziti) {
|
||||
init_req->init_status = ERR(ziti);
|
||||
}
|
||||
}
|
||||
|
||||
static void init_complete(uv_work_t* req, int status) {
|
||||
struct nf_init_req *init_req = req->data;
|
||||
|
||||
if (init_req->init_status == ZITI_OK) {
|
||||
struct nf_ctx *nf = init_req->nf;
|
||||
nf->loop = req->loop;
|
||||
nf->loop_thread = uv_thread_self();
|
||||
nf->ziti_timeout = DEFAULT_TIMEOUT;
|
||||
nf->ch_counter = 0;
|
||||
}
|
||||
|
||||
init_req->init_cb(init_req->nf, init_req->init_status, init_req->init_ctx);
|
||||
free(init_req);
|
||||
free(req);
|
||||
}
|
||||
|
||||
static size_t parse_ref(const char *val, const char **res) {
|
||||
size_t len = 0;
|
||||
*res = NULL;
|
||||
if (val != NULL) {
|
||||
if (strncmp("file:", val, 5) == 0) {
|
||||
// load file
|
||||
*res = val + strlen("file://");
|
||||
len = strlen(*res) + 1;
|
||||
}
|
||||
else if (strncmp("pem:", val, 4) == 0) {
|
||||
// load inline PEM
|
||||
*res = val + 4;
|
||||
len = strlen(val + 4) + 1;
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
int NF_init(const char* config, uv_loop_t* loop, nf_init_cb init_cb, void* init_ctx) {
|
||||
init_debug();
|
||||
|
||||
ZITI_LOG(INFO, "ZitiSDK version %s @%s(%s)", ziti_get_version(false), ziti_git_commit(), ziti_git_branch());
|
||||
|
||||
PREP(ziti);
|
||||
nf_config *cfg;
|
||||
TRY(ziti, load_config(config, &cfg));
|
||||
|
||||
CATCH(ziti) {
|
||||
return ERR(ziti);
|
||||
}
|
||||
|
||||
// load ca from nf config if present
|
||||
const char *ca, *key, *cert;
|
||||
size_t ca_len = parse_ref(cfg->ca, &ca);
|
||||
size_t key_len = parse_ref(cfg->key, &key);
|
||||
size_t cert_len = parse_ref(cfg->cert, &cert);
|
||||
|
||||
tls_context *tls = default_tls_context(ca, ca_len);
|
||||
tls->api->set_own_cert(tls->ctx, cert, cert_len, key, key_len);
|
||||
|
||||
return NF_init_with_tls(cfg->controller_url, tls, loop, init_cb, init_ctx);
|
||||
}
|
||||
|
||||
int
|
||||
NF_init_with_tls(const char *ctrl_url, tls_context *tls_context, uv_loop_t *loop, nf_init_cb init_cb, void *init_ctx) {
|
||||
init_debug();
|
||||
ZITI_LOG(INFO, "ZitiSDK version %s @%s(%s)", ziti_get_version(false), ziti_git_commit(), ziti_git_branch());
|
||||
|
||||
if (tls_context == NULL) {
|
||||
ZITI_LOG(ERROR, "tls context is required");
|
||||
return ZITI_CONFIG_NOT_FOUND;
|
||||
}
|
||||
|
||||
NEWP(ctx, struct nf_ctx);
|
||||
|
||||
struct http_parser_url url;
|
||||
http_parser_url_init(&url);
|
||||
http_parser_parse_url(ctrl_url, strlen(ctrl_url), 0, &url);
|
||||
strncpy(ctx->controller, ctrl_url + url.field_data[UF_HOST].off, url.field_data[UF_HOST].len);
|
||||
ctx->controller_port = url.port;
|
||||
|
||||
ctx->tlsCtx = tls_context;
|
||||
|
||||
NEWP(init_req, struct nf_init_req);
|
||||
init_req->init_cb = init_cb;
|
||||
init_req->init_ctx = init_ctx;
|
||||
init_req->nf = ctx;
|
||||
|
||||
NEWP(iw, uv_work_t);
|
||||
iw->data = init_req;
|
||||
uv_queue_work(loop, iw, init_work, init_complete);
|
||||
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int NF_set_timeout(nf_context ctx, int timeout) {
|
||||
if (timeout > 0) {
|
||||
ctx->ziti_timeout = timeout;
|
||||
}
|
||||
else {
|
||||
ctx->ziti_timeout = DEFAULT_TIMEOUT;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int NF_shutdown(nf_context ctx) {
|
||||
ZITI_LOG(INFO, "Ziti is shutting down");
|
||||
|
||||
ziti_close_channels(ctx);
|
||||
|
||||
return ziti_logout(ctx);
|
||||
}
|
||||
|
||||
int NF_free(nf_context *ctxp) {
|
||||
if ((*ctxp)->tlsCtx != NULL) {
|
||||
(*ctxp)->tlsCtx->api->free_ctx((*ctxp)->tlsCtx);
|
||||
}
|
||||
free(*ctxp);
|
||||
*ctxp = NULL;
|
||||
|
||||
ZITI_LOG(INFO, "shutdown is complete\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
void NF_dump(struct nf_ctx *ctx) {
|
||||
char info[1024];
|
||||
printf("Identity:\n%s\n", info);
|
||||
|
||||
printf("Session: %s\n", VAL_OR_ELSE(ctx->ziti_session, "<not logged in>"));
|
||||
|
||||
printf("\n=================\nServices:\n");
|
||||
for (int i = 0; ctx->services[i] != NULL; i++) {
|
||||
dump_ziti_service(ctx->services[i], 0);
|
||||
}
|
||||
|
||||
printf("\n==================\nNet Sessions:\n");
|
||||
for (int i = 0; ctx->net_sessions[i] != NULL; i++) {
|
||||
dump_ziti_net_session(ctx->net_sessions[i], 0);
|
||||
}
|
||||
}
|
||||
|
||||
int NF_conn_init(nf_context nf_ctx, nf_connection *conn, void *data) {
|
||||
struct nf_ctx *ctx = nf_ctx;
|
||||
NEWP(c, struct nf_conn);
|
||||
c->nf_ctx = nf_ctx;
|
||||
c->data = data;
|
||||
c->channel = NULL;
|
||||
c->state = Initial;
|
||||
c->timeout = ctx->ziti_timeout;
|
||||
|
||||
*conn = c;
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
void *NF_conn_data(nf_connection conn) {
|
||||
return conn->data;
|
||||
}
|
||||
|
||||
int NF_dial(nf_connection conn, const char *service, nf_conn_cb conn_cb, nf_data_cb data_cb) {
|
||||
return ziti_dial(conn, service, conn_cb, data_cb);
|
||||
}
|
||||
|
||||
int NF_close(nf_connection *conn) {
|
||||
struct nf_conn *c = *conn;
|
||||
|
||||
ziti_disconnect(c);
|
||||
|
||||
*conn = NULL;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int NF_write(nf_connection conn, uint8_t *buf, size_t length, nf_write_cb cb, void *ctx) {
|
||||
|
||||
NEWP(req, struct nf_write_req);
|
||||
req->conn = conn;
|
||||
req->buf = buf;
|
||||
req->len = length;
|
||||
req->cb = cb;
|
||||
req->ctx = ctx;
|
||||
|
||||
return ziti_write(req);
|
||||
}
|
||||
|
||||
int NF_service_available(nf_context nf, const char *service) {
|
||||
for(ziti_service **s = nf->services; s != NULL; s++) {
|
||||
if (strcmp(service, (*s)->name) == 0) {
|
||||
return ZITI_OK;
|
||||
}
|
||||
}
|
||||
|
||||
return ZITI_SERVICE_UNAVALABLE;
|
||||
}
|
||||
|
||||
extern int NF_listen(nf_connection serv_conn, const char *service, nf_listen_cb lcb, nf_client_cb cb) {
|
||||
return ziti_bind(serv_conn, service, lcb, cb);
|
||||
}
|
||||
|
||||
extern int NF_accept(nf_connection clt, nf_conn_cb cb, nf_data_cb data_cb) {
|
||||
return ziti_accept(clt, cb, data_cb);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "utils.h"
|
||||
#include "tls.h"
|
||||
#include "zt_internal.h"
|
||||
#include "controller.h"
|
||||
|
||||
|
||||
int ziti_logout(struct nf_ctx* ctx) {
|
||||
PREPF(ziti, ziti_errorstr);
|
||||
ziti_ctrl_logout(ctx, 0, NULL);
|
||||
|
||||
free_ziti_service_array(ctx->services);
|
||||
ctx->services = NULL;
|
||||
free_ziti_net_session_array(ctx->net_sessions);
|
||||
ctx->net_sessions = NULL;
|
||||
|
||||
CATCH(ziti);
|
||||
return ZITI_OK;
|
||||
}
|
||||
|
||||
int ziti_auth(struct nf_ctx *ctx) {
|
||||
PREPF(ziti, ziti_errorstr);
|
||||
|
||||
TRY(ziti, ziti_ctrl_process(ctx,
|
||||
ziti_ctrl_version,
|
||||
ziti_ctrl_login,
|
||||
ziti_ctrl_get_services,
|
||||
ziti_ctrl_get_network_sessions,
|
||||
NULL));
|
||||
|
||||
CATCH(ziti){
|
||||
return ERR(ziti);
|
||||
}
|
||||
|
||||
return ZITI_OK;
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//
|
||||
// Created by eugene on 1/8/18.
|
||||
//
|
||||
|
||||
#ifndef ZT_SDK_ZT_INTERNAL_H
|
||||
#define ZT_SDK_ZT_INTERNAL_H
|
||||
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <sys/queue.h>
|
||||
#include <uv_mbed/uv_mbed.h>
|
||||
|
||||
#include <nf/ziti.h>
|
||||
#include "tls.h"
|
||||
#include "model.h"
|
||||
#include "buffer.h"
|
||||
#include "message.h"
|
||||
|
||||
//#define SIZEOF(arr) (sizeof(arr) / sizeof((arr)[0]))
|
||||
|
||||
#if !defined(UUID_STR_LEN)
|
||||
#define UUID_STR_LEN 37
|
||||
#endif
|
||||
|
||||
|
||||
#if _WIN32
|
||||
#define uint unsigned int
|
||||
#endif
|
||||
|
||||
enum content_type {
|
||||
|
||||
ContentTypeHelloType = 0,
|
||||
ContentTypePingType = 1,
|
||||
ContentTypeResultType = 2,
|
||||
ContentTypeLatencyType = 3,
|
||||
|
||||
ContentTypeEdge = 0xED6E,
|
||||
ContentTypeConnect = 60783,
|
||||
ContentTypeStateConnected = 60784,
|
||||
ContentTypeStateClosed = 60785,
|
||||
ContentTypeData = 60786,
|
||||
ContentTypeDial = 60787,
|
||||
ContentTypeDialSuccess = 60788,
|
||||
ContentTypeDialFailed = 60789,
|
||||
ContentTypeBind = 60790,
|
||||
ContentTypeUnbind = 60791,
|
||||
};
|
||||
|
||||
enum header_id {
|
||||
ConnectionIdHeader = 0,
|
||||
ReplyForHeader = 1,
|
||||
ResultSuccessHeader = 2,
|
||||
HelloListenerHeader = 3,
|
||||
|
||||
// Headers in the range 128-255 inclusive will be reflected when creating replies
|
||||
ReflectedHeaderBitMask = 1 << 7,
|
||||
MaxReflectedHeader = (1 << 8) - 1,
|
||||
|
||||
ConnIdHeader = 1000,
|
||||
SeqHeader = 1001,
|
||||
SessionTokenHeader = 1002,
|
||||
};
|
||||
|
||||
typedef struct ziti_channel ziti_channel_t;
|
||||
|
||||
typedef void (*reply_cb)(void *ctx, message *m);
|
||||
|
||||
typedef void (*send_cb)(int status, void *ctx);
|
||||
|
||||
typedef void (*ch_connect_cb)(ziti_channel_t *ch, void *ctx, int status);
|
||||
|
||||
enum conn_state {
|
||||
Initial,
|
||||
Connecting,
|
||||
Connected,
|
||||
Binding,
|
||||
Bound,
|
||||
Accepting,
|
||||
Closed
|
||||
};
|
||||
|
||||
typedef struct ziti_channel {
|
||||
struct nf_ctx *ctx;
|
||||
char *ingress;
|
||||
|
||||
uint32_t id;
|
||||
char token[UUID_STR_LEN];
|
||||
uv_mbed_t connection;
|
||||
|
||||
enum conn_state state;
|
||||
|
||||
struct ch_conn_req **conn_reqs;
|
||||
int conn_reqs_n;
|
||||
|
||||
uint32_t conn_seq;
|
||||
uint32_t msg_seq;
|
||||
|
||||
buffer *incoming;
|
||||
|
||||
message *in_next;
|
||||
int in_body_offset;
|
||||
|
||||
SLIST_HEAD(con_list, nf_conn) connections;
|
||||
SLIST_HEAD(waiter, waiter_s) waiters;
|
||||
|
||||
SLIST_ENTRY(ziti_channel) next;
|
||||
} ziti_channel_t;
|
||||
|
||||
struct nf_write_req {
|
||||
struct nf_conn *conn;
|
||||
uint8_t *buf;
|
||||
size_t len;
|
||||
|
||||
uint8_t *payload; // internal buffer
|
||||
nf_write_cb cb;
|
||||
uv_timer_t *timeout;
|
||||
|
||||
void *ctx;
|
||||
};
|
||||
|
||||
struct nf_conn {
|
||||
char* token;
|
||||
|
||||
uint32_t edge_msg_seq;
|
||||
uint32_t conn_id;
|
||||
|
||||
struct nf_ctx *nf_ctx;
|
||||
ziti_channel_t *channel;
|
||||
nf_data_cb data_cb;
|
||||
nf_client_cb client_cb;
|
||||
enum conn_state state;
|
||||
int timeout;
|
||||
|
||||
int write_reqs;
|
||||
|
||||
void *data;
|
||||
|
||||
struct nf_conn *parent;
|
||||
uint32_t dial_req_seq;
|
||||
|
||||
SLIST_ENTRY(nf_conn) next;
|
||||
};
|
||||
|
||||
|
||||
struct nf_ctx {
|
||||
char controller[128];
|
||||
uint16_t controller_port;
|
||||
tls_context *tlsCtx;
|
||||
|
||||
char *ziti_session;
|
||||
ziti_service **services;
|
||||
ziti_net_session **net_sessions;
|
||||
|
||||
uv_loop_t *loop;
|
||||
uv_thread_t loop_thread;
|
||||
uint32_t ch_counter;
|
||||
|
||||
SLIST_HEAD(channels, ziti_channel) channels;
|
||||
|
||||
/* options */
|
||||
int ziti_timeout;
|
||||
};
|
||||
|
||||
|
||||
int ziti_close_channels(nf_context);
|
||||
|
||||
int ziti_channel_connect(nf_context nf, const char *url, ch_connect_cb, void *ctx);
|
||||
|
||||
int ziti_channel_close(ziti_channel_t *ch);
|
||||
|
||||
int ziti_channel_send(ziti_channel_t *ch, uint32_t content, const hdr_t *hdrs, int nhdrs, const uint8_t *body,
|
||||
uint32_t body_len,
|
||||
struct nf_write_req *wr);
|
||||
|
||||
int
|
||||
ziti_channel_send_for_reply(ziti_channel_t *ch, uint32_t content, const hdr_t *headers, int nhdrs, const uint8_t *body,
|
||||
uint32_t body_len, reply_cb,
|
||||
void *reply_ctx);
|
||||
|
||||
int load_config(const char *filename, nf_config **);
|
||||
|
||||
int tls_context_init(nf_config *config, nf_tls_context *tls);
|
||||
int tls_context_free(nf_tls_context *tls);
|
||||
|
||||
int ziti_auth(nf_context ctx);
|
||||
int ziti_logout(nf_context ctx);
|
||||
|
||||
int ziti_bind(nf_connection conn, const char *service, nf_listen_cb listen_cb, nf_client_cb on_clt_cb);
|
||||
|
||||
int ziti_accept(nf_connection conn, nf_conn_cb cb, nf_data_cb data_cb);
|
||||
|
||||
int ziti_dial(nf_connection conn, const char *service, nf_conn_cb conn_cb, nf_data_cb data_cb);
|
||||
|
||||
int ziti_write(struct nf_write_req *req);
|
||||
int ziti_disconnect(struct nf_conn *conn);
|
||||
|
||||
void on_write_completed(struct nf_conn *conn, struct nf_write_req *req, int status);
|
||||
#endif //ZT_SDK_ZT_INTERNAL_H
|
||||
@@ -0,0 +1,72 @@
|
||||
@echo off & setlocal
|
||||
pushd .
|
||||
set CSDK_HOME=%~dp0
|
||||
cd /d %CSDK_HOME%
|
||||
|
||||
set BUILDFOLDER=%CSDK_HOME%build2017
|
||||
|
||||
mkdir %BUILDFOLDER%
|
||||
pushd %BUILDFOLDER%
|
||||
|
||||
cmake .. -G "Visual Studio 15 2017" -A x64 -DCMAKE_INSTALL_INCLUDEDIR=include -DCMAKE_INSTALL_LIBDIR=lib
|
||||
ECHO Build from cmake using:
|
||||
ECHO cmake --build %BUILDFOLDER% --config Debug
|
||||
ECHO cmake --build %BUILDFOLDER% --config Release
|
||||
ECHO
|
||||
ECHO Or open %BUILDFOLDER%\ziti-sdk.sln
|
||||
|
||||
goto end
|
||||
|
||||
REM this is holdover from before protobuf files were checked in.
|
||||
REM leaving this behind for history if ever needed
|
||||
|
||||
|
||||
@echo off & setlocal
|
||||
set CSDK_HOME=%~dp0
|
||||
pushd %CSDK_HOME%
|
||||
|
||||
set BUILDFOLDER=build
|
||||
mkdir %CSDK_HOME%\%BUILDFOLDER%\protobuf_working_folder
|
||||
pushd %CSDK_HOME%\%BUILDFOLDER%\protobuf_working_folder
|
||||
|
||||
git clone https://github.com/protocolbuffers/protobuf
|
||||
|
||||
cd %CSDK_HOME%\%BUILDFOLDER%\protobuf_working_folder\protobuf
|
||||
set PROTOBUF_HOME=%CD%
|
||||
cd cmake
|
||||
mkdir %BUILDFOLDER%
|
||||
cd %BUILDFOLDER%
|
||||
set PROTO_C_PATH=%PROTOBUF_HOME%\cmake\%BUILDFOLDER%\Release
|
||||
cmake -G "Visual Studio 15 2017" -A x64 .. -Dprotobuf_BUILD_TESTS=OFF
|
||||
cmake --build . --config Release
|
||||
popd
|
||||
|
||||
pushd %CSDK_HOME%\deps\protobuf-c\build-cmake
|
||||
mkdir %BUILDFOLDER%
|
||||
cd %BUILDFOLDER%
|
||||
set CMAKE_INCLUDE_PATH=%PROTOBUF_HOME%\src
|
||||
set CMAKE_LIBRARY_PATH=%PROTOBUF_HOME%\cmake\%BUILDFOLDER%\Release
|
||||
set PROTO_C_GEN_C=%cd%\Release
|
||||
cmake -G "Visual Studio 15 2017" -A x64 .. -DCMAKE_CXX_FLAGS_RELEASE=/MT
|
||||
cmake --build . --config Release
|
||||
popd
|
||||
|
||||
mkdir %BUILDFOLDER%\cmake
|
||||
cd %BUILDFOLDER%\cmake
|
||||
mkdir lib
|
||||
copy %PROTO_C_PATH%\* lib
|
||||
copy %PROTO_C_GEN_C%\* lib
|
||||
|
||||
echo USING proto_c : %cd%\lib
|
||||
echo USING protoc_gen_c: %cd%\lib
|
||||
|
||||
cmake -G "Visual Studio 15 2017" -A x64 ..\.. -DCMAKE_INSTALL_INCLUDEDIR=include -Dproto_c=%cd%\lib -Dprotoc_gen_c=%cd%\lib
|
||||
cmake --build . --config Debug
|
||||
REM cmake --build . --config Release
|
||||
goto end
|
||||
|
||||
:abnormalend
|
||||
echo TERMINATED UNEXPECTEDLY
|
||||
|
||||
:end
|
||||
popd
|
||||
@@ -0,0 +1,88 @@
|
||||
@echo off & setlocal
|
||||
pushd .
|
||||
set CSDK_HOME=%~dp0
|
||||
cd /d %CSDK_HOME%
|
||||
|
||||
set BUILDFOLDER=%CSDK_HOME%build
|
||||
|
||||
mkdir %BUILDFOLDER%
|
||||
mkdir %BUILDFOLDER%\x86
|
||||
mkdir %BUILDFOLDER%\x64
|
||||
pushd %BUILDFOLDER%
|
||||
|
||||
pushd %BUILDFOLDER%\x86
|
||||
cmake ..\.. -G "Visual Studio 16 2019" -A Win32 -DCMAKE_INSTALL_INCLUDEDIR=include -DCMAKE_INSTALL_LIBDIR=lib
|
||||
popd
|
||||
|
||||
pushd %BUILDFOLDER%\x64
|
||||
cmake ..\.. -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_INCLUDEDIR=include -DCMAKE_INSTALL_LIBDIR=lib
|
||||
popd
|
||||
|
||||
ECHO Build from cmake using:
|
||||
ECHO cmake --build %BUILDFOLDER%\x86 --config Debug
|
||||
ECHO cmake --build %BUILDFOLDER%\x86 --config Release
|
||||
ECHO
|
||||
ECHO cmake --build %BUILDFOLDER%\x64 --config Debug
|
||||
ECHO cmake --build %BUILDFOLDER%\x64 --config Release
|
||||
ECHO
|
||||
ECHO Or open %BUILDFOLDER%\ziti-sdk.sln
|
||||
|
||||
goto end
|
||||
|
||||
:blank
|
||||
set BUILDFOLDER=%CSDK_HOME%\build
|
||||
GOTO params_set
|
||||
|
||||
|
||||
REM this is holdover from before protobuf files were checked in.
|
||||
REM leaving this behind for history if ever needed
|
||||
|
||||
cd /D "%~dp0"
|
||||
set CSDK_HOME=%CD%
|
||||
pushd .
|
||||
set BUILDFOLDER=build
|
||||
mkdir %CSDK_HOME%\%BUILDFOLDER%\protobuf_working_folder
|
||||
pushd %CSDK_HOME%\%BUILDFOLDER%\protobuf_working_folder
|
||||
|
||||
git clone https://github.com/protocolbuffers/protobuf
|
||||
git clone https://github.com/protobuf-c/protobuf-c.git
|
||||
|
||||
pushd %CSDK_HOME%\%BUILDFOLDER%\protobuf_working_folder\protobuf
|
||||
REM git checkout 3.7.x
|
||||
set PROTOBUF_HOME=%CD%
|
||||
cd cmake
|
||||
mkdir %BUILDFOLDER%
|
||||
cd %BUILDFOLDER%
|
||||
set PROTO_C_PATH=%PROTOBUF_HOME%\cmake\%BUILDFOLDER%\Release
|
||||
cmake .. -Dprotobuf_BUILD_TESTS=OFF
|
||||
cmake --build . --config Release
|
||||
popd
|
||||
|
||||
cd protobuf-c\build-cmake
|
||||
mkdir %BUILDFOLDER%
|
||||
cd %BUILDFOLDER%
|
||||
set CMAKE_INCLUDE_PATH=%PROTOBUF_HOME%\src
|
||||
set CMAKE_LIBRARY_PATH=%PROTOBUF_HOME%\cmake\%BUILDFOLDER%\Release
|
||||
set PROTO_C_GEN_C=%cd%\Release
|
||||
cmake .. -DCMAKE_CXX_FLAGS_RELEASE=/MT
|
||||
cmake --build . --config Release
|
||||
popd
|
||||
|
||||
mkdir %BUILDFOLDER%\cmake
|
||||
cd %BUILDFOLDER%\cmake
|
||||
mkdir lib
|
||||
copy %PROTO_C_PATH%\* lib
|
||||
copy %PROTO_C_GEN_C%\* lib
|
||||
|
||||
cmake ..\.. -DCMAKE_INSTALL_INCLUDEDIR=include -Dproto_c=%cd%\lib -Dprotoc_gen_c=%cd%\lib
|
||||
cmake --build . --config Debug
|
||||
REM cmake --build . --config Release
|
||||
|
||||
|
||||
goto end
|
||||
|
||||
:abnormalend
|
||||
echo TERMINATED UNEXPECTEDLY
|
||||
|
||||
:end
|
||||
popd
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
|
||||
add_subdirectory(ziti-prox-c)
|
||||
|
||||
add_subdirectory(sample_wttr)
|
||||
add_subdirectory(sample-host)
|
||||
@@ -0,0 +1,5 @@
|
||||
project(sample-host)
|
||||
|
||||
add_executable(sample-host
|
||||
sample-host.c)
|
||||
target_link_libraries(sample-host PUBLIC ziti)
|
||||
@@ -0,0 +1,91 @@
|
||||
//
|
||||
//
|
||||
//
|
||||
|
||||
#include <nf/errors.h>
|
||||
#include <nf/ziti.h>
|
||||
#include <string.h>
|
||||
|
||||
#define DIE(v) do { \
|
||||
int code = (v);\
|
||||
if (code != ZITI_OK) {\
|
||||
fprintf(stderr, "ERROR: " #v " => %s\n", ziti_errorstr(code));\
|
||||
exit(code);\
|
||||
}} while(0)
|
||||
|
||||
|
||||
static nf_context nf;
|
||||
static const char *service;
|
||||
|
||||
static void on_client_write(nf_connection clt, ssize_t status, void *ctx) {
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
static void on_client_data(nf_connection clt, uint8_t *data, int len) {
|
||||
if (len > 0) {
|
||||
printf("client sent:\n%*.*s", len, len, data);
|
||||
char *reply = malloc(128);
|
||||
size_t l = sprintf(reply, "%d\n", len);
|
||||
NF_write(clt, reply, l, on_client_write, reply);
|
||||
}
|
||||
else if (len == ZITI_EOF) {
|
||||
printf("client disconnected\n");
|
||||
}
|
||||
else {
|
||||
fprintf(stderr, "error: %d(%s)", len, ziti_errorstr(len));
|
||||
}
|
||||
}
|
||||
|
||||
static void on_client_connect(nf_connection clt, int status) {
|
||||
if (status == ZITI_OK) {
|
||||
uint8_t *msg = "Hello from byte counter!\n";
|
||||
NF_write(clt, msg, strlen(msg), on_client_write, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_client(nf_connection serv, nf_connection client, int status) {
|
||||
NF_accept(client, on_client_connect, on_client_data);
|
||||
}
|
||||
|
||||
static void listen_cb(nf_connection serv, int status) {
|
||||
if (status == ZITI_OK) {
|
||||
printf("Byte Counter is ready! %d(%s)\n", status, ziti_errorstr(status));
|
||||
}
|
||||
else {
|
||||
printf("ERROR The Byte Counter could not be started: %d(%s)\n", status, ziti_errorstr(status));
|
||||
NF_close(&serv);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_nf_init(nf_context nf_ctx, int status, void *init_ctx) {
|
||||
nf = nf_ctx;
|
||||
nf_connection conn;
|
||||
NF_conn_init(nf, &conn, NULL);
|
||||
NF_listen(conn, service, listen_cb, on_client);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
#if _WIN32
|
||||
//changes the output to UTF-8 so that the windows output looks correct and not all jumbly
|
||||
SetConsoleOutputCP(65001);
|
||||
#endif
|
||||
if (argc != 3) {
|
||||
fprintf(stderr, "Usage: %s <config-file> <service-name>", argv[0]);
|
||||
exit(1);
|
||||
}
|
||||
int res;
|
||||
uv_loop_t *loop = uv_default_loop();
|
||||
|
||||
service = argv[2];
|
||||
|
||||
DIE(NF_init(argv[1], loop, on_nf_init, NULL));
|
||||
|
||||
// loop will finish afger the request is complete and NF_shutdown is called
|
||||
uv_run(loop, UV_RUN_DEFAULT);
|
||||
|
||||
printf("========================\n"
|
||||
"uv loop is done\n");
|
||||
|
||||
NF_free(&nf);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
|
||||
project(sample_wttr)
|
||||
|
||||
add_executable(sample_wttr sample_wttr.c)
|
||||
target_link_libraries(sample_wttr PUBLIC ziti)
|
||||
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// Created by eugene on 2/25/19.
|
||||
//
|
||||
|
||||
#include <nf/ziti.h>
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <uv.h>
|
||||
|
||||
#define DIE(v) do { \
|
||||
int code = (v);\
|
||||
if (code != ZITI_OK) {\
|
||||
fprintf(stderr, "ERROR: " #v " => %s\n", ziti_errorstr(code));\
|
||||
exit(code);\
|
||||
}} while(0)
|
||||
|
||||
static size_t total;
|
||||
static nf_context nf;
|
||||
|
||||
void on_data(nf_connection c, uint8_t *buf, int len) {
|
||||
if (len == ZITI_EOF) {
|
||||
|
||||
printf("request completed: %s\n", ziti_errorstr(len));
|
||||
NF_close(&c);
|
||||
NF_shutdown(nf);
|
||||
|
||||
}
|
||||
else if (len < 0) {
|
||||
fprintf(stderr, "unexpected error: %s\n", ziti_errorstr(len));
|
||||
NF_close(&c);
|
||||
NF_shutdown(nf);
|
||||
}
|
||||
else {
|
||||
total += len;
|
||||
printf("%*.*s", len, len, buf);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static void on_write(nf_connection conn, ssize_t status, void *ctx) {
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "request failed to submit status[%zd]: %s\n", status, ziti_errorstr(status));
|
||||
}
|
||||
else {
|
||||
printf("request success: %zd bytes sent\n", status);
|
||||
}
|
||||
}
|
||||
|
||||
void on_connect(nf_connection conn, int status) {
|
||||
DIE(status);
|
||||
|
||||
printf("sending HTTP request\n");
|
||||
|
||||
uint8_t *req = "GET /Rochester HTTP/1.0\r\n"
|
||||
"Accept: */*\r\n"
|
||||
"Connection: close\r\n"
|
||||
"Host: wttr.in\r\n"
|
||||
"User-Agent: curl/7.59.0\r\n"
|
||||
"\r\n";
|
||||
|
||||
DIE(NF_write(conn, req, strlen(req), on_write, NULL));
|
||||
}
|
||||
|
||||
void on_nf_init(nf_context _nf, int status, void* ctx) {
|
||||
DIE(status);
|
||||
nf = _nf;
|
||||
|
||||
nf_connection conn;
|
||||
DIE(NF_conn_init(nf, &conn, NULL));
|
||||
DIE(NF_dial(conn, "demo-weather", on_connect, on_data));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
#if _WIN32
|
||||
//changes the output to UTF-8 so that the windows output looks correct and not all jumbly
|
||||
SetConsoleOutputCP(65001);
|
||||
#endif
|
||||
int res;
|
||||
uv_loop_t *loop = uv_default_loop();
|
||||
|
||||
DIE(NF_init(argv[1], loop, on_nf_init, NULL));
|
||||
|
||||
// loop will finish afger the request is complete and NF_shutdown is called
|
||||
uv_run(loop, UV_RUN_DEFAULT);
|
||||
|
||||
printf("========================\n");
|
||||
|
||||
NF_free(&nf);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
project(ziti-prox-c)
|
||||
|
||||
add_executable(ziti-prox-c proxy.c)
|
||||
|
||||
if(WIN32)
|
||||
target_include_directories(ziti-prox-c PRIVATE win32/include)
|
||||
target_sources(ziti-prox-c PRIVATE win32/src/getopt.c)
|
||||
endif()
|
||||
|
||||
target_link_libraries(ziti-prox-c PUBLIC ziti subcommand)
|
||||
target_include_directories(ziti-prox-c PRIVATE ${ziti-sdk_SOURCE_DIR}/inc_internal)
|
||||
|
||||
if(NOT WIN32)
|
||||
add_custom_target(ziti-prox-c-${ZITI_VERSION}-${CMAKE_SYSTEM_NAME}.tar.gz ALL
|
||||
DEPENDS ziti-prox-c
|
||||
COMMAND tar zcf ziti-prox-c-${ZITI_VERSION}-${CMAKE_SYSTEM_NAME}.tar.gz ziti-prox-c${CMAKE_EXECUTABLE_SUFFIX}
|
||||
)
|
||||
endif()
|
||||
|
||||
#add_dependencies(package ziti-prox-c-pack)
|
||||
|
||||
PUBCOMP(ziti-prox-c)
|
||||
@@ -0,0 +1,431 @@
|
||||
//
|
||||
// Created by eugene on 3/22/19.
|
||||
//
|
||||
|
||||
#include <uv.h>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <utils.h>
|
||||
#include <nf/ziti.h>
|
||||
#include <sys/queue.h>
|
||||
|
||||
#if(WIN32)
|
||||
#include <Windows.h>
|
||||
#define strsignal(s) "_windows_unimplemented_"
|
||||
#endif
|
||||
|
||||
#define MAX_WRITES 4
|
||||
|
||||
static const char *config = NULL;
|
||||
static nf_context nf;
|
||||
static uv_signal_t sig;
|
||||
|
||||
struct listener {
|
||||
const char *service_name;
|
||||
int port;
|
||||
uv_tcp_t server;
|
||||
SLIST_ENTRY(listener) next;
|
||||
};
|
||||
|
||||
struct client {
|
||||
struct sockaddr_in addr;
|
||||
char addr_s[32];
|
||||
nf_connection nf_conn;
|
||||
int closed;
|
||||
size_t inb_reqs;
|
||||
};
|
||||
|
||||
static int process_args(int argc, char *argv[]);
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
process_args(argc, argv);
|
||||
}
|
||||
|
||||
static void close_server_cb(uv_handle_t *h) {
|
||||
struct listener *l = h->data;
|
||||
ZITI_LOG(DEBUG, "listener closed for %s", l->service_name);
|
||||
}
|
||||
|
||||
static void signal_cb(uv_signal_t *s, int signum) {
|
||||
ZITI_LOG(INFO, "signal[%d/%s] received", signum, strsignal(signum));
|
||||
PREPF(uv, uv_strerror);
|
||||
|
||||
// shutdown listeners
|
||||
SLIST_HEAD(listeners, listener) *listeners = s->data;
|
||||
struct listener *l;
|
||||
SLIST_FOREACH(l, listeners, next) {
|
||||
if (uv_is_active((const uv_handle_t *) &l->server)) {
|
||||
uv_close((uv_handle_t *) &l->server, close_server_cb);
|
||||
}
|
||||
}
|
||||
|
||||
// try to cleanup
|
||||
NF_shutdown(nf);
|
||||
uv_loop_close(s->loop);
|
||||
|
||||
CATCH(uv);
|
||||
ZITI_LOG(INFO, "exiting");
|
||||
}
|
||||
|
||||
static void close_cb(uv_handle_t *h) {
|
||||
struct client *clt = h->data;
|
||||
ZITI_LOG(DEBUG, "client connection closed for %s", clt->addr_s);
|
||||
clt->closed = 1;
|
||||
if (clt->inb_reqs == 0) {
|
||||
free(clt);
|
||||
free(h);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_client_write(uv_write_t *req, int status) {
|
||||
|
||||
if (status < 0) {
|
||||
switch (status) {
|
||||
case UV_EPIPE:
|
||||
case UV_ECONNRESET:
|
||||
case UV_ECANCELED:
|
||||
break;
|
||||
default:
|
||||
ZITI_LOG(WARN, "unexpected: [%d/%s](%s)", status, uv_err_name(status), uv_strerror(status));
|
||||
}
|
||||
}
|
||||
free(req->data);
|
||||
free(req);
|
||||
}
|
||||
|
||||
static void alloc_cb(uv_handle_t *h, size_t suggested_size, uv_buf_t *buf) {
|
||||
struct client *clt = h->data;
|
||||
|
||||
// if too many writes are in flight throttle the client
|
||||
if (clt->inb_reqs < MAX_WRITES) {
|
||||
buf->base = malloc(suggested_size);
|
||||
buf->len = suggested_size;
|
||||
}
|
||||
else {
|
||||
buf->base = NULL;
|
||||
buf->len = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void on_nf_write(nf_connection conn, ssize_t status, void *ctx) {
|
||||
uv_stream_t *stream = NF_conn_data(conn);
|
||||
struct client *clt = stream->data;
|
||||
if (status < 0) {
|
||||
ZITI_LOG(ERROR, "nf_write failed status[%zd] %s", status, ziti_errorstr(status));
|
||||
uv_close((uv_handle_t *) stream, close_cb);
|
||||
}
|
||||
else {
|
||||
clt->inb_reqs--;
|
||||
if (clt->inb_reqs == 0 && clt->closed) {
|
||||
free(clt);
|
||||
free(stream);
|
||||
}
|
||||
}
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
static void data_cb(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) {
|
||||
struct client *clt = stream->data;
|
||||
|
||||
if (nread == UV_ENOBUFS) {
|
||||
// this error indicates that we are throttled by backend, see alloc_cb()
|
||||
}
|
||||
else if (nread < 0) {
|
||||
ZITI_LOG(DEBUG, "connection closed %s [%zd/%s](%s)",
|
||||
clt->addr_s, nread, uv_err_name(nread), uv_strerror(nread));
|
||||
|
||||
NF_close((nf_connection *) &clt->nf_conn);
|
||||
|
||||
uv_read_stop(stream);
|
||||
}
|
||||
else {
|
||||
clt->inb_reqs += 1;
|
||||
NF_write(clt->nf_conn, buf->base, nread, on_nf_write, buf->base);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void on_ziti_connect(nf_connection conn, int status) {
|
||||
uv_stream_t *clt = NF_conn_data(conn);
|
||||
|
||||
if (status == ZITI_OK) {
|
||||
uv_read_start(clt, alloc_cb, data_cb);
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(ERROR, "ziti connect failed: %s(%d)", ziti_errorstr(status), status);
|
||||
uv_close((uv_handle_t *) clt, close_cb);
|
||||
}
|
||||
}
|
||||
|
||||
void on_ziti_data(nf_connection conn, uint8_t *data, int len) {
|
||||
uv_tcp_t *clt = NF_conn_data(conn);
|
||||
struct client *c = clt->data;
|
||||
|
||||
if (len > 0) {
|
||||
NEWP(req, uv_write_t);
|
||||
char *copy = malloc(len);
|
||||
memcpy(copy, data, len);
|
||||
uv_buf_t buf = uv_buf_init(copy, len);
|
||||
req->data = copy;
|
||||
uv_write(req, (uv_stream_t *) clt, &buf, 1, on_client_write);
|
||||
ZITI_LOG(TRACE, "[%s] wqs[%zd]", c->addr_s, clt->write_queue_size);
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(DEBUG, "ziti connection closed with [%d](%s)", len, ziti_errorstr(len));
|
||||
uv_close((uv_handle_t *) clt, close_cb);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static void on_client(uv_stream_t *server, int status) {
|
||||
PREPF(uv, uv_err_name);
|
||||
|
||||
NEWP(c,uv_tcp_t);
|
||||
|
||||
TRY(uv, uv_tcp_init(server->loop, c));
|
||||
TRY(uv, uv_accept(server, (uv_stream_t *) c));
|
||||
|
||||
NEWP(clt, struct client);
|
||||
int len = sizeof(clt->addr);
|
||||
TRY(uv, uv_tcp_getpeername(c, (struct sockaddr *) &clt->addr, &len));
|
||||
sprintf(clt->addr_s, "%s:%hu", inet_ntoa(clt->addr.sin_addr), ntohs(clt->addr.sin_port));
|
||||
|
||||
CATCH(uv) {
|
||||
return;
|
||||
}
|
||||
|
||||
struct listener *l = server->data;
|
||||
ZITI_LOG(DEBUG, "client connection accepted from %s (%s:%d)",
|
||||
clt->addr_s, l->service_name, l->port);
|
||||
|
||||
PREPF(nf, ziti_errorstr);
|
||||
TRY(nf, NF_conn_init(nf, &clt->nf_conn, c));
|
||||
TRY(nf, NF_dial(clt->nf_conn, l->service_name, on_ziti_connect, on_ziti_data));
|
||||
c->data = clt;
|
||||
|
||||
CATCH(nf) {
|
||||
free(clt);
|
||||
ZITI_LOG(ERROR, "closing client [%s]", clt->addr_s);
|
||||
uv_close((uv_handle_t *) c, close_cb);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static void on_nf_init(nf_context nf_ctx, int status, void* ctx) {
|
||||
PREPF(uv, uv_strerror);
|
||||
PREPF(ziti, ziti_errorstr);
|
||||
TRY(ziti, status);
|
||||
CATCH(ziti) {
|
||||
exit(status);
|
||||
}
|
||||
|
||||
nf = nf_ctx;
|
||||
|
||||
SLIST_HEAD(listeners, listener) *listeners = ctx;
|
||||
struct listener *l;
|
||||
SLIST_FOREACH(l, listeners, next) {
|
||||
int rc;
|
||||
if ((rc = NF_service_available(nf, l->service_name)) == ZITI_OK) {
|
||||
|
||||
ZITI_LOG(INFO, "listening for service[%s] on port[%d]", l->service_name, l->port);
|
||||
|
||||
NEWP(addr, struct sockaddr_in);
|
||||
TRY(uv, uv_ip4_addr("0.0.0.0", l->port, addr));
|
||||
TRY(uv, uv_tcp_bind(&l->server, (const struct sockaddr *) addr, 0));
|
||||
TRY(uv, uv_listen((uv_stream_t *) &l->server, 5, on_client));
|
||||
}
|
||||
else {
|
||||
ZITI_LOG(WARN, "%s: %s[%d]", l->service_name, ziti_errorstr(rc), rc);
|
||||
}
|
||||
}
|
||||
|
||||
CATCH(uv) {
|
||||
exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
char* pxoxystrndup(const char* s, int n);
|
||||
|
||||
void run(int argc, char **argv) {
|
||||
PREPF(uv, uv_strerror);
|
||||
|
||||
NEWP(loop, uv_loop_t);
|
||||
uv_loop_init(loop);
|
||||
|
||||
SLIST_HEAD(listeners, listener) listeners = SLIST_HEAD_INITIALIZER(listeners);
|
||||
for (int i = 0; i < argc; i++) {
|
||||
|
||||
char *p = strchr(argv[i], ':');
|
||||
char* service_name = pxoxystrndup(argv[i], p - argv[i]);
|
||||
|
||||
NEWP(l, struct listener);
|
||||
l->service_name = service_name;
|
||||
l->port = (int) strtol(p + 1, NULL, 10);
|
||||
|
||||
TRY(uv, uv_tcp_init(loop, &l->server));
|
||||
|
||||
l->server.data = l;
|
||||
|
||||
SLIST_INSERT_HEAD(&listeners, l, next);
|
||||
}
|
||||
|
||||
NF_init(config, loop, on_nf_init, &listeners);
|
||||
|
||||
TRY(uv, uv_signal_init(loop, &sig));
|
||||
sig.data = &listeners;
|
||||
TRY(uv, uv_signal_start(&sig, signal_cb, SIGINT));
|
||||
TRY(uv, uv_signal_start(&sig, signal_cb, SIGTERM));
|
||||
uv_unref((uv_handle_t *) &sig);
|
||||
|
||||
ZITI_LOG(INFO, "starting event loop");
|
||||
uv_run(loop, UV_RUN_DEFAULT);
|
||||
|
||||
int excode = 0;
|
||||
CATCH(uv) {
|
||||
excode = ERR(uv);
|
||||
}
|
||||
|
||||
ZITI_LOG(INFO, "proxy event loop is done");
|
||||
free(loop);
|
||||
exit(excode);
|
||||
}
|
||||
|
||||
#define COMMAND_LINE_IMPLEMENTATION
|
||||
|
||||
#include <commandline.h>
|
||||
#include <getopt.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
CommandLine main_cmd;
|
||||
#define GLOBAL_FLAGS "[--debug=level|-d[ddd]] [--config|-c=<path>] "
|
||||
|
||||
int run_opts(int argc, char **argv) {
|
||||
static struct option long_options[] = {
|
||||
{"debug", optional_argument, NULL, 'd'},
|
||||
{"config", required_argument, NULL, 'c'},
|
||||
{NULL, 0, NULL, 0}
|
||||
};
|
||||
|
||||
int c, option_index, errors = 0;
|
||||
int debug_level = 1;
|
||||
bool debug_set = false;
|
||||
|
||||
optind = 0;
|
||||
|
||||
while ((c = getopt_long(argc, argv, "dc:",
|
||||
long_options, &option_index)) != -1) {
|
||||
switch (c) {
|
||||
case 'd':
|
||||
debug_set = true;
|
||||
if (optarg) {
|
||||
debug_level = (int) strtol(optarg, NULL, 10);
|
||||
}
|
||||
else {
|
||||
debug_level++;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'c':
|
||||
config = strdup(optarg);
|
||||
break;
|
||||
|
||||
default: {
|
||||
fprintf(stderr, "Unknown option \"%c\"\n", c);
|
||||
errors++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors > 0) {
|
||||
commandline_help(stderr);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (debug_set) {
|
||||
char level[6];
|
||||
sprintf(level, "%d", debug_level);
|
||||
#if _WIN32
|
||||
SetEnvironmentVariable("ZITI_LOG", level);
|
||||
#else
|
||||
setenv("ZITI_LOG", level, 1);
|
||||
#endif
|
||||
|
||||
}
|
||||
return optind;
|
||||
}
|
||||
|
||||
void usage(int argc, char **argv) {
|
||||
commandline_print_usage(&main_cmd, stderr);
|
||||
}
|
||||
|
||||
static int ver_verbose = 0;
|
||||
int version_opts(int argc, char **argv) {
|
||||
static struct option long_options[] = {
|
||||
{"verbose", no_argument, NULL, 'v'},
|
||||
{NULL, 0, NULL, 0}
|
||||
};
|
||||
|
||||
int c, option_index, errors = 0;
|
||||
optind = 0;
|
||||
|
||||
while ((c = getopt_long(argc, argv, "v",
|
||||
long_options, &option_index)) != -1) {
|
||||
switch (c) {
|
||||
case 'v':
|
||||
ver_verbose = 1;
|
||||
break;
|
||||
|
||||
default: {
|
||||
fprintf(stderr, "Unknown option '%c'\n", c);
|
||||
errors++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors > 0) {
|
||||
commandline_help(stderr);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
return optind;
|
||||
}
|
||||
|
||||
void version(int argc, char **argv) {
|
||||
printf("%s\n", ziti_get_version(ver_verbose));
|
||||
}
|
||||
|
||||
CommandLine run_cmd = make_command("run", "run proxy", "run <service-name>:port", "run help", run_opts, run);
|
||||
CommandLine ver_cmd = make_command("version", "show version", "version", NULL, version_opts, version);
|
||||
CommandLine help_cmd = make_command("help", "help", NULL, NULL, NULL, usage);
|
||||
CommandLine *main_cmds[] = {
|
||||
&run_cmd,
|
||||
&ver_cmd,
|
||||
&help_cmd,
|
||||
NULL
|
||||
};
|
||||
|
||||
CommandLine main_cmd = make_command_set("ziti-prox-c",
|
||||
"Ziti Proxy",
|
||||
GLOBAL_FLAGS
|
||||
"<command> [<args>]", "Ziti Proxy",
|
||||
NULL, main_cmds);
|
||||
|
||||
static int process_args(int argc, char *argv[]) {
|
||||
commandline_run(&main_cmd, argc, argv);
|
||||
return 0;
|
||||
}
|
||||
|
||||
char* pxoxystrndup(const char* s, int n)
|
||||
{
|
||||
size_t len = strnlen(s, n);
|
||||
char* new = (char*)malloc(len + 1);
|
||||
if (new == NULL)
|
||||
return NULL;
|
||||
new[len] = '\0';
|
||||
return (char*)memcpy(new, s, len);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#ifndef __GETOPT_H__
|
||||
/**
|
||||
* DISCLAIMER
|
||||
* This file has no copyright assigned and is placed in the Public Domain.
|
||||
* This file is a part of the w64 mingw-runtime package.
|
||||
*
|
||||
* The w64 mingw-runtime package and its code is distributed in the hope that it
|
||||
* will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR
|
||||
* IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to
|
||||
* warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
*/
|
||||
|
||||
#define __GETOPT_H__
|
||||
|
||||
/* All the headers include this file. */
|
||||
#include <crtdefs.h>
|
||||
|
||||
#if defined( WINGETOPT_SHARED_LIB )
|
||||
# if defined( BUILDING_WINGETOPT_DLL )
|
||||
# define WINGETOPT_API __declspec(dllexport)
|
||||
# else
|
||||
# define WINGETOPT_API __declspec(dllimport)
|
||||
# endif
|
||||
#else
|
||||
# define WINGETOPT_API
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
WINGETOPT_API extern int optind; /* index of first non-option in argv */
|
||||
WINGETOPT_API extern int optopt; /* single option character, as parsed */
|
||||
WINGETOPT_API extern int opterr; /* flag to enable built-in diagnostics... */
|
||||
/* (user may set to zero, to suppress) */
|
||||
|
||||
WINGETOPT_API extern char *optarg; /* pointer to argument of current option */
|
||||
|
||||
extern int getopt(int nargc, char * const *nargv, const char *options);
|
||||
|
||||
#ifdef _BSD_SOURCE
|
||||
/*
|
||||
* BSD adds the non-standard `optreset' feature, for reinitialisation
|
||||
* of `getopt' parsing. We support this feature, for applications which
|
||||
* proclaim their BSD heritage, before including this header; however,
|
||||
* to maintain portability, developers are advised to avoid it.
|
||||
*/
|
||||
# define optreset __mingw_optreset
|
||||
extern int optreset;
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
/*
|
||||
* POSIX requires the `getopt' API to be specified in `unistd.h';
|
||||
* thus, `unistd.h' includes this header. However, we do not want
|
||||
* to expose the `getopt_long' or `getopt_long_only' APIs, when
|
||||
* included in this manner. Thus, close the standard __GETOPT_H__
|
||||
* declarations block, and open an additional __GETOPT_LONG_H__
|
||||
* specific block, only when *not* __UNISTD_H_SOURCED__, in which
|
||||
* to declare the extended API.
|
||||
*/
|
||||
#endif /* !defined(__GETOPT_H__) */
|
||||
|
||||
#if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
|
||||
#define __GETOPT_LONG_H__
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct option /* specification for a long form option... */
|
||||
{
|
||||
const char *name; /* option name, without leading hyphens */
|
||||
int has_arg; /* does it take an argument? */
|
||||
int *flag; /* where to save its status, or NULL */
|
||||
int val; /* its associated status value */
|
||||
};
|
||||
|
||||
enum /* permitted values for its `has_arg' field... */
|
||||
{
|
||||
no_argument = 0, /* option never takes an argument */
|
||||
required_argument, /* option always requires an argument */
|
||||
optional_argument /* option may take an argument */
|
||||
};
|
||||
|
||||
extern int getopt_long(int nargc, char * const *nargv, const char *options,
|
||||
const struct option *long_options, int *idx);
|
||||
extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
|
||||
const struct option *long_options, int *idx);
|
||||
/*
|
||||
* Previous MinGW implementation had...
|
||||
*/
|
||||
#ifndef HAVE_DECL_GETOPT
|
||||
/*
|
||||
* ...for the long form API only; keep this for compatibility.
|
||||
*/
|
||||
# define HAVE_DECL_GETOPT 1
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */
|
||||
@@ -0,0 +1,562 @@
|
||||
/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */
|
||||
/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
|
||||
|
||||
/*
|
||||
* Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*
|
||||
* Sponsored in part by the Defense Advanced Research Projects
|
||||
* Agency (DARPA) and Air Force Research Laboratory, Air Force
|
||||
* Materiel Command, USAF, under agreement number F39502-99-1-0512.
|
||||
*/
|
||||
/*-
|
||||
* Copyright (c) 2000 The NetBSD Foundation, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This code is derived from software contributed to The NetBSD Foundation
|
||||
* by Dieter Baron and Thomas Klausner.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
|
||||
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
|
||||
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <getopt.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
|
||||
#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
|
||||
|
||||
#ifdef REPLACE_GETOPT
|
||||
int opterr = 1; /* if error message should be printed */
|
||||
int optind = 1; /* index into parent argv vector */
|
||||
int optopt = '?'; /* character checked for validity */
|
||||
#undef optreset /* see getopt.h */
|
||||
#define optreset __mingw_optreset
|
||||
int optreset; /* reset getopt */
|
||||
char *optarg; /* argument associated with option */
|
||||
#endif
|
||||
|
||||
#define PRINT_ERROR ((opterr) && (*options != ':'))
|
||||
|
||||
#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
|
||||
#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
|
||||
#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
|
||||
|
||||
/* return values */
|
||||
#define BADCH (int)'?'
|
||||
#define BADARG ((*options == ':') ? (int)':' : (int)'?')
|
||||
#define INORDER (int)1
|
||||
|
||||
#ifndef __CYGWIN__
|
||||
#define __progname __argv[0]
|
||||
#else
|
||||
extern char __declspec(dllimport) *__progname;
|
||||
#endif
|
||||
|
||||
#ifdef __CYGWIN__
|
||||
static char EMSG[] = "";
|
||||
#else
|
||||
#define EMSG ""
|
||||
#endif
|
||||
|
||||
static int getopt_internal(int, char * const *, const char *,
|
||||
const struct option *, int *, int);
|
||||
static int parse_long_options(char * const *, const char *,
|
||||
const struct option *, int *, int);
|
||||
static int gcd(int, int);
|
||||
static void permute_args(int, int, int, char * const *);
|
||||
|
||||
static char *place = EMSG; /* option letter processing */
|
||||
|
||||
/* XXX: set optreset to 1 rather than these two */
|
||||
static int nonopt_start = -1; /* first non option argument (for permute) */
|
||||
static int nonopt_end = -1; /* first option after non options (for permute) */
|
||||
|
||||
/* Error messages */
|
||||
static const char recargchar[] = "option requires an argument -- %c";
|
||||
static const char recargstring[] = "option requires an argument -- %s";
|
||||
static const char ambig[] = "ambiguous option -- %.*s";
|
||||
static const char noarg[] = "option doesn't take an argument -- %.*s";
|
||||
static const char illoptchar[] = "unknown option -- %c";
|
||||
static const char illoptstring[] = "unknown option -- %s";
|
||||
|
||||
static void
|
||||
_vwarnx(const char *fmt,va_list ap)
|
||||
{
|
||||
(void)fprintf(stderr,"%s: ",__progname);
|
||||
if (fmt != NULL)
|
||||
(void)vfprintf(stderr,fmt,ap);
|
||||
(void)fprintf(stderr,"\n");
|
||||
}
|
||||
|
||||
static void
|
||||
warnx(const char *fmt,...)
|
||||
{
|
||||
va_list ap;
|
||||
va_start(ap,fmt);
|
||||
_vwarnx(fmt,ap);
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
/*
|
||||
* Compute the greatest common divisor of a and b.
|
||||
*/
|
||||
static int
|
||||
gcd(int a, int b)
|
||||
{
|
||||
int c;
|
||||
|
||||
c = a % b;
|
||||
while (c != 0) {
|
||||
a = b;
|
||||
b = c;
|
||||
c = a % b;
|
||||
}
|
||||
|
||||
return (b);
|
||||
}
|
||||
|
||||
/*
|
||||
* Exchange the block from nonopt_start to nonopt_end with the block
|
||||
* from nonopt_end to opt_end (keeping the same order of arguments
|
||||
* in each block).
|
||||
*/
|
||||
static void
|
||||
permute_args(int panonopt_start, int panonopt_end, int opt_end,
|
||||
char * const *nargv)
|
||||
{
|
||||
int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
|
||||
char *swap;
|
||||
|
||||
/*
|
||||
* compute lengths of blocks and number and size of cycles
|
||||
*/
|
||||
nnonopts = panonopt_end - panonopt_start;
|
||||
nopts = opt_end - panonopt_end;
|
||||
ncycle = gcd(nnonopts, nopts);
|
||||
cyclelen = (opt_end - panonopt_start) / ncycle;
|
||||
|
||||
for (i = 0; i < ncycle; i++) {
|
||||
cstart = panonopt_end+i;
|
||||
pos = cstart;
|
||||
for (j = 0; j < cyclelen; j++) {
|
||||
if (pos >= panonopt_end)
|
||||
pos -= nnonopts;
|
||||
else
|
||||
pos += nopts;
|
||||
swap = nargv[pos];
|
||||
/* LINTED const cast */
|
||||
((char **) nargv)[pos] = nargv[cstart];
|
||||
/* LINTED const cast */
|
||||
((char **)nargv)[cstart] = swap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* parse_long_options --
|
||||
* Parse long options in argc/argv argument vector.
|
||||
* Returns -1 if short_too is set and the option does not match long_options.
|
||||
*/
|
||||
static int
|
||||
parse_long_options(char * const *nargv, const char *options,
|
||||
const struct option *long_options, int *idx, int short_too)
|
||||
{
|
||||
char *current_argv, *has_equal;
|
||||
size_t current_argv_len;
|
||||
int i, ambiguous, match;
|
||||
|
||||
#define IDENTICAL_INTERPRETATION(_x, _y) \
|
||||
(long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
|
||||
long_options[(_x)].flag == long_options[(_y)].flag && \
|
||||
long_options[(_x)].val == long_options[(_y)].val)
|
||||
|
||||
current_argv = place;
|
||||
match = -1;
|
||||
ambiguous = 0;
|
||||
|
||||
optind++;
|
||||
|
||||
if ((has_equal = strchr(current_argv, '=')) != NULL) {
|
||||
/* argument found (--option=arg) */
|
||||
current_argv_len = has_equal - current_argv;
|
||||
has_equal++;
|
||||
} else
|
||||
current_argv_len = strlen(current_argv);
|
||||
|
||||
for (i = 0; long_options[i].name; i++) {
|
||||
/* find matching long option */
|
||||
if (strncmp(current_argv, long_options[i].name,
|
||||
current_argv_len))
|
||||
continue;
|
||||
|
||||
if (strlen(long_options[i].name) == current_argv_len) {
|
||||
/* exact match */
|
||||
match = i;
|
||||
ambiguous = 0;
|
||||
break;
|
||||
}
|
||||
/*
|
||||
* If this is a known short option, don't allow
|
||||
* a partial match of a single character.
|
||||
*/
|
||||
if (short_too && current_argv_len == 1)
|
||||
continue;
|
||||
|
||||
if (match == -1) /* partial match */
|
||||
match = i;
|
||||
else if (!IDENTICAL_INTERPRETATION(i, match))
|
||||
ambiguous = 1;
|
||||
}
|
||||
if (ambiguous) {
|
||||
/* ambiguous abbreviation */
|
||||
if (PRINT_ERROR)
|
||||
warnx(ambig, (int)current_argv_len,
|
||||
current_argv);
|
||||
optopt = 0;
|
||||
return (BADCH);
|
||||
}
|
||||
if (match != -1) { /* option found */
|
||||
if (long_options[match].has_arg == no_argument
|
||||
&& has_equal) {
|
||||
if (PRINT_ERROR)
|
||||
warnx(noarg, (int)current_argv_len,
|
||||
current_argv);
|
||||
/*
|
||||
* XXX: GNU sets optopt to val regardless of flag
|
||||
*/
|
||||
if (long_options[match].flag == NULL)
|
||||
optopt = long_options[match].val;
|
||||
else
|
||||
optopt = 0;
|
||||
return (BADARG);
|
||||
}
|
||||
if (long_options[match].has_arg == required_argument ||
|
||||
long_options[match].has_arg == optional_argument) {
|
||||
if (has_equal)
|
||||
optarg = has_equal;
|
||||
else if (long_options[match].has_arg ==
|
||||
required_argument) {
|
||||
/*
|
||||
* optional argument doesn't use next nargv
|
||||
*/
|
||||
optarg = nargv[optind++];
|
||||
}
|
||||
}
|
||||
if ((long_options[match].has_arg == required_argument)
|
||||
&& (optarg == NULL)) {
|
||||
/*
|
||||
* Missing argument; leading ':' indicates no error
|
||||
* should be generated.
|
||||
*/
|
||||
if (PRINT_ERROR)
|
||||
warnx(recargstring,
|
||||
current_argv);
|
||||
/*
|
||||
* XXX: GNU sets optopt to val regardless of flag
|
||||
*/
|
||||
if (long_options[match].flag == NULL)
|
||||
optopt = long_options[match].val;
|
||||
else
|
||||
optopt = 0;
|
||||
--optind;
|
||||
return (BADARG);
|
||||
}
|
||||
} else { /* unknown option */
|
||||
if (short_too) {
|
||||
--optind;
|
||||
return (-1);
|
||||
}
|
||||
if (PRINT_ERROR)
|
||||
warnx(illoptstring, current_argv);
|
||||
optopt = 0;
|
||||
return (BADCH);
|
||||
}
|
||||
if (idx)
|
||||
*idx = match;
|
||||
if (long_options[match].flag) {
|
||||
*long_options[match].flag = long_options[match].val;
|
||||
return (0);
|
||||
} else
|
||||
return (long_options[match].val);
|
||||
#undef IDENTICAL_INTERPRETATION
|
||||
}
|
||||
|
||||
/*
|
||||
* getopt_internal --
|
||||
* Parse argc/argv argument vector. Called by user level routines.
|
||||
*/
|
||||
static int
|
||||
getopt_internal(int nargc, char * const *nargv, const char *options,
|
||||
const struct option *long_options, int *idx, int flags)
|
||||
{
|
||||
const char *oli; /* option letter list index */
|
||||
int optchar, short_too;
|
||||
static int posixly_correct = -1;
|
||||
|
||||
if (options == NULL)
|
||||
return (-1);
|
||||
|
||||
/*
|
||||
* XXX Some GNU programs (like cvs) set optind to 0 instead of
|
||||
* XXX using optreset. Work around this braindamage.
|
||||
*/
|
||||
if (optind == 0)
|
||||
optind = optreset = 1;
|
||||
|
||||
/*
|
||||
* Disable GNU extensions if POSIXLY_CORRECT is set or options
|
||||
* string begins with a '+'.
|
||||
*
|
||||
* CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
|
||||
* optreset != 0 for GNU compatibility.
|
||||
*/
|
||||
if (posixly_correct == -1 || optreset != 0)
|
||||
posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
|
||||
if (*options == '-')
|
||||
flags |= FLAG_ALLARGS;
|
||||
else if (posixly_correct || *options == '+')
|
||||
flags &= ~FLAG_PERMUTE;
|
||||
if (*options == '+' || *options == '-')
|
||||
options++;
|
||||
|
||||
optarg = NULL;
|
||||
if (optreset)
|
||||
nonopt_start = nonopt_end = -1;
|
||||
start:
|
||||
if (optreset || !*place) { /* update scanning pointer */
|
||||
optreset = 0;
|
||||
if (optind >= nargc) { /* end of argument vector */
|
||||
place = EMSG;
|
||||
if (nonopt_end != -1) {
|
||||
/* do permutation, if we have to */
|
||||
permute_args(nonopt_start, nonopt_end,
|
||||
optind, nargv);
|
||||
optind -= nonopt_end - nonopt_start;
|
||||
}
|
||||
else if (nonopt_start != -1) {
|
||||
/*
|
||||
* If we skipped non-options, set optind
|
||||
* to the first of them.
|
||||
*/
|
||||
optind = nonopt_start;
|
||||
}
|
||||
nonopt_start = nonopt_end = -1;
|
||||
return (-1);
|
||||
}
|
||||
if (*(place = nargv[optind]) != '-' ||
|
||||
(place[1] == '\0' && strchr(options, '-') == NULL)) {
|
||||
place = EMSG; /* found non-option */
|
||||
if (flags & FLAG_ALLARGS) {
|
||||
/*
|
||||
* GNU extension:
|
||||
* return non-option as argument to option 1
|
||||
*/
|
||||
optarg = nargv[optind++];
|
||||
return (INORDER);
|
||||
}
|
||||
if (!(flags & FLAG_PERMUTE)) {
|
||||
/*
|
||||
* If no permutation wanted, stop parsing
|
||||
* at first non-option.
|
||||
*/
|
||||
return (-1);
|
||||
}
|
||||
/* do permutation */
|
||||
if (nonopt_start == -1)
|
||||
nonopt_start = optind;
|
||||
else if (nonopt_end != -1) {
|
||||
permute_args(nonopt_start, nonopt_end,
|
||||
optind, nargv);
|
||||
nonopt_start = optind -
|
||||
(nonopt_end - nonopt_start);
|
||||
nonopt_end = -1;
|
||||
}
|
||||
optind++;
|
||||
/* process next argument */
|
||||
goto start;
|
||||
}
|
||||
if (nonopt_start != -1 && nonopt_end == -1)
|
||||
nonopt_end = optind;
|
||||
|
||||
/*
|
||||
* If we have "-" do nothing, if "--" we are done.
|
||||
*/
|
||||
if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
|
||||
optind++;
|
||||
place = EMSG;
|
||||
/*
|
||||
* We found an option (--), so if we skipped
|
||||
* non-options, we have to permute.
|
||||
*/
|
||||
if (nonopt_end != -1) {
|
||||
permute_args(nonopt_start, nonopt_end,
|
||||
optind, nargv);
|
||||
optind -= nonopt_end - nonopt_start;
|
||||
}
|
||||
nonopt_start = nonopt_end = -1;
|
||||
return (-1);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Check long options if:
|
||||
* 1) we were passed some
|
||||
* 2) the arg is not just "-"
|
||||
* 3) either the arg starts with -- we are getopt_long_only()
|
||||
*/
|
||||
if (long_options != NULL && place != nargv[optind] &&
|
||||
(*place == '-' || (flags & FLAG_LONGONLY))) {
|
||||
short_too = 0;
|
||||
if (*place == '-')
|
||||
place++; /* --foo long option */
|
||||
else if (*place != ':' && strchr(options, *place) != NULL)
|
||||
short_too = 1; /* could be short option too */
|
||||
|
||||
optchar = parse_long_options(nargv, options, long_options,
|
||||
idx, short_too);
|
||||
if (optchar != -1) {
|
||||
place = EMSG;
|
||||
return (optchar);
|
||||
}
|
||||
}
|
||||
|
||||
if ((optchar = (int)*place++) == (int)':' ||
|
||||
(optchar == (int)'-' && *place != '\0') ||
|
||||
(oli = strchr(options, optchar)) == NULL) {
|
||||
/*
|
||||
* If the user specified "-" and '-' isn't listed in
|
||||
* options, return -1 (non-option) as per POSIX.
|
||||
* Otherwise, it is an unknown option character (or ':').
|
||||
*/
|
||||
if (optchar == (int)'-' && *place == '\0')
|
||||
return (-1);
|
||||
if (!*place)
|
||||
++optind;
|
||||
if (PRINT_ERROR)
|
||||
warnx(illoptchar, optchar);
|
||||
optopt = optchar;
|
||||
return (BADCH);
|
||||
}
|
||||
if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
|
||||
/* -W long-option */
|
||||
if (*place) /* no space */
|
||||
/* NOTHING */;
|
||||
else if (++optind >= nargc) { /* no arg */
|
||||
place = EMSG;
|
||||
if (PRINT_ERROR)
|
||||
warnx(recargchar, optchar);
|
||||
optopt = optchar;
|
||||
return (BADARG);
|
||||
} else /* white space */
|
||||
place = nargv[optind];
|
||||
optchar = parse_long_options(nargv, options, long_options,
|
||||
idx, 0);
|
||||
place = EMSG;
|
||||
return (optchar);
|
||||
}
|
||||
if (*++oli != ':') { /* doesn't take argument */
|
||||
if (!*place)
|
||||
++optind;
|
||||
} else { /* takes (optional) argument */
|
||||
optarg = NULL;
|
||||
if (*place) /* no white space */
|
||||
optarg = place;
|
||||
else if (oli[1] != ':') { /* arg not optional */
|
||||
if (++optind >= nargc) { /* no arg */
|
||||
place = EMSG;
|
||||
if (PRINT_ERROR)
|
||||
warnx(recargchar, optchar);
|
||||
optopt = optchar;
|
||||
return (BADARG);
|
||||
} else
|
||||
optarg = nargv[optind];
|
||||
}
|
||||
place = EMSG;
|
||||
++optind;
|
||||
}
|
||||
/* dump back option letter */
|
||||
return (optchar);
|
||||
}
|
||||
|
||||
#ifdef REPLACE_GETOPT
|
||||
/*
|
||||
* getopt --
|
||||
* Parse argc/argv argument vector.
|
||||
*
|
||||
* [eventually this will replace the BSD getopt]
|
||||
*/
|
||||
int
|
||||
getopt(int nargc, char * const *nargv, const char *options)
|
||||
{
|
||||
|
||||
/*
|
||||
* We don't pass FLAG_PERMUTE to getopt_internal() since
|
||||
* the BSD getopt(3) (unlike GNU) has never done this.
|
||||
*
|
||||
* Furthermore, since many privileged programs call getopt()
|
||||
* before dropping privileges it makes sense to keep things
|
||||
* as simple (and bug-free) as possible.
|
||||
*/
|
||||
return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
|
||||
}
|
||||
#endif /* REPLACE_GETOPT */
|
||||
|
||||
/*
|
||||
* getopt_long --
|
||||
* Parse argc/argv argument vector.
|
||||
*/
|
||||
int
|
||||
getopt_long(int nargc, char * const *nargv, const char *options,
|
||||
const struct option *long_options, int *idx)
|
||||
{
|
||||
|
||||
return (getopt_internal(nargc, nargv, options, long_options, idx,
|
||||
FLAG_PERMUTE));
|
||||
}
|
||||
|
||||
/*
|
||||
* getopt_long_only --
|
||||
* Parse argc/argv argument vector.
|
||||
*/
|
||||
int
|
||||
getopt_long_only(int nargc, char * const *nargv, const char *options,
|
||||
const struct option *long_options, int *idx)
|
||||
{
|
||||
|
||||
return (getopt_internal(nargc, nargv, options, long_options, idx,
|
||||
FLAG_PERMUTE|FLAG_LONGONLY));
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
|
||||
variants=$(< build.variants)
|
||||
|
||||
for var in ${variants[@]}; do
|
||||
echo "publishing for ${var} variant"
|
||||
cmake --build build-$var --target publish
|
||||
done
|
||||
@@ -0,0 +1,32 @@
|
||||
|
||||
include(${ziti-deps_BINARY_DIR}/Catch2/${CMAKE_INSTALL_LIBDIR}/cmake/Catch2/Catch.cmake)
|
||||
include(${ziti-deps_BINARY_DIR}/Catch2/${CMAKE_INSTALL_LIBDIR}/cmake/Catch2/ParseAndAddCatchTests.cmake)
|
||||
|
||||
add_executable(all_tests
|
||||
all_tests.cpp
|
||||
test_keys.cpp
|
||||
test_model.cpp)
|
||||
set_property(TARGET all_tests PROPERTY CXX_STANDARD 11)
|
||||
|
||||
target_include_directories(all_tests PRIVATE ${ziti-deps_BINARY_DIR}/Catch2/include)
|
||||
target_link_libraries(all_tests
|
||||
PRIVATE ziti)
|
||||
|
||||
set(TEST_DATA
|
||||
test_key.pem
|
||||
softhsm2.conf
|
||||
init-test-data.sh
|
||||
find-softhsm-lib.sh)
|
||||
|
||||
add_custom_target(gen-test-data
|
||||
COMMAND ${CMAKE_CURRENT_BINARY_DIR}/init-test-data.sh
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
add_dependencies(all_tests gen-test-data)
|
||||
|
||||
file(COPY ${TEST_DATA}
|
||||
DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
include(CTest)
|
||||
ParseAndAddCatchTests(all_tests)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//
|
||||
// Created by eugene on 6/27/19.
|
||||
//
|
||||
|
||||
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
|
||||
|
||||
#include <catch2/catch.hpp>
|
||||
#include "../inc_internal/utils.h"
|
||||
#include <nf/errors.h>
|
||||
|
||||
int init() {
|
||||
init_debug();
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int _init = init();
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash -e
|
||||
|
||||
libname=libsofthsm2.so
|
||||
libdirs="$(compgen -G /usr/lib/softhsm) $(compgen -G /usr/lib64) $(compgen -G /usr/local/Cellar/softhsm)"
|
||||
lib=$(find ${libdirs} -type f -a -name "${libname}" 2> /dev/null | head -n 1)
|
||||
if [ -z "${lib}" ]; then
|
||||
echo "ERROR: unable to find ${libname}. Have you installed softhsm2?"
|
||||
exit 1
|
||||
fi
|
||||
echo "${lib}" | tee SOFTHSM2_LIB.txt
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
|
||||
conf=softhsm2.conf
|
||||
lib=$(bash ./find-softhsm-lib.sh)
|
||||
echo "using pkcs11 module: ${lib}"
|
||||
pin=2171
|
||||
|
||||
[ -e ${conf} ] || exit 1
|
||||
|
||||
|
||||
tokendir=$(awk '/^directories.tokendir/{print $3;}' ${conf})
|
||||
|
||||
mkdir -p ${tokendir}
|
||||
export SOFTHSM2_CONF=${conf}
|
||||
|
||||
softhsm2-util --init-token --slot 0 --label 'ziti-test-token' --so-pin ${pin} --pin ${pin}
|
||||
pkcs11-tool --module ${lib} -p ${pin} -k --key-type rsa:2048 --id 01 --label ziti-rsa-key
|
||||
pkcs11-tool --module ${lib} -p ${pin} -k --key-type EC:prime256v1 --id 02 --label ziti-ecdsa-key
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# SoftHSM v2 configuration file
|
||||
|
||||
directories.tokendir = softhsm-testdata
|
||||
objectstore.backend = file
|
||||
|
||||
# ERROR, WARNING, INFO, DEBUG
|
||||
log.level = ERROR
|
||||
|
||||
# If CKF_REMOVABLE_DEVICE flag should be set
|
||||
slots.removable = false
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIGkAgEBBDCTcb9VYa4Hwi6Tw7UPTgYLIrvNL0ywtNHWt0rgHW08mEgZOg3V4AMW
|
||||
eYvfvKoZS4agBwYFK4EEACKhZANiAARIxbNm7tYvdDmqeGVoMR1xZsEIJOY3y9av
|
||||
6DmbquCPxFTpiKN01mhoLLdaOr4R1SFR9Y6sRsVCWPvbSX9zqAdRNg4b1gj3RZ4X
|
||||
V9IwTC1BCcXCanQuR4Q3mceajgO8kYM=
|
||||
-----END EC PRIVATE KEY-----
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//
|
||||
// Created by eugene on 6/27/19.
|
||||
//
|
||||
|
||||
|
||||
#include <catch2/catch.hpp>
|
||||
#include <mbedtls/pk.h>
|
||||
#include <mbedtls/error.h>
|
||||
#if _WIN32
|
||||
#define PATH_MAX 256
|
||||
#include <Windows.h>
|
||||
#include <direct.h>
|
||||
#include <processenv.h>
|
||||
|
||||
#define getcwd _getcwd
|
||||
int setenv(const char* name, const char* value, int overwrite)
|
||||
{
|
||||
return SetEnvironmentVariable(name, value);
|
||||
}
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#include <cstring>
|
||||
#include <nf/errors.h>
|
||||
#include "../inc_internal/tls.h"
|
||||
|
||||
const char *pem = "pem:-----BEGIN EC PRIVATE KEY-----\n"
|
||||
"MIGkAgEBBDCTcb9VYa4Hwi6Tw7UPTgYLIrvNL0ywtNHWt0rgHW08mEgZOg3V4AMW\n"
|
||||
"eYvfvKoZS4agBwYFK4EEACKhZANiAARIxbNm7tYvdDmqeGVoMR1xZsEIJOY3y9av\n"
|
||||
"6DmbquCPxFTpiKN01mhoLLdaOr4R1SFR9Y6sRsVCWPvbSX9zqAdRNg4b1gj3RZ4X\n"
|
||||
"V9IwTC1BCcXCanQuR4Q3mceajgO8kYM=\n"
|
||||
"-----END EC PRIVATE KEY-----";
|
||||
const char *der = "der:MIGkAgEBBDCTcb9VYa4Hwi6Tw7UPTgYLIrvNL0ywtNHWt0rgHW08mEgZOg3V4AMWeYvfvKoZS4agBwYFK4EEACKhZANiA"
|
||||
"ARIxbNm7tYvdDmqeGVoMR1xZsEIJOY3y9av6DmbquCPxFTpiKN01mhoLLdaOr4R1SFR9Y6sRsVCWPvbSX9zqAdRNg4b1g"
|
||||
"j3RZ4XV9IwTC1BCcXCanQuR4Q3mceajgO8kYM=";
|
||||
|
||||
|
||||
const char *derRSA = "der:MIIEpAIBAAKCAQEAxNE0PZkfHqBdajp0OGt1D7H3WAO7R6giLIvsBbIxAZTYccMGmo8HRq3MHABaTQNBXA/mmXOcbl1b"
|
||||
"W9hCOa06ZdMM0mqtCqtM8tf/gKTF2LN88dh+rDtiEYKNzpS1X2FqcQI6iJStEtZuv3VW7NY9i5mEzUYysvVL6zHw3nBrps/ff"
|
||||
"XsFnoqtVUobgJRVugLJeN0MUrO4hKcCwv+VwIX2vePAscCxsI3kJVbHP+zHHmcDforlwZjBPW/xLBOizMHM2v4GFtWvnFRYPZ"
|
||||
"ajFvCoBYCNM68tACjnWqZ0GV0GVRe6II790+JZG0045E7mBKmXUYyb2QIPbeQvxYU/3EmHYwIDAQABAoIBACmeGy/TSxNM0bP+"
|
||||
"vEiZ4Fz7QtQnpdhXIzLMO5JQxbAR61rS5HiWOfGmGnzpTi7uu0leS2KzYaassv7O0eIkUS7q29E6oXCaHGFVbz+il/tkqMzy/I"
|
||||
"Yq4GfXdWjzZQ7QKJPQ5tOurJJJKY3un/zgqI72XXCSoXHaEL2hB8/hccIJ36enCXvittGC2rUPhTwzbEj7QEgglmrF3dl3vhvy"
|
||||
"mOnaDi9PndBVlXgE2+0A67cZLeRrsS8rSJe0JiNGGbkJwG5y6O67cyexzyCNN0iFkQF3+BzqEsNQaEimG/ZcYjylJO1BPdH+9N"
|
||||
"xw6/wwbGxeCeBYlt2ShQ/rjW0RkW6MRyECgYEA7Gbj/VeYIVNdCxgu03M9n8XecuhbciKTen/GUb3KcPxpFxuIaaPIFmzT5Hsh"
|
||||
"MIVbDBa5wgOk3KaZEG6xQcalbSLelnquHOvw6AYCQaaUQZpsFiMDFFQ7U1fxd4+fgLJn+LWYCwqNDEoM3gm7w4KVBNce6HskLZX"
|
||||
"shTST8I8dqCkCgYEA1SI3GV29VNe9U1sXeR5zIiea7p/wCiw0G3fqnXaLsr93ViyOtvaUQy4RY2GBWaLlFKyeTxnURXsUP5dcvq"
|
||||
"lP0BGeW4STa8N4xy6Ffo6tlFw1poZOL2ehQTtNHpf+wgYCYAU2N6GaCoKY1UXb3thXVFPik3EzcBQH0uZheBZ/FKsCgYEA4BVfw"
|
||||
"4NGd0B4D84qhNDV9x8ujylllTjlJtb7e/w1awg37Wlx0wEm5urdp9R3T3D5LupTxm6B1Y4txP/IEhtkL6E/8M/1PwD/aFBZzzVB"
|
||||
"jzX7grhJcPmvCn9wKe8AOJPkLkKkDsM/lAiVTdtYGikrbF0ltSUU1AkrG9EM8pgWepECgYBvypWJ+ZAgW1STzzi9r8oGBS4PsdZ"
|
||||
"PD6Z5Lenik9ZseF8Y1SA6OZXEsvot3WviXz23HV+f79VWaFtTi4n6+4XAhi1ApYZJxOqp1u3wVtgW9FKzuMhztvBu7bLitCjNDi"
|
||||
"faw4EPpvTMRHnzi8Pq3CDaO3GhkoO/atI7vdksCui3JwKBgQCF33nv55RgY8BVTyGoaRzNrW4hebKyJBLFLMPdKeNtDx69rZQNC"
|
||||
"Vje38arEoczZB5i7QicRpCYe27JJrQiK+kjkvkq8ca4v1mM+4UIuXEFuxuykt2IJPcspcJlD12u1k3A38cvtBS6ts7ZkzThCiyaj"
|
||||
"xU3HFAf02w4AWRNr7JajQ==";
|
||||
|
||||
static int validate_key(mbedtls_pk_context *key) {
|
||||
unsigned char msg[256];
|
||||
for (int idx = 0; idx < sizeof(msg); msg[idx++] = (char) rand()) {}
|
||||
|
||||
unsigned char sig[1024];
|
||||
mbedtls_md_type_t md_alg = MBEDTLS_MD_SHA256;
|
||||
size_t siglen;
|
||||
INFO("Signing");
|
||||
int rc = mbedtls_pk_sign(key, md_alg, msg, sizeof(msg), sig, &siglen,
|
||||
(int (*)(void *, unsigned char *, size_t)) NULL, NULL);
|
||||
if (rc != 0) {
|
||||
return rc;
|
||||
}
|
||||
|
||||
INFO("Verifying signature");
|
||||
rc = mbedtls_pk_verify(key, md_alg, msg, sizeof(msg), sig, siglen);
|
||||
|
||||
return rc;
|
||||
}
|
||||
|
||||
const char * softhsm_lib_path() {
|
||||
char * buffer = (char *)calloc(1, 1024);
|
||||
FILE * f = fopen("SOFTHSM2_LIB.txt", "rb");
|
||||
if (f) {
|
||||
if (fgets(buffer, 1024, f) != NULL) {
|
||||
fclose(f);
|
||||
buffer[strcspn(buffer, "\r\n")] = 0;
|
||||
}
|
||||
}
|
||||
if (buffer[0] == 0) {
|
||||
strcpy(buffer, "/usr/lib/softhsm/libsofthsm2.so");
|
||||
}
|
||||
|
||||
printf("using pkcs11 module: %s\n", buffer);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
TEST_CASE("PEM format", "[keys][pem]") {
|
||||
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
rc = load_key(&key, pem);
|
||||
REQUIRE(rc == ZITI_OK);
|
||||
|
||||
REQUIRE(validate_key(&key) == 0);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("DER format", "[keys][der]") {
|
||||
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
rc = load_key(&key, der);
|
||||
REQUIRE(rc == ZITI_OK);
|
||||
|
||||
REQUIRE(validate_key(&key) == 0);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
|
||||
TEST_CASE("DER format (RSA)", "[keys][der]") {
|
||||
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
rc = load_key(&key, derRSA);
|
||||
REQUIRE(rc == ZITI_OK);
|
||||
|
||||
REQUIRE(validate_key(&key) == 0);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("FILE format", "[keys][file]") {
|
||||
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
char cwd[PATH_MAX];
|
||||
getcwd(cwd, sizeof(cwd));
|
||||
char spec[PATH_MAX + 256];
|
||||
|
||||
sprintf(spec, "file://%s/test_key.pem", cwd);
|
||||
|
||||
rc = load_key(&key, spec);
|
||||
INFO(ziti_errorstr(rc));
|
||||
REQUIRE(rc == ZITI_OK);
|
||||
REQUIRE(validate_key(&key) == 0);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("engine-PKCS11 format RSA key", "[keys][pkcs11][rsa]") {
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
char cwd[PATH_MAX];
|
||||
getcwd(cwd, sizeof(cwd));
|
||||
char spec[1024];
|
||||
|
||||
setenv("SOFTHSM2_CONF", "softhsm2.conf", 1);
|
||||
sprintf(spec, "pkcs11://%s?pin=2171&id=01", softhsm_lib_path());
|
||||
|
||||
rc = load_key(&key, spec);
|
||||
INFO(ziti_errorstr(rc));
|
||||
REQUIRE(rc == ZITI_OK);
|
||||
REQUIRE(validate_key(&key) == 0);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("engine-PKCS11 format ECDSA key", "[keys][pkcs11][ecdsa]") {
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
char cwd[PATH_MAX];
|
||||
getcwd(cwd, sizeof(cwd));
|
||||
char spec[1024];
|
||||
|
||||
setenv("SOFTHSM2_CONF", "softhsm2.conf", 1);
|
||||
sprintf(spec, "pkcs11://%s?pin=2171&id=02", softhsm_lib_path());
|
||||
|
||||
rc = load_key(&key, spec);
|
||||
INFO(ziti_errorstr(rc));
|
||||
REQUIRE(rc == ZITI_OK);
|
||||
REQUIRE(validate_key(&key) == 0);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("engine-PKCS11: invalid driver", "[keys][pkcs11]") {
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
char cwd[PATH_MAX];
|
||||
getcwd(cwd, sizeof(cwd));
|
||||
char spec[1024];
|
||||
|
||||
|
||||
setenv("SOFTHSM2_CONF", "softhsm2.conf", 1);
|
||||
sprintf(spec, "pkcs11:///usr/lib/libnot-a-real-driver.so?pin=1111");
|
||||
|
||||
rc = load_key(&key, spec);
|
||||
INFO(ziti_errorstr(rc));
|
||||
REQUIRE(rc == ZITI_KEY_INVALID);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("engine-PKCS11: invalid pin", "[keys][pkcs11]") {
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
char cwd[PATH_MAX];
|
||||
getcwd(cwd, sizeof(cwd));
|
||||
char spec[1024];
|
||||
|
||||
setenv("SOFTHSM2_CONF", "softhsm2.conf", 1);
|
||||
sprintf(spec, "pkcs11://%s?pin=1111", softhsm_lib_path());
|
||||
|
||||
rc = load_key(&key, spec);
|
||||
INFO(ziti_errorstr(rc));
|
||||
REQUIRE(rc == ZITI_KEY_INVALID);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
TEST_CASE("engine-PKCS11: invalid slot", "[keys][pkcs11]") {
|
||||
mbedtls_pk_context key;
|
||||
mbedtls_pk_init(&key);
|
||||
int rc = 0;
|
||||
|
||||
char cwd[PATH_MAX];
|
||||
getcwd(cwd, sizeof(cwd));
|
||||
char spec[1024];
|
||||
|
||||
setenv("SOFTHSM2_CONF", "softhsm2.conf", 1);
|
||||
sprintf(spec, "pkcs11://%s?slot=0x1234", softhsm_lib_path());
|
||||
|
||||
rc = load_key(&key, spec);
|
||||
INFO(ziti_errorstr(rc));
|
||||
REQUIRE(rc == ZITI_KEY_INVALID);
|
||||
|
||||
mbedtls_pk_free(&key);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//
|
||||
// Created by eugene on 5/29/19.
|
||||
//
|
||||
|
||||
|
||||
#include <catch2/catch.hpp>
|
||||
#include <string.h>
|
||||
|
||||
#include "../library/model.h"
|
||||
|
||||
TEST_CASE("multi-gateway session", "[model]") {
|
||||
|
||||
const char *ns = "{\n"
|
||||
" \"_links\": {\n"
|
||||
" \"self\": {\n"
|
||||
" \"href\": \"./network-sessions/1276df75-3ba3-4658-98ad-fe5a0e96021a\"\n"
|
||||
" }\n"
|
||||
" },\n"
|
||||
" \"gateways\": [\n"
|
||||
" {\n"
|
||||
" \"hostname\": \"ec2-18-223-205-231.us-east-2.compute.amazonaws.com\",\n"
|
||||
" \"name\": \"ziti-bridge-us-east\",\n"
|
||||
" \"urls\": {\n"
|
||||
" \"tls\": \"tls://ec2-18-223-205-231.us-east-2.compute.amazonaws.com:3022\"\n"
|
||||
" }\n"
|
||||