From 78c65b5adff19bba2ff02aea266583d024ea7e71 Mon Sep 17 00:00:00 2001 From: Nikos Mavrogiannopoulos Date: Sun, 1 Dec 2024 15:16:53 +0100 Subject: [PATCH] Updated code to follow with kernel coding style Signed-off-by: Nikos Mavrogiannopoulos --- src/acct/pam.c | 34 +- src/acct/radius.c | 73 +- src/auth-unix.c | 44 +- src/auth-unix.h | 9 +- src/auth/common.h | 2 +- src/auth/gssapi.c | 117 ++- src/auth/openidconnect.c | 322 +++---- src/auth/pam.c | 142 ++-- src/auth/pam.h | 10 +- src/auth/plain.c | 160 ++-- src/auth/radius.c | 388 ++++++--- src/auth/radius.h | 36 +- src/common-config.h | 33 +- src/common/base64-helper.c | 25 +- src/common/base64-helper.h | 14 +- src/common/cloexec.c | 47 +- src/common/cloexec.h | 6 +- src/common/common.c | 174 ++-- src/common/common.h | 81 +- src/common/hmac.c | 11 +- src/common/hmac.h | 12 +- src/common/snapshot.c | 50 +- src/common/sockdiag.c | 98 +-- src/common/sockdiag.h | 4 +- src/common/system.c | 48 +- src/common/system.h | 23 +- src/config-kkdcp.c | 7 +- src/config-ports.c | 41 +- src/config.c | 1412 +++++++++++++++++++------------ src/defs.h | 9 +- src/gettime.h | 46 +- src/html.c | 43 +- src/html.h | 11 +- src/icmp-ping.c | 169 ++-- src/icmp-ping.h | 6 +- src/ip-lease.c | 318 ++++--- src/ip-lease.h | 32 +- src/ip-util.c | 67 +- src/ip-util.h | 32 +- src/isolate.c | 11 +- src/isolate.h | 2 +- src/kkdcp_asn1_tab.c | 22 +- src/log.c | 4 +- src/log.h | 119 +-- src/lzs.c | 122 +-- src/lzs.h | 8 +- src/main-auth.c | 82 +- src/main-ban.c | 154 ++-- src/main-ban.h | 21 +- src/main-ctl-unix.c | 377 +++++---- src/main-ctl.h | 13 +- src/main-limits.c | 24 +- src/main-limits.h | 9 +- src/main-log.c | 54 +- src/main-proc.c | 33 +- src/main-sec-mod-cmd.c | 485 +++++++---- src/main-user.c | 222 +++-- src/main-worker-cmd.c | 343 ++++---- src/main.c | 865 +++++++++++-------- src/main.h | 139 +-- src/namespace.c | 16 +- src/namespace.h | 9 +- src/occtl/cache.c | 46 +- src/occtl/ctl.h | 2 +- src/occtl/geoip.c | 66 +- src/occtl/geoip.h | 4 +- src/occtl/ip-cache.c | 32 +- src/occtl/json.c | 19 +- src/occtl/json.h | 4 +- src/occtl/maxmind.c | 82 +- src/occtl/nl.c | 37 +- src/occtl/occtl.c | 176 ++-- src/occtl/occtl.h | 131 +-- src/occtl/pager.c | 11 +- src/occtl/print.c | 90 +- src/occtl/session-cache.c | 26 +- src/occtl/time.c | 16 +- src/occtl/unix.c | 940 ++++++++++++-------- src/ocpasswd/ocpasswd.c | 168 ++-- src/proc-search.c | 115 +-- src/proc-search.h | 18 +- src/route-add.c | 79 +- src/route-add.h | 6 +- src/script-list.h | 14 +- src/sec-mod-acct.h | 21 +- src/sec-mod-auth.c | 472 +++++++---- src/sec-mod-auth.h | 28 +- src/sec-mod-cookies.c | 34 +- src/sec-mod-db.c | 59 +- src/sec-mod-resume.c | 47 +- src/sec-mod-resume.h | 13 +- src/sec-mod-sup-config.c | 14 +- src/sec-mod-sup-config.h | 10 +- src/sec-mod.c | 590 ++++++------- src/sec-mod.h | 68 +- src/setproctitle.c | 20 +- src/setproctitle.h | 19 +- src/str.c | 57 +- src/str.h | 38 +- src/subconfig.c | 111 ++- src/sup-config/file.c | 183 ++-- src/sup-config/radius.c | 42 +- src/tlslib.c | 474 ++++++----- src/tlslib.h | 141 +-- src/tun.c | 162 ++-- src/tun.h | 5 +- src/valid-hostname.c | 2 +- src/vasprintf.c | 12 +- src/vhost.h | 52 +- src/vpn.h | 236 +++--- src/worker-auth.c | 766 +++++++++-------- src/worker-bandwidth.c | 15 +- src/worker-bandwidth.h | 12 +- src/worker-http-handlers.c | 148 ++-- src/worker-http.c | 481 ++++++----- src/worker-kkdcp.c | 103 ++- src/worker-latency.c | 63 +- src/worker-latency.h | 7 +- src/worker-log.c | 32 +- src/worker-misc.c | 48 +- src/worker-privs.c | 45 +- src/worker-proxyproto.c | 190 +++-- src/worker-resume.c | 44 +- src/worker-svc.c | 54 +- src/worker-tun.c | 24 +- src/worker-vpn.c | 1196 ++++++++++++++------------ src/worker.c | 54 +- src/worker.h | 196 ++--- tests/ban-ips.c | 38 +- tests/cstp-recv.c | 28 +- tests/generate_oidc_test_data.c | 86 +- tests/html-escape.c | 26 +- tests/human_addr.c | 23 +- tests/ipv4-prefix.c | 2 +- tests/ipv6-prefix.c | 13 +- tests/json-escape.c | 16 +- tests/kkdcp-parsing.c | 36 +- tests/port-parsing.c | 43 +- tests/proxyproto-v1.c | 42 +- tests/str-test.c | 20 +- tests/str-test2.c | 16 +- tests/url-escape.c | 35 +- 142 files changed, 9273 insertions(+), 6911 deletions(-) diff --git a/src/acct/pam.c b/src/acct/pam.c index 74cde2d2..b5f07b8e 100644 --- a/src/acct/pam.c +++ b/src/acct/pam.c @@ -38,21 +38,22 @@ #include "auth/pam.h" static int ocserv_conv(int msg_size, const struct pam_message **msg, - struct pam_response **resp, void *uptr) + struct pam_response **resp, void *uptr) { *resp = NULL; return PAM_SUCCESS; } -static int pam_acct_open_session(void *vctx, unsigned auth_method, const struct common_acct_info_st *ai, const void *sid, unsigned sid_size) +static int pam_acct_open_session(void *vctx, unsigned int auth_method, + const struct common_acct_info_st *ai, + const void *sid, unsigned int sid_size) { -int pret; -pam_handle_t *ph; -struct pam_conv dc; + int pret; + pam_handle_t *ph; + struct pam_conv dc; if (ai->username[0] == 0) { - oc_syslog(LOG_NOTICE, - "PAM-acct: no username present"); + oc_syslog(LOG_NOTICE, "PAM-acct: no username present"); return ERR_AUTH_FAIL; } @@ -60,13 +61,15 @@ struct pam_conv dc; dc.appdata_ptr = NULL; pret = pam_start(PACKAGE, ai->username, &dc, &ph); if (pret != PAM_SUCCESS) { - oc_syslog(LOG_NOTICE, "PAM-acct init: %s", pam_strerror(ph, pret)); + oc_syslog(LOG_NOTICE, "PAM-acct init: %s", + pam_strerror(ph, pret)); goto fail1; } pret = pam_acct_mgmt(ph, PAM_DISALLOW_NULL_AUTHTOK); if (pret != PAM_SUCCESS) { - oc_syslog(LOG_INFO, "PAM-acct account error: %s", pam_strerror(ph, pret)); + oc_syslog(LOG_INFO, "PAM-acct account error: %s", + pam_strerror(ph, pret)); goto fail2; } @@ -77,18 +80,19 @@ fail2: pam_end(ph, pret); fail1: return -1; - } -static void pam_acct_close_session(void *vctx, unsigned auth_method, const struct common_acct_info_st *ai, stats_st *stats, unsigned status) +static void pam_acct_close_session(void *vctx, unsigned int auth_method, + const struct common_acct_info_st *ai, + stats_st *stats, unsigned int status) { } const struct acct_mod_st pam_acct_funcs = { - .type = ACCT_TYPE_PAM, - .auth_types = ALL_AUTH_TYPES, - .open_session = pam_acct_open_session, - .close_session = pam_acct_close_session, + .type = ACCT_TYPE_PAM, + .auth_types = ALL_AUTH_TYPES, + .open_session = pam_acct_open_session, + .close_session = pam_acct_close_session, }; #endif diff --git a/src/acct/radius.c b/src/acct/radius.c index 44f40ac3..fc44d489 100644 --- a/src/acct/radius.c +++ b/src/acct/radius.c @@ -33,9 +33,9 @@ #ifdef HAVE_RADIUS #ifdef LEGACY_RADIUS -# include +#include #else -# include +#include #endif #include @@ -61,19 +61,21 @@ static void acct_radius_vhost_init(void **_vctx, void *pool, void *additional) } if (config->nas_identifier) { - strlcpy(vctx->nas_identifier, config->nas_identifier, sizeof(vctx->nas_identifier)); + strlcpy(vctx->nas_identifier, config->nas_identifier, + sizeof(vctx->nas_identifier)); } else { vctx->nas_identifier[0] = 0; } - if (rc_read_dictionary(vctx->rh, rc_conf_str(vctx->rh, "dictionary")) != 0) { + if (rc_read_dictionary(vctx->rh, rc_conf_str(vctx->rh, "dictionary")) != + 0) { fprintf(stderr, "error reading the radius dictionary\n"); exit(EXIT_FAILURE); } *_vctx = vctx; return; - fail: +fail: fprintf(stderr, "radius initialization error\n"); exit(EXIT_FAILURE); } @@ -108,12 +110,15 @@ static void append_stats(rc_handle *rh, VALUE_PAIR **send, stats_st *stats) rc_avpair_add(rh, send, PW_ACCT_OUTPUT_GIGAWORDS, &uout, -1, 0); } -static void append_acct_standard(struct radius_vhost_ctx *vctx, rc_handle *rh, const common_acct_info_st *ai, VALUE_PAIR **send) +static void append_acct_standard(struct radius_vhost_ctx *vctx, rc_handle *rh, + const common_acct_info_st *ai, + VALUE_PAIR **send) { uint32_t i; if (vctx->nas_identifier[0] != 0) { - rc_avpair_add(rh, send, PW_NAS_IDENTIFIER, vctx->nas_identifier, -1, 0); + rc_avpair_add(rh, send, PW_NAS_IDENTIFIER, vctx->nas_identifier, + -1, 0); } if (ai->our_ip[0] != 0) { @@ -122,9 +127,11 @@ static void append_acct_standard(struct radius_vhost_ctx *vctx, rc_handle *rh, c if (inet_pton(AF_INET, ai->our_ip, &in) != 0) { in.s_addr = ntohl(in.s_addr); - rc_avpair_add(rh, send, PW_NAS_IP_ADDRESS, (char*)&in, sizeof(struct in_addr), 0); + rc_avpair_add(rh, send, PW_NAS_IP_ADDRESS, (char *)&in, + sizeof(struct in_addr), 0); } else if (inet_pton(AF_INET6, ai->our_ip, &in6) != 0) { - rc_avpair_add(rh, send, PW_NAS_IPV6_ADDRESS, (char*)&in6, sizeof(struct in6_addr), 0); + rc_avpair_add(rh, send, PW_NAS_IPV6_ADDRESS, + (char *)&in6, sizeof(struct in6_addr), 0); } } @@ -138,9 +145,11 @@ static void append_acct_standard(struct radius_vhost_ctx *vctx, rc_handle *rh, c if (ai->ipv4[0] != 0) { struct in_addr in; + if (inet_pton(AF_INET, ai->ipv4, &in) == 1) { in.s_addr = ntohl(in.s_addr); - if (rc_avpair_add(rh, send, PW_FRAMED_IP_ADDRESS, &in, sizeof(in), 0) == NULL) { + if (rc_avpair_add(rh, send, PW_FRAMED_IP_ADDRESS, &in, + sizeof(in), 0) == NULL) { return; } } @@ -149,8 +158,10 @@ static void append_acct_standard(struct radius_vhost_ctx *vctx, rc_handle *rh, c #ifndef LEGACY_RADIUS /* bug in freeradius-client */ if (ai->ipv6[0] != 0) { struct in6_addr in; + if (inet_pton(AF_INET6, ai->ipv6, &in) == 1) { - if (rc_avpair_add(rh, send, PW_FRAMED_IPV6_ADDRESS, &in, sizeof(in), 0) == NULL) { + if (rc_avpair_add(rh, send, PW_FRAMED_IPV6_ADDRESS, &in, + sizeof(in), 0) == NULL) { return; } } @@ -164,7 +175,9 @@ static void append_acct_standard(struct radius_vhost_ctx *vctx, rc_handle *rh, c rc_avpair_add(rh, send, PW_ACCT_AUTHENTIC, &i, -1, 0); } -static void radius_acct_session_stats(void *_vctx, unsigned auth_method, const common_acct_info_st *ai, stats_st *stats) +static void radius_acct_session_stats(void *_vctx, unsigned int auth_method, + const common_acct_info_st *ai, + stats_st *stats) { int ret; uint32_t status_type; @@ -175,7 +188,8 @@ static void radius_acct_session_stats(void *_vctx, unsigned auth_method, const c oc_syslog(LOG_DEBUG, "radius-auth: sending session interim update"); - if (rc_avpair_add(vctx->rh, &send, PW_ACCT_STATUS_TYPE, &status_type, -1, 0) == NULL) { + if (rc_avpair_add(vctx->rh, &send, PW_ACCT_STATUS_TYPE, &status_type, + -1, 0) == NULL) { goto cleanup; } @@ -188,15 +202,18 @@ static void radius_acct_session_stats(void *_vctx, unsigned auth_method, const c rc_avpair_free(recvd); if (ret != OK_RC) { - oc_syslog(LOG_NOTICE, "radius-auth: radius_open_session: %d", ret); + oc_syslog(LOG_NOTICE, "radius-auth: radius_open_session: %d", + ret); goto cleanup; } - cleanup: +cleanup: rc_avpair_free(send); } -static int radius_acct_open_session(void *_vctx, unsigned auth_method, const common_acct_info_st *ai, const void *sid, unsigned sid_size) +static int radius_acct_open_session(void *_vctx, unsigned int auth_method, + const common_acct_info_st *ai, + const void *sid, unsigned int sid_size) { int ret; uint32_t status_type; @@ -212,13 +229,15 @@ static int radius_acct_open_session(void *_vctx, unsigned auth_method, const com oc_syslog(LOG_DEBUG, "radius-auth: opening session %s", ai->safe_id); - if (rc_avpair_add(vctx->rh, &send, PW_ACCT_STATUS_TYPE, &status_type, -1, 0) == NULL) { + if (rc_avpair_add(vctx->rh, &send, PW_ACCT_STATUS_TYPE, &status_type, + -1, 0) == NULL) { ret = -1; goto cleanup; } if (ai->user_agent[0] != 0) { - rc_avpair_add(vctx->rh, &send, PW_CONNECT_INFO, ai->user_agent, -1, 0); + rc_avpair_add(vctx->rh, &send, PW_CONNECT_INFO, ai->user_agent, + -1, 0); } append_acct_standard(vctx, vctx->rh, ai, &send); @@ -229,18 +248,22 @@ static int radius_acct_open_session(void *_vctx, unsigned auth_method, const com rc_avpair_free(recvd); if (ret != OK_RC) { - oc_syslog(LOG_NOTICE, "radius-auth: radius_open_session: %d", ret); + oc_syslog(LOG_NOTICE, "radius-auth: radius_open_session: %d", + ret); ret = -1; goto cleanup; } ret = 0; - cleanup: +cleanup: rc_avpair_free(send); return ret; } -static void radius_acct_close_session(void *_vctx, unsigned auth_method, const common_acct_info_st *ai, stats_st *stats, unsigned discon_reason) +static void radius_acct_close_session(void *_vctx, unsigned int auth_method, + const common_acct_info_st *ai, + stats_st *stats, + unsigned int discon_reason) { int ret; uint32_t status_type; @@ -250,7 +273,8 @@ static void radius_acct_close_session(void *_vctx, unsigned auth_method, const c status_type = PW_STATUS_STOP; oc_syslog(LOG_DEBUG, "radius-auth: closing session"); - if (rc_avpair_add(vctx->rh, &send, PW_ACCT_STATUS_TYPE, &status_type, -1, 0) == NULL) + if (rc_avpair_add(vctx->rh, &send, PW_ACCT_STATUS_TYPE, &status_type, + -1, 0) == NULL) return; if (discon_reason == REASON_USER_DISCONNECT) @@ -277,11 +301,12 @@ static void radius_acct_close_session(void *_vctx, unsigned auth_method, const c rc_avpair_free(recvd); if (ret != OK_RC) { - oc_syslog(LOG_INFO, "radius-auth: radius_close_session: %d", ret); + oc_syslog(LOG_INFO, "radius-auth: radius_close_session: %d", + ret); goto cleanup; } - cleanup: +cleanup: rc_avpair_free(send); } diff --git a/src/auth-unix.c b/src/auth-unix.c index 631464d5..231e7471 100644 --- a/src/auth-unix.c +++ b/src/auth-unix.c @@ -35,10 +35,10 @@ int get_user_auth_group(const char *username, const char *suggested, char *groupname, int groupname_size) { -struct passwd * pwd; -struct group *grp; -int ret; -unsigned found; + struct passwd *pwd; + struct group *grp; + int ret; + unsigned int found; groupname[0] = 0; @@ -47,61 +47,69 @@ unsigned found; if (suggested != NULL) { gid_t groups[MAX_GROUPS]; int ngroups = ARRAY_SIZE(groups); - unsigned i; + unsigned int i; - ret = getgrouplist(username, pwd->pw_gid, groups, &ngroups); + ret = getgrouplist(username, pwd->pw_gid, groups, + &ngroups); if (ret <= 0) { return 0; } found = 0; - for (i=0;igr_name) == 0) { - strlcpy(groupname, grp->gr_name, groupname_size); + if (grp != NULL && + strcmp(suggested, grp->gr_name) == 0) { + strlcpy(groupname, grp->gr_name, + groupname_size); found = 1; break; } } if (found == 0) { - oc_syslog(LOG_NOTICE, - "user '%s' requested group '%s' but is not a member", - username, suggested); + oc_syslog( + LOG_NOTICE, + "user '%s' requested group '%s' but is not a member", + username, suggested); return -1; } } else { - struct group* grp = getgrgid(pwd->pw_gid); + struct group *grp = getgrgid(pwd->pw_gid); + if (grp != NULL) - strlcpy(groupname, grp->gr_name, groupname_size); + strlcpy(groupname, grp->gr_name, + groupname_size); } } return 0; } -void unix_group_list(void *pool, unsigned gid_min, char ***groupname, unsigned *groupname_size) +void unix_group_list(void *pool, unsigned int gid_min, char ***groupname, + unsigned int *groupname_size) { struct group *grp; setgrent(); *groupname_size = 0; - *groupname = talloc_size(pool, sizeof(char*)*MAX_GROUPS); + *groupname = talloc_size(pool, sizeof(char *) * MAX_GROUPS); if (*groupname == NULL) { goto exit; } while ((grp = getgrent()) != NULL && (*groupname_size) < MAX_GROUPS) { if (grp->gr_gid >= gid_min) { - (*groupname)[(*groupname_size)] = talloc_strdup(*groupname, grp->gr_name); + (*groupname)[(*groupname_size)] = + talloc_strdup(*groupname, grp->gr_name); if ((*groupname)[(*groupname_size)] == NULL) break; (*groupname_size)++; } } - exit: +exit: endgrent(); } diff --git a/src/auth-unix.h b/src/auth-unix.h index 7060031f..8dbf03ef 100644 --- a/src/auth-unix.h +++ b/src/auth-unix.h @@ -1,16 +1,17 @@ #ifndef OC_AUTH_UNIX_H -# define OC_AUTH_UNIX_H +#define OC_AUTH_UNIX_H -# include +#include #if defined(HAVE_GSSAPI) || defined(HAVE_PAM) -# define HAVE_GET_USER_AUTH_GROUP +#define HAVE_GET_USER_AUTH_GROUP #endif #ifdef HAVE_GET_USER_AUTH_GROUP int get_user_auth_group(const char *username, const char *suggested, char *groupname, int groupname_size); -void unix_group_list(void *pool, unsigned gid_min, char ***groupname, unsigned *groupname_size); +void unix_group_list(void *pool, unsigned int gid_min, char ***groupname, + unsigned int *groupname_size); #endif #endif diff --git a/src/auth/common.h b/src/auth/common.h index 5e4540af..a0854e91 100644 --- a/src/auth/common.h +++ b/src/auth/common.h @@ -1,5 +1,5 @@ #ifndef AUTH_COMMON_H -# define AUTH_COMMON_H +#define AUTH_COMMON_H #define MAX_PASSWORD_TRIES 3 diff --git a/src/auth/gssapi.c b/src/auth/gssapi.c index 79961933..9bc711e5 100644 --- a/src/auth/gssapi.c +++ b/src/auth/gssapi.c @@ -17,7 +17,6 @@ * along with this program. If not, see . */ - #include #ifdef HAVE_GSSAPI @@ -42,7 +41,7 @@ struct gssapi_vhost_ctx_st { gss_cred_id_t creds; gss_OID_set oids; - unsigned no_local_map; + unsigned int no_local_map; time_t ticket_freshness_secs; }; @@ -57,8 +56,7 @@ struct gssapi_ctx_st { }; /* Taken from openconnect's gssapi */ -static void print_gss_err(const char *where, - gss_OID mech, OM_uint32 err_maj, +static void print_gss_err(const char *where, gss_OID mech, OM_uint32 err_maj, OM_uint32 err_min) { OM_uint32 major, minor, msg_ctx = 0; @@ -69,7 +67,8 @@ static void print_gss_err(const char *where, mech, &msg_ctx, &status); if (GSS_ERROR(major)) break; - oc_syslog(LOG_ERR, "gssapi: %s[maj]: %s\n", where, (char *)status.value); + oc_syslog(LOG_ERR, "gssapi: %s[maj]: %s\n", where, + (char *)status.value); gss_release_buffer(&minor, &status); } while (msg_ctx); @@ -79,16 +78,15 @@ static void print_gss_err(const char *where, mech, &msg_ctx, &status); if (GSS_ERROR(major)) break; - oc_syslog(LOG_ERR, "gssapi: %s[min]: %s\n", where, (char *)status.value); + oc_syslog(LOG_ERR, "gssapi: %s[min]: %s\n", where, + (char *)status.value); gss_release_buffer(&minor, &status); } while (msg_ctx); } -const gss_OID_desc spnego_mech = {6, (void *)"\x2b\x06\x01\x05\x05\x02"}; -const gss_OID_set_desc desired_mechs = { - .count = 1, - .elements = (gss_OID)&spnego_mech -}; +const gss_OID_desc spnego_mech = { 6, (void *)"\x2b\x06\x01\x05\x05\x02" }; +const gss_OID_set_desc desired_mechs = { .count = 1, + .elements = (gss_OID)&spnego_mech }; static void gssapi_vhost_init(void **_vctx, void *pool, void *additional) { @@ -118,21 +116,26 @@ static void gssapi_vhost_init(void **_vctx, void *pool, void *additional) cred_store.count = 1; cred_store.elements = &element; - ret = gss_acquire_cred_from(&minor, name, 0, (gss_OID_set)&desired_mechs, 2, - &cred_store, &vctx->creds, &vctx->oids, &time); + ret = gss_acquire_cred_from(&minor, name, 0, + (gss_OID_set)&desired_mechs, 2, + &cred_store, &vctx->creds, + &vctx->oids, &time); if (ret != GSS_S_COMPLETE) { ret = -1; - print_gss_err("gss_acquire_cred(keytab)", GSS_C_NO_OID, ret, minor); + print_gss_err("gss_acquire_cred(keytab)", GSS_C_NO_OID, + ret, minor); exit(EXIT_FAILURE); } } else { - ret = gss_acquire_cred(&minor, name, 0, (gss_OID_set)&desired_mechs, 2, - &vctx->creds, &vctx->oids, &time); + ret = gss_acquire_cred(&minor, name, 0, + (gss_OID_set)&desired_mechs, 2, + &vctx->creds, &vctx->oids, &time); if (ret != GSS_S_COMPLETE) { ret = -1; - print_gss_err("gss_acquire_cred", GSS_C_NO_OID, ret, minor); + print_gss_err("gss_acquire_cred", GSS_C_NO_OID, ret, + minor); exit(EXIT_FAILURE); } } @@ -149,7 +152,8 @@ static void gssapi_vhost_deinit(void *_vctx) gss_release_cred(&minor, &vctx->creds); } -static int get_name(struct gssapi_ctx_st *pctx, gss_name_t client, gss_OID mech_type) +static int get_name(struct gssapi_ctx_st *pctx, gss_name_t client, + gss_OID mech_type) { int ret; OM_uint32 minor; @@ -168,20 +172,24 @@ static int get_name(struct gssapi_ctx_st *pctx, gss_name_t client, gss_OID mech_ pctx->username[name.length] = 0; } - oc_syslog(LOG_DEBUG, "gssapi: authenticated GSSAPI user: %.*s", (unsigned)name.length, (char*)name.value); + oc_syslog(LOG_DEBUG, "gssapi: authenticated GSSAPI user: %.*s", + (unsigned int)name.length, (char *)name.value); gss_release_buffer(&minor, &name); if (pctx->vctx->no_local_map == 0) { ret = gss_localname(&minor, client, mech_type, &name); if (GSS_ERROR(ret) || name.length >= MAX_USERNAME_SIZE) { print_gss_err("gss_localname", mech_type, ret, minor); - oc_syslog(LOG_INFO, "gssapi: authenticated user doesn't map to a local user"); + oc_syslog( + LOG_INFO, + "gssapi: authenticated user doesn't map to a local user"); return -1; } memcpy(pctx->username, name.value, name.length); pctx->username[name.length] = 0; - oc_syslog(LOG_INFO, "gssapi: authenticated local user: %s", pctx->username); + oc_syslog(LOG_INFO, "gssapi: authenticated local user: %s", + pctx->username); gss_release_buffer(&minor, &name); } @@ -192,38 +200,49 @@ static int get_name(struct gssapi_ctx_st *pctx, gss_name_t client, gss_OID mech_ return 0; } -static int verify_krb5_constraints(struct gssapi_ctx_st *pctx, gss_OID mech_type) +static int verify_krb5_constraints(struct gssapi_ctx_st *pctx, + gss_OID mech_type) { int ret; OM_uint32 minor; krb5_timestamp authtime; if (mech_type == NULL || - ((mech_type->length != gss_mech_krb5->length || memcmp(mech_type->elements, gss_mech_krb5->elements, mech_type->length) != 0) && - (mech_type->length != gss_mech_krb5_old->length || memcmp(mech_type->elements, gss_mech_krb5_old->elements, mech_type->length) != 0)) || + ((mech_type->length != gss_mech_krb5->length || + memcmp(mech_type->elements, gss_mech_krb5->elements, + mech_type->length) != 0) && + (mech_type->length != gss_mech_krb5_old->length || + memcmp(mech_type->elements, gss_mech_krb5_old->elements, + mech_type->length) != 0)) || pctx->vctx->ticket_freshness_secs == 0) { return 0; } - ret = gsskrb5_extract_authtime_from_sec_context (&minor, pctx->gssctx, &authtime); + ret = gsskrb5_extract_authtime_from_sec_context(&minor, pctx->gssctx, + &authtime); if (GSS_ERROR(ret)) { - print_gss_err("gsskrb5_extract_authtime_from_sec_context", mech_type, ret, minor); + print_gss_err("gsskrb5_extract_authtime_from_sec_context", + mech_type, ret, minor); return -1; } if (time(NULL) > authtime + pctx->vctx->ticket_freshness_secs) { - oc_syslog(LOG_INFO, "gssapi: the presented kerberos ticket for %s is too old", pctx->username); + oc_syslog( + LOG_INFO, + "gssapi: the presented kerberos ticket for %s is too old", + pctx->username); return -1; } return 0; } -static int gssapi_auth_init(void **ctx, void *pool, void *_vctx, const common_auth_init_st *info) +static int gssapi_auth_init(void **ctx, void *pool, void *_vctx, + const common_auth_init_st *info) { struct gssapi_ctx_st *pctx; OM_uint32 minor, flags, time; - gss_buffer_desc buf= GSS_C_EMPTY_BUFFER; + gss_buffer_desc buf = GSS_C_EMPTY_BUFFER; gss_name_t client = GSS_C_NO_NAME; gss_OID mech_type = GSS_C_NO_OID; int ret; @@ -243,20 +262,22 @@ static int gssapi_auth_init(void **ctx, void *pool, void *_vctx, const common_au pctx->vctx = vctx; - ret = oc_base64_decode_alloc(pctx, spnego, strlen(spnego), &raw, &raw_len); + ret = oc_base64_decode_alloc(pctx, spnego, strlen(spnego), &raw, + &raw_len); if (ret == 0) { - oc_syslog(LOG_ERR, "gssapi: error in base64 decoding %s", __func__); + oc_syslog(LOG_ERR, "gssapi: error in base64 decoding %s", + __func__); return ERR_AUTH_FAIL; } buf.value = raw; buf.length = raw_len; ret = gss_accept_sec_context(&minor, &pctx->gssctx, vctx->creds, &buf, - GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_type, &pctx->msg, - &flags, &time, &pctx->delegated_creds); + GSS_C_NO_CHANNEL_BINDINGS, &client, + &mech_type, &pctx->msg, &flags, &time, + &pctx->delegated_creds); talloc_free(raw); - if (ret == GSS_S_CONTINUE_NEEDED) { gss_release_name(&minor, &client); ret = ERR_AUTH_CONTINUE; @@ -277,11 +298,13 @@ static int gssapi_auth_init(void **ctx, void *pool, void *_vctx, const common_au return ret; } -static int gssapi_auth_group(void *ctx, const char *suggested, char *groupname, int groupname_size) +static int gssapi_auth_group(void *ctx, const char *suggested, char *groupname, + int groupname_size) { struct gssapi_ctx_st *pctx = ctx; - return get_user_auth_group(pctx->username, suggested, groupname, groupname_size); + return get_user_auth_group(pctx->username, suggested, groupname, + groupname_size); } static int gssapi_auth_user(void *ctx, char *username, int username_size) @@ -294,7 +317,8 @@ static int gssapi_auth_user(void *ctx, char *username, int username_size) /* Returns 0 if the user is successfully authenticated, and sets the appropriate group name. */ -static int gssapi_auth_pass(void *ctx, const char *spnego, unsigned spnego_len) +static int gssapi_auth_pass(void *ctx, const char *spnego, + unsigned int spnego_len) { struct gssapi_ctx_st *pctx = ctx; OM_uint32 minor, flags, time; @@ -308,15 +332,17 @@ static int gssapi_auth_pass(void *ctx, const char *spnego, unsigned spnego_len) /* nothing to be done */ ret = oc_base64_decode_alloc(pctx, spnego, spnego_len, &raw, &raw_len); if (ret == 0) { - oc_syslog(LOG_ERR, "gssapi: error in base64 decoding %s", __func__); + oc_syslog(LOG_ERR, "gssapi: error in base64 decoding %s", + __func__); return ERR_AUTH_FAIL; } buf.value = raw; buf.length = raw_len; - ret = gss_accept_sec_context(&minor, &pctx->gssctx, pctx->vctx->creds, &buf, - GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_type, &pctx->msg, - &flags, &time, &pctx->delegated_creds); + ret = gss_accept_sec_context(&minor, &pctx->gssctx, pctx->vctx->creds, + &buf, GSS_C_NO_CHANNEL_BINDINGS, &client, + &mech_type, &pctx->msg, &flags, &time, + &pctx->delegated_creds); talloc_free(raw); if (ret == GSS_S_CONTINUE_NEEDED) { @@ -340,15 +366,15 @@ static int gssapi_auth_msg(void *ctx, void *pool, passwd_msg_st *pst) { struct gssapi_ctx_st *pctx = ctx; OM_uint32 min; - unsigned length; + unsigned int length; /* our msg is our SPNEGO reply */ if (pctx->msg.value != NULL) { - length = BASE64_ENCODE_RAW_LENGTH(pctx->msg.length)+1; + length = BASE64_ENCODE_RAW_LENGTH(pctx->msg.length) + 1; pst->msg_str = talloc_size(pool, length); oc_base64_encode(pctx->msg.value, pctx->msg.length, - pst->msg_str, length); + pst->msg_str, length); gss_release_buffer(&min, &pctx->msg); pctx->msg.value = NULL; @@ -367,7 +393,8 @@ static void gssapi_auth_deinit(void *ctx) talloc_free(ctx); } -static void gssapi_group_list(void *pool, void *_additional, char ***groupname, unsigned *groupname_size) +static void gssapi_group_list(void *pool, void *_additional, char ***groupname, + unsigned int *groupname_size) { gssapi_cfg_st *config = _additional; gid_t min = 0; diff --git a/src/auth/openidconnect.c b/src/auth/openidconnect.c index 6a718897..0381e543 100644 --- a/src/auth/openidconnect.c +++ b/src/auth/openidconnect.c @@ -38,7 +38,7 @@ typedef struct oidc_vctx_st { json_t *config; json_t *jwks; - void * pool; + void *pool; int minimum_jwk_refresh_time; time_t last_jwks_load_time; } oidc_vctx_st; @@ -49,10 +49,10 @@ typedef struct oidc_ctx_st { int token_verified; } oidc_ctx_st; -static bool oidc_fetch_oidc_keys(oidc_vctx_st * vctx); -static bool oidc_verify_token(oidc_vctx_st * vctx, const char *token, - size_t token_length, - char user_name[MAX_USERNAME_SIZE]); +static bool oidc_fetch_oidc_keys(oidc_vctx_st *vctx); +static bool oidc_verify_token(oidc_vctx_st *vctx, const char *token, + size_t token_length, + char user_name[MAX_USERNAME_SIZE]); static void oidc_vhost_init(void **vctx, void *pool, void *additional) { @@ -76,30 +76,35 @@ static void oidc_vhost_init(void **vctx, void *pool, void *additional) vc->config = json_load_file(config, 0, &err); if (vc->config == NULL) { - oc_syslog(LOG_ERR, "ocserv-oidc: failed to load config file: %s\n", config); + oc_syslog(LOG_ERR, + "ocserv-oidc: failed to load config file: %s\n", + config); exit(EXIT_FAILURE); } if (!json_object_get(vc->config, "openid_configuration_url")) { - oc_syslog(LOG_ERR, - "ocserv-oidc: config file missing openid_configuration_url\n"); + oc_syslog( + LOG_ERR, + "ocserv-oidc: config file missing openid_configuration_url\n"); exit(EXIT_FAILURE); } if (!json_object_get(vc->config, "required_claims")) { oc_syslog(LOG_ERR, - "ocserv-oidc: config file missing required_claims\n"); + "ocserv-oidc: config file missing required_claims\n"); exit(EXIT_FAILURE); } if (!json_object_get(vc->config, "user_name_claim")) { oc_syslog(LOG_ERR, - "ocserv-oidc: config file missing user_name_claim\n"); + "ocserv-oidc: config file missing user_name_claim\n"); exit(EXIT_FAILURE); } if (json_object_get(vc->config, "minimum_jwk_refresh_time")) { - vc->minimum_jwk_refresh_time = json_integer_value(json_object_get(vc->config, "minimum_jwk_refresh_time")); + vc->minimum_jwk_refresh_time = json_integer_value( + json_object_get(vc->config, + "minimum_jwk_refresh_time")); } else { vc->minimum_jwk_refresh_time = MINIMUM_KEY_REFRESH_INTERVAL; } @@ -114,7 +119,7 @@ static void oidc_vhost_init(void **vctx, void *pool, void *additional) static void oidc_vhost_deinit(void *ctx) { - oidc_vctx_st *vctx = (oidc_vctx_st *) ctx; + oidc_vctx_st *vctx = (oidc_vctx_st *)ctx; if (!vctx) { return; @@ -132,10 +137,11 @@ static void oidc_vhost_deinit(void *ctx) } static int oidc_auth_init(void **ctx, void *pool, void *vctx, - const common_auth_init_st * info) + const common_auth_init_st *info) { - oidc_vctx_st *vt = (oidc_vctx_st *) vctx; + oidc_vctx_st *vt = (oidc_vctx_st *)vctx; oidc_ctx_st *ct; + ct = talloc_zero(pool, struct oidc_ctx_st); if (!ct) { return ERR_AUTH_FAIL; @@ -143,7 +149,8 @@ static int oidc_auth_init(void **ctx, void *pool, void *vctx, ct->vctx_st = vt; *ctx = (void *)ct; - if (oidc_verify_token(ct->vctx_st, info->username, strlen(info->username), ct->username)) { + if (oidc_verify_token(ct->vctx_st, info->username, + strlen(info->username), ct->username)) { ct->token_verified = 1; return 0; } else { @@ -153,7 +160,7 @@ static int oidc_auth_init(void **ctx, void *pool, void *vctx, static int oidc_auth_user(void *ctx, char *username, int username_size) { - oidc_ctx_st *ct = (oidc_ctx_st *) ctx; + oidc_ctx_st *ct = (oidc_ctx_st *)ctx; if (ct->token_verified) { strlcpy(username, ct->username, username_size); @@ -162,14 +169,14 @@ static int oidc_auth_user(void *ctx, char *username, int username_size) return ERR_AUTH_FAIL; } -static int oidc_auth_pass(void *ctx, const char *pass, unsigned pass_len) +static int oidc_auth_pass(void *ctx, const char *pass, unsigned int pass_len) { return ERR_AUTH_FAIL; } -static int oidc_auth_msg(void *ctx, void *pool, passwd_msg_st * pst) +static int oidc_auth_msg(void *ctx, void *pool, passwd_msg_st *pst) { - pst->counter = 0; /* we support a single password */ + pst->counter = 0; /* we support a single password */ /* use the default prompt */ return 0; @@ -180,19 +187,17 @@ static void oidc_auth_deinit(void *ctx) talloc_free(ctx); } -const struct auth_mod_st oidc_auth_funcs = { - .type = AUTH_TYPE_OIDC, - .allows_retries = 1, - .vhost_init = oidc_vhost_init, - .vhost_deinit = oidc_vhost_deinit, - .auth_init = oidc_auth_init, - .auth_deinit = oidc_auth_deinit, - .auth_msg = oidc_auth_msg, - .auth_pass = oidc_auth_pass, - .auth_user = oidc_auth_user, - .auth_group = NULL, - .group_list = NULL -}; +const struct auth_mod_st oidc_auth_funcs = { .type = AUTH_TYPE_OIDC, + .allows_retries = 1, + .vhost_init = oidc_vhost_init, + .vhost_deinit = oidc_vhost_deinit, + .auth_init = oidc_auth_init, + .auth_deinit = oidc_auth_deinit, + .auth_msg = oidc_auth_msg, + .auth_pass = oidc_auth_pass, + .auth_user = oidc_auth_user, + .auth_group = NULL, + .group_list = NULL }; // Key management typedef struct oidc_json_parser_context { @@ -204,10 +209,10 @@ typedef struct oidc_json_parser_context { // Callback from CURL for each block as it is downloaded static size_t oidc_json_parser_context_callback(char *ptr, size_t size, - size_t nmemb, void *userdata) + size_t nmemb, void *userdata) { oidc_json_parser_context *context = - (oidc_json_parser_context *) userdata; + (oidc_json_parser_context *)userdata; size_t new_offset = context->offset + nmemb; // Check for buffer overflow @@ -217,7 +222,9 @@ static size_t oidc_json_parser_context_callback(char *ptr, size_t size, if (context->offset + nmemb > context->length) { size_t new_size = (nmemb + context->length) * 3 / 2; - void * new_buffer = talloc_realloc_size(context->pool, context->buffer, new_size); + void *new_buffer = talloc_realloc_size( + context->pool, context->buffer, new_size); + if (new_buffer) { context->buffer = new_buffer; context->length = new_size; @@ -233,7 +240,7 @@ static size_t oidc_json_parser_context_callback(char *ptr, size_t size, } // Download a JSON file from the provided URI and return it in a jansson object -static json_t *oidc_fetch_json_from_uri(void * pool, const char *uri) +static json_t *oidc_fetch_json_from_uri(void *pool, const char *uri) { oidc_json_parser_context context = { pool, NULL, 0, 0 }; json_t *json = NULL; @@ -250,55 +257,60 @@ static json_t *oidc_fetch_json_from_uri(void * pool, const char *uri) curl = curl_easy_init(); if (!curl) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to download JSON document: URI %s\n", - uri); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to download JSON document: URI %s\n", + uri); goto cleanup; } res = curl_easy_setopt(curl, CURLOPT_URL, uri); if (res != CURLE_OK) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", - uri, res); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", + uri, res); goto cleanup; } - res = - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, - oidc_json_parser_context_callback); + res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, + oidc_json_parser_context_callback); if (res != CURLE_OK) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", - uri, res); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", + uri, res); goto cleanup; } res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &context); if (res != CURLE_OK) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", - uri, res); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", + uri, res); goto cleanup; } res = curl_easy_perform(curl); if (res != CURLE_OK) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", - uri, res); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to download JSON document: URI %s, CURLcode %d\n", + uri, res); goto cleanup; } json = json_loadb(context.buffer, context.offset, 0, &err); if (!json) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to parse JSON document: URI %s\n", - uri); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to parse JSON document: URI %s\n", + uri); goto cleanup; } - cleanup: +cleanup: if (context.buffer) { talloc_free(context.buffer); } @@ -311,47 +323,50 @@ static json_t *oidc_fetch_json_from_uri(void * pool, const char *uri) } // Download and parse the JWT keys for this virtual server context -static bool oidc_fetch_oidc_keys(oidc_vctx_st * vctx) +static bool oidc_fetch_oidc_keys(oidc_vctx_st *vctx) { bool result = false; json_t *jwks = NULL; json_t *oidc_config = NULL; json_t *openid_configuration_url = - json_object_get(vctx->config, "openid_configuration_url"); + json_object_get(vctx->config, "openid_configuration_url"); json_t *array; size_t index; json_t *value; if (!openid_configuration_url) { - oc_syslog(LOG_ERR, - "ocserv-oidc: openid_configuration_url missing from config\n"); + oc_syslog( + LOG_ERR, + "ocserv-oidc: openid_configuration_url missing from config\n"); goto cleanup; } - oidc_config = - oidc_fetch_json_from_uri(vctx->pool, - json_string_value - (openid_configuration_url)); + oidc_config = oidc_fetch_json_from_uri( + vctx->pool, json_string_value(openid_configuration_url)); if (!oidc_config) { oc_syslog(LOG_ERR, - "ocserv-oidc: Unable to fetch config doc from %s\n", json_string_value(openid_configuration_url)); + "ocserv-oidc: Unable to fetch config doc from %s\n", + json_string_value(openid_configuration_url)); goto cleanup; } json_t *jwks_uri = json_object_get(oidc_config, "jwks_uri"); + if (!jwks_uri || !json_string_value(jwks_uri)) { oc_syslog(LOG_ERR, - "ocserv-oidc: jwks_uri missing from config doc\n"); + "ocserv-oidc: jwks_uri missing from config doc\n"); goto cleanup; } - jwks = oidc_fetch_json_from_uri(vctx->pool, json_string_value(jwks_uri)); + jwks = oidc_fetch_json_from_uri(vctx->pool, + json_string_value(jwks_uri)); if (!jwks) { - oc_syslog(LOG_ERR, - "ocserv-oidc: failed to fetch keys from jwks_uri %s\n", - json_string_value(jwks_uri)); + oc_syslog( + LOG_ERR, + "ocserv-oidc: failed to fetch keys from jwks_uri %s\n", + json_string_value(jwks_uri)); goto cleanup; } @@ -362,12 +377,12 @@ static bool oidc_fetch_oidc_keys(oidc_vctx_st * vctx) } // Log the keys obtained - json_array_foreach(array, index, value) { + json_array_foreach(array, index, value) + { json_t *key_kid = json_object_get(value, "kid"); - oc_syslog(LOG_INFO, - "ocserv-oidc: fetched new JWK %s\n", - json_string_value(key_kid) - ); + + oc_syslog(LOG_INFO, "ocserv-oidc: fetched new JWK %s\n", + json_string_value(key_kid)); } if (vctx->jwks) { @@ -380,7 +395,7 @@ static bool oidc_fetch_oidc_keys(oidc_vctx_st * vctx) jwks = NULL; result = true; - cleanup: +cleanup: if (oidc_config) { json_decref(oidc_config); } @@ -391,7 +406,7 @@ static bool oidc_fetch_oidc_keys(oidc_vctx_st * vctx) return result; } -static bool oidc_verify_lifetime(json_t * token_claims) +static bool oidc_verify_lifetime(json_t *token_claims) { bool result = false; @@ -402,38 +417,42 @@ static bool oidc_verify_lifetime(json_t * token_claims) time_t current_time = time(NULL); if (!token_nbf || !json_integer_value(token_nbf)) { - oc_syslog(LOG_NOTICE, "ocserv-oidc: Token missing 'nbf' claim\n"); + oc_syslog(LOG_NOTICE, + "ocserv-oidc: Token missing 'nbf' claim\n"); goto cleanup; } if (!token_exp || !json_integer_value(token_exp)) { - oc_syslog(LOG_NOTICE, "ocserv-oidc: Token missing 'exp' claim\n"); + oc_syslog(LOG_NOTICE, + "ocserv-oidc: Token missing 'exp' claim\n"); goto cleanup; } if (!token_iat || !json_integer_value(token_iat)) { - oc_syslog(LOG_NOTICE, "ocserv-oidc: Token missing 'iat' claim\n"); + oc_syslog(LOG_NOTICE, + "ocserv-oidc: Token missing 'iat' claim\n"); goto cleanup; } // Check to ensure the token is within it's validity - if (json_integer_value(token_nbf) > current_time - || json_integer_value(token_exp) < current_time) { - oc_syslog(LOG_NOTICE, - "ocserv-oidc: Token not within validity period NBF: %lld EXP: %lld Current: %ld\n", - json_integer_value(token_nbf), - json_integer_value(token_exp), current_time); + if (json_integer_value(token_nbf) > current_time || + json_integer_value(token_exp) < current_time) { + oc_syslog( + LOG_NOTICE, + "ocserv-oidc: Token not within validity period NBF: %lld EXP: %lld Current: %ld\n", + json_integer_value(token_nbf), + json_integer_value(token_exp), current_time); goto cleanup; } result = true; - cleanup: +cleanup: return result; } -static bool oidc_verify_required_claims(json_t * required_claims, - json_t * token_claims) +static bool oidc_verify_required_claims(json_t *required_claims, + json_t *token_claims) { bool result = false; @@ -443,36 +462,38 @@ static bool oidc_verify_required_claims(json_t * required_claims, // Ensure all the required claims are present in the token json_object_foreach(required_claims, required_claim_name, - required_claim_value) { + required_claim_value) + { token_claim_value = - json_object_get(token_claims, required_claim_name); + json_object_get(token_claims, required_claim_name); if (!json_equal(required_claim_value, token_claim_value)) { - oc_syslog(LOG_NOTICE, - "ocserv-oidc: Required claim not met. Claim: %s Expected Value: %s\n", - required_claim_name, - json_string_value(required_claim_value)); + oc_syslog( + LOG_NOTICE, + "ocserv-oidc: Required claim not met. Claim: %s Expected Value: %s\n", + required_claim_name, + json_string_value(required_claim_value)); goto cleanup; } } result = true; - cleanup: +cleanup: return result; } -static bool oidc_map_user_name(json_t * user_name_claim, - json_t * token_claims, - char user_name[MAX_USERNAME_SIZE]) +static bool oidc_map_user_name(json_t *user_name_claim, json_t *token_claims, + char user_name[MAX_USERNAME_SIZE]) { bool result = false; // Pull the user name from the token - json_t *token_user_name_claim = - json_object_get(token_claims, json_string_value(user_name_claim)); - if (!token_user_name_claim || !json_string_value(token_user_name_claim)) { + json_t *token_user_name_claim = json_object_get( + token_claims, json_string_value(user_name_claim)); + if (!token_user_name_claim || + !json_string_value(token_user_name_claim)) { oc_syslog(LOG_NOTICE, "ocserv-oidc: Token missing '%s' claim\n", - json_string_value(user_name_claim)); + json_string_value(user_name_claim)); goto cleanup; } @@ -480,11 +501,11 @@ static bool oidc_map_user_name(json_t * user_name_claim, MAX_USERNAME_SIZE); result = true; - cleanup: +cleanup: return result; } -static json_t *oidc_extract_claims(cjose_jws_t * jws) +static json_t *oidc_extract_claims(cjose_jws_t *jws) { cjose_err err; json_error_t json_err; @@ -493,26 +514,27 @@ static json_t *oidc_extract_claims(cjose_jws_t * jws) json_t *token_claims = NULL; // Extract the claim portion from the token - if (!cjose_jws_get_plaintext(jws, &plain_text, &plain_text_size, &err)) { + if (!cjose_jws_get_plaintext(jws, &plain_text, &plain_text_size, + &err)) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Failed to get plain text from token\n"); + "ocserv-oidc: Failed to get plain text from token\n"); goto cleanup; } // Parse the claim JSON token_claims = - json_loadb((char *)plain_text, plain_text_size, 0, &json_err); + json_loadb((char *)plain_text, plain_text_size, 0, &json_err); if (!token_claims) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Failed to get claims from token\n"); + "ocserv-oidc: Failed to get claims from token\n"); goto cleanup; } - cleanup: +cleanup: return token_claims; } -static bool oidc_verify_signature(oidc_vctx_st * vctx, cjose_jws_t * jws) +static bool oidc_verify_signature(oidc_vctx_st *vctx, cjose_jws_t *jws) { bool result = false; @@ -540,26 +562,31 @@ static bool oidc_verify_signature(oidc_vctx_st * vctx, cjose_jws_t * jws) token_header = cjose_jws_get_protected(jws); if (token_header == NULL) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Token malformed - no header\n"); + "ocserv-oidc: Token malformed - no header\n"); goto cleanup; } // Get the kid of the key used to sign this token token_kid = json_object_get(token_header, "kid"); if (token_kid == NULL || !json_string_value(token_kid)) { - oc_syslog(LOG_NOTICE, "ocserv-oidc: Token malformed - no kid\n"); + oc_syslog(LOG_NOTICE, + "ocserv-oidc: Token malformed - no kid\n"); goto cleanup; } token_typ = json_object_get(token_header, "typ"); - if (token_typ == NULL || !json_string_value(token_typ) || strcmp(json_string_value(token_typ), "JWT")) { - oc_syslog(LOG_NOTICE, "ocserv-oidc: Token malformed - wrong typ claim\n"); + if (token_typ == NULL || !json_string_value(token_typ) || + strcmp(json_string_value(token_typ), "JWT")) { + oc_syslog(LOG_NOTICE, + "ocserv-oidc: Token malformed - wrong typ claim\n"); goto cleanup; } // Find the signing key in the keys collection - json_array_foreach(array, index, value) { + json_array_foreach(array, index, value) + { json_t *key_kid = json_object_get(value, "kid"); + if (json_equal(key_kid, token_kid)) { jwk = cjose_jwk_import_json(value, &err); break; @@ -568,16 +595,20 @@ static bool oidc_verify_signature(oidc_vctx_st * vctx, cjose_jws_t * jws) if (jwk == NULL) { time_t now; - oc_syslog(LOG_NOTICE, "ocserv-oidc: JWK with kid=%s not found\n", - json_string_value(token_kid)); - oc_syslog(LOG_NOTICE, "ocserv-oidc: attempting to download new JWKs"); + oc_syslog(LOG_NOTICE, + "ocserv-oidc: JWK with kid=%s not found\n", + json_string_value(token_kid)); + + oc_syslog(LOG_NOTICE, + "ocserv-oidc: attempting to download new JWKs"); now = time(NULL); - if ((now - vctx->last_jwks_load_time) > vctx->minimum_jwk_refresh_time) { + if ((now - vctx->last_jwks_load_time) > + vctx->minimum_jwk_refresh_time) { oidc_fetch_oidc_keys(vctx); - } - else { - oc_syslog(LOG_NOTICE, "ocserv-oidc: skipping JWK refresh"); + } else { + oc_syslog(LOG_NOTICE, + "ocserv-oidc: skipping JWK refresh"); } // Fail the request and let the client try again. @@ -585,14 +616,15 @@ static bool oidc_verify_signature(oidc_vctx_st * vctx, cjose_jws_t * jws) } if (!cjose_jws_verify(jws, jwk, &err)) { - oc_syslog(LOG_NOTICE, "ocserv-oidc: Token failed validation %s\n", - err.message); + oc_syslog(LOG_NOTICE, + "ocserv-oidc: Token failed validation %s\n", + err.message); goto cleanup; } result = true; - cleanup: +cleanup: if (jwk) { cjose_jwk_release(jwk); } @@ -601,9 +633,9 @@ static bool oidc_verify_signature(oidc_vctx_st * vctx, cjose_jws_t * jws) } // Verify that the provided token is signed -static bool oidc_verify_token(oidc_vctx_st * vctx, const char *token, - size_t token_length, - char user_name[MAX_USERNAME_SIZE]) +static bool oidc_verify_token(oidc_vctx_st *vctx, const char *token, + size_t token_length, + char user_name[MAX_USERNAME_SIZE]) { bool result = false; cjose_err err; @@ -613,47 +645,49 @@ static bool oidc_verify_token(oidc_vctx_st * vctx, const char *token, jws = cjose_jws_import(token, token_length, &err); if (jws == NULL) { oc_syslog(LOG_NOTICE, "ocserv-oidc: Token malformed - %s\n", - err.message); + err.message); goto cleanup; } if (!oidc_verify_signature(vctx, jws)) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Token signature validation failed\n"); + "ocserv-oidc: Token signature validation failed\n"); goto cleanup; } token_claims = oidc_extract_claims(jws); if (!token_claims) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Unable to access token claims\n"); + "ocserv-oidc: Unable to access token claims\n"); goto cleanup; } if (!oidc_verify_lifetime(token_claims)) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Token lifetime validation failed\n"); + "ocserv-oidc: Token lifetime validation failed\n"); goto cleanup; } - if (!oidc_verify_required_claims - (json_object_get(vctx->config, "required_claims"), token_claims)) { - oc_syslog(LOG_NOTICE, - "ocserv-oidc: Token required claims validation failed\n"); + if (!oidc_verify_required_claims(json_object_get(vctx->config, + "required_claims"), + token_claims)) { + oc_syslog( + LOG_NOTICE, + "ocserv-oidc: Token required claims validation failed\n"); goto cleanup; } - if (!oidc_map_user_name - (json_object_get(vctx->config, "user_name_claim"), token_claims, - user_name)) { + if (!oidc_map_user_name(json_object_get(vctx->config, + "user_name_claim"), + token_claims, user_name)) { oc_syslog(LOG_NOTICE, - "ocserv-oidc: Unable to map user name claim\n"); + "ocserv-oidc: Unable to map user name claim\n"); goto cleanup; } result = true; - cleanup: +cleanup: if (jws) { cjose_jws_release(jws); } diff --git a/src/auth/pam.c b/src/auth/pam.c index 43ab8004..2c38ce9c 100644 --- a/src/auth/pam.c +++ b/src/auth/pam.c @@ -48,7 +48,7 @@ #include "auth/pam.h" #include "auth-unix.h" -#define PAM_STACK_SIZE (1024*1024) +#define PAM_STACK_SIZE (1024 * 1024) #define MAX_REPLIES 2 @@ -59,10 +59,10 @@ enum { }; static int ocserv_conv(int msg_size, const struct pam_message **msg, - struct pam_response **resp, void *uptr) + struct pam_response **resp, void *uptr) { - struct pam_ctx_st * pctx = uptr; - unsigned i; + struct pam_ctx_st *pctx = uptr; + unsigned int i; int ret; if (msg_size == 0) @@ -70,15 +70,16 @@ static int ocserv_conv(int msg_size, const struct pam_message **msg, str_reset(&pctx->msg); - pctx->replies = calloc(1, msg_size*sizeof(*pctx->replies)); + pctx->replies = calloc(1, msg_size * sizeof(*pctx->replies)); if (pctx->replies == NULL) return PAM_BUF_ERR; - for (i=0;imsg_style) { case PAM_ERROR_MSG: case PAM_TEXT_INFO: - oc_syslog(LOG_DEBUG, "PAM-auth conv info: %s", msg[i]->msg); + oc_syslog(LOG_DEBUG, "PAM-auth conv info: %s", + msg[i]->msg); // That should never happen, but also not a big deal if we fail to add message here. // coverity[check_return : FALSE] @@ -87,7 +88,8 @@ static int ocserv_conv(int msg_size, const struct pam_message **msg, ret = str_append_data(&pctx->msg, " ", 1); if (ret < 0) { - oc_syslog(LOG_ERR, "Error in memory allocation in PAM"); + oc_syslog(LOG_ERR, + "Error in memory allocation in PAM"); return PAM_BUF_ERR; } @@ -99,18 +101,24 @@ static int ocserv_conv(int msg_size, const struct pam_message **msg, /* no message, just asking for password */ str_reset(&pctx->msg); pctx->sent_msg = 1; - } if (msg[i]->msg) { ret = str_append_str(&pctx->msg, msg[i]->msg); if (ret < 0) { - oc_syslog(LOG_ERR, "Error in memory allocation in PAM"); + oc_syslog( + LOG_ERR, + "Error in memory allocation in PAM"); return PAM_BUF_ERR; } } - oc_syslog(LOG_DEBUG, "PAM-auth conv: echo-%s, msg: '%s'", (msg[i]->msg_style==PAM_PROMPT_ECHO_ON)?"on":"off", msg[i]->msg!=NULL?msg[i]->msg:""); + oc_syslog(LOG_DEBUG, + "PAM-auth conv: echo-%s, msg: '%s'", + (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) ? + "on" : + "off", + msg[i]->msg != NULL ? msg[i]->msg : ""); pctx->state = PAM_S_WAIT_FOR_PASS; pctx->cr_ret = PAM_SUCCESS; @@ -120,13 +128,15 @@ static int ocserv_conv(int msg_size, const struct pam_message **msg, if (pctx->password[0] != 0) { pctx->replies[i].resp = strdup(pctx->password); if (pctx->replies[i].resp == NULL) { - oc_syslog(LOG_ERR, "Error in memory allocation in PAM"); + oc_syslog( + LOG_ERR, + "Error in memory allocation in PAM"); return PAM_BUF_ERR; } } pctx->sent_msg = 0; break; - } + } } *resp = pctx->replies; @@ -134,16 +144,17 @@ static int ocserv_conv(int msg_size, const struct pam_message **msg, return PAM_SUCCESS; } -static void co_auth_user(void* data) +static void co_auth_user(void *data) { -struct pam_ctx_st * pctx = data; -int pret; + struct pam_ctx_st *pctx = data; + int pret; pctx->state = PAM_S_INIT; pret = pam_authenticate(pctx->ph, 0); if (pret != PAM_SUCCESS) { - oc_syslog(LOG_INFO, "PAM authenticate error for '%s': %s", pctx->username, pam_strerror(pctx->ph, pret)); + oc_syslog(LOG_INFO, "PAM authenticate error for '%s': %s", + pctx->username, pam_strerror(pctx->ph, pret)); pctx->cr_ret = pret; goto wait; } @@ -151,14 +162,18 @@ int pret; pret = pam_acct_mgmt(pctx->ph, 0); if (pret == PAM_NEW_AUTHTOK_REQD) { /* change password */ - oc_syslog(LOG_INFO, "Password for user '%s' is expired. Attempting to update...", pctx->username); + oc_syslog( + LOG_INFO, + "Password for user '%s' is expired. Attempting to update...", + pctx->username); pctx->changing = 1; pret = pam_chauthtok(pctx->ph, PAM_CHANGE_EXPIRED_AUTHTOK); } if (pret != PAM_SUCCESS) { - oc_syslog(LOG_INFO, "PAM acct-mgmt error for '%s': %s", pctx->username, pam_strerror(pctx->ph, pret)); + oc_syslog(LOG_INFO, "PAM acct-mgmt error for '%s': %s", + pctx->username, pam_strerror(pctx->ph, pret)); pctx->cr_ret = pret; goto wait; } @@ -166,21 +181,21 @@ int pret; pctx->state = PAM_S_COMPLETE; pctx->cr_ret = PAM_SUCCESS; - wait: +wait: /* give control back to the main process */ while (1) { co_resume(); } } -static int pam_auth_init(void** ctx, void *pool, void *vctx, const common_auth_init_st *info) +static int pam_auth_init(void **ctx, void *pool, void *vctx, + const common_auth_init_st *info) { -int pret; -struct pam_ctx_st * pctx; + int pret; + struct pam_ctx_st *pctx; if (info->username == NULL || info->username[0] == 0) { - oc_syslog(LOG_NOTICE, - "pam-auth: no username present"); + oc_syslog(LOG_NOTICE, "pam-auth: no username present"); return ERR_AUTH_FAIL; } @@ -194,7 +209,8 @@ struct pam_ctx_st * pctx; pctx->dc.appdata_ptr = pctx; pret = pam_start(PACKAGE, info->username, &pctx->dc, &pctx->ph); if (pret != PAM_SUCCESS) { - oc_syslog(LOG_NOTICE, "PAM-auth init: %s", pam_strerror(pctx->ph, pret)); + oc_syslog(LOG_NOTICE, "PAM-auth init: %s", + pam_strerror(pctx->ph, pret)); goto fail1; } @@ -218,10 +234,10 @@ fail1: return -1; } -static int pam_auth_msg(void* ctx, void *pool, passwd_msg_st *pst) +static int pam_auth_msg(void *ctx, void *pool, passwd_msg_st *pst) { -struct pam_ctx_st * pctx = ctx; -size_t prompt_hash = 0; + struct pam_ctx_st *pctx = ctx; + size_t prompt_hash = 0; if (pctx->state != PAM_S_INIT && pctx->state != PAM_S_WAIT_FOR_PASS) { return 0; @@ -233,22 +249,24 @@ size_t prompt_hash = 0; co_call(pctx->cr); if (pctx->cr_ret != PAM_SUCCESS) { - oc_syslog(LOG_NOTICE, "PAM-auth pam_auth_msg: %s", pam_strerror(pctx->ph, pctx->cr_ret)); + oc_syslog(LOG_NOTICE, "PAM-auth pam_auth_msg: %s", + pam_strerror(pctx->ph, pctx->cr_ret)); return ERR_AUTH_FAIL; } } if (pctx->msg.length == 0) { - if (pctx->changing) - pst->msg_str = talloc_strdup(pool, "Please enter the new password."); - /* else use the default prompt */ + if (pctx->changing) + pst->msg_str = talloc_strdup( + pool, "Please enter the new password."); + /* else use the default prompt */ } else { if (str_append_data(&pctx->msg, "\0", 1) < 0) return -1; prompt_hash = hash_any(pctx->msg.data, pctx->msg.length, 0); - pst->msg_str = talloc_strdup(pool, (char*)pctx->msg.data); + pst->msg_str = talloc_strdup(pool, (char *)pctx->msg.data); } pst->counter = pctx->passwd_counter; @@ -265,15 +283,18 @@ size_t prompt_hash = 0; /* Returns 0 if the user is successfully authenticated */ -static int pam_auth_pass(void* ctx, const char* pass, unsigned pass_len) +static int pam_auth_pass(void *ctx, const char *pass, unsigned int pass_len) { -struct pam_ctx_st * pctx = ctx; + struct pam_ctx_st *pctx = ctx; - if (pass == NULL || pass_len+1 > sizeof(pctx->password)) + if (pass == NULL || pass_len + 1 > sizeof(pctx->password)) return -1; if (pctx->state != PAM_S_WAIT_FOR_PASS) { - oc_syslog(LOG_NOTICE, "PAM auth: conversation left in wrong state (%d/expecting %d)", pctx->state, PAM_S_WAIT_FOR_PASS); + oc_syslog( + LOG_NOTICE, + "PAM auth: conversation left in wrong state (%d/expecting %d)", + pctx->state, PAM_S_WAIT_FOR_PASS); return ERR_AUTH_FAIL; } @@ -284,7 +305,8 @@ struct pam_ctx_st * pctx = ctx; co_call(pctx->cr); if (pctx->cr_ret != PAM_SUCCESS) { - oc_syslog(LOG_NOTICE, "PAM-auth pam_auth_pass: %s", pam_strerror(pctx->ph, pctx->cr_ret)); + oc_syslog(LOG_NOTICE, "PAM-auth pam_auth_pass: %s", + pam_strerror(pctx->ph, pctx->cr_ret)); return ERR_AUTH_FAIL; } @@ -296,18 +318,20 @@ struct pam_ctx_st * pctx = ctx; /* Returns 0 if the user is successfully authenticated */ -static int pam_auth_group(void* ctx, const char *suggested, char *groupname, int groupname_size) +static int pam_auth_group(void *ctx, const char *suggested, char *groupname, + int groupname_size) { - struct pam_ctx_st * pctx = ctx; + struct pam_ctx_st *pctx = ctx; - return get_user_auth_group(pctx->username, suggested, groupname, groupname_size); + return get_user_auth_group(pctx->username, suggested, groupname, + groupname_size); } -static int pam_auth_user(void* ctx, char *username, int username_size) +static int pam_auth_user(void *ctx, char *username, int username_size) { -const char* user = NULL; -struct pam_ctx_st * pctx = ctx; -int pret; + const char *user = NULL; + struct pam_ctx_st *pctx = ctx; + int pret; username[0] = 0; @@ -326,9 +350,9 @@ int pret; return -1; } -static void pam_auth_deinit(void* ctx) +static void pam_auth_deinit(void *ctx) { -struct pam_ctx_st * pctx = ctx; + struct pam_ctx_st *pctx = ctx; pam_end(pctx->ph, pctx->cr_ret); free(pctx->replies); @@ -338,7 +362,8 @@ struct pam_ctx_st * pctx = ctx; talloc_free(pctx); } -static void pam_group_list(void *pool, void *_additional, char ***groupname, unsigned *groupname_size) +static void pam_group_list(void *pool, void *_additional, char ***groupname, + unsigned int *groupname_size) { struct pam_cfg_st *config = _additional; gid_t min = 0; @@ -349,15 +374,14 @@ static void pam_group_list(void *pool, void *_additional, char ***groupname, uns unix_group_list(pool, min, groupname, groupname_size); } -const struct auth_mod_st pam_auth_funcs = { - .type = AUTH_TYPE_PAM | AUTH_TYPE_USERNAME_PASS, - .auth_init = pam_auth_init, - .auth_deinit = pam_auth_deinit, - .auth_msg = pam_auth_msg, - .auth_pass = pam_auth_pass, - .auth_group = pam_auth_group, - .auth_user = pam_auth_user, - .group_list = pam_group_list -}; +const struct auth_mod_st pam_auth_funcs = { .type = AUTH_TYPE_PAM | + AUTH_TYPE_USERNAME_PASS, + .auth_init = pam_auth_init, + .auth_deinit = pam_auth_deinit, + .auth_msg = pam_auth_msg, + .auth_pass = pam_auth_pass, + .auth_group = pam_auth_group, + .auth_user = pam_auth_user, + .group_list = pam_group_list }; #endif diff --git a/src/auth/pam.h b/src/auth/pam.h index b850e956..31083ba7 100644 --- a/src/auth/pam.h +++ b/src/auth/pam.h @@ -35,17 +35,17 @@ extern const struct auth_mod_st pam_auth_funcs; struct pam_ctx_st { char password[MAX_PASSWORD_SIZE]; char username[MAX_USERNAME_SIZE]; - pam_handle_t * ph; + pam_handle_t *ph; struct pam_conv dc; coroutine_t cr; int cr_ret; - unsigned changing; /* whether we are entering a new password */ + unsigned int changing; /* whether we are entering a new password */ str_st msg; str_st prompt; - unsigned sent_msg; + unsigned int sent_msg; struct pam_response *replies; /* for safety */ - unsigned state; /* PAM_S_ */ - unsigned passwd_counter; + unsigned int state; /* PAM_S_ */ + unsigned int passwd_counter; size_t prev_prompt_hash; }; diff --git a/src/auth/plain.c b/src/auth/plain.c index d97b57b3..213f0507 100644 --- a/src/auth/plain.c +++ b/src/auth/plain.c @@ -31,12 +31,12 @@ #include #include #ifdef HAVE_LIBOATH -# include +#include #endif #ifdef HAVE_CRYPT_H - /* libcrypt in Fedora28 does not provide prototype +/* libcrypt in Fedora28 does not provide prototype * in unistd.h */ -# include +#include #endif #include "log.h" @@ -45,14 +45,14 @@ struct plain_ctx_st { char username[MAX_USERNAME_SIZE]; - char cpass[MAX_CPASS_SIZE]; /* crypt() passwd */ + char cpass[MAX_CPASS_SIZE]; /* crypt() passwd */ char *groupnames[MAX_GROUPS]; - unsigned groupnames_size; + unsigned int groupnames_size; const char *pass_msg; - unsigned retries; - unsigned failed; /* non-zero if the username is wrong */ + unsigned int retries; + unsigned int failed; /* non-zero if the username is wrong */ const struct plain_cfg_st *config; }; @@ -68,7 +68,7 @@ static void plain_vhost_init(void **vctx, void *pool, void *additional) exit(EXIT_FAILURE); } - *vctx = (void*)config; + *vctx = (void *)config; #ifdef HAVE_LIBOATH oath_init(); @@ -78,13 +78,13 @@ static void plain_vhost_init(void **vctx, void *pool, void *additional) /* Breaks a list of "xxx", "yyy", to a character array, of * MAX_COMMA_SEP_ELEMENTS size; Note that the given string is modified. */ -static void -break_group_list(void *pool, char *text, - char *broken_text[MAX_GROUPS], unsigned *elements) +static void break_group_list(void *pool, char *text, + char *broken_text[MAX_GROUPS], + unsigned int *elements) { char *p = talloc_strdup(pool, text); char *p2; - unsigned len; + unsigned int len; *elements = 0; @@ -98,16 +98,16 @@ break_group_list(void *pool, char *text, p = strchr(p, ','); if (p) { *p = 0; - len = p - broken_text[*elements-1]; + len = p - broken_text[*elements - 1]; /* remove any trailing space */ - p2 = p-1; + p2 = p - 1; while (isspace(*p2)) { *p2 = 0; p2--; } - p++; /* move to next entry and skip white + p++; /* move to next entry and skip white * space. */ while (isspace(*p)) @@ -118,7 +118,7 @@ break_group_list(void *pool, char *text, (*elements)--; } } else { - p2 = strrchr(broken_text[(*elements)-1], ' '); + p2 = strrchr(broken_text[(*elements) - 1], ' '); if (p2 != NULL) { while (isspace(*p2)) { *p2 = 0; @@ -126,13 +126,12 @@ break_group_list(void *pool, char *text, } } - if (strlen(broken_text[(*elements)-1]) == 1) { + if (strlen(broken_text[(*elements) - 1]) == 1) { /* skip the group */ (*elements)--; } } - } - while (p != NULL && *elements < MAX_GROUPS); + } while (p != NULL && *elements < MAX_GROUPS); } /* Returns 0 if the user is successfully authenticated, and sets the appropriate group name. @@ -155,13 +154,13 @@ static int read_auth_pass(struct plain_ctx_st *pctx) fp = fopen(pctx->config->passwd, "r"); if (fp == NULL) { oc_syslog(LOG_ERR, - "error in plain authentication; cannot open: %s", - pctx->config->passwd); + "error in plain authentication; cannot open: %s", + pctx->config->passwd); return -1; } - line[sizeof(line)-1] = 0; - while ((p=fgets(line, sizeof(line)-1, fp)) != NULL) { + line[sizeof(line) - 1] = 0; + while ((p = fgets(line, sizeof(line) - 1, fp)) != NULL) { ll = strlen(p); if (ll <= 4) @@ -182,11 +181,13 @@ static int read_auth_pass(struct plain_ctx_st *pctx) if (p != NULL && strcmp(pctx->username, p) == 0) { p = strsep(&sp, ":"); if (p != NULL) { - break_group_list(pctx, p, pctx->groupnames, &pctx->groupnames_size); + break_group_list(pctx, p, pctx->groupnames, + &pctx->groupnames_size); p = strsep(&sp, ":"); if (p != NULL) { - strlcpy(pctx->cpass, p, sizeof(pctx->cpass)); + strlcpy(pctx->cpass, p, + sizeof(pctx->cpass)); pctx->failed = 0; ret = 0; goto exit; @@ -200,11 +201,13 @@ static int read_auth_pass(struct plain_ctx_st *pctx) if (p != NULL && strcmp(pctx->username, p) == 0) { p = strtok_r(NULL, ":", &sp); if (p != NULL) { - break_group_list(pctx, p, pctx->groupnames, &pctx->groupnames_size); + break_group_list(pctx, p, pctx->groupnames, + &pctx->groupnames_size); p = strtok_r(NULL, ":", &sp); if (p != NULL) { - strlcpy(pctx->cpass, p, sizeof(pctx->cpass)); + strlcpy(pctx->cpass, p, + sizeof(pctx->cpass)); pctx->failed = 0; ret = 0; goto exit; @@ -216,20 +219,20 @@ static int read_auth_pass(struct plain_ctx_st *pctx) /* always succeed */ ret = 0; - exit: +exit: safe_memset(line, 0, sizeof(line)); fclose(fp); return ret; } -static int plain_auth_init(void **ctx, void *pool, void *vctx, const common_auth_init_st *info) +static int plain_auth_init(void **ctx, void *pool, void *vctx, + const common_auth_init_st *info) { struct plain_ctx_st *pctx; int ret; if (info->username == NULL || info->username[0] == 0) { - oc_syslog(LOG_ERR, - "plain-auth: no username present"); + oc_syslog(LOG_ERR, "plain-auth: no username present"); return ERR_AUTH_FAIL; } @@ -262,26 +265,29 @@ static int plain_auth_init(void **ctx, void *pool, void *vctx, const common_auth return ERR_AUTH_CONTINUE; } -static int plain_auth_group(void *ctx, const char *suggested, char *groupname, int groupname_size) +static int plain_auth_group(void *ctx, const char *suggested, char *groupname, + int groupname_size) { struct plain_ctx_st *pctx = ctx; - unsigned i, found = 0; + unsigned int i, found = 0; groupname[0] = 0; if (suggested != NULL) { - for (i=0;igroupnames_size;i++) { + for (i = 0; i < pctx->groupnames_size; i++) { if (strcmp(suggested, pctx->groupnames[i]) == 0) { - strlcpy(groupname, pctx->groupnames[i], groupname_size); + strlcpy(groupname, pctx->groupnames[i], + groupname_size); found = 1; break; } } if (found == 0) { - oc_syslog(LOG_NOTICE, - "user '%s' requested group '%s' but is not a member", - pctx->username, suggested); + oc_syslog( + LOG_NOTICE, + "user '%s' requested group '%s' but is not a member", + pctx->username, suggested); return -1; } } @@ -300,7 +306,7 @@ static int plain_auth_user(void *ctx, char *username, int username_size) /* Returns 0 if the user is successfully authenticated, and sets the appropriate group name. */ -static int plain_auth_pass(void *ctx, const char *pass, unsigned pass_len) +static int plain_auth_pass(void *ctx, const char *pass, unsigned int pass_len) { struct plain_ctx_st *pctx = ctx; const char *p; @@ -314,21 +320,22 @@ static int plain_auth_pass(void *ctx, const char *pass, unsigned pass_len) } if (pctx->failed) { - if (pctx->retries++ < MAX_PASSWORD_TRIES-1) { + if (pctx->retries++ < MAX_PASSWORD_TRIES - 1) { pctx->pass_msg = pass_msg_failed; return ERR_AUTH_CONTINUE; } else { oc_syslog(LOG_NOTICE, - "plain-auth: error authenticating user '%s'", - pctx->username); + "plain-auth: error authenticating user '%s'", + pctx->username); return ERR_AUTH_FAIL; } } if (pctx->cpass[0] == 0 && pctx->config->otp_file == NULL) { - oc_syslog(LOG_NOTICE, - "plain-auth: user '%s' has empty password and no OTP file configured", - pctx->username); + oc_syslog( + LOG_NOTICE, + "plain-auth: user '%s' has empty password and no OTP file configured", + pctx->username); return ERR_AUTH_FAIL; } @@ -344,12 +351,13 @@ static int plain_auth_pass(void *ctx, const char *pass, unsigned pass_len) } /* no primary password -> check OTP */ - ret = oath_authenticate_usersfile(pctx->config->otp_file, pctx->username, - pass, HOTP_WINDOW, NULL, &last); + ret = oath_authenticate_usersfile(pctx->config->otp_file, + pctx->username, pass, + HOTP_WINDOW, NULL, &last); if (ret != OATH_OK) { oc_syslog(LOG_NOTICE, - "plain-auth: OTP auth failed for '%s': %s", - pctx->username, oath_strerror(ret)); + "plain-auth: OTP auth failed for '%s': %s", + pctx->username, oath_strerror(ret)); return ERR_AUTH_FAIL; } } @@ -381,10 +389,11 @@ static void plain_auth_deinit(void *ctx) static size_t rehash(const void *_e, void *unused) { const char *e = _e; + return hash_any(e, strlen(e), 0); } -static bool str_cmp(const void* _c1, void* _c2) +static bool str_cmp(const void *_c1, void *_c2) { const char *c1 = _c1, *c2 = _c2; @@ -393,17 +402,18 @@ static bool str_cmp(const void* _c1, void* _c2) return 0; } -static void plain_group_list(void *pool, void *additional, char ***groupname, unsigned *groupname_size) +static void plain_group_list(void *pool, void *additional, char ***groupname, + unsigned int *groupname_size) { FILE *fp; char line[512]; ssize_t ll; char *p, *sp; - unsigned i; + unsigned int i; size_t hval; struct htable_iter iter; char *tgroup[MAX_GROUPS]; - unsigned tgroup_size; + unsigned int tgroup_size; struct htable hash; struct plain_cfg_st *config = additional; @@ -413,13 +423,13 @@ static void plain_group_list(void *pool, void *additional, char ***groupname, un fp = fopen(config->passwd, "r"); if (fp == NULL) { oc_syslog(LOG_NOTICE, - "error in plain authentication; cannot open: %s", - (char*)config->passwd); + "error in plain authentication; cannot open: %s", + (char *)config->passwd); return; } - line[sizeof(line)-1] = 0; - while ((p=fgets(line, sizeof(line)-1, fp)) != NULL) { + line[sizeof(line) - 1] = 0; + while ((p = fgets(line, sizeof(line) - 1, fp)) != NULL) { ll = strlen(p); if (ll <= 4) @@ -449,12 +459,15 @@ static void plain_group_list(void *pool, void *additional, char ***groupname, un if (p != NULL) { break_group_list(pool, p, tgroup, &tgroup_size); - for (i=0;i 1) - (void)htable_add(&hash, hval, tgroup[i]); + (void)htable_add( + &hash, hval, + tgroup[i]); } } } @@ -462,7 +475,7 @@ static void plain_group_list(void *pool, void *additional, char ***groupname, un } *groupname_size = 0; - *groupname = talloc_size(pool, sizeof(char*)*MAX_GROUPS); + *groupname = talloc_size(pool, sizeof(char *) * MAX_GROUPS); if (*groupname == NULL) { goto exit; } @@ -475,21 +488,20 @@ static void plain_group_list(void *pool, void *additional, char ***groupname, un } /* always succeed */ - exit: +exit: htable_clear(&hash); safe_memset(line, 0, sizeof(line)); fclose(fp); } -const struct auth_mod_st plain_auth_funcs = { - .type = AUTH_TYPE_PLAIN | AUTH_TYPE_USERNAME_PASS, - .allows_retries = 1, - .vhost_init = plain_vhost_init, - .auth_init = plain_auth_init, - .auth_deinit = plain_auth_deinit, - .auth_msg = plain_auth_msg, - .auth_pass = plain_auth_pass, - .auth_user = plain_auth_user, - .auth_group = plain_auth_group, - .group_list = plain_group_list -}; +const struct auth_mod_st plain_auth_funcs = { .type = AUTH_TYPE_PLAIN | + AUTH_TYPE_USERNAME_PASS, + .allows_retries = 1, + .vhost_init = plain_vhost_init, + .auth_init = plain_auth_init, + .auth_deinit = plain_auth_deinit, + .auth_msg = plain_auth_msg, + .auth_pass = plain_auth_pass, + .auth_user = plain_auth_user, + .auth_group = plain_auth_group, + .group_list = plain_group_list }; diff --git a/src/auth/radius.c b/src/auth/radius.c index 4dc6e717..13fd5088 100644 --- a/src/auth/radius.c +++ b/src/auth/radius.c @@ -36,39 +36,40 @@ #include "common-config.h" #ifdef LEGACY_RADIUS -# include +#include #else -# include +#include #endif #ifndef VENDOR_BIT_SIZE -# define VENDOR_BIT_SIZE 16 -# define VENDOR_MASK 0xffff +#define VENDOR_BIT_SIZE 16 +#define VENDOR_MASK 0xffff #else -# define VENDOR_MASK 0xffffffff +#define VENDOR_MASK 0xffffffff #endif -#define VATTRID_SET(a,v) ((a)|((uint64_t)((v)&VENDOR_MASK)) << VENDOR_BIT_SIZE) +#define VATTRID_SET(a, v) \ + ((a) | ((uint64_t)((v) & VENDOR_MASK)) << VENDOR_BIT_SIZE) #define RAD_GROUP_NAME PW_CLASS /* Microsoft - RFC 2548 */ #define MS_PRIMARY_DNS_SERVER VATTRID_SET(28, 311) #define MS_SECONDARY_DNS_SERVER VATTRID_SET(29, 311) /* Roaring Penguin */ -#define RP_UPSTREAM_SPEED_LIMIT VATTRID_SET(1, 10055) +#define RP_UPSTREAM_SPEED_LIMIT VATTRID_SET(1, 10055) #define RP_DOWNSTREAM_SPEED_LIMIT VATTRID_SET(2, 10055) #if defined(LEGACY_RADIUS) -# ifndef PW_DELEGATED_IPV6_PREFIX -# define PW_DELEGATED_IPV6_PREFIX 123 -# endif -# ifndef PW_ACCT_INTERIM_INTERVAL -# define PW_ACCT_INTERIM_INTERVAL 85 -# endif +#ifndef PW_DELEGATED_IPV6_PREFIX +#define PW_DELEGATED_IPV6_PREFIX 123 +#endif +#ifndef PW_ACCT_INTERIM_INTERVAL +#define PW_ACCT_INTERIM_INTERVAL 85 +#endif #endif #if RADCLI_VERSION_NUMBER < 0x010207 -# define CHALLENGE_RC 3 +#define CHALLENGE_RC 3 #endif #define MAX_CHALLENGES 16 @@ -91,19 +92,21 @@ static void radius_vhost_init(void **_vctx, void *pool, void *additional) } if (config->nas_identifier) { - strlcpy(vctx->nas_identifier, config->nas_identifier, sizeof(vctx->nas_identifier)); + strlcpy(vctx->nas_identifier, config->nas_identifier, + sizeof(vctx->nas_identifier)); } else { vctx->nas_identifier[0] = 0; } - if (rc_read_dictionary(vctx->rh, rc_conf_str(vctx->rh, "dictionary")) != 0) { + if (rc_read_dictionary(vctx->rh, rc_conf_str(vctx->rh, "dictionary")) != + 0) { fprintf(stderr, "error reading the radius dictionary\n"); exit(EXIT_FAILURE); } *_vctx = vctx; return; - fail: +fail: fprintf(stderr, "radius initialization error\n"); exit(EXIT_FAILURE); } @@ -116,15 +119,15 @@ static void radius_vhost_deinit(void *_vctx) rc_destroy(vctx->rh); } -static int radius_auth_init(void **ctx, void *pool, void *_vctx, const common_auth_init_st *info) +static int radius_auth_init(void **ctx, void *pool, void *_vctx, + const common_auth_init_st *info) { struct radius_ctx_st *pctx; char *default_realm; struct radius_vhost_ctx *vctx = _vctx; if (info->username == NULL || info->username[0] == 0) { - oc_syslog(LOG_NOTICE, - "radius-auth: no username present"); + oc_syslog(LOG_NOTICE, "radius-auth: no username present"); return ERR_AUTH_FAIL; } @@ -145,38 +148,43 @@ static int radius_auth_init(void **ctx, void *pool, void *_vctx, const common_au if ((strchr(info->username, '@') == NULL) && default_realm && default_realm[0] != 0) { - snprintf(pctx->username, sizeof(pctx->username), "%s@%s", info->username, default_realm); + snprintf(pctx->username, sizeof(pctx->username), "%s@%s", + info->username, default_realm); } else { strlcpy(pctx->username, info->username, sizeof(pctx->username)); } pctx->id = info->id; if (info->user_agent) - strlcpy(pctx->user_agent, info->user_agent, sizeof(pctx->user_agent)); + strlcpy(pctx->user_agent, info->user_agent, + sizeof(pctx->user_agent)); *ctx = pctx; return ERR_AUTH_CONTINUE; } -static int radius_auth_group(void *ctx, const char *suggested, char *groupname, int groupname_size) +static int radius_auth_group(void *ctx, const char *suggested, char *groupname, + int groupname_size) { struct radius_ctx_st *pctx = ctx; - unsigned i; + unsigned int i; groupname[0] = 0; if (suggested != NULL) { - for (i=0;igroupnames_size;i++) { + for (i = 0; i < pctx->groupnames_size; i++) { if (strcmp(suggested, pctx->groupnames[i]) == 0) { - strlcpy(groupname, pctx->groupnames[i], groupname_size); + strlcpy(groupname, pctx->groupnames[i], + groupname_size); return 0; } } - oc_syslog(LOG_NOTICE, - "radius-auth: user '%s' requested group '%s' but is not a member", - pctx->username, suggested); + oc_syslog( + LOG_NOTICE, + "radius-auth: user '%s' requested group '%s' but is not a member", + pctx->username, suggested); return -1; } @@ -193,13 +201,15 @@ static int radius_auth_user(void *ctx, char *username, int username_size) return -1; } -static void append_route(struct radius_ctx_st *pctx, const char *route, unsigned len) +static void append_route(struct radius_ctx_st *pctx, const char *route, + unsigned int len) { - unsigned i; + unsigned int i; char *p; /* accept route/mask */ - if ((p=strchr(route, '/')) == 0) + p = strchr(route, '/'); + if (p == 0) return; p = strchr(p, ' '); @@ -208,10 +218,11 @@ static void append_route(struct radius_ctx_st *pctx, const char *route, unsigned } if (pctx->routes_size == 0) { - pctx->routes = talloc_size(pctx, sizeof(char*)); + pctx->routes = talloc_size(pctx, sizeof(char *)); } else { pctx->routes = talloc_realloc_size(pctx, pctx->routes, - (pctx->routes_size+1)*sizeof(char*)); + (pctx->routes_size + 1) * + sizeof(char *)); } if (pctx->routes != NULL) { @@ -228,11 +239,13 @@ static void parse_groupnames(struct radius_ctx_st *pctx, const char *full) char *p, *p2; if (pctx->groupnames_size >= MAX_GROUPS) { - oc_syslog(LOG_WARNING, - "radius-auth: cannot handle more than %d groups, ignoring group string %s", - MAX_GROUPS, full); + oc_syslog( + LOG_WARNING, + "radius-auth: cannot handle more than %d groups, ignoring group string %s", + MAX_GROUPS, full); } else if (strncmp(full, "OU=", 3) == 0) { - oc_syslog(LOG_DEBUG, "radius-auth: found group string %s", full); + oc_syslog(LOG_DEBUG, "radius-auth: found group string %s", + full); full += 3; p = talloc_strdup(pctx, full); @@ -249,14 +262,16 @@ static void parse_groupnames(struct radius_ctx_st *pctx, const char *full) if (pctx->groupnames_size == MAX_GROUPS) { if (p2) - oc_syslog(LOG_WARNING, - "radius-auth: cannot handle more than %d groups, ignoring trailing group(s) %s", - MAX_GROUPS, p2); + oc_syslog( + LOG_WARNING, + "radius-auth: cannot handle more than %d groups, ignoring trailing group(s) %s", + MAX_GROUPS, p2); break; } } } else { - oc_syslog(LOG_DEBUG, "radius-auth: found group string %s", full); + oc_syslog(LOG_DEBUG, "radius-auth: found group string %s", + full); p = talloc_strdup(pctx, full); if (p == NULL) return; @@ -266,7 +281,7 @@ static void parse_groupnames(struct radius_ctx_st *pctx, const char *full) /* Returns 0 if the user is successfully authenticated, and sets the appropriate group name. */ -static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) +static int radius_auth_pass(void *ctx, const char *pass, unsigned int pass_len) { struct radius_ctx_st *pctx = ctx; VALUE_PAIR *send = NULL, *recvd = NULL; @@ -277,18 +292,24 @@ static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) int ret; /* send Access-Request */ - oc_syslog(LOG_DEBUG, "radius-auth: communicating username (%s) and password", pctx->username); - if (rc_avpair_add(pctx->vctx->rh, &send, PW_USER_NAME, pctx->username, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + oc_syslog(LOG_DEBUG, + "radius-auth: communicating username (%s) and password", + pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_USER_NAME, pctx->username, + -1, 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); return ERR_AUTH_FAIL; } - if (rc_avpair_add(pctx->vctx->rh, &send, PW_USER_PASSWORD, (char*)pass, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_USER_PASSWORD, (char *)pass, + -1, 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } @@ -299,18 +320,24 @@ static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) if (inet_pton(AF_INET, pctx->our_ip, &in) != 0) { in.s_addr = ntohl(in.s_addr); - if (rc_avpair_add(pctx->vctx->rh, &send, PW_NAS_IP_ADDRESS, (char*)&in, sizeof(struct in_addr), 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, + PW_NAS_IP_ADDRESS, (char *)&in, + sizeof(struct in_addr), 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } } else if (inet_pton(AF_INET6, pctx->our_ip, &in6) != 0) { - if (rc_avpair_add(pctx->vctx->rh, &send, PW_NAS_IPV6_ADDRESS, (char*)&in6, sizeof(struct in6_addr), 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, + PW_NAS_IPV6_ADDRESS, (char *)&in6, + sizeof(struct in6_addr), 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } @@ -318,56 +345,68 @@ static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) } if (pctx->vctx->nas_identifier[0] != 0) { - if (rc_avpair_add(pctx->vctx->rh, &send, PW_NAS_IDENTIFIER, pctx->vctx->nas_identifier, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_NAS_IDENTIFIER, + pctx->vctx->nas_identifier, -1, 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } } - if (rc_avpair_add(pctx->vctx->rh, &send, PW_CALLING_STATION_ID, pctx->remote_ip, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_CALLING_STATION_ID, + pctx->remote_ip, -1, 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } if (pctx->user_agent[0] != 0) { - if (rc_avpair_add(pctx->vctx->rh, &send, PW_CONNECT_INFO, pctx->user_agent, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_CONNECT_INFO, + pctx->user_agent, -1, 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } } service = PW_AUTHENTICATE_ONLY; - if (rc_avpair_add(pctx->vctx->rh, &send, PW_SERVICE_TYPE, &service, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_SERVICE_TYPE, &service, -1, + 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } service = PW_ASYNC; - if (rc_avpair_add(pctx->vctx->rh, &send, PW_NAS_PORT_TYPE, &service, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_NAS_PORT_TYPE, &service, -1, + 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } if (pctx->state != NULL) { - if (rc_avpair_add(pctx->vctx->rh, &send, PW_STATE, pctx->state, -1, 0) == NULL) { - oc_syslog(LOG_ERR, - "%s:%u: error in constructing radius message for user '%s'", __func__, __LINE__, - pctx->username); + if (rc_avpair_add(pctx->vctx->rh, &send, PW_STATE, pctx->state, + -1, 0) == NULL) { + oc_syslog( + LOG_ERR, + "%s:%u: error in constructing radius message for user '%s'", + __func__, __LINE__, pctx->username); ret = ERR_AUTH_FAIL; goto cleanup; } @@ -376,7 +415,8 @@ static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) } pctx->pass_msg[0] = 0; - ret = rc_aaa(pctx->vctx->rh, 0, send, &recvd, pctx->pass_msg, 0, PW_ACCESS_REQUEST); + ret = rc_aaa(pctx->vctx->rh, 0, send, &recvd, pctx->pass_msg, 0, + PW_ACCESS_REQUEST); if (ret == OK_RC) { uint32_t ipv4; @@ -385,90 +425,144 @@ static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) vp = recvd; while (vp != NULL) { - if (vp->attribute == PW_SERVICE_TYPE && vp->lvalue != PW_FRAMED) { - oc_syslog(LOG_ERR, - "%s:%u: unknown radius service type '%d'", __func__, __LINE__, - (int)vp->lvalue); + if (vp->attribute == PW_SERVICE_TYPE && + vp->lvalue != PW_FRAMED) { + oc_syslog( + LOG_ERR, + "%s:%u: unknown radius service type '%d'", + __func__, __LINE__, (int)vp->lvalue); goto fail; - } else if (vp->attribute == RAD_GROUP_NAME && vp->type == PW_TYPE_STRING) { + } else if (vp->attribute == RAD_GROUP_NAME && + vp->type == PW_TYPE_STRING) { /* Group-Name */ parse_groupnames(pctx, vp->strvalue); - } else if (vp->attribute == PW_FRAMED_IPV6_ADDRESS && vp->type == PW_TYPE_IPV6ADDR) { + } else if (vp->attribute == PW_FRAMED_IPV6_ADDRESS && + vp->type == PW_TYPE_IPV6ADDR) { /* Framed-IPv6-Address */ - if (inet_ntop(AF_INET6, vp->strvalue, pctx->ipv6, sizeof(pctx->ipv6)) != NULL) { + if (inet_ntop(AF_INET6, vp->strvalue, + pctx->ipv6, + sizeof(pctx->ipv6)) != NULL) { pctx->ipv6_subnet_prefix = 64; - strlcpy(pctx->ipv6_net, pctx->ipv6, sizeof(pctx->ipv6_net)); + strlcpy(pctx->ipv6_net, pctx->ipv6, + sizeof(pctx->ipv6_net)); } - } else if (vp->attribute == PW_DELEGATED_IPV6_PREFIX && vp->type == PW_TYPE_IPV6PREFIX) { + } else if (vp->attribute == PW_DELEGATED_IPV6_PREFIX && + vp->type == PW_TYPE_IPV6PREFIX) { /* Delegated-IPv6-Prefix */ - if (inet_ntop(AF_INET6, vp->strvalue, pctx->ipv6, sizeof(pctx->ipv6)) != NULL) { + if (inet_ntop(AF_INET6, vp->strvalue, + pctx->ipv6, + sizeof(pctx->ipv6)) != NULL) { memset(ipv6, 0, sizeof(ipv6)); - memcpy(ipv6, vp->strvalue+2, vp->lvalue-2); - if (inet_ntop(AF_INET6, ipv6, pctx->ipv6, sizeof(pctx->ipv6)) != NULL) { - pctx->ipv6_subnet_prefix = (unsigned)(unsigned char)vp->strvalue[1]; + memcpy(ipv6, vp->strvalue + 2, + vp->lvalue - 2); + if (inet_ntop(AF_INET6, ipv6, + pctx->ipv6, + sizeof(pctx->ipv6)) != + NULL) { + pctx->ipv6_subnet_prefix = + (unsigned int)(unsigned char) + vp->strvalue[1]; } } - } else if (vp->attribute == PW_FRAMED_IPV6_PREFIX && vp->type == PW_TYPE_IPV6PREFIX) { + } else if (vp->attribute == PW_FRAMED_IPV6_PREFIX && + vp->type == PW_TYPE_IPV6PREFIX) { if (vp->lvalue > 2 && vp->lvalue <= 18) { /* Framed-IPv6-Prefix */ memset(ipv6, 0, sizeof(ipv6)); - memcpy(ipv6, vp->strvalue+2, vp->lvalue-2); - if (inet_ntop(AF_INET6, ipv6, txt, sizeof(txt)) != NULL) { - snprintf(route, sizeof(route), "%s/%u", txt, (unsigned)(unsigned char)vp->strvalue[1]); - append_route(pctx, vp->strvalue, vp->lvalue); + memcpy(ipv6, vp->strvalue + 2, + vp->lvalue - 2); + if (inet_ntop(AF_INET6, ipv6, txt, + sizeof(txt)) != NULL) { + snprintf( + route, sizeof(route), + "%s/%u", txt, + (unsigned int)(unsigned char) + vp->strvalue[1]); + append_route(pctx, vp->strvalue, + vp->lvalue); } } - } else if (vp->attribute == PW_DNS_SERVER_IPV6_ADDRESS && vp->type == PW_TYPE_IPV6ADDR) { + } else if (vp->attribute == + PW_DNS_SERVER_IPV6_ADDRESS && + vp->type == PW_TYPE_IPV6ADDR) { /* DNS-Server-IPv6-Address */ if (pctx->ipv6_dns1[0] == 0) - inet_ntop(AF_INET6, vp->strvalue, pctx->ipv6_dns1, sizeof(pctx->ipv6_dns1)); + inet_ntop(AF_INET6, vp->strvalue, + pctx->ipv6_dns1, + sizeof(pctx->ipv6_dns1)); else if (pctx->ipv6_dns2[0] == 0) - inet_ntop(AF_INET6, vp->strvalue, pctx->ipv6_dns2, sizeof(pctx->ipv6_dns2)); + inet_ntop(AF_INET6, vp->strvalue, + pctx->ipv6_dns2, + sizeof(pctx->ipv6_dns2)); else { char dst[MAX_IP_STR]; - inet_ntop(AF_INET6, vp->strvalue, dst, sizeof(dst)); - oc_syslog(LOG_NOTICE, "radius-auth: cannot handle more than 2 DNS servers, ignoring additional DNS server from RADIUS: %s", dst); + + inet_ntop(AF_INET6, vp->strvalue, dst, + sizeof(dst)); + oc_syslog( + LOG_NOTICE, + "radius-auth: cannot handle more than 2 DNS servers, ignoring additional DNS server from RADIUS: %s", + dst); } - } else if (vp->attribute == PW_FRAMED_IP_ADDRESS && vp->type == PW_TYPE_IPADDR) { + } else if (vp->attribute == PW_FRAMED_IP_ADDRESS && + vp->type == PW_TYPE_IPADDR) { /* Framed-IP-Address */ - if (vp->lvalue != 0xffffffff && vp->lvalue != 0xfffffffe) { + if (vp->lvalue != 0xffffffff && + vp->lvalue != 0xfffffffe) { /* According to RFC2865 the values above (fe) instruct the * server to assign an address from the pool of the server, * and (ff) to assign address as negotiated with the client. * We don't negotiate with clients. */ ipv4 = htonl(vp->lvalue); - inet_ntop(AF_INET, &ipv4, pctx->ipv4, sizeof(pctx->ipv4)); + inet_ntop(AF_INET, &ipv4, pctx->ipv4, + sizeof(pctx->ipv4)); } - } else if (vp->attribute == PW_FRAMED_IP_NETMASK && vp->type == PW_TYPE_IPADDR) { + } else if (vp->attribute == PW_FRAMED_IP_NETMASK && + vp->type == PW_TYPE_IPADDR) { /* Framed-IP-Netmask */ ipv4 = htonl(vp->lvalue); - inet_ntop(AF_INET, &ipv4, pctx->ipv4_mask, sizeof(pctx->ipv4_mask)); - } else if (vp->attribute == MS_PRIMARY_DNS_SERVER && vp->type == PW_TYPE_IPADDR) { + inet_ntop(AF_INET, &ipv4, pctx->ipv4_mask, + sizeof(pctx->ipv4_mask)); + } else if (vp->attribute == MS_PRIMARY_DNS_SERVER && + vp->type == PW_TYPE_IPADDR) { /* MS-Primary-DNS-Server */ ipv4 = htonl(vp->lvalue); - inet_ntop(AF_INET, &ipv4, pctx->ipv4_dns1, sizeof(pctx->ipv4_dns1)); - } else if (vp->attribute == MS_SECONDARY_DNS_SERVER && vp->type == PW_TYPE_IPADDR) { + inet_ntop(AF_INET, &ipv4, pctx->ipv4_dns1, + sizeof(pctx->ipv4_dns1)); + } else if (vp->attribute == MS_SECONDARY_DNS_SERVER && + vp->type == PW_TYPE_IPADDR) { /* MS-Secondary-DNS-Server */ ipv4 = htonl(vp->lvalue); - inet_ntop(AF_INET, &ipv4, pctx->ipv4_dns2, sizeof(pctx->ipv4_dns2)); - } else if (vp->attribute == PW_FRAMED_ROUTE && vp->type == PW_TYPE_STRING) { + inet_ntop(AF_INET, &ipv4, pctx->ipv4_dns2, + sizeof(pctx->ipv4_dns2)); + } else if (vp->attribute == PW_FRAMED_ROUTE && + vp->type == PW_TYPE_STRING) { /* Framed-Route */ append_route(pctx, vp->strvalue, vp->lvalue); - } else if (vp->attribute == PW_FRAMED_IPV6_ROUTE && vp->type == PW_TYPE_STRING) { + } else if (vp->attribute == PW_FRAMED_IPV6_ROUTE && + vp->type == PW_TYPE_STRING) { /* Framed-IPv6-Route */ append_route(pctx, vp->strvalue, vp->lvalue); - } else if (vp->attribute == PW_ACCT_INTERIM_INTERVAL && vp->type == PW_TYPE_INTEGER) { + } else if (vp->attribute == PW_ACCT_INTERIM_INTERVAL && + vp->type == PW_TYPE_INTEGER) { pctx->interim_interval_secs = vp->lvalue; - } else if (vp->attribute == PW_SESSION_TIMEOUT && vp->type == PW_TYPE_INTEGER) { + } else if (vp->attribute == PW_SESSION_TIMEOUT && + vp->type == PW_TYPE_INTEGER) { pctx->session_timeout_secs = vp->lvalue; - } else if (vp->attribute == RP_UPSTREAM_SPEED_LIMIT && vp->type == PW_TYPE_INTEGER) { + } else if (vp->attribute == RP_UPSTREAM_SPEED_LIMIT && + vp->type == PW_TYPE_INTEGER) { pctx->rx_per_sec = vp->lvalue; - } else if (vp->attribute == RP_DOWNSTREAM_SPEED_LIMIT && vp->type == PW_TYPE_INTEGER) { + } else if (vp->attribute == RP_DOWNSTREAM_SPEED_LIMIT && + vp->type == PW_TYPE_INTEGER) { pctx->tx_per_sec = vp->lvalue; } else { - oc_syslog(LOG_DEBUG, "radius-auth: ignoring server's attribute (%u,%u) of type %u", - (unsigned)ATTRID(vp->attribute), (unsigned)VENDOR(vp->attribute), (unsigned)vp->type); + oc_syslog( + LOG_DEBUG, + "radius-auth: ignoring server's attribute (%u,%u) of type %u", + (unsigned int)ATTRID(vp->attribute), + (unsigned int)VENDOR(vp->attribute), + (unsigned int)vp->type); } vp = vp->next; } @@ -476,47 +570,58 @@ static int radius_auth_pass(void *ctx, const char *pass, unsigned pass_len) ret = 0; goto cleanup; } else if (ret == CHALLENGE_RC) { - vp = recvd; while (vp != NULL) { - if (vp->attribute == PW_STATE && vp->type == PW_TYPE_STRING) { + if (vp->attribute == PW_STATE && + vp->type == PW_TYPE_STRING) { /* State */ if (vp->lvalue > 0) - pctx->state = talloc_strdup(pctx, vp->strvalue); + pctx->state = talloc_strdup( + pctx, vp->strvalue); pctx->id++; - oc_syslog(LOG_DEBUG, "radius-auth: Access-Challenge response stage %u, State %s", pctx->passwd_counter, vp->strvalue); + oc_syslog( + LOG_DEBUG, + "radius-auth: Access-Challenge response stage %u, State %s", + pctx->passwd_counter, vp->strvalue); ret = ERR_AUTH_CONTINUE; } vp = vp->next; } /* PW_STATE or PW_REPLY_MESSAGE is empty or MAX_CHALLENGES limit exceeded */ - if ((pctx->pass_msg[0] == 0) || (pctx->state == NULL) || (pctx->passwd_counter >= MAX_CHALLENGES)) { - strlcpy(pctx->pass_msg, pass_msg_failed, sizeof(pctx->pass_msg)); - oc_syslog(LOG_ERR, "radius-auth: Access-Challenge with invalid State or Reply-Message, or max number of password requests exceeded"); + if ((pctx->pass_msg[0] == 0) || (pctx->state == NULL) || + (pctx->passwd_counter >= MAX_CHALLENGES)) { + strlcpy(pctx->pass_msg, pass_msg_failed, + sizeof(pctx->pass_msg)); + oc_syslog( + LOG_ERR, + "radius-auth: Access-Challenge with invalid State or Reply-Message, or max number of password requests exceeded"); ret = ERR_AUTH_FAIL; } goto cleanup; } else { - fail: +fail: if (pctx->pass_msg[0] == 0) - strlcpy(pctx->pass_msg, pass_msg_failed, sizeof(pctx->pass_msg)); + strlcpy(pctx->pass_msg, pass_msg_failed, + sizeof(pctx->pass_msg)); - if (pctx->retries++ < MAX_PASSWORD_TRIES-1 && pctx->passwd_counter == 0) { + if (pctx->retries++ < MAX_PASSWORD_TRIES - 1 && + pctx->passwd_counter == 0) { ret = ERR_AUTH_CONTINUE; goto cleanup; } - oc_syslog(LOG_NOTICE, - "radius-auth: error authenticating user '%s' (code %d)", - pctx->username, ret); + oc_syslog( + LOG_NOTICE, + "radius-auth: error authenticating user '%s' (code %d)", + pctx->username, ret); ret = ERR_AUTH_FAIL; goto cleanup; } - cleanup: +cleanup: if (send != NULL) rc_avpair_free(send); if (recvd != NULL) @@ -533,11 +638,11 @@ static int radius_auth_msg(void *ctx, void *pool, passwd_msg_st *pst) pst->msg_str = talloc_strdup(pool, pctx->pass_msg); if (pctx->state != NULL) { - /* differentiate password prompts, if the hash of the prompt * is different. */ - prompt_hash = hash_any(pctx->pass_msg, strlen(pctx->pass_msg), 0); + prompt_hash = + hash_any(pctx->pass_msg, strlen(pctx->pass_msg), 0); if (pctx->prev_prompt_hash != prompt_hash) pctx->passwd_counter++; pctx->prev_prompt_hash = prompt_hash; @@ -551,6 +656,7 @@ static int radius_auth_msg(void *ctx, void *pool, passwd_msg_st *pst) static void radius_auth_deinit(void *ctx) { struct radius_ctx_st *pctx = ctx; + talloc_free(pctx); } diff --git a/src/auth/radius.h b/src/auth/radius.h index 5916892e..2654807d 100644 --- a/src/auth/radius.h +++ b/src/auth/radius.h @@ -19,18 +19,18 @@ * along with this program. If not, see */ #ifndef RADIUS_H -# define RADIUS_H +#define RADIUS_H -# include -# include "common/common.h" +#include +#include "common/common.h" -# ifdef HAVE_RADIUS +#ifdef HAVE_RADIUS -# ifdef LEGACY_RADIUS -# include -# else -# include -# endif +#ifdef LEGACY_RADIUS +#include +#else +#include +#endif struct radius_vhost_ctx { rc_handle *rh; @@ -38,16 +38,16 @@ struct radius_vhost_ctx { }; struct radius_ctx_st { - char username[MAX_USERNAME_SIZE*2]; + char username[MAX_USERNAME_SIZE * 2]; char user_agent[MAX_AGENT_NAME]; char *groupnames[MAX_GROUPS]; - unsigned groupnames_size; + unsigned int groupnames_size; char remote_ip[MAX_IP_STR]; char our_ip[MAX_IP_STR]; - unsigned interim_interval_secs; - unsigned session_timeout_secs; + unsigned int interim_interval_secs; + unsigned int session_timeout_secs; /* variables for configuration */ char ipv4[MAX_IP_STR]; @@ -65,19 +65,19 @@ struct radius_ctx_st { uint32_t tx_per_sec; char **routes; - unsigned routes_size; + unsigned int routes_size; char pass_msg[PW_MAX_MSG_SIZE]; - unsigned retries; - unsigned id; + unsigned int retries; + unsigned int id; struct radius_vhost_ctx *vctx; char *state; - unsigned passwd_counter; + unsigned int passwd_counter; size_t prev_prompt_hash; }; extern const struct auth_mod_st radius_auth_funcs; -# endif +#endif #endif diff --git a/src/common-config.h b/src/common-config.h index 6e1f415f..9b01e8d8 100644 --- a/src/common-config.h +++ b/src/common-config.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_COMMON_CONFIG_H -# define OC_COMMON_CONFIG_H +#define OC_COMMON_CONFIG_H #include #include @@ -27,8 +27,9 @@ char *sanitize_config_value(void *pool, const char *value); int _add_multi_line_val(void *pool, char ***varname, size_t *num, - const char *val); -int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const char *str); + const char *val); +int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, + const char *str); #define MAX_SUBOPTIONS 5 @@ -39,7 +40,7 @@ typedef struct subcfg_val_st { typedef struct gssapi_cfg_st { char *keytab; - unsigned no_local_map; + unsigned int no_local_map; time_t ticket_freshness_secs; int gid_min; } gssapi_cfg_st; @@ -58,17 +59,27 @@ typedef struct pam_cfg_st { int gid_min; } pam_cfg_st; -#define CHECK_TRUE(str) ((str != NULL && (strcasecmp(str, "true") == 0 || strcasecmp(str, "yes") == 0))?1:0) +#define CHECK_TRUE(str) \ + ((str != NULL && \ + (strcasecmp(str, "true") == 0 || strcasecmp(str, "yes") == 0)) ? \ + 1 : \ + 0) struct perm_cfg_st; void *get_brackets_string1(void *pool, const char *str); -void *gssapi_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str); -void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str); -void *pam_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str); -void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str); -void *oidc_get_brackets_string(void * pool, struct perm_cfg_st *config, const char *str); +void *gssapi_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str); +void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str); +void *pam_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str); +void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str); +void *oidc_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str); -void parse_kkdcp_string(char *str, int *socktype, char **_port, char **_server, char **_path, char **_realm); +void parse_kkdcp_string(char *str, int *socktype, char **_port, char **_server, + char **_path, char **_realm); #endif diff --git a/src/common/base64-helper.c b/src/common/base64-helper.c index fd423ca1..d4d555c8 100644 --- a/src/common/base64-helper.c +++ b/src/common/base64-helper.c @@ -22,21 +22,20 @@ #include #include "base64-helper.h" -void oc_base64_encode (const char *in, size_t inlen, - char *out, size_t outlen) +void oc_base64_encode(const char *in, size_t inlen, char *out, size_t outlen) { - unsigned raw = BASE64_ENCODE_RAW_LENGTH(inlen); - if (outlen < raw+1) { + unsigned int raw = BASE64_ENCODE_RAW_LENGTH(inlen); + + if (outlen < raw + 1) { snprintf(out, outlen, "(too long data)"); return; } - base64_encode_raw((void*)out, inlen, (uint8_t*)in); + base64_encode_raw((void *)out, inlen, (uint8_t *)in); out[raw] = 0; } -int -oc_base64_decode(const uint8_t *src, unsigned src_length, - uint8_t *dst, size_t *dst_length) +int oc_base64_decode(const uint8_t *src, unsigned int src_length, uint8_t *dst, + size_t *dst_length) { struct base64_decode_ctx ctx; int ret; @@ -46,12 +45,14 @@ oc_base64_decode(const uint8_t *src, unsigned src_length, #ifdef NETTLE_OLD_BASE64_API { unsigned int len = *dst_length; + ret = base64_decode_update(&ctx, &len, dst, src_length, src); if (ret != 0) *dst_length = len; } #else - ret = base64_decode_update(&ctx, dst_length, dst, src_length, (void*)src); + ret = base64_decode_update(&ctx, dst_length, dst, src_length, + (void *)src); #endif if (ret == 0) @@ -60,8 +61,8 @@ oc_base64_decode(const uint8_t *src, unsigned src_length, return base64_decode_final(&ctx); } -int oc_base64_decode_alloc(void *pool, const char *in, size_t inlen, - char **out, size_t *outlen) +int oc_base64_decode_alloc(void *pool, const char *in, size_t inlen, char **out, + size_t *outlen) { int len, ret; void *tmp; @@ -73,7 +74,7 @@ int oc_base64_decode_alloc(void *pool, const char *in, size_t inlen, return 0; *outlen = len; - ret = oc_base64_decode((void*)in, inlen, tmp, outlen); + ret = oc_base64_decode((void *)in, inlen, tmp, outlen); if (ret == 0) { talloc_free(tmp); return 0; diff --git a/src/common/base64-helper.h b/src/common/base64-helper.h index b5941f7a..c625f385 100644 --- a/src/common/base64-helper.h +++ b/src/common/base64-helper.h @@ -19,20 +19,18 @@ * along with this program. If not, see */ #ifndef BASE64_HELPER_H -# define BASE64_HELPER_H +#define BASE64_HELPER_H #include /* Prototypes compatible with the gnulib's */ -int -oc_base64_decode(const uint8_t *src, unsigned src_length, - uint8_t *dst, size_t *dst_length); +int oc_base64_decode(const uint8_t *src, unsigned int src_length, uint8_t *dst, + size_t *dst_length); -int oc_base64_decode_alloc(void *pool, const char *in, size_t inlen, - char **out, size_t *outlen); +int oc_base64_decode_alloc(void *pool, const char *in, size_t inlen, char **out, + size_t *outlen); -void oc_base64_encode (const char *in, size_t inlen, - char *out, size_t outlen); +void oc_base64_encode(const char *in, size_t inlen, char *out, size_t outlen); #endif diff --git a/src/common/cloexec.c b/src/common/cloexec.c index ed5bea71..f8852b98 100644 --- a/src/common/cloexec.c +++ b/src/common/cloexec.c @@ -35,49 +35,44 @@ open or pipe2 that accept flags like O_CLOEXEC to create DESC non-inheritable in the first place. */ -int -set_cloexec_flag (int desc, bool value) +int set_cloexec_flag(int desc, bool value) { #ifdef F_SETFD - int flags = fcntl (desc, F_GETFD, 0); + int flags = fcntl(desc, F_GETFD, 0); - if (0 <= flags) - { - int newflags = (value ? flags | FD_CLOEXEC : flags & ~FD_CLOEXEC); + if (flags >= 0) { + int newflags = + (value ? flags | FD_CLOEXEC : flags & ~FD_CLOEXEC); - if (flags == newflags - || fcntl (desc, F_SETFD, newflags) != -1) - return 0; - } + if (flags == newflags || fcntl(desc, F_SETFD, newflags) != -1) + return 0; + } - return -1; + return -1; #else /* !F_SETFD */ - /* Use dup2 to reject invalid file descriptors; the cloexec flag + /* Use dup2 to reject invalid file descriptors; the cloexec flag will be unaffected. */ - if (desc < 0) - { - errno = EBADF; - return -1; - } - if (dup2 (desc, desc) < 0) - /* errno is EBADF here. */ - return -1; + if (desc < 0) { + errno = EBADF; + return -1; + } + if (dup2(desc, desc) < 0) + /* errno is EBADF here. */ + return -1; - /* There is nothing we can do on this kind of platform. Punt. */ - return 0; + /* There is nothing we can do on this kind of platform. Punt. */ + return 0; #endif /* !F_SETFD */ } - /* Duplicates a file handle FD, while marking the copy to be closed prior to exec or spawn. Returns -1 and sets errno if FD could not be duplicated. */ -int -dup_cloexec (int fd) +int dup_cloexec(int fd) { - return fcntl (fd, F_DUPFD_CLOEXEC, 0); + return fcntl(fd, F_DUPFD_CLOEXEC, 0); } diff --git a/src/common/cloexec.h b/src/common/cloexec.h index 860cd360..efdfe007 100644 --- a/src/common/cloexec.h +++ b/src/common/cloexec.h @@ -18,7 +18,7 @@ */ #ifndef CLOEXEC_H -# define CLOEXEC_H +#define CLOEXEC_H #include @@ -32,12 +32,12 @@ open or pipe2 that accept flags like O_CLOEXEC to create DESC non-inheritable in the first place. */ -int set_cloexec_flag (int desc, bool value); +int set_cloexec_flag(int desc, bool value); /* Duplicates a file handle FD, while marking the copy to be closed prior to exec or spawn. Returns -1 and sets errno if FD could not be duplicated. */ -int dup_cloexec (int fd); +int dup_cloexec(int fd); #endif /* CLOEXEC_H */ diff --git a/src/common/common.c b/src/common/common.c index ccf46107..5670e1b8 100644 --- a/src/common/common.c +++ b/src/common/common.c @@ -37,8 +37,8 @@ #include "common/base64-helper.h" #include "log.h" -int saved_argc = 0; -char **saved_argv = NULL; +int saved_argc; +char **saved_argv; const char *_vhost_prefix(const char *name) { @@ -50,7 +50,8 @@ const char *_vhost_prefix(const char *name) /* A hash of the input, to a 20-byte output. The goal is one-wayness. */ -static void safe_hash(const uint8_t *data, unsigned data_size, uint8_t output[20]) +static void safe_hash(const uint8_t *data, unsigned int data_size, + uint8_t output[20]) { struct sha1_ctx ctx; @@ -60,13 +61,13 @@ static void safe_hash(const uint8_t *data, unsigned data_size, uint8_t output[20 sha1_digest(&ctx, 20, output); } - -char *calc_safe_id(const uint8_t *data, unsigned size, char *output, unsigned output_size) +char *calc_safe_id(const uint8_t *data, unsigned int size, char *output, + unsigned int output_size) { uint8_t safe_id[20]; safe_hash(data, size, safe_id); - oc_base64_encode((char*)safe_id, 20, output, output_size); + oc_base64_encode((char *)safe_id, 20, output, output_size); return output; } @@ -74,7 +75,7 @@ char *calc_safe_id(const uint8_t *data, unsigned size, char *output, unsigned ou /* Note that meaning slightly changes depending on whether we are * referring to the cookie or the session itself. */ -const char *ps_status_to_str(int status, unsigned cookie) +const char *ps_status_to_str(int status, unsigned int cookie) { switch (status) { case PS_AUTH_COMPLETED: @@ -94,7 +95,7 @@ const char *ps_status_to_str(int status, unsigned cookie) } } -const char *cmd_request_to_str(unsigned _cmd) +const char *cmd_request_to_str(unsigned int _cmd) { cmd_request_t cmd = _cmd; static char tmp[32]; @@ -172,7 +173,7 @@ const char *cmd_request_to_str(unsigned _cmd) } } -const char *discon_reason_to_str(unsigned reason) +const char *discon_reason_to_str(unsigned int reason) { static char tmp[32]; @@ -271,7 +272,7 @@ ssize_t force_read(int sockfd, void *buf, size_t len) return len; } -ssize_t force_read_timeout(int sockfd, void *buf, size_t len, unsigned sec) +ssize_t force_read_timeout(int sockfd, void *buf, size_t len, unsigned int sec) { int left = len; int ret; @@ -325,6 +326,7 @@ void set_non_block(int fd) * https://patchwork.kernel.org/project/qemu-devel/patch/20200331133536.3328-1-linus.walleij@linaro.org/ */ int e = errno; + oc_syslog(LOG_ERR, "set_non_block: %s", strerror(e)); } } @@ -337,11 +339,12 @@ void set_block(int fd) ret = fcntl(fd, F_SETFL, val & (~O_NONBLOCK)); if (ret == -1) { int e = errno; + oc_syslog(LOG_ERR, "set_non_block: %s", strerror(e)); } } -ssize_t recv_timeout(int sockfd, void *buf, size_t len, unsigned sec) +ssize_t recv_timeout(int sockfd, void *buf, size_t len, unsigned int sec) { int ret; struct pollfd pfd; @@ -362,8 +365,8 @@ ssize_t recv_timeout(int sockfd, void *buf, size_t len, unsigned sec) return recv(sockfd, buf, len, 0); } -ssize_t recvmsg_timeout(int sockfd, struct msghdr * msg, int flags, - unsigned sec) +ssize_t recvmsg_timeout(int sockfd, struct msghdr *msg, int flags, + unsigned int sec) { int ret; @@ -391,7 +394,8 @@ ssize_t recvmsg_timeout(int sockfd, struct msghdr * msg, int flags, return ret; } -int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsigned timeout) +int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, + unsigned int timeout) { struct iovec iov[3]; char data[5]; @@ -414,8 +418,9 @@ int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsign ret = recvmsg_timeout(ifd, &hdr, 0, timeout); if (ret == -1) { int e = errno; + oc_syslog(LOG_ERR, "%s:%u: recvmsg: %s", __FILE__, __LINE__, - strerror(e)); + strerror(e)); return ERR_BAD_COMMAND; } @@ -425,7 +430,7 @@ int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsign if (rcmd != icmd) { oc_syslog(LOG_ERR, "%s:%u: expected %d, received %d", __FILE__, - __LINE__, (int)rcmd, (int)icmd); + __LINE__, (int)rcmd, (int)icmd); return ERR_BAD_COMMAND; } @@ -436,7 +441,7 @@ int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsign ret = force_write(ofd, data, 5); if (ret != 5) { oc_syslog(LOG_ERR, "%s:%u: cannot send headers: %s", __FILE__, - __LINE__, strerror(errno)); + __LINE__, strerror(errno)); return ERR_BAD_COMMAND; } @@ -449,15 +454,17 @@ int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsign if (ret == -1 || ret == 0) { if (errno == EAGAIN || errno == EINTR) continue; - oc_syslog(LOG_ERR, "%s:%u: cannot send between descriptors: %s", __FILE__, - __LINE__, strerror(errno)); + oc_syslog(LOG_ERR, + "%s:%u: cannot send between descriptors: %s", + __FILE__, __LINE__, strerror(errno)); return ERR_BAD_COMMAND; } ret = force_write(ofd, buf, ret); if (ret == -1 || ret == 0) { - oc_syslog(LOG_ERR, "%s:%u: cannot send between descriptors: %s", __FILE__, - __LINE__, strerror(errno)); + oc_syslog(LOG_ERR, + "%s:%u: cannot send between descriptors: %s", + __FILE__, __LINE__, strerror(errno)); return ERR_BAD_COMMAND; } @@ -468,9 +475,8 @@ int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsign } /* Sends message + socketfd */ -int send_socket_msg(void *pool, int fd, uint8_t cmd, - int socketfd, const void *msg, - pack_size_func get_size, pack_func pack) +int send_socket_msg(void *pool, int fd, uint8_t cmd, int socketfd, + const void *msg, pack_size_func get_size, pack_func pack) { struct iovec iov[3]; struct msghdr hdr; @@ -506,7 +512,7 @@ int send_socket_msg(void *pool, int fd, uint8_t cmd, packed = talloc_size(pool, length); if (packed == NULL) { oc_syslog(LOG_ERR, "%s:%u: memory error", __FILE__, - __LINE__); + __LINE__); return -1; } @@ -516,7 +522,7 @@ int send_socket_msg(void *pool, int fd, uint8_t cmd, ret = pack(msg, packed); if (ret == 0) { oc_syslog(LOG_ERR, "%s:%u: packing error", __FILE__, - __LINE__); + __LINE__); ret = -1; goto cleanup; } @@ -540,17 +546,19 @@ int send_socket_msg(void *pool, int fd, uint8_t cmd, } while (ret == -1 && errno == EINTR); if (ret < 0) { int e = errno; - oc_syslog(LOG_ERR, "%s:%u: %s", __FILE__, __LINE__, strerror(e)); + + oc_syslog(LOG_ERR, "%s:%u: %s", __FILE__, __LINE__, + strerror(e)); } - cleanup: +cleanup: if (length > 0) safe_memset(packed, 0, length); talloc_free(packed); return ret; } -int recv_msg_headers(int fd, uint8_t *cmd, unsigned timeout) +int recv_msg_headers(int fd, uint8_t *cmd, unsigned int timeout) { struct iovec iov[3]; char buffer[5]; @@ -568,8 +576,9 @@ int recv_msg_headers(int fd, uint8_t *cmd, unsigned timeout) ret = recvmsg_timeout(fd, &hdr, 0, timeout); if (ret == -1) { int e = errno; + oc_syslog(LOG_WARNING, "%s:%u: recvmsg: %s", __FILE__, __LINE__, - strerror(e)); + strerror(e)); return ERR_BAD_COMMAND; } @@ -612,8 +621,9 @@ int recv_msg_data(int fd, uint8_t *cmd, uint8_t *data, size_t data_size, ret = recvmsg_timeout(fd, &hdr, 0, MAIN_SEC_MOD_TIMEOUT); if (ret == -1) { int e = errno; + oc_syslog(LOG_ERR, "%s:%u: recvmsg: %s", __FILE__, __LINE__, - strerror(e)); + strerror(e)); return ERR_BAD_COMMAND; } @@ -625,24 +635,28 @@ int recv_msg_data(int fd, uint8_t *cmd, uint8_t *data, size_t data_size, if (received_fd != NULL) { *received_fd = -1; - if ((cmptr = CMSG_FIRSTHDR(&hdr)) != NULL - && cmptr->cmsg_len == CMSG_LEN(sizeof(int))) { - if (cmptr->cmsg_level != SOL_SOCKET - || cmptr->cmsg_type != SCM_RIGHTS) { - oc_syslog(LOG_ERR, - "%s:%u: recvmsg returned invalid msg type", - __FILE__, __LINE__); + if ((cmptr = CMSG_FIRSTHDR(&hdr)) != NULL && + cmptr->cmsg_len == CMSG_LEN(sizeof(int))) { + if (cmptr->cmsg_level != SOL_SOCKET || + cmptr->cmsg_type != SCM_RIGHTS) { + oc_syslog( + LOG_ERR, + "%s:%u: recvmsg returned invalid msg type", + __FILE__, __LINE__); return ERR_BAD_COMMAND; } if (CMSG_DATA(cmptr)) - memcpy(received_fd, CMSG_DATA(cmptr), sizeof(int)); + memcpy(received_fd, CMSG_DATA(cmptr), + sizeof(int)); } } if (l32 > data_size) { - oc_syslog(LOG_ERR, "%s:%u: recv_msg_data: received more data than expected", __FILE__, - __LINE__); + oc_syslog( + LOG_ERR, + "%s:%u: recv_msg_data: received more data than expected", + __FILE__, __LINE__); ret = ERR_BAD_COMMAND; goto cleanup; } @@ -650,15 +664,16 @@ int recv_msg_data(int fd, uint8_t *cmd, uint8_t *data, size_t data_size, ret = force_read_timeout(fd, data, l32, MAIN_SEC_MOD_TIMEOUT); if (ret < l32) { int e = errno; - oc_syslog(LOG_ERR, "%s:%u: recvmsg: %s", __FILE__, - __LINE__, strerror(e)); + + oc_syslog(LOG_ERR, "%s:%u: recvmsg: %s", __FILE__, __LINE__, + strerror(e)); ret = ERR_BAD_COMMAND; goto cleanup; } ret = l32; - cleanup: +cleanup: if (ret < 0 && received_fd != NULL && *received_fd != -1) { close(*received_fd); *received_fd = -1; @@ -666,9 +681,8 @@ int recv_msg_data(int fd, uint8_t *cmd, uint8_t *data, size_t data_size, return ret; } -int recv_socket_msg(void *pool, int fd, uint8_t cmd, - int *socketfd, void **msg, unpack_func unpack, - unsigned timeout) +int recv_socket_msg(void *pool, int fd, uint8_t cmd, int *socketfd, void **msg, + unpack_func unpack, unsigned int timeout) { struct iovec iov[3]; uint32_t length; @@ -681,6 +695,7 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, } control_un; struct cmsghdr *cmptr; int ret; + PROTOBUF_ALLOCATOR(pa, pool); iov[0].iov_base = &rcmd; @@ -699,8 +714,9 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, ret = recvmsg_timeout(fd, &hdr, 0, timeout); if (ret == -1) { int e = errno; + oc_syslog(LOG_ERR, "%s:%u: recvmsg: %s", __FILE__, __LINE__, - strerror(e)); + strerror(e)); return ERR_BAD_COMMAND; } @@ -710,19 +726,20 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, if (rcmd != cmd) { oc_syslog(LOG_ERR, "%s:%u: expected %d, received %d", __FILE__, - __LINE__, (int)rcmd, (int)cmd); + __LINE__, (int)rcmd, (int)cmd); return ERR_BAD_COMMAND; } /* try to receive socket (if any) */ if (socketfd != NULL) { - if ((cmptr = CMSG_FIRSTHDR(&hdr)) != NULL - && cmptr->cmsg_len == CMSG_LEN(sizeof(int))) { - if (cmptr->cmsg_level != SOL_SOCKET - || cmptr->cmsg_type != SCM_RIGHTS) { - oc_syslog(LOG_ERR, - "%s:%u: recvmsg returned invalid msg type", - __FILE__, __LINE__); + if ((cmptr = CMSG_FIRSTHDR(&hdr)) != NULL && + cmptr->cmsg_len == CMSG_LEN(sizeof(int))) { + if (cmptr->cmsg_level != SOL_SOCKET || + cmptr->cmsg_type != SCM_RIGHTS) { + oc_syslog( + LOG_ERR, + "%s:%u: recvmsg returned invalid msg type", + __FILE__, __LINE__); return ERR_BAD_COMMAND; } @@ -745,8 +762,9 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, ret = force_read_timeout(fd, data, length, timeout); if (ret < length) { int e = errno; + oc_syslog(LOG_ERR, "%s:%u: recvmsg: %s", __FILE__, - __LINE__, strerror(e)); + __LINE__, strerror(e)); ret = ERR_BAD_COMMAND; goto cleanup; } @@ -754,7 +772,7 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, *msg = unpack(&pa, length, data); if (*msg == NULL) { oc_syslog(LOG_ERR, "%s:%u: unpacking error", __FILE__, - __LINE__); + __LINE__); ret = ERR_MEM; goto cleanup; } @@ -762,7 +780,7 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, ret = 0; - cleanup: +cleanup: talloc_free(data); if (ret < 0 && socketfd != NULL && *socketfd != -1) { close(*socketfd); @@ -771,7 +789,6 @@ int recv_socket_msg(void *pool, int fd, uint8_t cmd, return ret; } - void _talloc_free2(void *ctx, void *ptr) { talloc_free(ptr); @@ -788,8 +805,8 @@ void *_talloc_size2(void *ctx, size_t size) * in our_addr. */ ssize_t oc_recvfrom_at(int sockfd, void *buf, size_t len, int flags, - struct sockaddr * src_addr, socklen_t * addrlen, - struct sockaddr * our_addr, socklen_t * our_addrlen, + struct sockaddr *src_addr, socklen_t *addrlen, + struct sockaddr *our_addr, socklen_t *our_addrlen, int def_port) { int ret; @@ -816,13 +833,13 @@ ssize_t oc_recvfrom_at(int sockfd, void *buf, size_t len, int flags, for (cmsg = CMSG_FIRSTHDR(&mh); cmsg != NULL; cmsg = CMSG_NXTHDR(&mh, cmsg)) { #if defined(IP_PKTINFO) - if (cmsg->cmsg_level == IPPROTO_IP - && cmsg->cmsg_type == IP_PKTINFO) { + if (cmsg->cmsg_level == IPPROTO_IP && + cmsg->cmsg_type == IP_PKTINFO) { struct in_pktinfo *pi = (void *)CMSG_DATA(cmsg); struct sockaddr_in *a = (struct sockaddr_in *)our_addr; - if (*our_addrlen < sizeof(struct sockaddr_in) - || pi == NULL) + if (*our_addrlen < sizeof(struct sockaddr_in) || + pi == NULL) return -1; a->sin_family = AF_INET; @@ -833,13 +850,13 @@ ssize_t oc_recvfrom_at(int sockfd, void *buf, size_t len, int flags, break; } #elif defined(IP_RECVDSTADDR) - if (cmsg->cmsg_level == IPPROTO_IP - && cmsg->cmsg_type == IP_RECVDSTADDR) { + if (cmsg->cmsg_level == IPPROTO_IP && + cmsg->cmsg_type == IP_RECVDSTADDR) { struct in_addr *pi = (void *)CMSG_DATA(cmsg); struct sockaddr_in *a = (struct sockaddr_in *)our_addr; - if (*our_addrlen < sizeof(struct sockaddr_in) - || pi == NULL) + if (*our_addrlen < sizeof(struct sockaddr_in) || + pi == NULL) return -1; a->sin_family = AF_INET; @@ -851,14 +868,14 @@ ssize_t oc_recvfrom_at(int sockfd, void *buf, size_t len, int flags, } #endif #ifdef IPV6_RECVPKTINFO - if (cmsg->cmsg_level == IPPROTO_IPV6 - && cmsg->cmsg_type == IPV6_PKTINFO) { + if (cmsg->cmsg_level == IPPROTO_IPV6 && + cmsg->cmsg_type == IPV6_PKTINFO) { struct in6_pktinfo *pi = (void *)CMSG_DATA(cmsg); struct sockaddr_in6 *a = - (struct sockaddr_in6 *)our_addr; + (struct sockaddr_in6 *)our_addr; - if (*our_addrlen < sizeof(struct sockaddr_in6) - || pi == NULL) + if (*our_addrlen < sizeof(struct sockaddr_in6) || + pi == NULL) return -1; a->sin6_family = AF_INET6; @@ -917,11 +934,12 @@ size_t oc_strlcpy(char *dst, char const *src, size_t siz) /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) - *d = '\0'; /* NUL-terminate dst */ - while (*s++) ; + *d = '\0'; /* NUL-terminate dst */ + while (*s++) + ; } - return (s - src - 1); /* count does not include NUL */ + return (s - src - 1); /* count does not include NUL */ } #endif diff --git a/src/common/common.h b/src/common/common.h index 9bc60004..e706175e 100644 --- a/src/common/common.h +++ b/src/common/common.h @@ -20,7 +20,7 @@ * along with this program. If not, see */ #ifndef COMMON_H -# define COMMON_H +#define COMMON_H #include #include @@ -40,15 +40,17 @@ void *_talloc_size2(void *ctx, size_t size); #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) -#define PROTOBUF_ALLOCATOR(name, pool) \ - ProtobufCAllocator name = {.alloc = _talloc_size2, .free = _talloc_free2, .allocator_data = pool} +#define PROTOBUF_ALLOCATOR(name, pool) \ + ProtobufCAllocator name = { .alloc = _talloc_size2, \ + .free = _talloc_free2, \ + .allocator_data = pool } #ifndef MIN -# define MIN(x,y) (((x)<(y))?(x):(y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) #endif #ifndef MAX -# define MAX(x,y) (((x)>(y))?(x):(y)) +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) #endif void set_non_block(int fd); @@ -56,56 +58,53 @@ void set_block(int fd); ssize_t force_write(int sockfd, const void *buf, size_t len); ssize_t force_read(int sockfd, void *buf, size_t len); -ssize_t force_read_timeout(int sockfd, void *buf, size_t len, unsigned sec); -ssize_t recv_timeout(int sockfd, void *buf, size_t len, unsigned sec); +ssize_t force_read_timeout(int sockfd, void *buf, size_t len, unsigned int sec); +ssize_t recv_timeout(int sockfd, void *buf, size_t len, unsigned int sec); -typedef size_t (*pack_func)(const void*, uint8_t *); -typedef size_t (*pack_size_func)(const void*); +typedef size_t (*pack_func)(const void *, uint8_t *); +typedef size_t (*pack_size_func)(const void *); -typedef void* (*unpack_func)(ProtobufCAllocator *allocator, - size_t len, - const uint8_t *data); +typedef void *(*unpack_func)(ProtobufCAllocator *allocator, size_t len, + const uint8_t *data); -int send_socket_msg(void *pool, int fd, uint8_t cmd, - int socketfd, - const void* msg, pack_size_func get_size, pack_func pack); +int send_socket_msg(void *pool, int fd, uint8_t cmd, int socketfd, + const void *msg, pack_size_func get_size, pack_func pack); -int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, unsigned timeout); +int forward_msg(void *pool, int ifd, uint8_t icmd, int ofd, uint8_t ocmd, + unsigned int timeout); -inline static -int send_msg(void *pool, int fd, uint8_t cmd, - const void *msg, pack_size_func get_size, pack_func pack) +inline static int send_msg(void *pool, int fd, uint8_t cmd, const void *msg, + pack_size_func get_size, pack_func pack) { return send_socket_msg(pool, fd, cmd, -1, msg, get_size, pack); } +int recv_socket_msg(void *pool, int fd, uint8_t cmd, int *socketfd, void **msg, + unpack_func, unsigned int timeout); -int recv_socket_msg(void *pool, int fd, uint8_t cmd, - int *socketfd, void** msg, unpack_func, unsigned timeout); - -inline static int recv_msg(void *pool, int fd, uint8_t cmd, - void **msg, unpack_func unpack, unsigned timeout) +inline static int recv_msg(void *pool, int fd, uint8_t cmd, void **msg, + unpack_func unpack, unsigned int timeout) { return recv_socket_msg(pool, fd, cmd, NULL, msg, unpack, timeout); } -int recv_msg_headers(int fd, uint8_t *cmd, unsigned timeout); -int recv_msg_data(int fd, uint8_t *cmd, uint8_t *data, size_t data_size, int *received_fd); +int recv_msg_headers(int fd, uint8_t *cmd, unsigned int timeout); +int recv_msg_data(int fd, uint8_t *cmd, uint8_t *data, size_t data_size, + int *received_fd); -const char* cmd_request_to_str(unsigned cmd); -const char* discon_reason_to_str(unsigned reason); -unsigned int discon_reason_to_log_level(unsigned reason); +const char *cmd_request_to_str(unsigned int cmd); +const char *discon_reason_to_str(unsigned int reason); +unsigned int discon_reason_to_log_level(unsigned int reason); ssize_t oc_recvfrom_at(int sockfd, void *buf, size_t len, int flags, - struct sockaddr *src_addr, socklen_t *addrlen, - struct sockaddr *our_addr, socklen_t *our_addrlen, - int def_port); + struct sockaddr *src_addr, socklen_t *addrlen, + struct sockaddr *our_addr, socklen_t *our_addrlen, + int def_port); -inline static -void safe_memset(void *data, int c, size_t size) +inline static void safe_memset(void *data, int c, size_t size) { volatile unsigned volatile_zero = 0; - volatile char *vdata = (volatile char*)data; + volatile char *vdata = (volatile char *)data; /* This is based on a nice trick for safe memset, * sent by David Jacobson in the openssl-dev mailing list. @@ -117,8 +116,7 @@ void safe_memset(void *data, int c, size_t size) } while (vdata[volatile_zero] != c); } -inline static -void ms_sleep(unsigned ms) +inline static void ms_sleep(unsigned int ms) { struct timespec tv; int ret; @@ -136,17 +134,18 @@ void ms_sleep(unsigned ms) } while (ret == -1 && errno == EINTR); } -const char *ps_status_to_str(int status, unsigned cookie); +const char *ps_status_to_str(int status, unsigned int cookie); const char *_vhost_prefix(const char *name); #ifndef HAVE_STRLCPY size_t oc_strlcpy(char *dst, char const *src, size_t siz); -# define strlcpy oc_strlcpy +#define strlcpy oc_strlcpy #endif -#define SAFE_ID_SIZE (BASE64_ENCODE_RAW_LENGTH(20)+1) -char *calc_safe_id(const uint8_t *data, unsigned size, char *output, unsigned output_size); +#define SAFE_ID_SIZE (BASE64_ENCODE_RAW_LENGTH(20) + 1) +char *calc_safe_id(const uint8_t *data, unsigned int size, char *output, + unsigned int output_size); extern int saved_argc; extern char **saved_argv; diff --git a/src/common/hmac.c b/src/common/hmac.c index dc3e1341..d3d026c6 100644 --- a/src/common/hmac.c +++ b/src/common/hmac.c @@ -30,13 +30,14 @@ #include #include -bool hmac_init_key(size_t key_length, uint8_t * key) +bool hmac_init_key(size_t key_length, uint8_t *key) { return gnutls_rnd(GNUTLS_RND_RANDOM, key, key_length) == 0; } -void generate_hmac(size_t key_length, const uint8_t * key, size_t component_count, - const hmac_component_st * components, uint8_t digest[HMAC_DIGEST_SIZE]) +void generate_hmac(size_t key_length, const uint8_t *key, + size_t component_count, const hmac_component_st *components, + uint8_t digest[HMAC_DIGEST_SIZE]) { struct hmac_sha256_ctx ctx; size_t i; @@ -44,10 +45,8 @@ void generate_hmac(size_t key_length, const uint8_t * key, size_t component_coun hmac_sha256_set_key(&ctx, key_length, key); for (i = 0; i < component_count; i++) { - if (components[i].data) { - hmac_sha256_update(&ctx, - components[i].length, + hmac_sha256_update(&ctx, components[i].length, (const uint8_t *)components[i].data); } } diff --git a/src/common/hmac.h b/src/common/hmac.h index 0f0fb8de..d6c38453 100644 --- a/src/common/hmac.h +++ b/src/common/hmac.h @@ -19,21 +19,21 @@ * along with this program. If not, see */ - #ifndef HMAC_H #define HMAC_H #include #define HMAC_DIGEST_SIZE 32 -bool hmac_init_key(size_t key_length, uint8_t * key); +bool hmac_init_key(size_t key_length, uint8_t *key); -typedef struct hmac_component_st { +typedef struct hmac_component_st { size_t length; - void * data; + void *data; } hmac_component_st; -void generate_hmac(size_t key_length, const uint8_t * key, size_t component_count, - const hmac_component_st * components, uint8_t digest[HMAC_DIGEST_SIZE]); +void generate_hmac(size_t key_length, const uint8_t *key, + size_t component_count, const hmac_component_st *components, + uint8_t digest[HMAC_DIGEST_SIZE]); #endif diff --git a/src/common/snapshot.c b/src/common/snapshot.c index 9405fec5..f0dc2d63 100644 --- a/src/common/snapshot.c +++ b/src/common/snapshot.c @@ -61,7 +61,8 @@ static size_t snapshot_hash_filename(const char *file_name) static size_t snapshot_rehash(const void *elem, void *priv) { - snapshot_entry_t *entry = (snapshot_entry_t *) elem; + snapshot_entry_t *entry = (snapshot_entry_t *)elem; + return snapshot_hash_filename(entry->name); } @@ -71,6 +72,7 @@ static snapshot_entry_t *snapshot_find(struct snapshot_t *snapshot, struct htable_iter iter; size_t hash = snapshot_hash_filename(filename); snapshot_entry_t *entry = htable_firstval(&snapshot->ht, &iter, hash); + while (entry != NULL) { if (strcmp(entry->name, filename) == 0) { break; @@ -84,6 +86,7 @@ static int snapshot_file_name_from_fd(int fd, char *file_name, size_t file_name_length) { int ret = snprintf(file_name, file_name_length, "/proc/self/fd/%d", fd); + if (ret >= file_name_length) { return -1; } else { @@ -91,29 +94,28 @@ static int snapshot_file_name_from_fd(int fd, char *file_name, } } -static int snapshot_add_entry(snapshot_t * snapshot, const char *filename, +static int snapshot_add_entry(snapshot_t *snapshot, const char *filename, int fd) { int retval = -1; snapshot_entry_t *entry = NULL; size_t file_name_length = strlen(filename) + 1; - entry = - (snapshot_entry_t *) talloc_zero_array(snapshot->pool, char, - sizeof(uint32_t) + - file_name_length); + + entry = (snapshot_entry_t *)talloc_zero_array( + snapshot->pool, char, sizeof(uint32_t) + file_name_length); if (entry == NULL) goto cleanup; entry->fd = fd; strlcpy((char *)entry->name, filename, file_name_length); - if (!htable_add - (&snapshot->ht, snapshot_hash_filename(entry->name), entry)) + if (!htable_add(&snapshot->ht, snapshot_hash_filename(entry->name), + entry)) goto cleanup; entry = NULL; retval = 0; - cleanup: +cleanup: if (entry) talloc_free(entry); @@ -138,12 +140,11 @@ int snapshot_init(void *pool, struct snapshot_t **snapshot, const char *prefix) new_snapshot->pool = pool; new_snapshot->tmp_filename_template = - talloc_array(pool, char, tmp_filename_template_length); + talloc_array(pool, char, tmp_filename_template_length); - if (snprintf - ((char *)new_snapshot->tmp_filename_template, - tmp_filename_template_length, "%sXXXXXX", - prefix) >= tmp_filename_template_length) + if (snprintf((char *)new_snapshot->tmp_filename_template, + tmp_filename_template_length, "%sXXXXXX", + prefix) >= tmp_filename_template_length) goto cleanup; htable_init(&new_snapshot->ht, snapshot_rehash, new_snapshot); @@ -151,11 +152,11 @@ int snapshot_init(void *pool, struct snapshot_t **snapshot, const char *prefix) *snapshot = new_snapshot; new_snapshot = NULL; - cleanup: +cleanup: if (new_snapshot != NULL) { if (new_snapshot->tmp_filename_template != NULL) - talloc_free((char *)new_snapshot-> - tmp_filename_template); + talloc_free( + (char *)new_snapshot->tmp_filename_template); talloc_free(new_snapshot); } @@ -170,6 +171,7 @@ void snapshot_terminate(struct snapshot_t *snapshot) { struct htable_iter iter; snapshot_entry_t *entry = htable_first(&snapshot->ht, &iter); + while (entry != NULL) { htable_delval(&snapshot->ht, &iter); close(entry->fd); @@ -203,6 +205,7 @@ int snapshot_create(struct snapshot_t *snapshot, const char *filename) fd_out = mkstemp(tmp_file_name); if (fd_out == -1) { int err = errno; + fprintf(stderr, ERRSTR "cannot create temp file '%s' : %s\n", tmp_file_name, strerror(err)); goto cleanup; @@ -213,10 +216,12 @@ int snapshot_create(struct snapshot_t *snapshot, const char *filename) for (;;) { int byteRead = read(fd_in, buffer, sizeof(buffer)); int bytesWritten; + if (byteRead == 0) { break; } else if (byteRead == -1) { int err = errno; + fprintf(stderr, ERRSTR " reading %s failed %s\n", filename, strerror(err)); goto cleanup; @@ -224,6 +229,7 @@ int snapshot_create(struct snapshot_t *snapshot, const char *filename) bytesWritten = write(fd_out, buffer, byteRead); if (bytesWritten != byteRead) { int err = errno; + fprintf(stderr, ERRSTR " writing %s failed %s\n", tmp_file_name, strerror(err)); @@ -250,7 +256,7 @@ int snapshot_create(struct snapshot_t *snapshot, const char *filename) ret = 0; entry = NULL; - cleanup: +cleanup: if (fd_in != -1) close(fd_in); @@ -264,6 +270,7 @@ int snapshot_first(struct snapshot_t *snapshot, struct htable_iter *iter, int *fd, const char **file_name) { snapshot_entry_t *entry = htable_first(&snapshot->ht, iter); + if (entry == NULL) { return -1; } else { @@ -277,6 +284,7 @@ int snapshot_next(struct snapshot_t *snapshot, struct htable_iter *iter, int *fd, const char **file_name) { snapshot_entry_t *entry = htable_next(&snapshot->ht, iter); + if (entry == NULL) { return -1; } else { @@ -290,13 +298,14 @@ int snapshot_restore_entry(struct snapshot_t *snapshot, int fd, const char *file_name) { int ret = snapshot_add_entry(snapshot, file_name, fd); + if (ret < 0) return ret; return 0; } -size_t snapshot_entry_count(struct snapshot_t * snapshot) +size_t snapshot_entry_count(struct snapshot_t *snapshot) { struct htable_iter iter; size_t count = 0; @@ -317,6 +326,7 @@ int snapshot_lookup_filename(struct snapshot_t *snapshot, const char *file_name, char fd_path[128]; char *new_file_name = NULL; snapshot_entry_t *entry = snapshot_find(snapshot, file_name); + if (entry == NULL) goto cleanup; @@ -332,7 +342,7 @@ int snapshot_lookup_filename(struct snapshot_t *snapshot, const char *file_name, ret = 0; - cleanup: +cleanup: if (new_file_name != NULL) talloc_free(new_file_name); diff --git a/src/common/sockdiag.c b/src/common/sockdiag.c index f161c600..6b92e327 100644 --- a/src/common/sockdiag.c +++ b/src/common/sockdiag.c @@ -37,32 +37,23 @@ static int send_query(int fd, int inode, int states, int show) { int err; - struct sockaddr_nl nladdr = { - .nl_family = AF_NETLINK - }; + struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK }; struct { struct nlmsghdr nlh; struct unix_diag_req udr; - } req = { - .nlh = { - .nlmsg_len = sizeof(req),.nlmsg_type = - SOCK_DIAG_BY_FAMILY,.nlmsg_flags = - NLM_F_REQUEST | (inode ? 0 : NLM_F_DUMP) - } - ,.udr = { - .sdiag_family = AF_UNIX,.udiag_states = - states,.udiag_show = show,.udiag_ino = inode} - }; - struct iovec iov = { - .iov_base = &req, - .iov_len = sizeof(req) - }; - struct msghdr msg = { - .msg_name = (void *)&nladdr, - .msg_namelen = sizeof(nladdr), - .msg_iov = &iov, - .msg_iovlen = 1 - }; + } req = { .nlh = { .nlmsg_len = sizeof(req), + .nlmsg_type = SOCK_DIAG_BY_FAMILY, + .nlmsg_flags = NLM_F_REQUEST | + (inode ? 0 : NLM_F_DUMP) }, + .udr = { .sdiag_family = AF_UNIX, + .udiag_states = states, + .udiag_show = show, + .udiag_ino = inode } }; + struct iovec iov = { .iov_base = &req, .iov_len = sizeof(req) }; + struct msghdr msg = { .msg_name = (void *)&nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = &iov, + .msg_iovlen = 1 }; for (;;) { if (sendmsg(fd, &msg, 0) < 0) { @@ -78,7 +69,7 @@ static int send_query(int fd, int inode, int states, int show) } } -typedef int (*process_response)(const struct unix_diag_msg * diag, +typedef int (*process_response)(const struct unix_diag_msg *diag, unsigned int len, void *context); struct match_name_context { @@ -95,12 +86,12 @@ static int match_name(const struct unix_diag_msg *diag, unsigned int len, struct rtattr *attr; unsigned int rta_len = len - NLMSG_LENGTH(sizeof(*diag)); size_t path_len = 0; - char path[sizeof(((struct sockaddr_un *) 0)->sun_path) + 1]; + char path[sizeof(((struct sockaddr_un *)0)->sun_path) + 1]; struct unix_diag_rqlen rqlen; int rqlen_valid = 0; - for (attr = (struct rtattr *)(diag + 1); - RTA_OK(attr, rta_len); attr = RTA_NEXT(attr, rta_len)) { + for (attr = (struct rtattr *)(diag + 1); RTA_OK(attr, rta_len); + attr = RTA_NEXT(attr, rta_len)) { switch (attr->rta_type) { case UNIX_DIAG_NAME: if (!path_len) { @@ -142,22 +133,15 @@ static int receive_responses(int fd, process_response process, void *context) { int err; long buf[8192 / sizeof(long)]; - struct sockaddr_nl nladdr = { - .nl_family = AF_NETLINK - }; - struct iovec iov = { - .iov_base = buf, - .iov_len = sizeof(buf) - }; + struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK }; + struct iovec iov = { .iov_base = buf, .iov_len = sizeof(buf) }; int flags = 0; for (;;) { - struct msghdr msg = { - .msg_name = (void *)&nladdr, - .msg_namelen = sizeof(nladdr), - .msg_iov = &iov, - .msg_iovlen = 1 - }; + struct msghdr msg = { .msg_name = (void *)&nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = &iov, + .msg_iovlen = 1 }; ssize_t ret = recvmsg(fd, &msg, flags); @@ -191,12 +175,14 @@ static int receive_responses(int fd, process_response process, void *context) const struct nlmsgerr *err = NLMSG_DATA(h); if (h->nlmsg_len < NLMSG_LENGTH(sizeof(*err))) { - oc_syslog(LOG_ERR, - "nlmsg_type NLMSG_ERROR has short nlmsg_len %d", - h->nlmsg_len); + oc_syslog( + LOG_ERR, + "nlmsg_type NLMSG_ERROR has short nlmsg_len %d", + h->nlmsg_len); } else { - oc_syslog(LOG_ERR, "NLM query failed %s", - strerror(-err->error)); + oc_syslog(LOG_ERR, + "NLM query failed %s", + strerror(-err->error)); } return -1; @@ -204,22 +190,23 @@ static int receive_responses(int fd, process_response process, void *context) if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY) { oc_syslog(LOG_ERR, "unexpected nlmsg_type %u\n", - (unsigned)h->nlmsg_type); + (unsigned int)h->nlmsg_type); return -1; } diag = (const struct unix_diag_msg *)NLMSG_DATA(h); if (h->nlmsg_len < NLMSG_LENGTH(sizeof(*diag))) { - oc_syslog(LOG_ERR, - "nlmsg_type SOCK_DIAG_BY_FAMILY has short nlmsg_len %d", - h->nlmsg_len); + oc_syslog( + LOG_ERR, + "nlmsg_type SOCK_DIAG_BY_FAMILY has short nlmsg_len %d", + h->nlmsg_len); return -1; } if (diag->udiag_family != AF_UNIX) { oc_syslog(LOG_ERR, "unexpected family %u\n", - diag->udiag_family); + diag->udiag_family); return -1; } @@ -235,10 +222,7 @@ int sockdiag_query_unix_domain_socket_queue_length(const char *socket_name, { int err; int ret = -1; - struct match_name_context ctx = { - .name = socket_name, - .inode = 0 - }; + struct match_name_context ctx = { .name = socket_name, .inode = 0 }; int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG); @@ -248,8 +232,8 @@ int sockdiag_query_unix_domain_socket_queue_length(const char *socket_name, goto cleanup; } - if (send_query - (fd, 0, 1 << TCP_LISTEN, UDIAG_SHOW_NAME | UDIAG_SHOW_RQLEN)) + if (send_query(fd, 0, 1 << TCP_LISTEN, + UDIAG_SHOW_NAME | UDIAG_SHOW_RQLEN)) goto cleanup; if (receive_responses(fd, match_name, &ctx)) @@ -260,7 +244,7 @@ int sockdiag_query_unix_domain_socket_queue_length(const char *socket_name, ret = 0; - cleanup: +cleanup: if (fd >= 0) { close(fd); } diff --git a/src/common/sockdiag.h b/src/common/sockdiag.h index 5bf3cae5..a3b32cf4 100644 --- a/src/common/sockdiag.h +++ b/src/common/sockdiag.h @@ -24,6 +24,8 @@ #include -int sockdiag_query_unix_domain_socket_queue_length(const char * socket_name, int * sock_rqueue, int * sock_wqueue); +int sockdiag_query_unix_domain_socket_queue_length(const char *socket_name, + int *sock_rqueue, + int *sock_wqueue); #endif diff --git a/src/common/system.c b/src/common/system.c index 3490a647..d4d4ccb9 100644 --- a/src/common/system.c +++ b/src/common/system.c @@ -21,7 +21,7 @@ #include #include #ifdef __linux__ -# include +#include #endif #include #include @@ -47,8 +47,9 @@ void pr_set_undumpable(const char *mod) #ifdef __linux__ if (prctl(PR_SET_DUMPABLE, 0) == -1) { int e = errno; - oc_syslog(LOG_ERR, "%s: prctl(PR_SET_DUMPABLE) failed %s", - mod, strerror(e)); + + oc_syslog(LOG_ERR, "%s: prctl(PR_SET_DUMPABLE) failed %s", mod, + strerror(e)); } #endif } @@ -60,17 +61,18 @@ SIGHANDLER_T ocsignal(int signum, SIGHANDLER_T handler) memset(&new_action, 0, sizeof(new_action)); new_action.sa_handler = handler; - sigemptyset (&new_action.sa_mask); + sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; - sigaction (signum, &new_action, &old_action); + sigaction(signum, &new_action, &old_action); return old_action.sa_handler; } /* Checks whether the peer in a socket has the expected @uid and @gid. * Returns zero on success. */ -int check_upeer_id(const char *mod, int debug, int cfd, uid_t uid, uid_t gid, uid_t *ruid, pid_t *pid) +int check_upeer_id(const char *mod, int debug, int cfd, uid_t uid, uid_t gid, + uid_t *ruid, pid_t *pid) { int e, ret; #if defined(SO_PEERCRED) && defined(HAVE_STRUCT_UCRED) @@ -85,15 +87,15 @@ int check_upeer_id(const char *mod, int debug, int cfd, uid_t uid, uid_t gid, ui ret = getsockopt(cfd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len); if (ret == -1) { e = errno; - oc_syslog(LOG_ERR, "%s: getsockopt SO_PEERCRED error: %s", - mod, strerror(e)); + oc_syslog(LOG_ERR, "%s: getsockopt SO_PEERCRED error: %s", mod, + strerror(e)); return -1; } if (debug >= OCLOG_DEBUG) oc_syslog(LOG_DEBUG, - "%s: received request from pid %u and uid %u", - mod, (unsigned)cr.pid, (unsigned)cr.uid); + "%s: received request from pid %u and uid %u", mod, + (unsigned int)cr.pid, (unsigned int)cr.uid); if (ruid) *ruid = cr.uid; @@ -102,10 +104,11 @@ int check_upeer_id(const char *mod, int debug, int cfd, uid_t uid, uid_t gid, ui *pid = cr.pid; if (cr.uid != 0 && (cr.uid != uid || cr.gid != gid)) { - oc_syslog(LOG_ERR, - "%s: received unauthorized request from pid %u and uid %u", - mod, (unsigned)cr.pid, (unsigned)cr.uid); - return -1; + oc_syslog( + LOG_ERR, + "%s: received unauthorized request from pid %u and uid %u", + mod, (unsigned int)cr.pid, (unsigned int)cr.uid); + return -1; } #elif defined(HAVE_GETPEEREID) uid_t euid; @@ -115,8 +118,8 @@ int check_upeer_id(const char *mod, int debug, int cfd, uid_t uid, uid_t gid, ui if (ret == -1) { e = errno; - oc_syslog(LOG_DEBUG, "%s: getpeereid error: %s", - mod, strerror(e)); + oc_syslog(LOG_DEBUG, "%s: getpeereid error: %s", mod, + strerror(e)); return -1; } @@ -128,14 +131,15 @@ int check_upeer_id(const char *mod, int debug, int cfd, uid_t uid, uid_t gid, ui if (debug >= OCLOG_DEBUG) oc_syslog(LOG_DEBUG, - "%s: received request from a processes with uid %u", - mod, (unsigned)euid); + "%s: received request from a processes with uid %u", + mod, (unsigned int)euid); if (euid != 0 && (euid != uid || egid != gid)) { - oc_syslog(LOG_ERR, - "%s: received unauthorized request from a process with uid %u", - mod, (unsigned)euid); - return -1; + oc_syslog( + LOG_ERR, + "%s: received unauthorized request from a process with uid %u", + mod, (unsigned int)euid); + return -1; } #else #error "Unsupported UNIX variant" diff --git a/src/common/system.h b/src/common/system.h index 5c4b1013..6864fd92 100644 --- a/src/common/system.h +++ b/src/common/system.h @@ -19,30 +19,29 @@ * along with this program. If not, see */ #ifndef DIE_H -# define DIE_H +#define DIE_H -# include -# include -# include +#include +#include +#include #ifdef HAVE_SIGHANDLER_T -# define SIGHANDLER_T sighandler_t +#define SIGHANDLER_T sighandler_t #elif HAVE_SIG_T -# define SIGHANDLER_T sig_t +#define SIGHANDLER_T sig_t #elif HAVE___SIGHANDLER_T -# define SIGHANDLER_T __sighandler_t +#define SIGHANDLER_T __sighandler_t #else typedef void (*sighandler_t)(int); -# define SIGHANDLER_T sighandler_t +#define SIGHANDLER_T sighandler_t #endif -void pr_set_undumpable(const char* mod); +void pr_set_undumpable(const char *mod); void kill_on_parent_kill(int sig); SIGHANDLER_T ocsignal(int signum, SIGHANDLER_T handler); -int check_upeer_id(const char *mod, int debug, int cfg, uid_t uid, uid_t gid, uid_t *ruid, pid_t *pid); - - +int check_upeer_id(const char *mod, int debug, int cfg, uid_t uid, uid_t gid, + uid_t *ruid, pid_t *pid); #endif diff --git a/src/config-kkdcp.c b/src/config-kkdcp.c index 0f4b2160..eb27fa0b 100644 --- a/src/config-kkdcp.c +++ b/src/config-kkdcp.c @@ -38,7 +38,8 @@ static char *find_space(char *str) return NULL; } -void parse_kkdcp_string(char *str, int *socktype, char **_port, char **_server, char **_path, char **_realm) +void parse_kkdcp_string(char *str, int *socktype, char **_port, char **_server, + char **_path, char **_realm) { char *path, *server, *port, *realm, *p; @@ -73,7 +74,7 @@ void parse_kkdcp_string(char *str, int *socktype, char **_port, char **_server, *socktype = SOCK_STREAM; } else { fprintf(stderr, "cannot handle protocol %s\n", server); - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } server += 4; @@ -86,7 +87,7 @@ void parse_kkdcp_string(char *str, int *socktype, char **_port, char **_server, *p = 0; p = strchr(server, '['); if (p) - server = p+1; + server = p + 1; } } diff --git a/src/config-ports.c b/src/config-ports.c index a4b7262f..7705384e 100644 --- a/src/config-ports.c +++ b/src/config-ports.c @@ -27,11 +27,13 @@ #include -static int append_port(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, int port, fw_proto_t proto, unsigned negate) +static int append_port(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, + int port, fw_proto_t proto, unsigned int negate) { FwPortSt *current; - *fw_ports = talloc_realloc(pool, *fw_ports, FwPortSt*, (*n_fw_ports)+1); + *fw_ports = + talloc_realloc(pool, *fw_ports, FwPortSt *, (*n_fw_ports) + 1); if (*fw_ports == NULL) return -1; @@ -56,10 +58,11 @@ static int append_port(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, int /* Parse strings of the format tcp(443), udp(111), and fill in * allowed_tcp_ports and allowed_udp_ports. */ -int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const char *str) +int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, + const char *str) { const char *p, *p2; - unsigned finish = 0; + unsigned int finish = 0; int port, ret; fw_proto_t proto; int negate = 0, bracket_start = 0; @@ -82,13 +85,14 @@ int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const } if (bracket_start == 0) { - oc_syslog(LOG_ERR, "no bracket following negation at %d '%s'", (int)(ptrdiff_t)(p-str), str); + oc_syslog(LOG_ERR, + "no bracket following negation at %d '%s'", + (int)(ptrdiff_t)(p - str), str); return -1; } } do { - while (isspace(*p)) p++; @@ -111,7 +115,10 @@ int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const proto = PROTO_ESP; p += 3; } else { - oc_syslog(LOG_ERR, "unknown protocol on restrict-user-to-ports at %d '%s'", (int)(ptrdiff_t)(p-str), str); + oc_syslog( + LOG_ERR, + "unknown protocol on restrict-user-to-ports at %d '%s'", + (int)(ptrdiff_t)(p - str), str); return -1; } @@ -119,14 +126,18 @@ int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const p++; if (*p != '(') { - oc_syslog(LOG_ERR, "expected parenthesis on restrict-user-to-ports at %d '%s'", (int)(ptrdiff_t)(p-str), str); + oc_syslog( + LOG_ERR, + "expected parenthesis on restrict-user-to-ports at %d '%s'", + (int)(ptrdiff_t)(p - str), str); return -1; } p++; port = atoi(p); - ret = append_port(pool, fw_ports, n_fw_ports, port, proto, negate); + ret = append_port(pool, fw_ports, n_fw_ports, port, proto, + negate); if (ret < 0) { oc_syslog(LOG_ERR, "memory error"); return -1; @@ -134,7 +145,10 @@ int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const p2 = strchr(p, ')'); if (p2 == NULL) { - oc_syslog(LOG_ERR, "expected closing parenthesis on restrict-user-to-ports at %d '%s'", (int)(ptrdiff_t)(p-str), str); + oc_syslog( + LOG_ERR, + "expected closing parenthesis on restrict-user-to-ports at %d '%s'", + (int)(ptrdiff_t)(p - str), str); return -1; } @@ -145,10 +159,13 @@ int cfg_parse_ports(void *pool, FwPortSt ***fw_ports, size_t *n_fw_ports, const if (*p2 == 0 || (negate != 0 && *p2 == ')')) { finish = 1; } else if (*p2 != ',') { - oc_syslog(LOG_ERR, "expected comma or end of line on restrict-user-to-ports at %d '%s'", (int)(ptrdiff_t)(p2-str), str); + oc_syslog( + LOG_ERR, + "expected comma or end of line on restrict-user-to-ports at %d '%s'", + (int)(ptrdiff_t)(p2 - str), str); return -1; } - p=p2; + p = p2; p++; } while (finish == 0); diff --git a/src/config.c b/src/config.c index c064729e..ba45e5d5 100644 --- a/src/config.c +++ b/src/config.c @@ -68,89 +68,105 @@ static char cfg_file[_POSIX_PATH_MAX] = DEFAULT_CFG_FILE; static void archive_cfg(struct list_head *head); static void clear_cfg(struct list_head *head); -static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned silent); +static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, + unsigned int silent); #define ERRSTR "error: " #define WARNSTR "warning: " #define NOTESTR "note: " -#define READ_MULTI_LINE(varname, num) { \ - if (_add_multi_line_val(pool, &varname, &num, value) < 0) { \ - fprintf(stderr, ERRSTR"memory\n"); \ - exit(EXIT_FAILURE); \ - }} - -#define READ_MULTI_BRACKET_LINE(varname, varname2, num) { \ - if (varname == NULL || varname2 == NULL) { \ - num = 0; \ - varname = talloc_size(pool, sizeof(char*)*DEFAULT_CONFIG_ENTRIES); \ - varname2 = talloc_size(pool, sizeof(char*)*DEFAULT_CONFIG_ENTRIES); \ - if (varname == NULL || varname2 == NULL) { \ - fprintf(stderr, ERRSTR"memory\n"); \ - exit(EXIT_FAILURE); \ - } \ - } \ - if (num < DEFAULT_CONFIG_ENTRIES) { \ - char *xp; \ - varname[num] = talloc_strdup(pool, value); \ - xp = strchr(varname[num], '['); if (xp != NULL) *xp = 0; \ - varname2[num] = get_brackets_string1(pool, value); \ - num++; \ - varname[num] = NULL; \ - varname2[num] = NULL; \ - }} - -#define PREAD_STRING(pool, varname) { \ - unsigned len = strlen(value); \ - while (len > 0 && isspace(value[len-1])) \ - len--; \ - varname = talloc_strndup(pool, value, len); \ +#define READ_MULTI_LINE(varname, num) \ + { \ + if (_add_multi_line_val(pool, &varname, &num, value) < 0) { \ + fprintf(stderr, ERRSTR "memory\n"); \ + exit(EXIT_FAILURE); \ + } \ } -#define READ_STRING(varname) \ - PREAD_STRING(pool, varname) - -#define READ_STATIC_STRING(varname) { \ - strlcpy(varname, value, sizeof(varname)); \ +#define READ_MULTI_BRACKET_LINE(varname, varname2, num) \ + { \ + if (varname == NULL || varname2 == NULL) { \ + num = 0; \ + varname = talloc_size(pool, \ + sizeof(char *) * \ + DEFAULT_CONFIG_ENTRIES); \ + varname2 = talloc_size( \ + pool, \ + sizeof(char *) * DEFAULT_CONFIG_ENTRIES); \ + if (varname == NULL || varname2 == NULL) { \ + fprintf(stderr, ERRSTR "memory\n"); \ + exit(EXIT_FAILURE); \ + } \ + } \ + if (num < DEFAULT_CONFIG_ENTRIES) { \ + char *xp; \ + varname[num] = talloc_strdup(pool, value); \ + xp = strchr(varname[num], '['); \ + if (xp != NULL) \ + *xp = 0; \ + varname2[num] = get_brackets_string1(pool, value); \ + num++; \ + varname[num] = NULL; \ + varname2[num] = NULL; \ + } \ } -#define READ_TF(varname) { \ - if (strcasecmp(value, "true") == 0 || strcasecmp(value, "yes") == 0) \ - varname = 1; \ - else \ - varname = 0; \ +#define PREAD_STRING(pool, varname) \ + { \ + unsigned int len = strlen(value); \ + while (len > 0 && isspace(value[len - 1])) \ + len--; \ + varname = talloc_strndup(pool, value, len); \ } -#define READ_NUMERIC(varname) { \ - varname = strtol(value, NULL, 10); \ +#define READ_STRING(varname) PREAD_STRING(pool, varname) + +#define READ_STATIC_STRING(varname) \ + { \ + strlcpy(varname, value, sizeof(varname)); \ } -#define READ_PRIO_TOS(varname) { \ - if (strncmp(value, "0x", 2) == 0) { \ - varname = strtol(value, NULL, 16); \ - varname = TOS_PACK(varname); \ - } else { \ +#define READ_TF(varname) \ + { \ + if (strcasecmp(value, "true") == 0 || \ + strcasecmp(value, "yes") == 0) \ + varname = 1; \ + else \ + varname = 0; \ + } + +#define READ_NUMERIC(varname) \ + { \ varname = strtol(value, NULL, 10); \ - varname++; \ - }} + } -struct snapshot_t * config_snapshot = NULL; +#define READ_PRIO_TOS(varname) \ + { \ + if (strncmp(value, "0x", 2) == 0) { \ + varname = strtol(value, NULL, 16); \ + varname = TOS_PACK(varname); \ + } else { \ + varname = strtol(value, NULL, 10); \ + varname++; \ + } \ + } -char ** pam_auth_group_list = NULL; -char ** gssapi_auth_group_list = NULL; -char ** plain_auth_group_list = NULL; -unsigned pam_auth_group_list_size = 0; -unsigned gssapi_auth_group_list_size = 0; -unsigned plain_auth_group_list_size = 0; +struct snapshot_t *config_snapshot; +char **pam_auth_group_list; +char **gssapi_auth_group_list; +char **plain_auth_group_list; +unsigned int pam_auth_group_list_size; +unsigned int gssapi_auth_group_list_size; +unsigned int plain_auth_group_list_size; /* Parses the string ::1/prefix, to return prefix * and modify the string to contain the network only. */ -unsigned extract_prefix(char *network) +unsigned int extract_prefix(char *network) { char *p; - unsigned prefix; + unsigned int prefix; if (network == NULL) return 0; @@ -160,7 +176,7 @@ unsigned extract_prefix(char *network) if (p == NULL) return 0; - prefix = atoi(p+1); + prefix = atoi(p + 1); *p = 0; return prefix; @@ -168,41 +184,52 @@ unsigned extract_prefix(char *network) typedef struct auth_types_st { const char *name; - unsigned name_size; + unsigned int name_size; const struct auth_mod_st *mod; - unsigned type; - void *(*get_brackets_string)(void *pool, struct perm_cfg_st *config, const char *); + unsigned int type; + void *(*get_brackets_string)(void *pool, struct perm_cfg_st *config, + const char *); } auth_types_st; -#define NAME(x) (x),(sizeof(x)-1) -static auth_types_st avail_auth_types[] = -{ +#define NAME(x) (x), (sizeof(x) - 1) +static auth_types_st avail_auth_types[] = { + #ifdef HAVE_PAM - {NAME("pam"), &pam_auth_funcs, AUTH_TYPE_PAM, pam_get_brackets_string}, + { NAME("pam"), &pam_auth_funcs, AUTH_TYPE_PAM, + pam_get_brackets_string }, #endif #ifdef HAVE_GSSAPI - {NAME("gssapi"), &gssapi_auth_funcs, AUTH_TYPE_GSSAPI, gssapi_get_brackets_string}, + { NAME("gssapi"), &gssapi_auth_funcs, AUTH_TYPE_GSSAPI, + gssapi_get_brackets_string }, #endif #ifdef HAVE_RADIUS - {NAME("radius"), &radius_auth_funcs, AUTH_TYPE_RADIUS, radius_get_brackets_string}, + { NAME("radius"), &radius_auth_funcs, AUTH_TYPE_RADIUS, + radius_get_brackets_string }, #endif - {NAME("plain"), &plain_auth_funcs, AUTH_TYPE_PLAIN, plain_get_brackets_string}, - {NAME("certificate"), NULL, AUTH_TYPE_CERTIFICATE, NULL}, + { NAME("plain"), &plain_auth_funcs, AUTH_TYPE_PLAIN, + plain_get_brackets_string }, + { NAME("certificate"), NULL, AUTH_TYPE_CERTIFICATE, NULL }, #ifdef SUPPORT_OIDC_AUTH - {NAME("oidc"), &oidc_auth_funcs, AUTH_TYPE_OIDC, oidc_get_brackets_string}, + { NAME("oidc"), &oidc_auth_funcs, AUTH_TYPE_OIDC, + oidc_get_brackets_string }, #endif }; -static void check_for_duplicate_password_auth(struct perm_cfg_st *config, const char *vhostname, unsigned type) +static void check_for_duplicate_password_auth(struct perm_cfg_st *config, + const char *vhostname, + unsigned int type) { - unsigned i; + unsigned int i; if (type & AUTH_TYPE_USERNAME_PASS) { - for (i=0;iauth[i].enabled == 0) break; if (config->auth[i].type & AUTH_TYPE_USERNAME_PASS) { - fprintf(stderr, ERRSTR"%s: you cannot mix multiple password authentication methods\n", vhostname); + fprintf(stderr, + ERRSTR + "%s: you cannot mix multiple password authentication methods\n", + vhostname); exit(EXIT_FAILURE); } } @@ -210,11 +237,12 @@ static void check_for_duplicate_password_auth(struct perm_cfg_st *config, const } static void figure_auth_funcs(void *pool, const char *vhostname, - struct perm_cfg_st *config, char **auth, unsigned auth_size, - unsigned primary, unsigned is_worker) + struct perm_cfg_st *config, char **auth, + unsigned int auth_size, unsigned int primary, + unsigned int is_worker) { - unsigned j, i; - unsigned found; + unsigned int j, i; + unsigned int found; if (auth == NULL) return; @@ -224,27 +252,52 @@ static void figure_auth_funcs(void *pool, const char *vhostname, if (primary != 0) { /* Set the primary authentication methods */ - for (j=0;jauth[0].additional = avail_auth_types[i].get_brackets_string(pool, config, auth[j]+avail_auth_types[i].name_size); + for (i = 0; i < ARRAY_SIZE(avail_auth_types); i++) { + if (strncasecmp( + auth[j], avail_auth_types[i].name, + avail_auth_types[i].name_size) == + 0) { + if (avail_auth_types[i] + .get_brackets_string) + config->auth[0].additional = + avail_auth_types[i].get_brackets_string( + pool, config, + auth[j] + + avail_auth_types[i] + .name_size); - if (config->auth[0].amod != NULL && avail_auth_types[i].mod != NULL) { - fprintf(stderr, ERRSTR"%s: you cannot mix multiple authentication methods of %s type\n", vhostname, auth[j]); + if (config->auth[0].amod != NULL && + avail_auth_types[i].mod != NULL) { + fprintf(stderr, + ERRSTR + "%s: you cannot mix multiple authentication methods of %s type\n", + vhostname, auth[j]); exit(EXIT_FAILURE); } if (config->auth[0].amod == NULL) - config->auth[0].amod = avail_auth_types[i].mod; - config->auth[0].type |= avail_auth_types[i].type; + config->auth[0].amod = + avail_auth_types[i].mod; + config->auth[0].type |= + avail_auth_types[i].type; if (config->auth[0].name == NULL) { - config->auth[0].name = talloc_strdup(pool, avail_auth_types[i].name); + config->auth[0] + .name = talloc_strdup( + pool, + avail_auth_types[i] + .name); } else { char *tmp; - tmp = talloc_asprintf(pool, "%s+%s", config->auth[0].name, avail_auth_types[i].name); - talloc_free(config->auth[0].name); + + tmp = talloc_asprintf( + pool, "%s+%s", + config->auth[0].name, + avail_auth_types[i] + .name); + talloc_free( + config->auth[0].name); config->auth[0].name = tmp; } config->auth[0].enabled = 1; @@ -255,36 +308,64 @@ static void figure_auth_funcs(void *pool, const char *vhostname, } if (found == 0) { - fprintf(stderr, ERRSTR"%s: unknown or unsupported auth method: %s\n", vhostname, auth[j]); + fprintf(stderr, + ERRSTR + "%s: unknown or unsupported auth method: %s\n", + vhostname, auth[j]); exit(EXIT_FAILURE); } talloc_free(auth[j]); } if (!is_worker) - fprintf(stderr, NOTESTR"%s: setting '%s' as primary authentication method\n", vhostname, config->auth[0].name); + fprintf(stderr, + NOTESTR + "%s: setting '%s' as primary authentication method\n", + vhostname, config->auth[0].name); } else { - unsigned x = config->auth_methods; + unsigned int x = config->auth_methods; /* Append authentication methods (alternative options) */ - for (j=0;jauth[x].additional = avail_auth_types[i].get_brackets_string(pool, config, auth[j]+avail_auth_types[i].name_size); + for (i = 0; i < ARRAY_SIZE(avail_auth_types); i++) { + if (strncasecmp( + auth[j], avail_auth_types[i].name, + avail_auth_types[i].name_size) == + 0) { + if (avail_auth_types[i] + .get_brackets_string) + config->auth[x].additional = + avail_auth_types[i].get_brackets_string( + pool, config, + auth[j] + + avail_auth_types[i] + .name_size); - config->auth[x].name = talloc_strdup(pool, avail_auth_types[i].name); + config->auth[x].name = talloc_strdup( + pool, avail_auth_types[i].name); if (!is_worker) - fprintf(stderr, NOTESTR"%s: enabling '%s' as authentication method\n", vhostname, avail_auth_types[i].name); + fprintf(stderr, + NOTESTR + "%s: enabling '%s' as authentication method\n", + vhostname, + avail_auth_types[i] + .name); - check_for_duplicate_password_auth(config, vhostname, avail_auth_types[i].type); - config->auth[x].amod = avail_auth_types[i].mod; - config->auth[x].type |= avail_auth_types[i].type; + check_for_duplicate_password_auth( + config, vhostname, + avail_auth_types[i].type); + config->auth[x].amod = + avail_auth_types[i].mod; + config->auth[x].type |= + avail_auth_types[i].type; config->auth[x].enabled = 1; found = 1; x++; if (x >= MAX_AUTH_METHODS) { - fprintf(stderr, ERRSTR"%s: you cannot enable more than %d authentication methods\n", vhostname, x); + fprintf(stderr, + ERRSTR + "%s: you cannot enable more than %d authentication methods\n", + vhostname, x); exit(EXIT_FAILURE); } break; @@ -292,7 +373,10 @@ static void figure_auth_funcs(void *pool, const char *vhostname, } if (found == 0) { - fprintf(stderr, ERRSTR"%s: unknown or unsupported auth method: %s\n", vhostname, auth[j]); + fprintf(stderr, + ERRSTR + "%s: unknown or unsupported auth method: %s\n", + vhostname, auth[j]); exit(EXIT_FAILURE); } talloc_free(auth[j]); @@ -304,41 +388,52 @@ static void figure_auth_funcs(void *pool, const char *vhostname, typedef struct acct_types_st { const char *name; - unsigned name_size; + unsigned int name_size; const struct acct_mod_st *mod; - void *(*get_brackets_string)(void *pool, struct perm_cfg_st *config, const char *); + void *(*get_brackets_string)(void *pool, struct perm_cfg_st *config, + const char *); } acct_types_st; -static acct_types_st avail_acct_types[] = -{ +static acct_types_st avail_acct_types[] = { + #ifdef HAVE_RADIUS - {NAME("radius"), &radius_acct_funcs, radius_get_brackets_string}, + { NAME("radius"), &radius_acct_funcs, radius_get_brackets_string }, #endif #ifdef HAVE_PAM - {NAME("pam"), &pam_acct_funcs, NULL}, + { NAME("pam"), &pam_acct_funcs, NULL }, #endif }; -static void figure_acct_funcs(void *pool, const char *vhostname, struct perm_cfg_st *config, - const char *acct, unsigned is_worker) +static void figure_acct_funcs(void *pool, const char *vhostname, + struct perm_cfg_st *config, const char *acct, + unsigned int is_worker) { - unsigned i; - unsigned found = 0; + unsigned int i; + unsigned int found = 0; if (acct == NULL) return; /* Set the accounting method */ - for (i=0;iacct.additional = avail_acct_types[i].get_brackets_string(pool, config, acct+avail_acct_types[i].name_size); + config->acct.additional = + avail_acct_types[i].get_brackets_string( + pool, config, + acct + avail_acct_types[i] + .name_size); - if ((avail_acct_types[i].mod->auth_types & config->auth[0].type) == 0) { - fprintf(stderr, ERRSTR"%s: you cannot mix the '%s' accounting method with the '%s' authentication method\n", vhostname, acct, config->auth[0].name); + if ((avail_acct_types[i].mod->auth_types & + config->auth[0].type) == 0) { + fprintf(stderr, + ERRSTR + "%s: you cannot mix the '%s' accounting method with the '%s' authentication method\n", + vhostname, acct, config->auth[0].name); exit(EXIT_FAILURE); } @@ -350,47 +445,53 @@ static void figure_acct_funcs(void *pool, const char *vhostname, struct perm_cfg } if (found == 0) { - fprintf(stderr, ERRSTR"%s: unknown or unsupported accounting method: %s\n", vhostname, acct); + fprintf(stderr, + ERRSTR + "%s: unknown or unsupported accounting method: %s\n", + vhostname, acct); exit(EXIT_FAILURE); } if (!is_worker) - fprintf(stderr, NOTESTR"%ssetting '%s' as accounting method\n", vhostname, config->acct.name); + fprintf(stderr, NOTESTR "%ssetting '%s' as accounting method\n", + vhostname, config->acct.name); } #ifdef HAVE_GSSAPI -static void parse_kkdcp(struct cfg_st *config, char **urlfw, unsigned urlfw_size) +static void parse_kkdcp(struct cfg_st *config, char **urlfw, + unsigned int urlfw_size) { - unsigned i, j; + unsigned int i, j; char *path, *server, *port, *realm; struct addrinfo hints, *res; int ret; struct kkdcp_st *kkdcp; struct kkdcp_realm_st *kkdcp_realm; - config->kkdcp = talloc_zero_size(config, urlfw_size*sizeof(kkdcp_st)); + config->kkdcp = talloc_zero_size(config, urlfw_size * sizeof(kkdcp_st)); if (config->kkdcp == NULL) { - fprintf(stderr, ERRSTR"memory\n"); + fprintf(stderr, ERRSTR "memory\n"); exit(EXIT_FAILURE); } config->kkdcp_size = 0; - for (i=0;ikkdcp_size;j++) { + for (j = 0; j < config->kkdcp_size; j++) { if (strcmp(path, config->kkdcp[j].url) == 0) { kkdcp = &config->kkdcp[j]; } @@ -403,7 +504,10 @@ static void parse_kkdcp(struct cfg_st *config, char **urlfw, unsigned urlfw_size } if (kkdcp->realms_size >= MAX_KRB_REALMS) { - fprintf(stderr, ERRSTR"reached maximum number (%d) of realms per URL\n", MAX_KRB_REALMS); + fprintf(stderr, + ERRSTR + "reached maximum number (%d) of realms per URL\n", + MAX_KRB_REALMS); exit(EXIT_FAILURE); } @@ -420,7 +524,6 @@ static void parse_kkdcp(struct cfg_st *config, char **urlfw, unsigned urlfw_size freeaddrinfo(res); kkdcp->realms_size++; } - } #endif @@ -432,9 +535,9 @@ struct iroute_ctx { char *sanitize_config_value(void *pool, const char *value) { ssize_t len = strlen(value); - unsigned i = 0; + unsigned int i = 0; - while (isspace(value[len-1]) || value[len-1] == '"') + while (isspace(value[len - 1]) || value[len - 1] == '"') len--; while (isspace(value[i]) || value[i] == '"') { @@ -446,21 +549,22 @@ char *sanitize_config_value(void *pool, const char *value) return NULL; return talloc_strndup(pool, &value[i], len); - } -static int iroutes_handler(void *_ctx, const char *section, const char *name, const char* _value) +static int iroutes_handler(void *_ctx, const char *section, const char *name, + const char *_value) { struct iroute_ctx *ctx = _ctx; int ret; char *value; if (section != NULL && section[0] != 0) { - fprintf(stderr, WARNSTR"skipping unknown section '%s'\n", section); + fprintf(stderr, WARNSTR "skipping unknown section '%s'\n", + section); return 0; } - if (strcmp(name, "iroute")!=0) + if (strcmp(name, "iroute") != 0) return 0; value = sanitize_config_value(ctx->config, _value); @@ -468,9 +572,10 @@ static int iroutes_handler(void *_ctx, const char *section, const char *name, co return 0; ret = _add_multi_line_val(ctx->config, &ctx->config->known_iroutes, - &ctx->config->known_iroutes_size, value); + &ctx->config->known_iroutes_size, value); if (ret < 0) { - fprintf(stderr, ERRSTR"cannot load iroute from %s\n", ctx->file); + fprintf(stderr, ERRSTR "cannot load iroute from %s\n", + ctx->file); } talloc_free(value); @@ -481,7 +586,7 @@ static void append_iroutes_from_file(struct cfg_st *config, const char *file) { struct iroute_ctx ctx; int ret; - unsigned j; + unsigned int j; ctx.file = file; ctx.config = config; @@ -490,8 +595,9 @@ static void append_iroutes_from_file(struct cfg_st *config, const char *file) if (ret != 0) return; - for (j=0;jknown_iroutes_size;j++) { - if (ip_route_sanity_check(config->known_iroutes, &config->known_iroutes[j]) != 0) + for (j = 0; j < config->known_iroutes_size; j++) { + if (ip_route_sanity_check(config->known_iroutes, + &config->known_iroutes[j]) != 0) exit(EXIT_FAILURE); } } @@ -511,9 +617,13 @@ static void load_iroutes(struct cfg_st *config) do { r = readdir(dir); if (r != NULL && r->d_type == DT_REG) { - ret = snprintf(path, sizeof(path), "%s/%s", config->per_user_dir, r->d_name); + ret = snprintf(path, sizeof(path), "%s/%s", + config->per_user_dir, r->d_name); if (ret != (int)strlen(path)) { - fprintf(stderr, NOTESTR"path name too long and truncated: %s\n", path); + fprintf(stderr, + NOTESTR + "path name too long and truncated: %s\n", + path); } append_iroutes_from_file(config, path); } @@ -522,26 +632,30 @@ static void load_iroutes(struct cfg_st *config) } } -static void apply_default_conf(vhost_cfg_st *vhost, unsigned reload) +static void apply_default_conf(vhost_cfg_st *vhost, unsigned int reload) { /* set config (no-zero) default vals */ if (!reload) { /* perm config defaults */ tls_vhost_init(vhost); - vhost->perm_config.stats_reset_time = 24*60*60*7; /* weekly */ + vhost->perm_config.stats_reset_time = + 24 * 60 * 60 * 7; /* weekly */ vhost->perm_config.log_level = DEFAULT_LOG_LEVEL; } - vhost->perm_config.config->mobile_idle_timeout = (unsigned)-1; + vhost->perm_config.config->mobile_idle_timeout = (unsigned int)-1; #ifdef ENABLE_COMPRESSION - vhost->perm_config.config->no_compress_limit = DEFAULT_NO_COMPRESS_LIMIT; + vhost->perm_config.config->no_compress_limit = + DEFAULT_NO_COMPRESS_LIMIT; #endif - vhost->perm_config.config->rekey_time = 24*60*60; - vhost->perm_config.config->cookie_timeout = DEFAULT_COOKIE_RECON_TIMEOUT; + vhost->perm_config.config->rekey_time = 24 * 60 * 60; + vhost->perm_config.config->cookie_timeout = + DEFAULT_COOKIE_RECON_TIMEOUT; vhost->perm_config.config->auth_timeout = DEFAULT_AUTH_TIMEOUT_SECS; vhost->perm_config.config->ban_reset_time = DEFAULT_BAN_RESET_TIME; vhost->perm_config.config->max_ban_score = DEFAULT_MAX_BAN_SCORE; - vhost->perm_config.config->ban_points_wrong_password = DEFAULT_PASSWORD_POINTS; + vhost->perm_config.config->ban_points_wrong_password = + DEFAULT_PASSWORD_POINTS; vhost->perm_config.config->ban_points_connect = DEFAULT_CONNECT_POINTS; vhost->perm_config.config->ban_points_kkdcp = DEFAULT_KKDCP_POINTS; vhost->perm_config.config->dpd = DEFAULT_DPD_TIME; @@ -552,25 +666,26 @@ static void apply_default_conf(vhost_cfg_st *vhost, unsigned reload) vhost->perm_config.config->use_utmp = 1; vhost->perm_config.config->keepalive = 3600; vhost->perm_config.config->dpd = 60; - } -static void cfg_new(struct vhost_cfg_st *vhost, unsigned reload) +static void cfg_new(struct vhost_cfg_st *vhost, unsigned int reload) { vhost->perm_config.config = talloc_zero(vhost->pool, struct cfg_st); if (vhost->perm_config.config == NULL) exit(EXIT_FAILURE); - vhost->perm_config.config->usage_count = talloc_zero(vhost->perm_config.config, int); + vhost->perm_config.config->usage_count = + talloc_zero(vhost->perm_config.config, int); if (vhost->perm_config.config->usage_count == NULL) { - fprintf(stderr, ERRSTR"memory\n"); + fprintf(stderr, ERRSTR "memory\n"); exit(EXIT_FAILURE); } apply_default_conf(vhost, reload); } -static vhost_cfg_st *vhost_add(void *pool, struct list_head *head, const char *name, unsigned reload) +static vhost_cfg_st *vhost_add(void *pool, struct list_head *head, + const char *name, unsigned int reload) { vhost_cfg_st *vhost; @@ -584,7 +699,7 @@ static vhost_cfg_st *vhost_add(void *pool, struct list_head *head, const char *n if (name) { vhost->name = talloc_strdup(vhost, name); if (vhost->name == NULL) { - fprintf(stderr, ERRSTR"memory\n"); + fprintf(stderr, ERRSTR "memory\n"); exit(EXIT_FAILURE); } } @@ -592,7 +707,6 @@ static vhost_cfg_st *vhost_add(void *pool, struct list_head *head, const char *n vhost->perm_config.sup_config_type = SUP_CONFIG_FILE; list_head_init(&vhost->perm_config.attic); - list_add(head, &vhost->list); return vhost; @@ -600,60 +714,76 @@ static vhost_cfg_st *vhost_add(void *pool, struct list_head *head, const char *n struct ini_ctx_st { struct list_head *head; - unsigned reload; - unsigned is_worker; + unsigned int reload; + unsigned int is_worker; const char *file; void *pool; }; -#define WARN_ON_VHOST_ONLY(vname, oname) \ - ({int rval; \ - if (vname) { \ - fprintf(stderr, WARNSTR"%s is ignored on %s virtual host\n", oname, vname); \ - rval = 1; \ - } else { \ - rval = 0; \ - } \ - rval; \ +#define WARN_ON_VHOST_ONLY(vname, oname) \ + ({ \ + int rval; \ + if (vname) { \ + fprintf(stderr, \ + WARNSTR "%s is ignored on %s virtual host\n", \ + oname, vname); \ + rval = 1; \ + } else { \ + rval = 0; \ + } \ + rval; \ }) -#define WARN_ON_VHOST(vname, oname, member) \ - ({int rval; \ - if (vname) { \ - fprintf(stderr, WARNSTR"%s is ignored on %s virtual host\n", oname, vname); \ - memcpy(&config->member, &defvhost->perm_config.config->member, sizeof(config->member)); \ - rval = 1; \ - } else { \ - rval = 0; \ - } \ - rval; \ +#define WARN_ON_VHOST(vname, oname, member) \ + ({ \ + int rval; \ + if (vname) { \ + fprintf(stderr, \ + WARNSTR "%s is ignored on %s virtual host\n", \ + oname, vname); \ + memcpy(&config->member, \ + &defvhost->perm_config.config->member, \ + sizeof(config->member)); \ + rval = 1; \ + } else { \ + rval = 0; \ + } \ + rval; \ }) -#define PWARN_ON_VHOST(vname, oname, member) \ - ({int rval; \ - if (vname) { \ - fprintf(stderr, WARNSTR"%s is ignored on %s virtual host\n", oname, vname); \ - vhost->perm_config.member = defvhost->perm_config.member; \ - rval = 1; \ - } else { \ - rval = 0; \ - } \ - rval; \ +#define PWARN_ON_VHOST(vname, oname, member) \ + ({ \ + int rval; \ + if (vname) { \ + fprintf(stderr, \ + WARNSTR "%s is ignored on %s virtual host\n", \ + oname, vname); \ + vhost->perm_config.member = \ + defvhost->perm_config.member; \ + rval = 1; \ + } else { \ + rval = 0; \ + } \ + rval; \ }) -#define PWARN_ON_VHOST_STRDUP(vname, oname, member) \ - ({int rval; \ - if (vname) { \ - fprintf(stderr, WARNSTR"%s is ignored on %s virtual host\n", oname, vname); \ - vhost->perm_config.member = talloc_strdup(pool, defvhost->perm_config.member); \ - rval = 1; \ - } else { \ - rval = 0; \ - } \ - rval; \ +#define PWARN_ON_VHOST_STRDUP(vname, oname, member) \ + ({ \ + int rval; \ + if (vname) { \ + fprintf(stderr, \ + WARNSTR "%s is ignored on %s virtual host\n", \ + oname, vname); \ + vhost->perm_config.member = talloc_strdup( \ + pool, defvhost->perm_config.member); \ + rval = 1; \ + } else { \ + rval = 0; \ + } \ + rval; \ }) -static char *idna_map(void *pool, const char *name, unsigned size) +static char *idna_map(void *pool, const char *name, unsigned int size) { #if GNUTLS_VERSION_NUMBER > 0x030508 int ret; @@ -664,15 +794,14 @@ static char *idna_map(void *pool, const char *name, unsigned size) goto fallback; } - return talloc_strdup(pool, (char*)out.data); + return talloc_strdup(pool, (char *)out.data); - fallback: +fallback: #endif return talloc_strndup(pool, name, size); } -static -char *sanitize_name(void *pool, const char *p) +static char *sanitize_name(void *pool, const char *p) { size_t len; /* cleanup spaces before and after */ @@ -681,28 +810,29 @@ char *sanitize_name(void *pool, const char *p) len = strlen(p); if (len > 0) { - while (isspace(p[len-1])) + while (isspace(p[len - 1])) len--; } return idna_map(pool, p, len); } -static int cfg_ini_handler(void *_ctx, const char *section, const char *name, const char *_value) +static int cfg_ini_handler(void *_ctx, const char *section, const char *name, + const char *_value) { struct ini_ctx_st *ctx = _ctx; vhost_cfg_st *vhost, *vtmp = NULL, *defvhost; - unsigned use_dbus; + unsigned int use_dbus; struct cfg_st *config; void *pool; - unsigned reload = ctx->reload; - unsigned is_worker = ctx->is_worker; + unsigned int reload = ctx->reload; + unsigned int is_worker = ctx->is_worker; int ret; - unsigned stage1_found = 1; - unsigned force_cert_auth; - unsigned prefix = 0; - unsigned prefix4 = 0; - unsigned found_vhost; + unsigned int stage1_found = 1; + unsigned int force_cert_auth; + unsigned int prefix = 0; + unsigned int prefix4 = 0; + unsigned int found_vhost; char *value; defvhost = vhost = default_vhost(ctx->head); @@ -714,19 +844,25 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co if (strncmp(section, "vhost:", 6) != 0) { if (reload == 0 && is_worker == 0) - fprintf(stderr, WARNSTR"skipping unknown section '%s'\n", section); + fprintf(stderr, + WARNSTR + "skipping unknown section '%s'\n", + section); return 1; } - vname = sanitize_name(ctx->pool, section+6); + vname = sanitize_name(ctx->pool, section + 6); if (vname == NULL || vname[0] == 0) { - fprintf(stderr, ERRSTR"virtual host name is illegal '%s'\n", section+6); + fprintf(stderr, + ERRSTR "virtual host name is illegal '%s'\n", + section + 6); return 0; } /* virtual host */ found_vhost = 0; - list_for_each(ctx->head, vtmp, list) { + list_for_each(ctx->head, vtmp, list) + { if (vtmp->name && strcmp(vtmp->name, vname) == 0) { vhost = vtmp; found_vhost = 1; @@ -734,16 +870,20 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } } - if (strcasecmp(section+6, vname) != 0) { + if (strcasecmp(section + 6, vname) != 0) { if (reload == 0 && is_worker == 0) - fprintf(stderr, NOTESTR"virtual host name '%s' was canonicalized to '%s'\n", - section+6, vname); + fprintf(stderr, + NOTESTR + "virtual host name '%s' was canonicalized to '%s'\n", + section + 6, vname); } if (!found_vhost) { /* add */ if (reload == 0 && is_worker == 0) - fprintf(stderr, NOTESTR"adding virtual host: %s\n", vname); + fprintf(stderr, + NOTESTR "adding virtual host: %s\n", + vname); vhost = vhost_add(ctx->pool, ctx->head, vname, reload); } talloc_free(vname); @@ -768,10 +908,12 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "udp-listen-host") == 0) { PREAD_STRING(pool, vhost->perm_config.udp_listen_host); } else if (strcmp(name, "listen-clear-file") == 0) { - fprintf(stderr, ERRSTR"the 'listen-clear-file' option was removed in ocserv 1.1.2\n"); + fprintf(stderr, ERRSTR + "the 'listen-clear-file' option was removed in ocserv 1.1.2\n"); return 0; } else if (strcmp(name, "listen-netns") == 0) { - vhost->perm_config.listen_netns_name = talloc_strdup(pool, value); + vhost->perm_config.listen_netns_name = + talloc_strdup(pool, value); } else if (strcmp(name, "tcp-port") == 0) { if (!PWARN_ON_VHOST(vhost->name, "tcp-port", port)) READ_NUMERIC(vhost->perm_config.port); @@ -780,26 +922,34 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co READ_NUMERIC(vhost->perm_config.udp_port); } else if (strcmp(name, "run-as-user") == 0) { if (!PWARN_ON_VHOST(vhost->name, "run-as-user", uid)) { - const struct passwd* pwd = getpwnam(value); + const struct passwd *pwd = getpwnam(value); + if (pwd == NULL) { - fprintf(stderr, ERRSTR"unknown user: %s\n", value); + fprintf(stderr, + ERRSTR "unknown user: %s\n", + value); return 0; } vhost->perm_config.uid = pwd->pw_uid; } } else if (strcmp(name, "run-as-group") == 0) { if (!PWARN_ON_VHOST(vhost->name, "run-as-group", gid)) { - const struct group* grp = getgrnam(value); + const struct group *grp = getgrnam(value); + if (grp == NULL) { - fprintf(stderr, ERRSTR"unknown group: %s\n", value); + fprintf(stderr, + ERRSTR "unknown group: %s\n", + value); return 0; } vhost->perm_config.gid = grp->gr_gid; } } else if (strcmp(name, "server-cert") == 0) { - READ_MULTI_LINE(vhost->perm_config.cert, vhost->perm_config.cert_size); + READ_MULTI_LINE(vhost->perm_config.cert, + vhost->perm_config.cert_size); } else if (strcmp(name, "server-key") == 0) { - READ_MULTI_LINE(vhost->perm_config.key, vhost->perm_config.key_size); + READ_MULTI_LINE(vhost->perm_config.key, + vhost->perm_config.key_size); } else if (strcmp(name, "debug-no-secmod-stats") == 0) { READ_TF(vhost->perm_config.debug_no_secmod_stats); } else if (strcmp(name, "dh-params") == 0) { @@ -817,26 +967,40 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co READ_STRING(vhost->perm_config.srk_pin); #endif } else if (strcmp(name, "socket-file") == 0) { - if (!PWARN_ON_VHOST_STRDUP(vhost->name, "socket-file", socket_file_prefix)) - PREAD_STRING(pool, vhost->perm_config.socket_file_prefix); + if (!PWARN_ON_VHOST_STRDUP(vhost->name, "socket-file", + socket_file_prefix)) + PREAD_STRING( + pool, + vhost->perm_config.socket_file_prefix); } else if (strcmp(name, "occtl-socket-file") == 0) { - if (!PWARN_ON_VHOST_STRDUP(vhost->name, "occtl-socket-file", occtl_socket_file)) - PREAD_STRING(pool, vhost->perm_config.occtl_socket_file); + if (!PWARN_ON_VHOST_STRDUP(vhost->name, + "occtl-socket-file", + occtl_socket_file)) + PREAD_STRING( + pool, + vhost->perm_config.occtl_socket_file); } else if (strcmp(name, "chroot-dir") == 0) { - if (!PWARN_ON_VHOST_STRDUP(vhost->name, "chroot-dir", chroot_dir)) - PREAD_STRING(pool, vhost->perm_config.chroot_dir); + if (!PWARN_ON_VHOST_STRDUP(vhost->name, "chroot-dir", + chroot_dir)) + PREAD_STRING(pool, + vhost->perm_config.chroot_dir); } else if (strcmp(name, "server-stats-reset-time") == 0) { /* cannot be modified as it would require sec-mod to * re-read configuration too */ - if (!PWARN_ON_VHOST(vhost->name, "server-stats-reset-time", stats_reset_time)) - READ_NUMERIC(vhost->perm_config.stats_reset_time); + if (!PWARN_ON_VHOST(vhost->name, + "server-stats-reset-time", + stats_reset_time)) + READ_NUMERIC( + vhost->perm_config.stats_reset_time); } else if (strcmp(name, "pid-file") == 0) { if (pid_file[0] == 0) { READ_STATIC_STRING(pid_file); } else if (reload == 0 && !ctx->is_worker) - fprintf(stderr, NOTESTR"skipping 'pid-file' config option\n"); + fprintf(stderr, NOTESTR + "skipping 'pid-file' config option\n"); } else if (strcmp(name, "sec-mod-scale") == 0) { - if (!PWARN_ON_VHOST(vhost->name, "sec-mod-scale", sec_mod_scale)) + if (!PWARN_ON_VHOST(vhost->name, "sec-mod-scale", + sec_mod_scale)) READ_NUMERIC(vhost->perm_config.sec_mod_scale); } else if (strcmp(name, "log-level") == 0) { READ_NUMERIC(vhost->perm_config.log_level); @@ -848,7 +1012,6 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co goto exit; } - /* read the rest of the (non-permanent) configuration */ pool = vhost->perm_config.config; config = vhost->perm_config.config; @@ -859,7 +1022,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co if (strcmp(name, "listen-host-is-dyndns") == 0) { READ_TF(config->is_dyndns); } else if (strcmp(name, "listen-proxy-proto") == 0) { - if (!WARN_ON_VHOST(vhost->name, "listen-proxy-proto", listen_proxy_proto)) + if (!WARN_ON_VHOST(vhost->name, "listen-proxy-proto", + listen_proxy_proto)) READ_TF(config->listen_proxy_proto); } else if (strcmp(name, "append-routes") == 0) { READ_TF(config->append_routes); @@ -881,7 +1045,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co if (!WARN_ON_VHOST(vhost->name, "rate-limit-ms", rate_limit_ms)) READ_NUMERIC(config->rate_limit_ms); } else if (strcmp(name, "server-drain-ms") == 0) { - if (!WARN_ON_VHOST(vhost->name, "server-drain-ms", server_drain_ms)) + if (!WARN_ON_VHOST(vhost->name, "server-drain-ms", + server_drain_ms)) READ_NUMERIC(config->server_drain_ms); } else if (strcmp(name, "ocsp-response") == 0) { READ_STRING(config->ocsp_response); @@ -900,16 +1065,20 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "cert-group-oid") == 0) { READ_STRING(config->cert_group_oid); } else if (strcmp(name, "connect-script") == 0) { - if (!WARN_ON_VHOST(vhost->name, "connect-script", connect_script)) + if (!WARN_ON_VHOST(vhost->name, "connect-script", + connect_script)) READ_STRING(config->connect_script); } else if (strcmp(name, "host-update-script") == 0) { - if (!WARN_ON_VHOST(vhost->name, "host-update-script", host_update_script)) + if (!WARN_ON_VHOST(vhost->name, "host-update-script", + host_update_script)) READ_STRING(config->host_update_script); } else if (strcmp(name, "disconnect-script") == 0) { - if (!WARN_ON_VHOST(vhost->name, "disconnect-script", disconnect_script)) + if (!WARN_ON_VHOST(vhost->name, "disconnect-script", + disconnect_script)) READ_STRING(config->disconnect_script); } else if (strcmp(name, "session-control") == 0) { - fprintf(stderr, WARNSTR"the option 'session-control' is deprecated\n"); + fprintf(stderr, + WARNSTR "the option 'session-control' is deprecated\n"); } else if (strcmp(name, "banner") == 0) { READ_STRING(config->banner); } else if (strcmp(name, "pre-login-banner") == 0) { @@ -921,7 +1090,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "always-require-cert") == 0) { READ_TF(force_cert_auth); if (force_cert_auth == 0) { - fprintf(stderr, NOTESTR"'always-require-cert' was replaced by 'cisco-client-compat'\n"); + fprintf(stderr, NOTESTR + "'always-require-cert' was replaced by 'cisco-client-compat'\n"); config->cisco_client_compat = 1; } } else if (strcmp(name, "cisco-svc-client-compat") == 0) { @@ -935,10 +1105,14 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "compression") == 0) { READ_TF(config->enable_compression); } else if (strcmp(name, "compression-algo-priority") == 0) { - if (!WARN_ON_VHOST_ONLY(vhost->name, "compression-algo-priority")) { + if (!WARN_ON_VHOST_ONLY(vhost->name, + "compression-algo-priority")) { #if defined(OCSERV_WORKER_PROCESS) if (switch_comp_priority(pool, value) == 0) { - fprintf(stderr, WARNSTR"invalid compression modstring %s\n", value); + fprintf(stderr, + WARNSTR + "invalid compression modstring %s\n", + value); } #endif } @@ -948,7 +1122,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "use-seccomp") == 0) { READ_TF(config->isolate); if (config->isolate) - fprintf(stderr, NOTESTR"'use-seccomp' was replaced by 'isolate-workers'\n"); + fprintf(stderr, NOTESTR + "'use-seccomp' was replaced by 'isolate-workers'\n"); } else if (strcmp(name, "isolate-workers") == 0) { if (!WARN_ON_VHOST(vhost->name, "isolate-workers", isolate)) READ_TF(config->isolate); @@ -960,7 +1135,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "use-dbus") == 0) { READ_TF(use_dbus); if (use_dbus != 0) { - fprintf(stderr, NOTESTR"'use-dbus' was replaced by 'use-occtl'\n"); + fprintf(stderr, NOTESTR + "'use-dbus' was replaced by 'use-occtl'\n"); config->use_occtl = use_dbus; } } else if (strcmp(name, "use-occtl") == 0) { @@ -975,9 +1151,11 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "restrict-user-to-routes") == 0) { READ_TF(config->restrict_user_to_routes); } else if (strcmp(name, "restrict-user-to-ports") == 0) { - ret = cfg_parse_ports(pool, &config->fw_ports, &config->n_fw_ports, value); + ret = cfg_parse_ports(pool, &config->fw_ports, + &config->n_fw_ports, value); if (ret < 0) { - fprintf(stderr, ERRSTR"cannot parse restrict-user-to-ports\n"); + fprintf(stderr, + ERRSTR "cannot parse restrict-user-to-ports\n"); return 0; } } else if (strcmp(name, "tls-priorities") == 0) { @@ -1006,7 +1184,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co else if (strcmp(value, "new-tunnel") == 0) config->rekey_method = REKEY_METHOD_NEW_TUNNEL; else { - fprintf(stderr, ERRSTR"unknown rekey method '%s'\n", value); + fprintf(stderr, ERRSTR "unknown rekey method '%s'\n", + value); return 0; } } else if (strcmp(name, "cookie-timeout") == 0) { @@ -1026,22 +1205,27 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co if (!WARN_ON_VHOST(vhost->name, "max-clients", max_clients)) READ_NUMERIC(config->max_clients); } else if (strcmp(name, "min-reauth-time") == 0) { - if (!WARN_ON_VHOST(vhost->name, "min-reauth-time", min_reauth_time)) + if (!WARN_ON_VHOST(vhost->name, "min-reauth-time", + min_reauth_time)) READ_NUMERIC(config->min_reauth_time); } else if (strcmp(name, "ban-reset-time") == 0) { - if (!WARN_ON_VHOST(vhost->name, "ban-reset-time", ban_reset_time)) + if (!WARN_ON_VHOST(vhost->name, "ban-reset-time", + ban_reset_time)) READ_NUMERIC(config->ban_reset_time); } else if (strcmp(name, "max-ban-score") == 0) { if (!WARN_ON_VHOST(vhost->name, "max-ban-score", max_ban_score)) - READ_NUMERIC( config->max_ban_score); + READ_NUMERIC(config->max_ban_score); } else if (strcmp(name, "ban-points-wrong-password") == 0) { - if (!WARN_ON_VHOST(vhost->name, "ban-points-wrong-password", ban_points_wrong_password)) + if (!WARN_ON_VHOST(vhost->name, "ban-points-wrong-password", + ban_points_wrong_password)) READ_NUMERIC(config->ban_points_wrong_password); } else if (strcmp(name, "ban-points-connection") == 0) { - if (!WARN_ON_VHOST(vhost->name, "ban-points-connection", ban_points_connect)) + if (!WARN_ON_VHOST(vhost->name, "ban-points-connection", + ban_points_connect)) READ_NUMERIC(config->ban_points_connect); } else if (strcmp(name, "ban-points-kkdcp") == 0) { - if (!WARN_ON_VHOST(vhost->name, "ban-points-kkdcp", ban_points_kkdcp)) + if (!WARN_ON_VHOST(vhost->name, "ban-points-kkdcp", + ban_points_kkdcp)) READ_NUMERIC(config->ban_points_kkdcp); } else if (strcmp(name, "max-same-clients") == 0) { READ_NUMERIC(config->max_same_clients); @@ -1056,7 +1240,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co READ_STRING(config->network.ipv4); prefix4 = extract_prefix(config->network.ipv4); if (prefix4 != 0) { - config->network.ipv4_netmask = ipv4_prefix_to_strmask(config, prefix4); + config->network.ipv4_netmask = + ipv4_prefix_to_strmask(config, prefix4); } } else if (strcmp(name, "ipv4-netmask") == 0) { READ_STRING(config->network.ipv4_netmask); @@ -1069,7 +1254,8 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co READ_NUMERIC(config->network.ipv6_prefix); if (valid_ipv6_prefix(config->network.ipv6_prefix) == 0) { - fprintf(stderr, ERRSTR"invalid IPv6 prefix: %u\n", prefix); + fprintf(stderr, ERRSTR "invalid IPv6 prefix: %u\n", + prefix); return 0; } } else if (strcmp(name, "ipv6-subnet-prefix") == 0) { @@ -1079,24 +1265,32 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co config->network.ipv6_subnet_prefix = prefix; if (valid_ipv6_prefix(prefix) == 0) { - fprintf(stderr, ERRSTR"invalid IPv6 subnet prefix: %u\n", prefix); + fprintf(stderr, + ERRSTR + "invalid IPv6 subnet prefix: %u\n", + prefix); return 0; } } } else if (strcmp(name, "custom-header") == 0) { - READ_MULTI_LINE(config->custom_header, config->custom_header_size); + READ_MULTI_LINE(config->custom_header, + config->custom_header_size); } else if (strcmp(name, "split-dns") == 0) { READ_MULTI_LINE(config->split_dns, config->split_dns_size); - } else if (strcmp(name, "included-http-headers") == 0) { + } else if (strcmp(name, "included-http-headers") == 0) { // Don't use sanitized input since http header values can contain optional trailing blanks and double quotes - if (_add_multi_line_val(pool, &(config->included_http_headers), &(config->included_http_headers_size), _value) < 0) { - fprintf(stderr, ERRSTR"memory\n"); + if (_add_multi_line_val(pool, &(config->included_http_headers), + &(config->included_http_headers_size), + _value) < 0) { + fprintf(stderr, ERRSTR "memory\n"); exit(EXIT_FAILURE); } } else if (strcmp(name, "route") == 0) { - READ_MULTI_LINE(config->network.routes, config->network.routes_size); + READ_MULTI_LINE(config->network.routes, + config->network.routes_size); } else if (strcmp(name, "no-route") == 0) { - READ_MULTI_LINE(config->network.no_routes, config->network.no_routes_size); + READ_MULTI_LINE(config->network.no_routes, + config->network.no_routes_size); } else if (strcmp(name, "default-select-group") == 0) { READ_STRING(config->default_select_group); } else if (strcmp(name, "select-group-by-url") == 0) { @@ -1114,11 +1308,14 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co } else if (strcmp(name, "ipv6-dns") == 0) { READ_MULTI_LINE(config->network.dns, config->network.dns_size); } else if (strcmp(name, "nbns") == 0) { - READ_MULTI_LINE(config->network.nbns, config->network.nbns_size); + READ_MULTI_LINE(config->network.nbns, + config->network.nbns_size); } else if (strcmp(name, "ipv4-nbns") == 0) { - READ_MULTI_LINE(config->network.nbns, config->network.nbns_size); + READ_MULTI_LINE(config->network.nbns, + config->network.nbns_size); } else if (strcmp(name, "ipv6-nbns") == 0) { - READ_MULTI_LINE(config->network.nbns, config->network.nbns_size); + READ_MULTI_LINE(config->network.nbns, + config->network.nbns_size); } else if (strcmp(name, "route-add-cmd") == 0) { if (!WARN_ON_VHOST(vhost->name, "route-add-cmd", route_add_cmd)) READ_STRING(config->route_add_cmd); @@ -1143,32 +1340,33 @@ static int cfg_ini_handler(void *_ctx, const char *section, const char *name, co READ_STRING(config->camouflage_realm); } else { if (reload == 0) - fprintf(stderr, WARNSTR"skipping unknown option '%s'\n", name); + fprintf(stderr, + WARNSTR "skipping unknown option '%s'\n", name); } - exit: +exit: talloc_free(value); return 1; } enum { - CFG_FLAG_RELOAD = (1<<0), - CFG_FLAG_SECMOD = (1<<1), - CFG_FLAG_WORKER = (1<<2) + CFG_FLAG_RELOAD = (1 << 0), + CFG_FLAG_SECMOD = (1 << 1), + CFG_FLAG_WORKER = (1 << 2) }; -static void replace_file_with_snapshot(char ** file_name) +static void replace_file_with_snapshot(char **file_name) { - char * snapshot_file_name; + char *snapshot_file_name; + if (*file_name == NULL) { return; } - if (snapshot_lookup_filename( - config_snapshot, - *file_name, - &snapshot_file_name) < 0) { - fprintf(stderr, ERRSTR"cannot find snapshot for file %s\n", *file_name); + if (snapshot_lookup_filename(config_snapshot, *file_name, + &snapshot_file_name) < 0) { + fprintf(stderr, ERRSTR "cannot find snapshot for file %s\n", + *file_name); exit(EXIT_FAILURE); } @@ -1176,14 +1374,18 @@ static void replace_file_with_snapshot(char ** file_name) *file_name = snapshot_file_name; } -#define CONFIG_ERROR(filename, err) { \ - if (err > 0) \ - fprintf(stderr, ERRSTR"config file error in line %d\n", err); \ - else \ - fprintf(stderr, ERRSTR"cannot load config file %s\n", filename); } +#define CONFIG_ERROR(filename, err) \ + { \ + if (err > 0) \ + fprintf(stderr, \ + ERRSTR "config file error in line %d\n", err); \ + else \ + fprintf(stderr, ERRSTR "cannot load config file %s\n", \ + filename); \ + } static void parse_cfg_file(void *pool, const char *file, struct list_head *head, - unsigned flags) + unsigned int flags) { int ret, silent = 0; struct cfg_st *config; @@ -1193,18 +1395,23 @@ static void parse_cfg_file(void *pool, const char *file, struct list_head *head, memset(&ctx, 0, sizeof(ctx)); ctx.file = file; - ctx.reload = (flags&CFG_FLAG_RELOAD)?1:0; - ctx.is_worker = (flags&CFG_FLAG_WORKER)?1:0; + ctx.reload = (flags & CFG_FLAG_RELOAD) ? 1 : 0; + ctx.is_worker = (flags & CFG_FLAG_WORKER) ? 1 : 0; ctx.head = head; #if defined(PROC_FS_SUPPORTED) // Worker always reads from snapshot if ((flags & CFG_FLAG_WORKER) == CFG_FLAG_WORKER) { - char * snapshot_file = NULL; + char *snapshot_file = NULL; - if ((snapshot_lookup_filename(config_snapshot, file, &snapshot_file) < 0) && - (snapshot_lookup_filename(config_snapshot, OLD_DEFAULT_CFG_FILE, &snapshot_file) < 0)) { - fprintf(stderr, ERRSTR"snapshot_lookup failed for file %s\n", file); + if ((snapshot_lookup_filename(config_snapshot, file, + &snapshot_file) < 0) && + (snapshot_lookup_filename(config_snapshot, + OLD_DEFAULT_CFG_FILE, + &snapshot_file) < 0)) { + fprintf(stderr, + ERRSTR "snapshot_lookup failed for file %s\n", + file); exit(EXIT_FAILURE); } @@ -1216,19 +1423,25 @@ static void parse_cfg_file(void *pool, const char *file, struct list_head *head, talloc_free(snapshot_file); // Walk the config, replacing filename with the snapshot equivalent - list_for_each(head, vhost, list) { + list_for_each(head, vhost, list) + { size_t index; - replace_file_with_snapshot(&vhost->perm_config.dh_params_file); - replace_file_with_snapshot(&vhost->perm_config.config->ocsp_response); - for (index = 0; index < vhost->perm_config.cert_size; index ++) { - replace_file_with_snapshot(&vhost->perm_config.cert[index]); + + replace_file_with_snapshot( + &vhost->perm_config.dh_params_file); + replace_file_with_snapshot( + &vhost->perm_config.config->ocsp_response); + for (index = 0; index < vhost->perm_config.cert_size; + index++) { + replace_file_with_snapshot( + &vhost->perm_config.cert[index]); } } } else { const char *local_cfg_file = file; if (local_cfg_file == NULL) { - fprintf(stderr, ERRSTR"no config file!\n"); + fprintf(stderr, ERRSTR "no config file!\n"); exit(EXIT_FAILURE); } @@ -1246,25 +1459,33 @@ static void parse_cfg_file(void *pool, const char *file, struct list_head *head, } ret = snapshot_create(config_snapshot, local_cfg_file); - if (ret < 0){ - fprintf(stderr, ERRSTR"cannot snapshot config file %s\n", local_cfg_file); + if (ret < 0) { + fprintf(stderr, + ERRSTR "cannot snapshot config file %s\n", + local_cfg_file); exit(EXIT_FAILURE); } - list_for_each(head, vhost, list) { + list_for_each(head, vhost, list) + { size_t index; - snapshot_create(config_snapshot, vhost->perm_config.dh_params_file); - snapshot_create(config_snapshot, vhost->perm_config.config->ocsp_response); - for (index = 0; index < vhost->perm_config.cert_size; index ++) { - snapshot_create(config_snapshot, vhost->perm_config.cert[index]); + + snapshot_create(config_snapshot, + vhost->perm_config.dh_params_file); + snapshot_create( + config_snapshot, + vhost->perm_config.config->ocsp_response); + for (index = 0; index < vhost->perm_config.cert_size; + index++) { + snapshot_create(config_snapshot, + vhost->perm_config.cert[index]); } } - } #else - const char * local_cfg_file = file; + const char *local_cfg_file = file; if (local_cfg_file == NULL) { - fprintf(stderr, ERRSTR"no config file!\n"); + fprintf(stderr, ERRSTR "no config file!\n"); exit(EXIT_FAILURE); } @@ -1286,40 +1507,54 @@ static void parse_cfg_file(void *pool, const char *file, struct list_head *head, * We start from the last, which is the default server (firstly * added). */ - list_for_each_rev(head, vhost, list) { + list_for_each_rev(head, vhost, list) + { config = vhost->perm_config.config; if (vhost->auth_init == 0) { if (vhost->auth_size == 0) { - fprintf(stderr, ERRSTR"%sthe 'auth' configuration option was not specified!\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sthe 'auth' configuration option was not specified!\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } - figure_auth_funcs(vhost, PREFIX_VHOST(vhost), &vhost->perm_config, - vhost->auth, vhost->auth_size, 1, ctx.is_worker); - figure_auth_funcs(vhost, PREFIX_VHOST(vhost), &vhost->perm_config, - vhost->eauth, vhost->eauth_size, 0, ctx.is_worker); + figure_auth_funcs(vhost, PREFIX_VHOST(vhost), + &vhost->perm_config, vhost->auth, + vhost->auth_size, 1, ctx.is_worker); + figure_auth_funcs(vhost, PREFIX_VHOST(vhost), + &vhost->perm_config, vhost->eauth, + vhost->eauth_size, 0, ctx.is_worker); - figure_acct_funcs(vhost, PREFIX_VHOST(vhost), &vhost->perm_config, - vhost->acct, ctx.is_worker); + figure_acct_funcs(vhost, PREFIX_VHOST(vhost), + &vhost->perm_config, vhost->acct, + ctx.is_worker); vhost->auth_init = 1; } - if (config->auto_select_group != 0 && vhost->perm_config.auth[0].amod != NULL && vhost->perm_config.auth[0].amod->group_list != NULL) { - vhost->perm_config.auth[0].amod->group_list(config, vhost->perm_config.auth[0].additional, &config->group_list, &config->group_list_size); + if (config->auto_select_group != 0 && + vhost->perm_config.auth[0].amod != NULL && + vhost->perm_config.auth[0].amod->group_list != NULL) { + vhost->perm_config.auth[0].amod->group_list( + config, vhost->perm_config.auth[0].additional, + &config->group_list, &config->group_list_size); switch (vhost->perm_config.auth[0].amod->type) { - case AUTH_TYPE_PAM|AUTH_TYPE_USERNAME_PASS: + case AUTH_TYPE_PAM | AUTH_TYPE_USERNAME_PASS: pam_auth_group_list = config->group_list; - pam_auth_group_list_size = config->group_list_size; + pam_auth_group_list_size = + config->group_list_size; break; case AUTH_TYPE_GSSAPI: gssapi_auth_group_list = config->group_list; - gssapi_auth_group_list_size = config->group_list_size; + gssapi_auth_group_list_size = + config->group_list_size; break; - case AUTH_TYPE_PLAIN|AUTH_TYPE_USERNAME_PASS: + case AUTH_TYPE_PLAIN | AUTH_TYPE_USERNAME_PASS: plain_auth_group_list = config->group_list; - plain_auth_group_list_size = config->group_list_size; + plain_auth_group_list_size = + config->group_list_size; break; } } @@ -1353,17 +1588,20 @@ static void parse_cfg_file(void *pool, const char *file, struct list_head *head, } #endif if (!ctx.is_worker) - fprintf(stderr, NOTESTR"%ssetting '%s' as supplemental config option\n", + fprintf(stderr, + NOTESTR + "%ssetting '%s' as supplemental config option\n", PREFIX_VHOST(vhost), - sup_config_name(vhost->perm_config.sup_config_type)); + sup_config_name( + vhost->perm_config.sup_config_type)); } } - /* sanity checks on config */ -static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned silent) +static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, + unsigned int silent) { - unsigned j, i; + unsigned int j, i; struct cfg_st *config; assert(vhost->name == NULL || defvhost != NULL); @@ -1371,16 +1609,23 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile config = vhost->perm_config.config; if (vhost->perm_config.auth[0].enabled == 0) { - fprintf(stderr, ERRSTR"%sno authentication method was specified!\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR "%sno authentication method was specified!\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } if (vhost->perm_config.socket_file_prefix == NULL) { if (vhost->name) { - vhost->perm_config.socket_file_prefix = talloc_strdup(vhost, defvhost->perm_config.socket_file_prefix); + vhost->perm_config.socket_file_prefix = talloc_strdup( + vhost, + defvhost->perm_config.socket_file_prefix); } else { /* The 'socket-file' is not mandatory on main server */ - fprintf(stderr, ERRSTR"%sthe 'socket-file' configuration option must be specified!\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sthe 'socket-file' configuration option must be specified!\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } } @@ -1389,50 +1634,69 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile if (defvhost) { vhost->perm_config.port = defvhost->perm_config.port; } else { - fprintf(stderr, ERRSTR"%sthe tcp-port option is mandatory!\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR "%sthe tcp-port option is mandatory!\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } } - if (vhost->perm_config.cert_size == 0 || vhost->perm_config.key_size == 0) { - fprintf(stderr, ERRSTR"%sthe 'server-cert' and 'server-key' configuration options must be specified!\n", PREFIX_VHOST(vhost)); + if (vhost->perm_config.cert_size == 0 || + vhost->perm_config.key_size == 0) { + fprintf(stderr, + ERRSTR + "%sthe 'server-cert' and 'server-key' configuration options must be specified!\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } if (config->network.ipv4 == NULL && config->network.ipv6 == NULL) { - fprintf(stderr, ERRSTR"%sno ipv4-network or ipv6-network options set.\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sno ipv4-network or ipv6-network options set.\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } - if (config->network.ipv4 != NULL && config->network.ipv4_netmask == NULL) { - fprintf(stderr, ERRSTR"%sno mask found for IPv4 network.\n", PREFIX_VHOST(vhost)); + if (config->network.ipv4 != NULL && + config->network.ipv4_netmask == NULL) { + fprintf(stderr, ERRSTR "%sno mask found for IPv4 network.\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } if (config->network.ipv6 != NULL && config->network.ipv6_prefix == 0) { - fprintf(stderr, ERRSTR"%sno prefix found for IPv6 network.\n", PREFIX_VHOST(vhost)); + fprintf(stderr, ERRSTR "%sno prefix found for IPv6 network.\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } if (config->banner && strlen(config->banner) > MAX_BANNER_SIZE) { - fprintf(stderr, ERRSTR"%sbanner size is too long\n", PREFIX_VHOST(vhost)); + fprintf(stderr, ERRSTR "%sbanner size is too long\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } if (vhost->perm_config.cert_size != vhost->perm_config.key_size) { - fprintf(stderr, ERRSTR"%sthe specified number of keys doesn't match the certificates\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sthe specified number of keys doesn't match the certificates\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } - if ((vhost->perm_config.auth[0].type & AUTH_TYPE_CERTIFICATE) && vhost->perm_config.auth_methods == 1) { + if ((vhost->perm_config.auth[0].type & AUTH_TYPE_CERTIFICATE) && + vhost->perm_config.auth_methods == 1) { if (config->cisco_client_compat == 0) config->cert_req = GNUTLS_CERT_REQUIRE; else config->cert_req = GNUTLS_CERT_REQUEST; } else { - unsigned i; - for (i=0;iperm_config.auth_methods;i++) { - if (vhost->perm_config.auth[i].type & AUTH_TYPE_CERTIFICATE) { + unsigned int i; + + for (i = 0; i < vhost->perm_config.auth_methods; i++) { + if (vhost->perm_config.auth[i].type & + AUTH_TYPE_CERTIFICATE) { config->cert_req = GNUTLS_CERT_REQUEST; break; } @@ -1440,37 +1704,53 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile } if (config->cert_req != 0 && config->cert_user_oid == NULL) { - fprintf(stderr, ERRSTR"%sa certificate is requested by the option 'cert-user-oid' is not set\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sa certificate is requested by the option 'cert-user-oid' is not set\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } if (config->cert_req != 0 && config->cert_user_oid != NULL) { - if (!isdigit(config->cert_user_oid[0]) && strcmp(config->cert_user_oid, "SAN(rfc822name)") != 0) { - fprintf(stderr, ERRSTR"%sthe option 'cert-user-oid' has a unsupported value\n", PREFIX_VHOST(vhost)); + if (!isdigit(config->cert_user_oid[0]) && + strcmp(config->cert_user_oid, "SAN(rfc822name)") != 0) { + fprintf(stderr, + ERRSTR + "%sthe option 'cert-user-oid' has a unsupported value\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } } #ifdef ANYCONNECT_CLIENT_COMPAT if (vhost->perm_config.cert && vhost->perm_config.cert_hash == NULL) { - vhost->perm_config.cert_hash = calc_sha1_hash(vhost->pool, vhost->perm_config.cert[0], 1); + vhost->perm_config.cert_hash = calc_sha1_hash( + vhost->pool, vhost->perm_config.cert[0], 1); } if (config->xml_config_file) { - config->xml_config_hash = calc_sha1_hash(vhost->pool, config->xml_config_file, 0); - if (config->xml_config_hash == NULL && vhost->perm_config.chroot_dir != NULL) { + config->xml_config_hash = + calc_sha1_hash(vhost->pool, config->xml_config_file, 0); + if (config->xml_config_hash == NULL && + vhost->perm_config.chroot_dir != NULL) { char path[_POSIX_PATH_MAX]; - snprintf(path, sizeof(path), "%s/%s", vhost->perm_config.chroot_dir, config->xml_config_file); - config->xml_config_hash = calc_sha1_hash(vhost->pool, path, 0); + snprintf(path, sizeof(path), "%s/%s", + vhost->perm_config.chroot_dir, + config->xml_config_file); + config->xml_config_hash = + calc_sha1_hash(vhost->pool, path, 0); if (config->xml_config_hash == NULL) { - fprintf(stderr, ERRSTR"%scannot open file '%s'\n", PREFIX_VHOST(vhost), path); + fprintf(stderr, + ERRSTR "%scannot open file '%s'\n", + PREFIX_VHOST(vhost), path); exit(EXIT_FAILURE); } } if (config->xml_config_hash == NULL) { - fprintf(stderr, ERRSTR"%scannot open file '%s'\n", PREFIX_VHOST(vhost), config->xml_config_file); + fprintf(stderr, ERRSTR "%scannot open file '%s'\n", + PREFIX_VHOST(vhost), config->xml_config_file); exit(EXIT_FAILURE); } } @@ -1478,13 +1758,20 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile if (config->cisco_svc_client_compat) { if (!config->dtls_legacy && !silent) { - fprintf(stderr, NOTESTR"%sthe cisco-svc-client-compat option implies dtls-legacy = true; enabling\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + NOTESTR + "%sthe cisco-svc-client-compat option implies dtls-legacy = true; enabling\n", + PREFIX_VHOST(vhost)); } config->dtls_legacy = 1; /* The client will only connect to port 443 */ - if (vhost->perm_config.udp_port != 0 && vhost->perm_config.udp_port != 443) { - fprintf(stderr, ERRSTR"%s cisco-svc-client-compat option requires udp-port = 443\n", PREFIX_VHOST(vhost)); + if (vhost->perm_config.udp_port != 0 && + vhost->perm_config.udp_port != 443) { + fprintf(stderr, + ERRSTR + "%s cisco-svc-client-compat option requires udp-port = 443\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } } @@ -1499,28 +1786,41 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile } if (defvhost) { - config->priorities = talloc_asprintf(config, "%s%s", defvhost->perm_config.config->priorities, tmp); + config->priorities = talloc_asprintf( + config, "%s%s", + defvhost->perm_config.config->priorities, tmp); } else { - config->priorities = talloc_asprintf(config, "%s%s", "NORMAL:%SERVER_PRECEDENCE:%COMPAT", tmp); + config->priorities = talloc_asprintf( + config, "%s%s", + "NORMAL:%SERVER_PRECEDENCE:%COMPAT", tmp); } } if (vhost->perm_config.occtl_socket_file == NULL) - vhost->perm_config.occtl_socket_file = talloc_strdup(vhost, OCCTL_UNIX_SOCKET); + vhost->perm_config.occtl_socket_file = + talloc_strdup(vhost, OCCTL_UNIX_SOCKET); - - if (config->network.ipv6_prefix && config->network.ipv6_prefix >= config->network.ipv6_subnet_prefix) { - fprintf(stderr, ERRSTR"%sthe subnet prefix (%u) cannot be smaller or equal to network's (%u)\n", - PREFIX_VHOST(vhost), config->network.ipv6_subnet_prefix, config->network.ipv6_prefix); + if (config->network.ipv6_prefix && + config->network.ipv6_prefix >= config->network.ipv6_subnet_prefix) { + fprintf(stderr, + ERRSTR + "%sthe subnet prefix (%u) cannot be smaller or equal to network's (%u)\n", + PREFIX_VHOST(vhost), config->network.ipv6_subnet_prefix, + config->network.ipv6_prefix); exit(EXIT_FAILURE); } if (config->network.name[0] == 0) { if (!vhost->name) { - fprintf(stderr, ERRSTR"%sthe 'device' configuration option must be specified!\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sthe 'device' configuration option must be specified!\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } else { - strlcpy(config->network.name, defvhost->perm_config.config->network.name, sizeof(config->network.name)); + strlcpy(config->network.name, + defvhost->perm_config.config->network.name, + sizeof(config->network.name)); } } @@ -1529,24 +1829,33 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile if (config->cisco_client_compat) { if (!config->dtls_legacy && !silent) { - fprintf(stderr, NOTESTR"%sthe cisco-client-compat option implies dtls-legacy = true; enabling\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + NOTESTR + "%sthe cisco-client-compat option implies dtls-legacy = true; enabling\n", + PREFIX_VHOST(vhost)); } config->dtls_legacy = 1; if (!config->select_group_by_url && !silent) { - fprintf(stderr, NOTESTR"%sthe cisco-client-compat option implies select-group-by-url = true; enabling\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + NOTESTR + "%sthe cisco-client-compat option implies select-group-by-url = true; enabling\n", + PREFIX_VHOST(vhost)); } config->select_group_by_url = 1; } if (config->match_dtls_and_tls) { if (config->dtls_legacy) { - fprintf(stderr, ERRSTR"%s'match-tls-dtls-ciphers' cannot be applied when 'dtls-legacy' or 'cisco-client-compat' is on\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%s'match-tls-dtls-ciphers' cannot be applied when 'dtls-legacy' or 'cisco-client-compat' is on\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } } - if (config->mobile_idle_timeout == (unsigned)-1) + if (config->mobile_idle_timeout == (unsigned int)-1) config->mobile_idle_timeout = config->idle_timeout; #ifdef ENABLE_COMPRESSION @@ -1555,101 +1864,121 @@ static void check_cfg(vhost_cfg_st *vhost, vhost_cfg_st *defvhost, unsigned sile #endif /* use tcp listen host by default */ - if (vhost->perm_config.udp_listen_host == NULL) { - vhost->perm_config.udp_listen_host = vhost->perm_config.listen_host; + if (vhost->perm_config.udp_listen_host == NULL) { + vhost->perm_config.udp_listen_host = + vhost->perm_config.listen_host; } #if !defined(HAVE_LIBSECCOMP) if (config->isolate != 0 && !silent) { - fprintf(stderr, ERRSTR"%s'isolate-workers' is set to true, but not compiled with seccomp or Linux namespaces support\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%s'isolate-workers' is set to true, but not compiled with seccomp or Linux namespaces support\n", + PREFIX_VHOST(vhost)); } #endif - for (j=0;jnetwork.routes_size;j++) { - if (ip_route_sanity_check(config->network.routes, &config->network.routes[j]) != 0) + for (j = 0; j < config->network.routes_size; j++) { + if (ip_route_sanity_check(config->network.routes, + &config->network.routes[j]) != 0) exit(EXIT_FAILURE); if (strcmp(config->network.routes[j], "0.0.0.0/0") == 0 || strcmp(config->network.routes[j], "default") == 0) { /* set default route */ - for (i=0;inetwork.routes[i]); config->network.routes_size = 0; break; } } - for (j=0;jnetwork.no_routes_size;j++) { - if (ip_route_sanity_check(config->network.no_routes, &config->network.no_routes[j]) != 0) + for (j = 0; j < config->network.no_routes_size; j++) { + if (ip_route_sanity_check(config->network.no_routes, + &config->network.no_routes[j]) != 0) exit(EXIT_FAILURE); } - for (j=0;jnetwork.dns_size;j++) { + for (j = 0; j < config->network.dns_size; j++) { if (strcmp(config->network.dns[j], "local") == 0) { - fprintf(stderr, ERRSTR"%sthe 'local' DNS keyword is no longer supported.\n", PREFIX_VHOST(vhost)); + fprintf(stderr, + ERRSTR + "%sthe 'local' DNS keyword is no longer supported.\n", + PREFIX_VHOST(vhost)); exit(EXIT_FAILURE); } } if (config->per_user_dir || config->per_group_dir) { if (vhost->perm_config.sup_config_type != SUP_CONFIG_FILE) { - fprintf(stderr, ERRSTR"%sspecified config-per-user or config-per-group but supplemental config is '%s'\n", - PREFIX_VHOST(vhost), sup_config_name(vhost->perm_config.sup_config_type)); + fprintf(stderr, + ERRSTR + "%sspecified config-per-user or config-per-group but supplemental config is '%s'\n", + PREFIX_VHOST(vhost), + sup_config_name( + vhost->perm_config.sup_config_type)); exit(EXIT_FAILURE); } } - } #define OPT_NO_CHDIR 1 static const struct option long_options[] = { - {"debug", 1, 0, 'd'}, - {"log-stderr", 0, 0, 'e'}, - {"syslog", 0, 0, 's'}, - {"config", 1, 0, 'c'}, - {"pid-file", 1, 0, 'p'}, - {"test-config", 0, 0, 't'}, - {"foreground", 0, 0, 'f'}, - {"no-chdir", 0, 0, OPT_NO_CHDIR}, - {"help", 0, 0, 'h'}, - {"traceable", 0, 0, 'x'}, - {"version", 0, 0, 'v'}, - {NULL, 0, 0, 0} + { "debug", 1, 0, 'd' }, { "log-stderr", 0, 0, 'e' }, + { "syslog", 0, 0, 's' }, { "config", 1, 0, 'c' }, + { "pid-file", 1, 0, 'p' }, { "test-config", 0, 0, 't' }, + { "foreground", 0, 0, 'f' }, { "no-chdir", 0, 0, OPT_NO_CHDIR }, + { "help", 0, 0, 'h' }, { "traceable", 0, 0, 'x' }, + { "version", 0, 0, 'v' }, { NULL, 0, 0, 0 } }; -static -void usage(void) +static void usage(void) { - fprintf(stderr, PACKAGE" - "PACKAGE_NAME"\n"); - fprintf(stderr, "Usage: ocserv [ - [] | --[{=| }] ]...\n\n"); + fprintf(stderr, PACKAGE " - " PACKAGE_NAME "\n"); + fprintf(stderr, + "Usage: ocserv [ - [] | --[{=| }] ]...\n\n"); - fprintf(stderr, " -f, --foreground Do not fork into background\n"); - fprintf(stderr, " -d, --debug=num Enable verbose network debugging information\n"); - fprintf(stderr, " - it must be in the range:\n"); + fprintf(stderr, + " -f, --foreground Do not fork into background\n"); + fprintf(stderr, + " -d, --debug=num Enable verbose network debugging information\n"); + fprintf(stderr, + " - it must be in the range:\n"); fprintf(stderr, " 0 to 9\n"); - fprintf(stderr, " -c, --config=file Configuration file for the server\n"); + fprintf(stderr, + " -c, --config=file Configuration file for the server\n"); fprintf(stderr, " - file must exist\n"); - fprintf(stderr, " -t, --test-config Test the provided configuration file\n"); - fprintf(stderr, " --no-chdir Do not perform a chdir on daemonize\n"); - fprintf(stderr, " -p, --pid-file=file Specify pid file for the server\n"); - fprintf(stderr, " -v, --version output version information and exit\n"); - fprintf(stderr, " -x, --traceable Allow processes tracing\n"); + fprintf(stderr, + " -t, --test-config Test the provided configuration file\n"); + fprintf(stderr, + " --no-chdir Do not perform a chdir on daemonize\n"); + fprintf(stderr, + " -p, --pid-file=file Specify pid file for the server\n"); + fprintf(stderr, + " -v, --version output version information and exit\n"); + fprintf(stderr, + " -x, --traceable Allow processes tracing\n"); fprintf(stderr, " - use for debugging purposes only\n"); fprintf(stderr, " -e, --log-stderr Log to stderr\n"); - fprintf(stderr, " -s, --syslog Log to syslog (default)\n"); - fprintf(stderr, " -h, --help Display extended usage information and exit\n\n"); + fprintf(stderr, + " -s, --syslog Log to syslog (default)\n"); + fprintf(stderr, + " -h, --help Display extended usage information and exit\n\n"); - fprintf(stderr, PACKAGE_NAME" ("PACKAGE") is a VPN server compatible with the\n"); - fprintf(stderr, "OpenConnect VPN client. It follows the TLS and DTLS-based AnyConnect VPN\n"); + fprintf(stderr, PACKAGE_NAME " (" PACKAGE + ") is a VPN server compatible with the\n"); + fprintf(stderr, + "OpenConnect VPN client. It follows the TLS and DTLS-based AnyConnect VPN\n"); fprintf(stderr, "protocol which is used by several CISCO routers.\n\n"); - fprintf(stderr, "Please file bug reports at: "PACKAGE_BUGREPORT"\n"); + fprintf(stderr, "Please file bug reports at: " PACKAGE_BUGREPORT "\n"); } -int cmd_parser (void *pool, int argc, char **argv, struct list_head *head, bool worker) +int cmd_parser(void *pool, int argc, char **argv, struct list_head *head, + bool worker) { - unsigned test_only = 0; - unsigned debug_asked = 0; + unsigned int test_only = 0; + unsigned int debug_asked = 0; int c; vhost_cfg_st *vhost; @@ -1701,19 +2030,25 @@ int cmd_parser (void *pool, int argc, char **argv, struct list_head *head, bool } if (optind != argc) { - fprintf(stderr, ERRSTR"no additional command line options are allowed\n\n"); + fprintf(stderr, ERRSTR + "no additional command line options are allowed\n\n"); exit(EXIT_FAILURE); } - if (vhost->perm_config.log_stderr == 0 && vhost->perm_config.syslog == 0) { + if (vhost->perm_config.log_stderr == 0 && + vhost->perm_config.syslog == 0) { vhost->perm_config.syslog = 1; /* default if nothing specified*/ if (debug_asked) - vhost->perm_config.log_stderr = 1; /* compatible with previous behavior */ + vhost->perm_config.log_stderr = + 1; /* compatible with previous behavior */ } if (access(cfg_file, R_OK) != 0) { - fprintf(stderr, ERRSTR"cannot access config file: %s\n", cfg_file); - fprintf(stderr, "Usage: %s -c [config]\nUse %s --help for more information.\n", argv[0], argv[0]); + fprintf(stderr, ERRSTR "cannot access config file: %s\n", + cfg_file); + fprintf(stderr, + "Usage: %s -c [config]\nUse %s --help for more information.\n", + argv[0], argv[0]); exit(EXIT_FAILURE); } @@ -1723,15 +2058,15 @@ int cmd_parser (void *pool, int argc, char **argv, struct list_head *head, bool exit(EXIT_SUCCESS); return 0; - } static void archive_cfg(struct list_head *head) { attic_entry_st *e; - struct vhost_cfg_st* vhost = NULL; + struct vhost_cfg_st *vhost = NULL; - list_for_each(head, vhost, list) { + list_for_each(head, vhost, list) + { /* we don't clear anything as it may be referenced by some * client (proc_st). We move everything to attic and * once nothing is in use we clear that */ @@ -1760,7 +2095,8 @@ static void clear_cfg(struct list_head *head) { vhost_cfg_st *cpos = NULL, *ctmp; - list_for_each_safe(head, cpos, ctmp, list) { + list_for_each_safe(head, cpos, ctmp, list) + { /* we rely on talloc freeing recursively */ talloc_free(cpos->perm_config.config); cpos->perm_config.config = NULL; @@ -1771,7 +2107,8 @@ void clear_vhosts(struct list_head *head) { vhost_cfg_st *vhost = NULL, *ctmp; - list_for_each_safe(head, vhost, ctmp, list) { + list_for_each_safe(head, vhost, ctmp, list) + { tls_vhost_deinit(vhost); /* we rely on talloc freeing recursively */ talloc_free(vhost->perm_config.config); @@ -1781,7 +2118,7 @@ void clear_vhosts(struct list_head *head) static void append(const char *option) { - static int have_previous_val = 0; + static int have_previous_val; if (have_previous_val == 0) { have_previous_val = 1; @@ -1826,17 +2163,18 @@ static void print_version(void) p = gnutls_check_version(NULL); if (strcmp(p, GNUTLS_VERSION) != 0) { - fprintf(stderr, "GnuTLS version: %s (compiled with %s)\n", p, GNUTLS_VERSION); + fprintf(stderr, "GnuTLS version: %s (compiled with %s)\n", p, + GNUTLS_VERSION); } else { fprintf(stderr, "GnuTLS version: %s\n", p); } } - -void reload_cfg_file(void *pool, struct list_head *configs, unsigned sec_mod) +void reload_cfg_file(void *pool, struct list_head *configs, + unsigned int sec_mod) { - struct vhost_cfg_st* vhost = NULL; - unsigned flags = CFG_FLAG_RELOAD; + struct vhost_cfg_st *vhost = NULL; + unsigned int flags = CFG_FLAG_RELOAD; if (sec_mod) flags |= CFG_FLAG_SECMOD; @@ -1848,7 +2186,8 @@ void reload_cfg_file(void *pool, struct list_head *configs, unsigned sec_mod) clear_cfg(configs); /* Create new config structures and apply defaults */ - list_for_each(configs, vhost, list) { + list_for_each(configs, vhost, list) + { if (vhost->perm_config.config == NULL) cfg_new(vhost, 1); } @@ -1859,44 +2198,44 @@ void reload_cfg_file(void *pool, struct list_head *configs, unsigned sec_mod) void write_pid_file(void) { - FILE* fp; + FILE *fp; - if (pid_file[0]==0) + if (pid_file[0] == 0) return; fp = fopen(pid_file, "w"); if (fp == NULL) { - fprintf(stderr, ERRSTR"cannot open pid file '%s'\n", pid_file); + fprintf(stderr, ERRSTR "cannot open pid file '%s'\n", pid_file); exit(EXIT_FAILURE); } - fprintf(fp, "%u", (unsigned)getpid()); + fprintf(fp, "%u", (unsigned int)getpid()); fclose(fp); } void remove_pid_file(void) { - if (pid_file[0]==0) + if (pid_file[0] == 0) return; (void)remove(pid_file); } int _add_multi_line_val(void *pool, char ***varname, size_t *num, - const char *value) + const char *value) { - unsigned _max = DEFAULT_CONFIG_ENTRIES; + unsigned int _max = DEFAULT_CONFIG_ENTRIES; void *tmp; if (*varname == NULL) { *num = 0; - *varname = talloc_array(pool, char*, _max); + *varname = talloc_array(pool, char *, _max); if (*varname == NULL) return -1; } - if (*num >= _max-1) { - tmp = talloc_realloc(pool, *varname, char*, (*num)+2); + if (*num >= _max - 1) { + tmp = talloc_realloc(pool, *varname, char *, (*num) + 2); if (tmp == NULL) return -1; *varname = tmp; @@ -1914,9 +2253,11 @@ void clear_old_configs(struct list_head *head) attic_entry_st *e = NULL, *pos; vhost_cfg_st *cpos = NULL; - list_for_each(head, cpos, list) { + list_for_each(head, cpos, list) + { /* go through the attic and clear old configurations if unused */ - list_for_each_safe(&cpos->perm_config.attic, e, pos, list) { + list_for_each_safe(&cpos->perm_config.attic, e, pos, list) + { if (*e->usage_count == 0) { list_del(&e->list); talloc_free(e); @@ -1939,120 +2280,114 @@ void clear_old_configs(struct list_head *head) // When compiles as part of ocserv-worker, the auth subsystem is not present. // To work around this, the group information is passed from ocserv-main to // ocserv-worker, which then caches it and returns it when queried. -static void pam_group_list(void *pool, void *_additional, char ***groupname, unsigned *groupname_size) +static void pam_group_list(void *pool, void *_additional, char ***groupname, + unsigned int *groupname_size) { *groupname = pam_auth_group_list; *groupname_size = pam_auth_group_list_size; } -static void gssapi_group_list(void *pool, void *_additional, char ***groupname, unsigned *groupname_size) +static void gssapi_group_list(void *pool, void *_additional, char ***groupname, + unsigned int *groupname_size) { *groupname = gssapi_auth_group_list; *groupname_size = gssapi_auth_group_list_size; } -static void plain_group_list(void *pool, void *_additional, char ***groupname, unsigned *groupname_size) +static void plain_group_list(void *pool, void *_additional, char ***groupname, + unsigned int *groupname_size) { *groupname = plain_auth_group_list; *groupname_size = plain_auth_group_list_size; } -const struct acct_mod_st radius_acct_funcs = { - .type = ACCT_TYPE_RADIUS, - .auth_types = ALL_AUTH_TYPES, - .vhost_init = NULL, - .vhost_deinit = NULL, - .open_session = NULL, - .close_session = NULL, - .session_stats = NULL -}; +const struct acct_mod_st radius_acct_funcs = { .type = ACCT_TYPE_RADIUS, + .auth_types = ALL_AUTH_TYPES, + .vhost_init = NULL, + .vhost_deinit = NULL, + .open_session = NULL, + .close_session = NULL, + .session_stats = NULL }; const struct acct_mod_st pam_acct_funcs = { - .type = ACCT_TYPE_PAM, - .auth_types = ALL_AUTH_TYPES, - .open_session = NULL, - .close_session = NULL, + .type = ACCT_TYPE_PAM, + .auth_types = ALL_AUTH_TYPES, + .open_session = NULL, + .close_session = NULL, }; -const struct auth_mod_st pam_auth_funcs = { - .type = AUTH_TYPE_PAM | AUTH_TYPE_USERNAME_PASS, - .auth_init = NULL, - .auth_deinit = NULL, - .auth_msg = NULL, - .auth_pass = NULL, - .auth_group = NULL, - .auth_user = NULL, - .group_list = pam_group_list -}; +const struct auth_mod_st pam_auth_funcs = { .type = AUTH_TYPE_PAM | + AUTH_TYPE_USERNAME_PASS, + .auth_init = NULL, + .auth_deinit = NULL, + .auth_msg = NULL, + .auth_pass = NULL, + .auth_group = NULL, + .auth_user = NULL, + .group_list = pam_group_list }; -const struct auth_mod_st gssapi_auth_funcs = { - .type = AUTH_TYPE_GSSAPI, - .auth_init = NULL, - .auth_deinit = NULL, - .auth_msg = NULL, - .auth_pass = NULL, - .auth_user = NULL, - .auth_group = NULL, - .vhost_init = NULL, - .vhost_deinit = NULL, - .group_list = gssapi_group_list -}; +const struct auth_mod_st gssapi_auth_funcs = { .type = AUTH_TYPE_GSSAPI, + .auth_init = NULL, + .auth_deinit = NULL, + .auth_msg = NULL, + .auth_pass = NULL, + .auth_user = NULL, + .auth_group = NULL, + .vhost_init = NULL, + .vhost_deinit = NULL, + .group_list = + gssapi_group_list }; -const struct auth_mod_st plain_auth_funcs = { - .type = AUTH_TYPE_PLAIN | AUTH_TYPE_USERNAME_PASS, - .allows_retries = 1, - .vhost_init = NULL, - .auth_init = NULL, - .auth_deinit = NULL, - .auth_msg = NULL, - .auth_pass = NULL, - .auth_user = NULL, - .auth_group = NULL, - .group_list = plain_group_list -}; +const struct auth_mod_st plain_auth_funcs = { .type = AUTH_TYPE_PLAIN | + AUTH_TYPE_USERNAME_PASS, + .allows_retries = 1, + .vhost_init = NULL, + .auth_init = NULL, + .auth_deinit = NULL, + .auth_msg = NULL, + .auth_pass = NULL, + .auth_user = NULL, + .auth_group = NULL, + .group_list = plain_group_list }; +const struct auth_mod_st radius_auth_funcs = { .type = AUTH_TYPE_RADIUS | + AUTH_TYPE_USERNAME_PASS, + .allows_retries = 1, + .vhost_init = NULL, + .vhost_deinit = NULL, + .auth_init = NULL, + .auth_deinit = NULL, + .auth_msg = NULL, + .auth_pass = NULL, + .auth_user = NULL, + .auth_group = NULL, + .group_list = NULL }; -const struct auth_mod_st radius_auth_funcs = { - .type = AUTH_TYPE_RADIUS | AUTH_TYPE_USERNAME_PASS, - .allows_retries = 1, - .vhost_init = NULL, - .vhost_deinit = NULL, - .auth_init = NULL, - .auth_deinit = NULL, - .auth_msg = NULL, - .auth_pass = NULL, - .auth_user = NULL, - .auth_group = NULL, - .group_list = NULL -}; - -const struct auth_mod_st oidc_auth_funcs = { - .type = AUTH_TYPE_OIDC, - .allows_retries = 1, - .vhost_init = NULL, - .vhost_deinit = NULL, - .auth_init = NULL, - .auth_deinit = NULL, - .auth_msg = NULL, - .auth_pass = NULL, - .auth_user = NULL, - .auth_group = NULL, - .group_list = NULL -}; - +const struct auth_mod_st oidc_auth_funcs = { .type = AUTH_TYPE_OIDC, + .allows_retries = 1, + .vhost_init = NULL, + .vhost_deinit = NULL, + .auth_init = NULL, + .auth_deinit = NULL, + .auth_msg = NULL, + .auth_pass = NULL, + .auth_user = NULL, + .auth_group = NULL, + .group_list = NULL }; #else -int get_cert_names(struct worker_st * ws, const gnutls_datum_t * raw) +int get_cert_names(struct worker_st *ws, const gnutls_datum_t *raw) { return -1; } #endif -char secmod_socket_file_name_socket_file[_POSIX_PATH_MAX] = {0}; +char secmod_socket_file_name_socket_file[_POSIX_PATH_MAX] = { 0 }; -void restore_secmod_socket_file_name(const char * save_path) +void restore_secmod_socket_file_name(const char *save_path) { - strlcpy(secmod_socket_file_name_socket_file, save_path, sizeof(secmod_socket_file_name_socket_file)); + strlcpy(secmod_socket_file_name_socket_file, save_path, + sizeof(secmod_socket_file_name_socket_file)); } /* Creates a permanent filename to use for secmod to main communication @@ -2070,7 +2405,8 @@ const char *secmod_socket_file_name(struct perm_cfg_st *perm_config) exit(EXIT_FAILURE); /* make socket name */ - snprintf(secmod_socket_file_name_socket_file, sizeof(secmod_socket_file_name_socket_file), "%s.%x", + snprintf(secmod_socket_file_name_socket_file, + sizeof(secmod_socket_file_name_socket_file), "%s.%x", perm_config->socket_file_prefix, rnd); return secmod_socket_file_name_socket_file; diff --git a/src/defs.h b/src/defs.h index 10cf37e4..0a88e146 100644 --- a/src/defs.h +++ b/src/defs.h @@ -28,7 +28,6 @@ #define LOG_TRANSFER_DEBUG 2049 #define LOG_SENSITIVE 2050 - /* User Disconnect reasons (must be > 0) */ #define REASON_ANY 1 #define REASON_USER_DISCONNECT 2 @@ -46,12 +45,12 @@ /* Debug definitions for logger */ #define OCLOG_BASIC 1 -#define OCLOG_INFO 2 +#define OCLOG_INFO 2 #define OCLOG_DEBUG 3 -#define OCLOG_HTTP 4 +#define OCLOG_HTTP 4 #define OCLOG_TRANSFERRED 5 #define OCLOG_SENSITIVE 8 -#define OCLOG_TLS 9 +#define OCLOG_TLS 9 /* Authentication states */ enum { @@ -90,7 +89,7 @@ typedef enum { CMD_SEC_CLI_STATS, /* from main to sec-mod and vice versa */ - MIN_SECM_CMD=239, + MIN_SECM_CMD = 239, CMD_SECM_SESSION_OPEN, /* sync: reply is CMD_SECM_SESSION_REPLY */ CMD_SECM_SESSION_CLOSE, /* sync: reply is CMD_SECM_CLI_STATS */ CMD_SECM_SESSION_REPLY, diff --git a/src/gettime.h b/src/gettime.h index 44b57213..4306f18f 100644 --- a/src/gettime.h +++ b/src/gettime.h @@ -28,49 +28,43 @@ /* emulate gnulib's gettime using gettimeofday to avoid linking to * librt */ -inline static void -gettime (struct timespec *t) +inline static void gettime(struct timespec *t) { #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_REALTIME_COARSE) - clock_gettime (CLOCK_REALTIME_COARSE, t); + clock_gettime(CLOCK_REALTIME_COARSE, t); #elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_REALTIME) - clock_gettime (CLOCK_REALTIME, t); + clock_gettime(CLOCK_REALTIME, t); #else -struct timeval tv; - gettimeofday (&tv, NULL); - t->tv_sec = tv.tv_sec; - t->tv_nsec = tv.tv_usec * 1000; + struct timeval tv; + gettimeofday(&tv, NULL); + t->tv_sec = tv.tv_sec; + t->tv_nsec = tv.tv_usec * 1000; #endif } -inline static void -gettime_realtime (struct timespec *t) +inline static void gettime_realtime(struct timespec *t) { #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_REALTIME) - clock_gettime (CLOCK_REALTIME, t); + clock_gettime(CLOCK_REALTIME, t); #else -struct timeval tv; - gettimeofday (&tv, NULL); - t->tv_sec = tv.tv_sec; - t->tv_nsec = tv.tv_usec * 1000; + struct timeval tv; + gettimeofday(&tv, NULL); + t->tv_sec = tv.tv_sec; + t->tv_nsec = tv.tv_usec * 1000; #endif } -inline static -unsigned int -timespec_sub_ms (struct timespec *a, struct timespec *b) +inline static unsigned int timespec_sub_ms(struct timespec *a, + struct timespec *b) { - return (a->tv_sec * 1000 + a->tv_nsec / (1000 * 1000) - - (b->tv_sec * 1000 + b->tv_nsec / (1000 * 1000))); + return (a->tv_sec * 1000 + a->tv_nsec / (1000 * 1000) - + (b->tv_sec * 1000 + b->tv_nsec / (1000 * 1000))); } - -inline static -uint64_t -timespec_sub_us (struct timespec *a, struct timespec *b) +inline static uint64_t timespec_sub_us(struct timespec *a, struct timespec *b) { - return (a->tv_sec * 1000000ULL + a->tv_nsec / (1000) - - (b->tv_sec * 1000000ULL + b->tv_nsec / (1000))); + return (a->tv_sec * 1000000ULL + a->tv_nsec / (1000) - + (b->tv_sec * 1000000ULL + b->tv_nsec / (1000))); } #endif diff --git a/src/html.c b/src/html.c index 85d59a09..60d4f823 100644 --- a/src/html.c +++ b/src/html.c @@ -29,18 +29,19 @@ #include "html.h" #include "log.h" -char *unescape_html(void *pool, const char *html, unsigned len, unsigned *out_len) +char *unescape_html(void *pool, const char *html, unsigned int len, + unsigned int *out_len) { char *msg; int pos; - unsigned i; + unsigned int i; msg = talloc_size(pool, len + 1); if (msg == NULL) return NULL; for (i = pos = 0; i < len;) { - if (len-pos < 1) { + if (len - pos < 1) { goto fail; } @@ -68,28 +69,31 @@ char *unescape_html(void *pool, const char *html, unsigned len, unsigned *out_le char *endptr = NULL; long val; - if (p[2]=='x') { + if (p[2] == 'x') { p += 3; val = strtol(p, &endptr, 16); } else { p += 2; val = strtol(p, &endptr, 10); } - if (endptr == NULL || *endptr != ';' || val > WCHAR_MAX) { + if (endptr == NULL || *endptr != ';' || + val > WCHAR_MAX) { /* skip */ msg[pos++] = html[i++]; } else { char tmpmb[MB_CUR_MAX]; wchar_t ch = val; mbstate_t ps; + memset(&ps, 0, sizeof(ps)); - i += (ptrdiff_t)(1+endptr-(&html[i])); + i += (ptrdiff_t)(1 + endptr - + (&html[i])); val = wcrtomb(tmpmb, ch, &ps); if (val == -1) goto fail; - if (len-pos > val) + if (len - pos > val) memcpy(&msg[pos], tmpmb, val); else goto fail; @@ -106,16 +110,17 @@ char *unescape_html(void *pool, const char *html, unsigned len, unsigned *out_le *out_len = pos; return msg; - fail: +fail: talloc_free(msg); return NULL; } -char *unescape_url(void *pool, const char *url, unsigned len, unsigned *out_len) +char *unescape_url(void *pool, const char *url, unsigned int len, + unsigned int *out_len) { char *msg; int pos; - unsigned i; + unsigned int i; msg = talloc_size(pool, len + 1); if (msg == NULL) @@ -132,7 +137,8 @@ char *unescape_url(void *pool, const char *url, unsigned len, unsigned *out_len) if (sscanf(b, "%02x", &u) <= 0) { talloc_free(msg); - oc_syslog(LOG_ERR, "%s: error parsing URL: %s", __func__, url); + oc_syslog(LOG_ERR, "%s: error parsing URL: %s", + __func__, url); return NULL; } @@ -152,25 +158,28 @@ char *unescape_url(void *pool, const char *url, unsigned len, unsigned *out_len) return msg; } -char *escape_url(void *pool, const char *url, unsigned len, unsigned *out_len) +char *escape_url(void *pool, const char *url, unsigned int len, + unsigned int *out_len) { char *msg; int pos; - unsigned i; + unsigned int i; - msg = talloc_size(pool, 3*len + 1); + msg = talloc_size(pool, 3 * len + 1); if (msg == NULL) return NULL; for (i = pos = 0; i < len;) { - if (isalnum(url[i]) || url[i]=='-' || url[i]=='_' || url[i]=='.' || url[i]=='~') { + if (isalnum(url[i]) || url[i] == '-' || url[i] == '_' || + url[i] == '.' || url[i] == '~') { msg[pos++] = url[i++]; } else if (url[i] == ' ') { msg[pos++] = '+'; i++; } else { - snprintf(&msg[pos], 4, "%%%02X", (unsigned)url[i++]); - pos+=3; + snprintf(&msg[pos], 4, "%%%02X", + (unsigned int)url[i++]); + pos += 3; } } msg[pos] = 0; diff --git a/src/html.h b/src/html.h index 1db9b280..a12b422f 100644 --- a/src/html.h +++ b/src/html.h @@ -19,10 +19,13 @@ * along with this program. If not, see */ #ifndef OC_HTML_H -# define OC_HTML_H +#define OC_HTML_H -char* unescape_html(void *pool, const char *html, unsigned len, unsigned *out_len); -char *unescape_url(void *pool, const char *url, unsigned len, unsigned *out_len); -char *escape_url(void *pool, const char *url, unsigned len, unsigned *out_len); +char *unescape_html(void *pool, const char *html, unsigned int len, + unsigned int *out_len); +char *unescape_url(void *pool, const char *url, unsigned int len, + unsigned int *out_len); +char *escape_url(void *pool, const char *url, unsigned int len, + unsigned int *out_len); #endif diff --git a/src/icmp-ping.c b/src/icmp-ping.c index 2093845e..e47e7ed7 100644 --- a/src/icmp-ping.c +++ b/src/icmp-ping.c @@ -74,7 +74,7 @@ #include #include #ifdef HAVE_NETINET_IN_SYSTM_H -# include +#include #endif #include #include @@ -89,11 +89,11 @@ #include #ifndef ICMP_DEST_UNREACH -# ifdef ICMP_UNREACH -# define ICMP_DEST_UNREACH ICMP_UNREACH -# else -# define ICMP_DEST_UNREACH 3 -# endif +#ifdef ICMP_UNREACH +#define ICMP_DEST_UNREACH ICMP_UNREACH +#else +#define ICMP_DEST_UNREACH 3 +#endif #endif /* I see RENUMBERED constants in bits/in.h - !!? @@ -110,7 +110,7 @@ enum { MAXPACKET = 65468, MAX_DUP_CHK = (8 * 128), MAXWAIT = 10, - PINGINTERVAL = 1, /* 1 second */ + PINGINTERVAL = 1, /* 1 second */ }; /* common routines */ @@ -128,7 +128,7 @@ static int in_cksum(unsigned short *buf, int sz) } if (nleft == 1) { - *(unsigned char *) (&ans) = *(unsigned char *) w; + *(unsigned char *)(&ans) = *(unsigned char *)w; sum += ans; } @@ -148,29 +148,26 @@ inline static int retry(int e) #define PING_TIMEOUT 3 -static -ssize_t recvfrom_timeout(int sockfd, void *buf, size_t len, int flags, - struct sockaddr *src_addr, socklen_t * addrlen) +static ssize_t recvfrom_timeout(int sockfd, void *buf, size_t len, int flags, + struct sockaddr *src_addr, socklen_t *addrlen) { int ret; - struct pollfd pfd; + struct pollfd pfd; - pfd.fd = sockfd; - pfd.events = POLLIN; - pfd.revents = 0; + pfd.fd = sockfd; + pfd.events = POLLIN; + pfd.revents = 0; - ret = poll(&pfd, 1, 250); + ret = poll(&pfd, 1, 250); if (ret == -1) return -1; else if (ret > 0) return recvfrom(sockfd, buf, len, 0, src_addr, addrlen); else return -1; - - } -int icmp_ping4(main_server_st * s, struct sockaddr_in *addr1) +int icmp_ping4(main_server_st *s, struct sockaddr_in *addr1) { struct icmp *pkt; int pingsock, c, e; @@ -178,14 +175,15 @@ int icmp_ping4(main_server_st * s, struct sockaddr_in *addr1) char buf1[64]; time_t now; uint16_t id1; - unsigned gotreply = 0, unreachable = 0; + unsigned int gotreply = 0, unreachable = 0; if (GETCONFIG(s)->ping_leases == 0) return 0; - if ((e=gnutls_rnd(GNUTLS_RND_NONCE, &id1, sizeof(id1))) < 0) { - mslog(s, NULL, LOG_ERR, - "error in the random generator: %s", gnutls_strerror(e)); + e = gnutls_rnd(GNUTLS_RND_NONCE, &id1, sizeof(id1)); + if (e < 0) { + mslog(s, NULL, LOG_ERR, "error in the random generator: %s", + gnutls_strerror(e)); return 0; } @@ -197,47 +195,51 @@ int icmp_ping4(main_server_st * s, struct sockaddr_in *addr1) return 0; } - pkt = (struct icmp *) packet1; + pkt = (struct icmp *)packet1; memset(pkt, 0, sizeof(packet1)); pkt->icmp_type = ICMP_ECHO; pkt->icmp_id = id1; - pkt->icmp_cksum = - in_cksum((unsigned short *) pkt, sizeof(packet1)); + pkt->icmp_cksum = in_cksum((unsigned short *)pkt, sizeof(packet1)); while (sendto(pingsock, packet1, DEFDATALEN + ICMP_MINLEN, 0, - (struct sockaddr *) addr1, - sizeof(*addr1) == -1) && retry(errno)); + (struct sockaddr *)addr1, sizeof(*addr1) == -1) && + retry(errno)) + ; /* listen for replies */ now = time(NULL); - while (time(NULL) - now < PING_TIMEOUT - && (unreachable + gotreply) < 2) { + while (time(NULL) - now < PING_TIMEOUT && + (unreachable + gotreply) < 2) { struct sockaddr_in from; socklen_t fromlen = sizeof(from); c = recvfrom_timeout(pingsock, packet1, sizeof(packet1), 0, - (struct sockaddr *) &from, &fromlen); + (struct sockaddr *)&from, &fromlen); if (c < 0) { continue; - } else if (c >= 76 && fromlen == sizeof(struct sockaddr_in)) { /* icmp6_hdr */ - if (memcmp - (SA_IN_P(&from), SA_IN_P(addr1), - SA_IN_SIZE(sizeof(*addr1))) == 0) { - + } else if (c >= 76 && + fromlen == + sizeof(struct sockaddr_in)) { /* icmp6_hdr */ + if (memcmp(SA_IN_P(&from), SA_IN_P(addr1), + SA_IN_SIZE(sizeof(*addr1))) == 0) { #ifdef HAVE_STRUCT_IPHDR_IHL - struct iphdr *iphdr = - (struct iphdr *) packet1; - pkt = (struct icmp *) (packet1 + (iphdr->ihl << 2)); /* skip ip hdr */ + struct iphdr *iphdr = (struct iphdr *)packet1; + pkt = (struct icmp *)(packet1 + + (iphdr->ihl + << 2)); /* skip ip hdr */ #else - pkt = (struct icmp *) (packet1 + ((packet1[0] & 0x0f) << 2)); /* skip ip hdr */ + pkt = (struct icmp *)(packet1 + + ((packet1[0] & 0x0f) + << 2)); /* skip ip hdr */ #endif if (pkt->icmp_id == id1) { if (pkt->icmp_type == ICMP_ECHOREPLY) gotreply++; - else if (pkt->icmp_type == ICMP_DEST_UNREACH) + else if (pkt->icmp_type == + ICMP_DEST_UNREACH) unreachable++; - } + } } } } @@ -245,24 +247,19 @@ int icmp_ping4(main_server_st * s, struct sockaddr_in *addr1) close(pingsock); if (gotreply > 0) { - mslog(s, NULL, LOG_INFO, - "pinged %s and is in use", - human_addr((void *) addr1, - sizeof(struct sockaddr_in), buf1, - sizeof(buf1))); + mslog(s, NULL, LOG_INFO, "pinged %s and is in use", + human_addr((void *)addr1, sizeof(struct sockaddr_in), + buf1, sizeof(buf1))); return gotreply; } else { - mslog(s, NULL, LOG_INFO, - "pinged %s and is not in use", - human_addr((void *) addr1, - sizeof(struct sockaddr_in), buf1, - sizeof(buf1))); + mslog(s, NULL, LOG_INFO, "pinged %s and is not in use", + human_addr((void *)addr1, sizeof(struct sockaddr_in), + buf1, sizeof(buf1))); return 0; } } -int icmp_ping6(main_server_st * s, - struct sockaddr_in6 *addr1) +int icmp_ping6(main_server_st *s, struct sockaddr_in6 *addr1) { struct icmp6_hdr *pkt; char buf1[64]; @@ -272,15 +269,16 @@ int icmp_ping6(main_server_st * s, #endif char packet1[DEFDATALEN + MAXIPLEN + MAXICMPLEN]; uint16_t id1; - unsigned gotreply = 0, unreachable = 0; + unsigned int gotreply = 0, unreachable = 0; time_t now; if (GETCONFIG(s)->ping_leases == 0) return 0; - if ((e=gnutls_rnd(GNUTLS_RND_NONCE, &id1, sizeof(id1))) < 0) { - mslog(s, NULL, LOG_ERR, - "error in the random generator: %s", gnutls_strerror(e)); + e = gnutls_rnd(GNUTLS_RND_NONCE, &id1, sizeof(id1)); + if (e < 0) { + mslog(s, NULL, LOG_ERR, "error in the random generator: %s", + gnutls_strerror(e)); return 0; } @@ -292,43 +290,42 @@ int icmp_ping6(main_server_st * s, return 0; } - pkt = (struct icmp6_hdr *) packet1; + pkt = (struct icmp6_hdr *)packet1; memset(pkt, 0, sizeof(packet1)); pkt->icmp6_type = ICMP6_ECHO_REQUEST; pkt->icmp6_id = id1; #if defined(SOL_RAW) && defined(IPV6_CHECKSUM) sockopt = offsetof(struct icmp6_hdr, icmp6_cksum); - setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, - &sockopt, sizeof(sockopt)); + setsockopt(pingsock, SOL_RAW, IPV6_CHECKSUM, &sockopt, sizeof(sockopt)); #endif - while (sendto(pingsock, packet1, - DEFDATALEN + sizeof(struct icmp6_hdr), 0, - (struct sockaddr *) addr1, - sizeof(*addr1) == -1) && retry(errno)); + while (sendto(pingsock, packet1, DEFDATALEN + sizeof(struct icmp6_hdr), + 0, (struct sockaddr *)addr1, sizeof(*addr1) == -1) && + retry(errno)) + ; /* listen for replies */ now = time(NULL); - while (time(NULL) - now < PING_TIMEOUT - && (unreachable + gotreply) < 2) { + while (time(NULL) - now < PING_TIMEOUT && + (unreachable + gotreply) < 2) { struct sockaddr_in6 from; socklen_t fromlen = sizeof(from); - c = recvfrom_timeout(pingsock, packet1, - sizeof(packet1), 0, - (struct sockaddr *) - &from, &fromlen); + + c = recvfrom_timeout(pingsock, packet1, sizeof(packet1), 0, + (struct sockaddr *)&from, &fromlen); if (c < 0) { continue; - } else if (c >= 8 && fromlen == sizeof(struct sockaddr_in6)) { /* icmp6_hdr */ - if (memcmp - (SA_IN6_P(&from), SA_IN6_P(addr1), - SA_IN_SIZE(sizeof(*addr1))) == 0) { - - pkt = (struct icmp6_hdr *) packet1; + } else if (c >= 8 && + fromlen == + sizeof(struct sockaddr_in6)) { /* icmp6_hdr */ + if (memcmp(SA_IN6_P(&from), SA_IN6_P(addr1), + SA_IN_SIZE(sizeof(*addr1))) == 0) { + pkt = (struct icmp6_hdr *)packet1; if (pkt->icmp6_id == id1) { if (pkt->icmp6_type == ICMP6_ECHO_REPLY) gotreply++; - else if (pkt->icmp6_type == ICMP6_DST_UNREACH) + else if (pkt->icmp6_type == + ICMP6_DST_UNREACH) unreachable++; } } @@ -338,18 +335,14 @@ int icmp_ping6(main_server_st * s, close(pingsock); if (gotreply > 0) { - mslog(s, NULL, LOG_INFO, - "pinged %s and is in use", - human_addr((void *) addr1, - sizeof(struct sockaddr_in6), buf1, - sizeof(buf1))); + mslog(s, NULL, LOG_INFO, "pinged %s and is in use", + human_addr((void *)addr1, sizeof(struct sockaddr_in6), + buf1, sizeof(buf1))); return gotreply; } else { - mslog(s, NULL, LOG_INFO, - "pinged %s and is not in use", - human_addr((void *) addr1, - sizeof(struct sockaddr_in6), buf1, - sizeof(buf1))); + mslog(s, NULL, LOG_INFO, "pinged %s and is not in use", + human_addr((void *)addr1, sizeof(struct sockaddr_in6), + buf1, sizeof(buf1))); return 0; } } diff --git a/src/icmp-ping.h b/src/icmp-ping.h index c81a5d60..0f5936c4 100644 --- a/src/icmp-ping.h +++ b/src/icmp-ping.h @@ -19,13 +19,13 @@ * along with this program. If not, see */ #ifndef OC_ICMP_PING_H -# define OC_ICMP_PING_H +#define OC_ICMP_PING_H #include /* returns the number of positive replies received or * 0 if no host with this IP exists. */ -int icmp_ping4(main_server_st* s, struct sockaddr_in* addr1); -int icmp_ping6(main_server_st* s, struct sockaddr_in6* addr1); +int icmp_ping4(main_server_st *s, struct sockaddr_in *addr1); +int icmp_ping6(main_server_st *s, struct sockaddr_in6 *addr1); #endif diff --git a/src/ip-lease.c b/src/ip-lease.c index de1fab69..b807d714 100644 --- a/src/ip-lease.c +++ b/src/ip-lease.c @@ -27,8 +27,8 @@ #include #include -static void ip_from_seed(uint8_t *seed, unsigned seed_size, - void *ip, size_t ip_size) +static void ip_from_seed(uint8_t *seed, unsigned int seed_size, void *ip, + size_t ip_size) { uint8_t digest[20]; int ret; @@ -45,13 +45,12 @@ static void ip_from_seed(uint8_t *seed, unsigned seed_size, } memcpy(ip, digest, ip_size); - } -void ip_lease_deinit(struct ip_lease_db_st* db) +void ip_lease_deinit(struct ip_lease_db_st *db) { -struct ip_lease_st * cache; -struct htable_iter iter; + struct ip_lease_st *cache; + struct htable_iter iter; cache = htable_first(&db->ht, &iter); while (cache != NULL) { @@ -64,44 +63,46 @@ struct htable_iter iter; htable_clear(&db->ht); } -static size_t rehash(const void* _e, void* unused) +static size_t rehash(const void *_e, void *unused) { -const struct ip_lease_st * e = _e; + const struct ip_lease_st *e = _e; - return hash_any(SA_IN_P_GENERIC(&e->sig, e->sig_len), SA_IN_SIZE(e->sig_len), 0); + return hash_any(SA_IN_P_GENERIC(&e->sig, e->sig_len), + SA_IN_SIZE(e->sig_len), 0); } -void ip_lease_init(struct ip_lease_db_st* db) +void ip_lease_init(struct ip_lease_db_st *db) { htable_init(&db->ht, rehash, NULL); } -static bool ip_lease_cmp(const void* _c1, void* _c2) +static bool ip_lease_cmp(const void *_c1, void *_c2) { -const struct ip_lease_st* c1 = _c1; -struct ip_lease_st* c2 = _c2; + const struct ip_lease_st *c1 = _c1; + struct ip_lease_st *c2 = _c2; - if (c1->sig_len == c2->sig_len && - ip_cmp(&c1->sig, &c2->sig) == 0) + if (c1->sig_len == c2->sig_len && ip_cmp(&c1->sig, &c2->sig) == 0) return 1; return 0; } -static int ip_lease_exists(main_server_st* s, struct sockaddr_storage* ip, size_t sockaddrlen) +static int ip_lease_exists(main_server_st *s, struct sockaddr_storage *ip, + size_t sockaddrlen) { -struct ip_lease_st t; + struct ip_lease_st t; t.sig_len = sockaddrlen; memcpy(&t.sig, ip, sizeof(*ip)); - if (htable_get(&s->ip_leases.ht, rehash(&t, NULL), ip_lease_cmp, &t) != 0) + if (htable_get(&s->ip_leases.ht, rehash(&t, NULL), ip_lease_cmp, &t) != + 0) return 1; return 0; } -void steal_ip_leases(struct proc_st* proc, struct proc_st *thief) +void steal_ip_leases(struct proc_st *proc, struct proc_st *thief) { /* here we reset the old tun device, and assign the old addresses * to a new device. We cannot reuse the old device because the @@ -120,9 +121,12 @@ void steal_ip_leases(struct proc_st* proc, struct proc_st *thief) if (proc->ipv4 != NULL) { proc->ipv4->rip_len = thief->ipv4->rip_len; proc->ipv4->lip_len = thief->ipv4->lip_len; - memcpy(&proc->ipv4->rip, &thief->ipv4->rip, thief->ipv4->rip_len); - memcpy(&proc->ipv4->lip, &thief->ipv4->lip, thief->ipv4->lip_len); - memcpy(&proc->ipv4->sig, &thief->ipv4->sig, thief->ipv4->sig_len); + memcpy(&proc->ipv4->rip, &thief->ipv4->rip, + thief->ipv4->rip_len); + memcpy(&proc->ipv4->lip, &thief->ipv4->lip, + thief->ipv4->lip_len); + memcpy(&proc->ipv4->sig, &thief->ipv4->sig, + thief->ipv4->sig_len); } } @@ -133,14 +137,19 @@ void steal_ip_leases(struct proc_st* proc, struct proc_st *thief) proc->ipv6->prefix = thief->ipv6->prefix; proc->ipv6->rip_len = thief->ipv6->rip_len; proc->ipv6->lip_len = thief->ipv6->lip_len; - memcpy(&proc->ipv6->rip, &thief->ipv6->rip, thief->ipv6->rip_len); - memcpy(&proc->ipv6->lip, &thief->ipv6->lip, thief->ipv6->lip_len); - memcpy(&proc->ipv6->sig, &thief->ipv6->sig, thief->ipv6->sig_len); + memcpy(&proc->ipv6->rip, &thief->ipv6->rip, + thief->ipv6->rip_len); + memcpy(&proc->ipv6->lip, &thief->ipv6->lip, + thief->ipv6->lip_len); + memcpy(&proc->ipv6->sig, &thief->ipv6->sig, + thief->ipv6->sig_len); } } } -static int is_ipv6_ok(main_server_st *s, struct sockaddr_storage *ip, struct sockaddr_storage *tun, struct sockaddr_storage *subnet) +static int is_ipv6_ok(main_server_st *s, struct sockaddr_storage *ip, + struct sockaddr_storage *tun, + struct sockaddr_storage *subnet) { /* check that IP & mask don't match tun IP */ if (ip_cmp(subnet, tun) == 0) { @@ -155,19 +164,20 @@ static int is_ipv6_ok(main_server_st *s, struct sockaddr_storage *ip, struct soc return 1; } -static int is_ipv4_ok(main_server_st *s, struct sockaddr_storage *ip, struct sockaddr_storage *net, struct sockaddr_storage *mask) +static int is_ipv4_ok(main_server_st *s, struct sockaddr_storage *ip, + struct sockaddr_storage *net, + struct sockaddr_storage *mask) { struct sockaddr_storage broadcast; - unsigned i; + unsigned int i; memcpy(&broadcast, net, sizeof(broadcast)); - for (i=0;iconfig->ipv4_netmask; } else { c_network = proc->vhost->perm_config.config->network.ipv4; - c_netmask = proc->vhost->perm_config.config->network.ipv4_netmask; + c_netmask = + proc->vhost->perm_config.config->network.ipv4_netmask; } if (c_network == NULL || c_netmask == NULL) { @@ -203,32 +212,31 @@ int get_ipv4_lease(main_server_st* s, struct proc_st* proc) return 0; } - ret = - inet_pton(AF_INET, c_network, SA_IN_P(&network)); + ret = inet_pton(AF_INET, c_network, SA_IN_P(&network)); if (ret != 1) { mslog(s, NULL, LOG_ERR, "error reading IP: %s", c_network); return -1; } - ret = - inet_pton(AF_INET, c_netmask, SA_IN_P(&mask)); + ret = inet_pton(AF_INET, c_netmask, SA_IN_P(&mask)); if (ret != 1) { mslog(s, NULL, LOG_ERR, "error reading mask: %s", c_netmask); return -1; } /* mask the network (just in case it is wrong) */ - for (i=0;isin_family = AF_INET; - ((struct sockaddr_in*)&network)->sin_port = 0; + ((struct sockaddr_in *)&network)->sin_family = AF_INET; + ((struct sockaddr_in *)&network)->sin_port = 0; if (proc->config->explicit_ipv4) { - ret = - inet_pton(AF_INET, proc->config->explicit_ipv4, SA_IN_P(&tmp)); + ret = inet_pton(AF_INET, proc->config->explicit_ipv4, + SA_IN_P(&tmp)); if (ret != 1) { - mslog(s, NULL, LOG_ERR, "error reading explicit IP: %s", proc->config->explicit_ipv4); + mslog(s, NULL, LOG_ERR, "error reading explicit IP: %s", + proc->config->explicit_ipv4); return -1; } @@ -236,16 +244,19 @@ int get_ipv4_lease(main_server_st* s, struct proc_st* proc) if (proc->ipv4 == NULL) return ERR_MEM; - ((struct sockaddr_in*)&tmp)->sin_family = AF_INET; - ((struct sockaddr_in*)&tmp)->sin_port = 0; + ((struct sockaddr_in *)&tmp)->sin_family = AF_INET; + ((struct sockaddr_in *)&tmp)->sin_port = 0; memcpy(&proc->ipv4->rip, &tmp, sizeof(struct sockaddr_in)); proc->ipv4->rip_len = sizeof(struct sockaddr_in); memcpy(&proc->ipv4->sig, &tmp, sizeof(struct sockaddr_in)); if (is_ipv4_ok(s, &proc->ipv4->rip, &network, &mask) == 0) { - mslog(s, proc, LOG_DEBUG, "cannot assign explicit IP %s; it is in use or invalid", - human_addr((void*)&tmp, sizeof(struct sockaddr_in), buf, sizeof(buf))); + mslog(s, proc, LOG_DEBUG, + "cannot assign explicit IP %s; it is in use or invalid", + human_addr((void *)&tmp, + sizeof(struct sockaddr_in), buf, + sizeof(buf))); ret = ERR_NO_IP; goto fail; } @@ -256,7 +267,9 @@ int get_ipv4_lease(main_server_st* s, struct proc_st* proc) SA_IN_U8_P(&proc->ipv4->lip)[3] |= 1; if (ip_cmp(&proc->ipv4->lip, &proc->ipv4->rip) == 0) { - mslog(s, NULL, LOG_ERR, "cannot assign explicit IP %s; network: %s", proc->config->explicit_ipv4, c_network); + mslog(s, NULL, LOG_ERR, + "cannot assign explicit IP %s; network: %s", + proc->config->explicit_ipv4, c_network); ret = ERR_NO_IP; goto fail; } @@ -271,49 +284,59 @@ int get_ipv4_lease(main_server_st* s, struct proc_st* proc) proc->ipv4->db = &s->ip_leases; memcpy(&tmp, &network, sizeof(tmp)); - ((struct sockaddr_in*)&tmp)->sin_family = AF_INET; - ((struct sockaddr_in*)&tmp)->sin_port = 0; + ((struct sockaddr_in *)&tmp)->sin_family = AF_INET; + ((struct sockaddr_in *)&tmp)->sin_port = 0; memset(&rnd, 0, sizeof(rnd)); - ((struct sockaddr_in*)&rnd)->sin_family = AF_INET; - ((struct sockaddr_in*)&rnd)->sin_port = 0; + ((struct sockaddr_in *)&rnd)->sin_family = AF_INET; + ((struct sockaddr_in *)&rnd)->sin_port = 0; do { if (max_loops == 0) { - mslog(s, proc, LOG_ERR, "could not figure out a valid IPv4 IP"); + mslog(s, proc, LOG_ERR, + "could not figure out a valid IPv4 IP"); ret = ERR_NO_IP; goto fail; } if (max_loops == MAX_IP_TRIES) { memcpy(SA_IN_U8_P(&rnd), proc->ipv4_seed, 4); } else { - if (max_loops < MAX_IP_TRIES-FIXED_IPS) { - ret = gnutls_rnd(GNUTLS_RND_NONCE, SA_IN_U8_P(&rnd), sizeof(struct in_addr)); + if (max_loops < MAX_IP_TRIES - FIXED_IPS) { + ret = gnutls_rnd(GNUTLS_RND_NONCE, + SA_IN_U8_P(&rnd), + sizeof(struct in_addr)); if (ret < 0) { - mslog(s, proc, LOG_ERR, "error in the random generator: %s", gnutls_strerror(ret)); + mslog(s, proc, LOG_ERR, + "error in the random generator: %s", + gnutls_strerror(ret)); ret = ERR_NO_IP; goto fail; } } else { - ip_from_seed(SA_IN_U8_P(&rnd), sizeof(struct in_addr), - SA_IN_U8_P(&rnd), sizeof(struct in_addr)); + ip_from_seed(SA_IN_U8_P(&rnd), + sizeof(struct in_addr), + SA_IN_U8_P(&rnd), + sizeof(struct in_addr)); } } max_loops--; /* Mask the random number with the netmask */ - for (i=0;iipv4->lip_len = sizeof(struct sockaddr_in); SA_IN_U8_P(&proc->ipv4->lip)[3] |= 1; - if (memcmp(SA_IN_U8_P(&proc->ipv4->lip), SA_IN_U8_P(&proc->ipv4->rip), sizeof(struct in_addr)) == 0) { + if (memcmp(SA_IN_U8_P(&proc->ipv4->lip), + SA_IN_U8_P(&proc->ipv4->rip), + sizeof(struct in_addr)) == 0) { continue; } mslog(s, proc, LOG_DEBUG, "selected IP: %s", - human_addr((void*)&proc->ipv4->rip, proc->ipv4->rip_len, buf, sizeof(buf))); + human_addr((void *)&proc->ipv4->rip, proc->ipv4->rip_len, + buf, sizeof(buf))); - if (icmp_ping4(s, (void*)&proc->ipv4->rip) == 0) + if (icmp_ping4(s, (void *)&proc->ipv4->rip) == 0) break; } while (1); return 0; - fail: +fail: talloc_free(proc->ipv4); proc->ipv4 = NULL; return ret; } -static -int get_ipv6_lease(main_server_st* s, struct proc_st* proc) +static int get_ipv6_lease(main_server_st *s, struct proc_st *proc) { - struct sockaddr_storage tmp, mask, network, rnd, subnet_mask; - unsigned i, max_loops = MAX_IP_TRIES; - const char* c_network = NULL; - unsigned prefix, subnet_prefix ; + unsigned int i, max_loops = MAX_IP_TRIES; + const char *c_network = NULL; + unsigned int prefix, subnet_prefix; int ret; char buf[64]; @@ -365,7 +389,8 @@ int get_ipv6_lease(main_server_st* s, struct proc_st* proc) } else { c_network = proc->vhost->perm_config.config->network.ipv6; prefix = proc->vhost->perm_config.config->network.ipv6_prefix; - subnet_prefix = proc->vhost->perm_config.config->network.ipv6_subnet_prefix; + subnet_prefix = proc->vhost->perm_config.config->network + .ipv6_subnet_prefix; } if (c_network == NULL || prefix == 0 || subnet_prefix == 0) { @@ -380,21 +405,21 @@ int get_ipv6_lease(main_server_st* s, struct proc_st* proc) ret = ipv6_prefix_to_mask(SA_IN6_P(&subnet_mask), subnet_prefix); if (ret == 0) { - mslog(s, NULL, LOG_ERR, "error reading prefix: %u", subnet_prefix); + mslog(s, NULL, LOG_ERR, "error reading prefix: %u", + subnet_prefix); return -1; } - ret = - inet_pton(AF_INET6, c_network, SA_IN6_P(&network)); + ret = inet_pton(AF_INET6, c_network, SA_IN6_P(&network)); if (ret != 1) { mslog(s, NULL, LOG_ERR, "error reading IP: %s", c_network); return -1; } /* mask the network */ - ((struct sockaddr_in6*)&network)->sin6_family = AF_INET6; - ((struct sockaddr_in6*)&network)->sin6_port = 0; - for (i=0;isin6_family = AF_INET6; + ((struct sockaddr_in6 *)&network)->sin6_port = 0; + for (i = 0; i < sizeof(struct in6_addr); i++) SA_IN6_U8_P(&network)[i] &= (SA_IN6_U8_P(&mask)[i]); proc->ipv6 = talloc_zero(proc, struct ip_lease_st); @@ -409,26 +434,34 @@ int get_ipv6_lease(main_server_st* s, struct proc_st* proc) if (proc->config->explicit_ipv6) { memset(&tmp, 0, sizeof(tmp)); - ret = - inet_pton(AF_INET6, proc->config->explicit_ipv6, SA_IN6_P(&tmp)); + ret = inet_pton(AF_INET6, proc->config->explicit_ipv6, + SA_IN6_P(&tmp)); if (ret != 1) { - mslog(s, NULL, LOG_ERR, "error reading explicit IP %s", proc->config->explicit_ipv6); + mslog(s, NULL, LOG_ERR, "error reading explicit IP %s", + proc->config->explicit_ipv6); ret = ERR_NO_IP; goto fail; } - ((struct sockaddr_in6*)&tmp)->sin6_family = AF_INET6; + ((struct sockaddr_in6 *)&tmp)->sin6_family = AF_INET6; memcpy(&proc->ipv6->rip, &tmp, sizeof(struct sockaddr_in6)); proc->ipv6->rip_len = sizeof(struct sockaddr_in6); /* create our sig */ - for (i=0;iipv6->sig)[i] = SA_IN6_U8_P(&proc->ipv6->rip)[i] & SA_IN6_U8_P(&subnet_mask)[i]; + for (i = 0; i < sizeof(struct in6_addr); i++) { + uint8_t *p = SA_IN6_U8_P(&proc->ipv6->sig); + p[i] = (SA_IN6_U8_P(&proc->ipv6->rip)[i]) & + SA_IN6_U8_P(&subnet_mask)[i]; + } - if (is_ipv6_ok(s, &tmp, &proc->ipv6->lip, &proc->ipv6->sig) == 0) { - mslog(s, proc, LOG_DEBUG, "cannot assign explicit IP %s; it is in use or invalid", - human_addr((void*)&tmp, sizeof(struct sockaddr_in6), buf, sizeof(buf))); + if (is_ipv6_ok(s, &tmp, &proc->ipv6->lip, &proc->ipv6->sig) == + 0) { + mslog(s, proc, LOG_DEBUG, + "cannot assign explicit IP %s; it is in use or invalid", + human_addr((void *)&tmp, + sizeof(struct sockaddr_in6), buf, + sizeof(buf))); ret = ERR_NO_IP; goto fail; } @@ -440,56 +473,70 @@ int get_ipv6_lease(main_server_st* s, struct proc_st* proc) proc->ipv6->db = &s->ip_leases; memcpy(&tmp, &network, sizeof(tmp)); - ((struct sockaddr_in6*)&tmp)->sin6_family = AF_INET6; - ((struct sockaddr_in6*)&tmp)->sin6_port = 0; + ((struct sockaddr_in6 *)&tmp)->sin6_family = AF_INET6; + ((struct sockaddr_in6 *)&tmp)->sin6_port = 0; do { if (max_loops == 0) { - mslog(s, NULL, LOG_ERR, "could not figure out a valid IPv6 IP"); + mslog(s, NULL, LOG_ERR, + "could not figure out a valid IPv6 IP"); ret = ERR_NO_IP; goto fail; } memset(&rnd, 0, sizeof(rnd)); - ((struct sockaddr_in6*)&rnd)->sin6_family = AF_INET6; + ((struct sockaddr_in6 *)&rnd)->sin6_family = AF_INET6; if (max_loops == MAX_IP_TRIES) { - ip_from_seed(proc->ipv4_seed, 4, - SA_IN6_U8_P(&rnd), sizeof(struct in6_addr)); + ip_from_seed(proc->ipv4_seed, 4, SA_IN6_U8_P(&rnd), + sizeof(struct in6_addr)); } else { - if (max_loops < MAX_IP_TRIES-FIXED_IPS) { - ret = gnutls_rnd(GNUTLS_RND_NONCE, SA_IN_U8_P(&rnd), sizeof(struct in6_addr)); + if (max_loops < MAX_IP_TRIES - FIXED_IPS) { + ret = gnutls_rnd(GNUTLS_RND_NONCE, + SA_IN_U8_P(&rnd), + sizeof(struct in6_addr)); if (ret < 0) { - mslog(s, proc, LOG_ERR, "error in the random generator: %s", gnutls_strerror(ret)); + mslog(s, proc, LOG_ERR, + "error in the random generator: %s", + gnutls_strerror(ret)); ret = ERR_NO_IP; goto fail; } } else { - ip_from_seed(SA_IN6_U8_P(&rnd), sizeof(struct in6_addr), - SA_IN6_U8_P(&rnd), sizeof(struct in6_addr)); + ip_from_seed(SA_IN6_U8_P(&rnd), + sizeof(struct in6_addr), + SA_IN6_U8_P(&rnd), + sizeof(struct in6_addr)); } } max_loops--; /* Mask the random number with the netmask */ - for (i=0;iipv6->sig)->sin6_family = AF_INET6; - ((struct sockaddr_in6*)&proc->ipv6->sig)->sin6_port = 0; - for (i=0;iipv6->sig)[i] = SA_IN6_U8_P(&rnd)[i] & SA_IN6_U8_P(&subnet_mask)[i]; + ((struct sockaddr_in6 *)&proc->ipv6->sig)->sin6_family = + AF_INET6; + ((struct sockaddr_in6 *)&proc->ipv6->sig)->sin6_port = 0; + for (i = 0; i < sizeof(struct in6_addr); i++) { + SA_IN6_U8_P(&proc->ipv6->sig) + [i] = SA_IN6_U8_P(&rnd)[i] & + SA_IN6_U8_P(&subnet_mask)[i]; } /* check if it exists in the hash table */ - if (is_ipv6_ok(s, &rnd, &proc->ipv6->lip, &proc->ipv6->sig) == 0) { - mslog(s, proc, LOG_DEBUG, "cannot assign IP %s; it is in use or invalid", - human_addr((void*)&rnd, sizeof(struct sockaddr_in6), buf, sizeof(buf))); + if (is_ipv6_ok(s, &rnd, &proc->ipv6->lip, &proc->ipv6->sig) == + 0) { + mslog(s, proc, LOG_DEBUG, + "cannot assign IP %s; it is in use or invalid", + human_addr((void *)&rnd, + sizeof(struct sockaddr_in6), buf, + sizeof(buf))); continue; } @@ -497,26 +544,26 @@ int get_ipv6_lease(main_server_st* s, struct proc_st* proc) memcpy(&proc->ipv6->rip, &rnd, proc->ipv6->rip_len); mslog(s, proc, LOG_DEBUG, "selected IP: %s", - human_addr((void*)&proc->ipv6->rip, proc->ipv6->rip_len, buf, sizeof(buf))); + human_addr((void *)&proc->ipv6->rip, proc->ipv6->rip_len, + buf, sizeof(buf))); - if (proc->ipv6->prefix != 128 || icmp_ping6(s, (void*)&proc->ipv6->rip) == 0) + if (proc->ipv6->prefix != 128 || + icmp_ping6(s, (void *)&proc->ipv6->rip) == 0) break; } while (1); - finish: +finish: proc->ipv6->prefix = subnet_prefix; return 0; - fail: +fail: talloc_free(proc->ipv6); proc->ipv6 = NULL; return ret; - } -static -int unref_ip_lease(struct ip_lease_st *lease) +static int unref_ip_lease(struct ip_lease_st *lease) { if (lease->db) { htable_del(&lease->db->ht, rehash(lease, NULL), lease); @@ -527,8 +574,8 @@ int unref_ip_lease(struct ip_lease_st *lease) int get_ip_leases(main_server_st *s, struct proc_st *proc) { -int ret; -char buf[128]; + int ret; + char buf[128]; if (proc->ipv4 == NULL) { ret = get_ipv4_lease(s, proc); @@ -536,8 +583,11 @@ char buf[128]; return ret; if (proc->ipv4 && proc->ipv4->db) { - if (htable_add(&s->ip_leases.ht, rehash(proc->ipv4, NULL), proc->ipv4) == 0) { - mslog(s, proc, LOG_ERR, "could not add IPv4 lease to hash table"); + if (htable_add(&s->ip_leases.ht, + rehash(proc->ipv4, NULL), + proc->ipv4) == 0) { + mslog(s, proc, LOG_ERR, + "could not add IPv4 lease to hash table"); return -1; } talloc_set_destructor(proc->ipv4, unref_ip_lease); @@ -550,8 +600,11 @@ char buf[128]; return ret; if (proc->ipv6 && proc->ipv6->db) { - if (htable_add(&s->ip_leases.ht, rehash(proc->ipv6, NULL), proc->ipv6) == 0) { - mslog(s, proc, LOG_ERR, "could not add IPv6 lease to hash table"); + if (htable_add(&s->ip_leases.ht, + rehash(proc->ipv6, NULL), + proc->ipv6) == 0) { + mslog(s, proc, LOG_ERR, + "could not add IPv6 lease to hash table"); return -1; } talloc_set_destructor(proc->ipv6, unref_ip_lease); @@ -559,23 +612,26 @@ char buf[128]; } if (proc->ipv4 == 0 && proc->ipv6 == 0) { - mslog(s, proc, LOG_ERR, "no IPv4 or IPv6 addresses are configured. Cannot obtain lease"); + mslog(s, proc, LOG_ERR, + "no IPv4 or IPv6 addresses are configured. Cannot obtain lease"); return -1; } if (proc->ipv4) mslog(s, proc, LOG_DEBUG, "assigned IPv4: %s", - human_addr((void*)&proc->ipv4->rip, proc->ipv4->rip_len, buf, sizeof(buf))); + human_addr((void *)&proc->ipv4->rip, proc->ipv4->rip_len, + buf, sizeof(buf))); if (proc->ipv6) mslog(s, proc, LOG_DEBUG, "assigned IPv6: %s/%u", - human_addr((void*)&proc->ipv6->rip, proc->ipv6->rip_len, buf, sizeof(buf)), - proc->ipv6->prefix); + human_addr((void *)&proc->ipv6->rip, proc->ipv6->rip_len, + buf, sizeof(buf)), + proc->ipv6->prefix); return 0; } -void remove_ip_leases(main_server_st* s, struct proc_st* proc) +void remove_ip_leases(main_server_st *s, struct proc_st *proc) { if (proc->ipv4) { talloc_free(proc->ipv4); @@ -587,7 +643,7 @@ void remove_ip_leases(main_server_st* s, struct proc_st* proc) } } -void remove_ip_lease(main_server_st* s, struct ip_lease_st * lease) +void remove_ip_lease(main_server_st *s, struct ip_lease_st *lease) { talloc_free(lease); } diff --git a/src/ip-lease.h b/src/ip-lease.h index 1cc6247f..208172b9 100644 --- a/src/ip-lease.h +++ b/src/ip-lease.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_IP_LEASE_H -# define OC_IP_LEASE_H +#define OC_IP_LEASE_H #include #include @@ -28,28 +28,28 @@ #include struct ip_lease_st { - /* In IPv4 this is the same as rip, in IPv6 - * that's the network address */ - struct sockaddr_storage sig; + /* In IPv4 this is the same as rip, in IPv6 + * that's the network address */ + struct sockaddr_storage sig; #define sig_len rip_len - struct sockaddr_storage rip; - socklen_t rip_len; + struct sockaddr_storage rip; + socklen_t rip_len; - struct sockaddr_storage lip; - socklen_t lip_len; - unsigned prefix; /* in ipv6 */ + struct sockaddr_storage lip; + socklen_t lip_len; + unsigned int prefix; /* in ipv6 */ - struct ip_lease_db_st* db; + struct ip_lease_db_st *db; }; -void ip_lease_deinit(struct ip_lease_db_st* db); -void ip_lease_init(struct ip_lease_db_st* db); +void ip_lease_deinit(struct ip_lease_db_st *db); +void ip_lease_init(struct ip_lease_db_st *db); -void steal_ip_leases(struct proc_st* proc, struct proc_st *thief); +void steal_ip_leases(struct proc_st *proc, struct proc_st *thief); -int get_ip_leases(struct main_server_st* s, struct proc_st* proc); -void remove_ip_leases(struct main_server_st* s, struct proc_st* proc); -void remove_ip_lease(main_server_st* s, struct ip_lease_st * lease); +int get_ip_leases(struct main_server_st *s, struct proc_st *proc); +void remove_ip_leases(struct main_server_st *s, struct proc_st *proc); +void remove_ip_lease(main_server_st *s, struct ip_lease_st *lease); #endif diff --git a/src/ip-util.c b/src/ip-util.c index 13011d8e..409a576f 100644 --- a/src/ip-util.c +++ b/src/ip-util.c @@ -35,16 +35,17 @@ int ip_cmp(const struct sockaddr_storage *s1, const struct sockaddr_storage *s2) { - if (((struct sockaddr*)s1)->sa_family == AF_INET) { + if (((struct sockaddr *)s1)->sa_family == AF_INET) { return memcmp(SA_IN_P(s1), SA_IN_P(s2), sizeof(struct in_addr)); } else { /* inet6 */ - return memcmp(SA_IN6_P(s1), SA_IN6_P(s2), sizeof(struct in6_addr)); + return memcmp(SA_IN6_P(s1), SA_IN6_P(s2), + sizeof(struct in6_addr)); } } /* returns an allocated string with the mask to apply for the prefix */ -char* ipv4_prefix_to_strmask(void *pool, unsigned prefix) +char *ipv4_prefix_to_strmask(void *pool, unsigned int prefix) { struct in_addr in; char str[MAX_IP_STR]; @@ -59,7 +60,7 @@ char* ipv4_prefix_to_strmask(void *pool, unsigned prefix) return talloc_strdup(pool, str); } -unsigned ipv6_prefix_to_mask(struct in6_addr *in6, unsigned prefix) +unsigned int ipv6_prefix_to_mask(struct in6_addr *in6, unsigned int prefix) { int i, j; @@ -71,7 +72,7 @@ unsigned ipv6_prefix_to_mask(struct in6_addr *in6, unsigned prefix) if (i >= 8) { in6->s6_addr[j] = 0xff; } else { - in6->s6_addr[j] = (unsigned long)(0xffU << ( 8 - i )); + in6->s6_addr[j] = (unsigned long)(0xffU << (8 - i)); } } @@ -87,7 +88,7 @@ unsigned ipv6_prefix_to_mask(struct in6_addr *in6, unsigned prefix) int ip_route_sanity_check(void *pool, char **_route) { char *p; - unsigned prefix; + unsigned int prefix; char *route = *_route, *n; char *slash_ptr, *pstr; @@ -98,7 +99,10 @@ int ip_route_sanity_check(void *pool, char **_route) p = strchr(p, '/'); if (p == NULL) { - oc_syslog(LOG_ERR, "route '%s' in wrong format, use xxx.xxx.xxx.xxx/xxx.xxx.xxx.xxx\n", route); + oc_syslog( + LOG_ERR, + "route '%s' in wrong format, use xxx.xxx.xxx.xxx/xxx.xxx.xxx.xxx\n", + route); return -1; } slash_ptr = p; @@ -113,7 +117,8 @@ int ip_route_sanity_check(void *pool, char **_route) pstr = ipv4_prefix_to_strmask(pool, prefix); if (pstr == NULL) { - oc_syslog(LOG_ERR, "cannot figure format of route '%s'\n", route); + oc_syslog(LOG_ERR, "cannot figure format of route '%s'\n", + route); return -1; } @@ -131,8 +136,7 @@ int ip_route_sanity_check(void *pool, char **_route) return 0; } -static -int bit_count(uint32_t i) +static int bit_count(uint32_t i) { int c = 0; unsigned int seen_one = 0; @@ -157,8 +161,7 @@ static int mask2prefix(struct in_addr mask) return bit_count(ntohl(mask.s_addr)); } -static -int ipv4_mask_to_int(const char *prefix) +static int ipv4_mask_to_int(const char *prefix) { int ret; struct in_addr in; @@ -188,7 +191,7 @@ char *ipv4_route_to_cidr(void *pool, const char *route) if (p == NULL) { return NULL; } - len = (ptrdiff_t)(p-route); + len = (ptrdiff_t)(p - route); p++; /* if we are in CIDR format exit */ @@ -202,14 +205,14 @@ char *ipv4_route_to_cidr(void *pool, const char *route) return talloc_asprintf(pool, "%.*s/%d", len, route, prefix); } -char *human_addr2(const struct sockaddr *sa, socklen_t salen, - void *_buf, size_t buflen, unsigned full) +char *human_addr2(const struct sockaddr *sa, socklen_t salen, void *_buf, + size_t buflen, unsigned int full) { char *save_buf = _buf; char *buf = _buf; size_t l; const char *ret; - unsigned port; + unsigned int port; if (!buf || !buflen) return NULL; @@ -219,20 +222,26 @@ char *human_addr2(const struct sockaddr *sa, socklen_t salen, } if (salen == sizeof(struct sockaddr_in6)) { - port = (unsigned)ntohs(((struct sockaddr_in6*)sa)->sin6_port); + port = (unsigned int)ntohs( + ((struct sockaddr_in6 *)sa)->sin6_port); if (full != 0 && port != 0) { - assert(buflen > 0); /* already checked, but to avoid regression */ + assert(buflen > + 0); /* already checked, but to avoid regression */ *buf = '['; buf++; buflen--; } - ret = inet_ntop(AF_INET6, &((struct sockaddr_in6*)sa)->sin6_addr, buf, buflen); + ret = inet_ntop(AF_INET6, + &((struct sockaddr_in6 *)sa)->sin6_addr, buf, + buflen); } else { - port = (unsigned)ntohs(((struct sockaddr_in*)sa)->sin_port); + port = (unsigned int)ntohs( + ((struct sockaddr_in *)sa)->sin_port); - ret = inet_ntop(AF_INET, &((struct sockaddr_in*)sa)->sin_addr, buf, buflen); + ret = inet_ntop(AF_INET, &((struct sockaddr_in *)sa)->sin_addr, + buf, buflen); } if (ret == NULL) { @@ -272,7 +281,7 @@ void set_mtu_disc(int fd, int family, int val) y = val; #if defined(IPV6_DONTFRAG) if (setsockopt(fd, IPPROTO_IPV6, IPV6_DONTFRAG, - (const void *) &y, sizeof(y)) < 0) + (const void *)&y, sizeof(y)) < 0) oc_syslog(LOG_INFO, "setsockopt(IPV6_DF) failed"); #elif defined(IPV6_MTU_DISCOVER) if (val) @@ -280,14 +289,15 @@ void set_mtu_disc(int fd, int family, int val) else y = IP_PMTUDISC_DONT; if (setsockopt(fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, - (const void *) &y, sizeof(y)) < 0) - oc_syslog(LOG_INFO, "setsockopt(IPV6_MTU_DISCOVER) failed"); + (const void *)&y, sizeof(y)) < 0) + oc_syslog(LOG_INFO, + "setsockopt(IPV6_MTU_DISCOVER) failed"); #endif } else { y = val; #if defined(IP_DONTFRAG) - if (setsockopt(fd, IPPROTO_IP, IP_DONTFRAG, - (const void *) &y, sizeof(y)) < 0) + if (setsockopt(fd, IPPROTO_IP, IP_DONTFRAG, (const void *)&y, + sizeof(y)) < 0) oc_syslog(LOG_INFO, "setsockopt(IP_DF) failed"); #elif defined(IP_MTU_DISCOVER) if (val) @@ -295,8 +305,9 @@ void set_mtu_disc(int fd, int family, int val) else y = IP_PMTUDISC_DONT; if (setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, - (const void *) &y, sizeof(y)) < 0) - oc_syslog(LOG_INFO, "setsockopt(IP_MTU_DISCOVER) failed"); + (const void *)&y, sizeof(y)) < 0) + oc_syslog(LOG_INFO, + "setsockopt(IP_MTU_DISCOVER) failed"); #endif } } diff --git a/src/ip-util.h b/src/ip-util.h index b18a27ff..aab11f09 100644 --- a/src/ip-util.h +++ b/src/ip-util.h @@ -20,7 +20,7 @@ * along with this program. If not, see */ #ifndef OC_IP_UTIL_H -# define OC_IP_UTIL_H +#define OC_IP_UTIL_H #include #include @@ -28,15 +28,16 @@ // Lower MTU bound is the value defined in RFC 791 #define RFC_791_MTU (68) // Upper bound is the maximum DTLS frame size -#define MAX_DTLS_MTU (1<<14) +#define MAX_DTLS_MTU (1 << 14) void set_mtu_disc(int fd, int family, int val); int ip_route_sanity_check(void *pool, char **_route); -int ip_cmp(const struct sockaddr_storage *s1, const struct sockaddr_storage *s2); -char* ipv4_prefix_to_strmask(void *pool, unsigned prefix); -unsigned ipv6_prefix_to_mask(struct in6_addr *in6, unsigned prefix); -inline static int valid_ipv6_prefix(unsigned prefix) +int ip_cmp(const struct sockaddr_storage *s1, + const struct sockaddr_storage *s2); +char *ipv4_prefix_to_strmask(void *pool, unsigned int prefix); +unsigned int ipv6_prefix_to_mask(struct in6_addr *in6, unsigned int prefix); +inline static int valid_ipv6_prefix(unsigned int prefix) { if (prefix > 10 && prefix <= 128) return 1; @@ -48,19 +49,24 @@ char *ipv4_route_to_cidr(void *pool, const char *route); /* Helper casts */ #define SA_IN_P(p) (&((struct sockaddr_in *)(p))->sin_addr) -#define SA_IN_U8_P(p) ((uint8_t*)(&((struct sockaddr_in *)(p))->sin_addr)) +#define SA_IN_U8_P(p) ((uint8_t *)(&((struct sockaddr_in *)(p))->sin_addr)) #define SA_IN6_P(p) (&((struct sockaddr_in6 *)(p))->sin6_addr) -#define SA_IN6_U8_P(p) ((uint8_t*)(&((struct sockaddr_in6 *)(p))->sin6_addr)) +#define SA_IN6_U8_P(p) ((uint8_t *)(&((struct sockaddr_in6 *)(p))->sin6_addr)) #define SA_IN_PORT(p) (((struct sockaddr_in *)(p))->sin_port) #define SA_IN6_PORT(p) (((struct sockaddr_in6 *)(p))->sin6_port) -#define SA_IN_P_GENERIC(addr, size) ((size==sizeof(struct sockaddr_in))?SA_IN_U8_P(addr):SA_IN6_U8_P(addr)) -#define SA_IN_P_TYPE(addr, type) ((type==AF_INET)?SA_IN_U8_P(addr):SA_IN6_U8_P(addr)) -#define SA_IN_SIZE(size) ((size==sizeof(struct sockaddr_in))?sizeof(struct in_addr):sizeof(struct in6_addr)) +#define SA_IN_P_GENERIC(addr, size) \ + ((size == sizeof(struct sockaddr_in)) ? SA_IN_U8_P(addr) : \ + SA_IN6_U8_P(addr)) +#define SA_IN_P_TYPE(addr, type) \ + ((type == AF_INET) ? SA_IN_U8_P(addr) : SA_IN6_U8_P(addr)) +#define SA_IN_SIZE(size) \ + ((size == sizeof(struct sockaddr_in)) ? sizeof(struct in_addr) : \ + sizeof(struct in6_addr)) -char *human_addr2(const struct sockaddr *sa, socklen_t salen, - void *buf, size_t buflen, unsigned full); +char *human_addr2(const struct sockaddr *sa, socklen_t salen, void *buf, + size_t buflen, unsigned int full); #define human_addr(x, y, z, w) human_addr2(x, y, z, w, 1) diff --git a/src/isolate.c b/src/isolate.c index f3f7bf40..e3e8944b 100644 --- a/src/isolate.c +++ b/src/isolate.c @@ -35,17 +35,15 @@ void set_worker_fd_limits(struct worker_st *ws) ret = getrlimit(RLIMIT_NOFILE, &def_set); if (ret < 0) { int e = errno; - oclog(ws, LOG_ERR, - "error in getrlimit: %s\n", strerror(e)); + + oclog(ws, LOG_ERR, "error in getrlimit: %s\n", strerror(e)); exit(EXIT_FAILURE); } ret = setrlimit(RLIMIT_NOFILE, &def_set); if (ret < 0) { - oclog(ws, LOG_INFO, - "cannot update file limit(%u): %s\n", - (unsigned)def_set.rlim_cur, - strerror(errno)); + oclog(ws, LOG_INFO, "cannot update file limit(%u): %s\n", + (unsigned int)def_set.rlim_cur, strerror(errno)); } #endif } @@ -98,7 +96,6 @@ void drop_privileges(struct worker_st *ws, main_server_st *s) oclog(ws, LOG_ERR, "cannot set uid to %d: %s\n", (int)GETPCONFIG(s)->uid, strerror(e)); exit(EXIT_FAILURE); - } } diff --git a/src/isolate.h b/src/isolate.h index 15ef81aa..ddd8cd81 100644 --- a/src/isolate.h +++ b/src/isolate.h @@ -17,7 +17,7 @@ */ #ifndef OC_ISOLATE_H -# define OC_ISOLATE_H +#define OC_ISOLATE_H void set_worker_fd_limits(struct worker_st *); diff --git a/src/kkdcp_asn1_tab.c b/src/kkdcp_asn1_tab.c index ccd1cde8..07163e0f 100644 --- a/src/kkdcp_asn1_tab.c +++ b/src/kkdcp_asn1_tab.c @@ -1,18 +1,18 @@ #if HAVE_CONFIG_H -# include "config.h" +#include "config.h" #endif #include const asn1_static_node kkdcp_asn1_tab[] = { - { "KKDCP", 536872976, NULL }, - { NULL, 1073741836, NULL }, - { "KDC-PROXY-MESSAGE", 536870917, NULL }, - { "kerb-message", 1610620935, NULL }, - { NULL, 2056, "0"}, - { "target-domain", 1610637339, NULL }, - { NULL, 2056, "1"}, - { "dclocator-hint", 536895491, NULL }, - { NULL, 2056, "2"}, - { NULL, 0, NULL } + { "KKDCP", 536872976, NULL }, + { NULL, 1073741836, NULL }, + { "KDC-PROXY-MESSAGE", 536870917, NULL }, + { "kerb-message", 1610620935, NULL }, + { NULL, 2056, "0" }, + { "target-domain", 1610637339, NULL }, + { NULL, 2056, "1" }, + { "dclocator-hint", 536895491, NULL }, + { NULL, 2056, "2" }, + { NULL, 0, NULL } }; diff --git a/src/log.c b/src/log.c index 167773e4..49e7800a 100644 --- a/src/log.c +++ b/src/log.c @@ -34,8 +34,8 @@ /* This global variable is used by oc_syslog() */ int global_log_prio = DEFAULT_LOG_LEVEL; -void __attribute__ ((format(printf, 2, 3))) - oc_syslog(int priority, const char *fmt, ...) +void __attribute__((format(printf, 2, 3))) oc_syslog(int priority, + const char *fmt, ...) { char buf[512]; va_list args; diff --git a/src/log.h b/src/log.h index d2f6f720..aea9bb34 100644 --- a/src/log.h +++ b/src/log.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_LOG_H -# define OC_LOG_H +#define OC_LOG_H #include #include @@ -31,9 +31,9 @@ extern int global_log_prio; /* For logging in the main process or sec-mod use the following: * mslog(const struct main_server_st * s, const struct proc_st* proc, - * int priority, const char *fmt, ...); + * int priority, const char *fmt, ...); * seclog(const struct sec_mod_st* sec, int priority, const char *fmt, ...); - * int priority, const char *fmt, ...); + * int priority, const char *fmt, ...); * * For logging in the worker process: * oclog(const struct worker_st * server, int priority, const char *fmt, ...); @@ -47,28 +47,32 @@ extern int global_log_prio; */ #ifdef __GNUC__ -# define _oc_syslog(prio, fmt, ...) do { \ - if (syslog_open) { \ - syslog(prio, fmt, ## __VA_ARGS__); \ - } else { \ - fprintf(stderr, fmt "\n", ## __VA_ARGS__); \ - }} while(0) +#define _oc_syslog(prio, fmt, ...) \ + do { \ + if (syslog_open) { \ + syslog(prio, fmt, ##__VA_ARGS__); \ + } else { \ + fprintf(stderr, fmt "\n", ##__VA_ARGS__); \ + } \ + } while (0) #else -# define _oc_syslog(prio, ...) do { \ - if (syslog_open) { \ - syslog(prio, __VA_ARGS__); \ - } else { \ - fprintf(stderr, __VA_ARGS__); \ - fputc('\n', stderr); \ - }} while(0) +#define _oc_syslog(prio, ...) \ + do { \ + if (syslog_open) { \ + syslog(prio, __VA_ARGS__); \ + } else { \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + } \ + } while (0) #endif #ifdef UNDER_TEST /* for testing */ -# define mslog(...) -# define oclog(...) -# define seclog(...) -# define oc_syslog _oc_syslog +#define mslog(...) +#define oclog(...) +#define seclog(...) +#define oc_syslog _oc_syslog #else @@ -77,54 +81,56 @@ struct worker_st; struct proc_st; struct sec_mod_st; -void -__attribute__ ((format(printf, 4, 5))) - _mslog(const struct main_server_st * s, const struct proc_st* proc, - int priority, const char *fmt, ...); +void __attribute__((format(printf, 4, 5))) +_mslog(const struct main_server_st *s, const struct proc_st *proc, int priority, + const char *fmt, ...); -void __attribute__ ((format(printf, 3, 4))) - _oclog(const struct worker_st * server, int priority, const char *fmt, ...); +void __attribute__((format(printf, 3, 4))) +_oclog(const struct worker_st *server, int priority, const char *fmt, ...); -void __attribute__ ((format(printf, 3, 4))) - _seclog(const struct sec_mod_st* sec, int priority, const char *fmt, ...); +void __attribute__((format(printf, 3, 4))) +_seclog(const struct sec_mod_st *sec, int priority, const char *fmt, ...); -void __attribute__ ((format(printf, 2, 3))) - oc_syslog(int priority, const char *fmt, ...); +void __attribute__((format(printf, 2, 3))) oc_syslog(int priority, + const char *fmt, ...); +#ifdef __GNUC__ +#define mslog(s, proc, prio, fmt, ...) \ + (prio == LOG_ERR) ? _mslog(s, proc, prio, "%s:%d: " fmt, __FILE__, \ + __LINE__, ##__VA_ARGS__) : \ + _mslog(s, proc, prio, fmt, ##__VA_ARGS__) -# ifdef __GNUC__ -# define mslog(s, proc, prio, fmt, ...) \ - (prio==LOG_ERR)?_mslog(s, proc, prio, "%s:%d: "fmt, __FILE__, __LINE__, ##__VA_ARGS__): \ - _mslog(s, proc, prio, fmt, ##__VA_ARGS__) +#define oclog(server, prio, fmt, ...) \ + (prio == LOG_ERR) ? _oclog(server, prio, "%s:%d: " fmt, __FILE__, \ + __LINE__, ##__VA_ARGS__) : \ + _oclog(server, prio, fmt, ##__VA_ARGS__) -# define oclog(server, prio, fmt, ...) \ - (prio==LOG_ERR)?_oclog(server, prio, "%s:%d: "fmt, __FILE__, __LINE__, ##__VA_ARGS__): \ - _oclog(server, prio, fmt, ##__VA_ARGS__) +#define seclog(sec, prio, fmt, ...) \ + (prio == LOG_ERR) ? _seclog(sec, prio, "%s:%d: " fmt, __FILE__, \ + __LINE__, ##__VA_ARGS__) : \ + _seclog(sec, prio, fmt, ##__VA_ARGS__) +#else +#define mslog _mslog +#define seclog _seclog +#define oclog _oclog +#endif -# define seclog(sec, prio, fmt, ...) \ - (prio==LOG_ERR)?_seclog(sec, prio, "%s:%d: "fmt, __FILE__, __LINE__, ##__VA_ARGS__): \ - _seclog(sec, prio, fmt, ##__VA_ARGS__) -# else -# define mslog _mslog -# define seclog _seclog -# define oclog _oclog -# endif +void mslog_hex(const struct main_server_st *s, const struct proc_st *proc, + int priority, const char *prefix, uint8_t *bin, + unsigned int bin_size, unsigned int b64); -void mslog_hex(const struct main_server_st * s, const struct proc_st* proc, - int priority, const char *prefix, uint8_t* bin, unsigned bin_size, unsigned b64); +void oclog_hex(const struct worker_st *ws, int priority, const char *prefix, + uint8_t *bin, unsigned int bin_size, unsigned int b64); -void oclog_hex(const struct worker_st* ws, int priority, - const char *prefix, uint8_t* bin, unsigned bin_size, unsigned b64); - -void seclog_hex(const struct sec_mod_st* sec, int priority, - const char *prefix, uint8_t* bin, unsigned bin_size, unsigned b64); +void seclog_hex(const struct sec_mod_st *sec, int priority, const char *prefix, + uint8_t *bin, unsigned int bin_size, unsigned int b64); #endif /* Returns zero when the given priority is not sufficient * for logging. Updates the priority with */ -inline static -unsigned log_check_priority(int oc_priority, int log_prio, int *syslog_prio) +inline static unsigned int log_check_priority(int oc_priority, int log_prio, + int *syslog_prio) { switch (oc_priority) { case LOG_ERR: @@ -157,7 +163,6 @@ unsigned log_check_priority(int oc_priority, int log_prio, int *syslog_prio) if (log_prio < OCLOG_TRANSFERRED) return 0; - if (syslog_prio) *syslog_prio = LOG_DEBUG; break; @@ -173,9 +178,9 @@ unsigned log_check_priority(int oc_priority, int log_prio, int *syslog_prio) if (syslog_prio) *syslog_prio = LOG_DEBUG; - } + } - return 1; + return 1; } #endif /* OC_LOG_H */ diff --git a/src/lzs.c b/src/lzs.c index 440adfca..fce1e969 100644 --- a/src/lzs.c +++ b/src/lzs.c @@ -23,9 +23,9 @@ #include "lzs.h" -#define GET_BITS(bits) \ -do { \ - /* Strictly speaking, this check ought to be on \ +#define GET_BITS(bits) \ + do { \ + /* Strictly speaking, this check ought to be on \ * (srclen < 1 + (bits_left < bits)). However, when bits == 9 \ * the (bits_left < bits) comparison is always true so it \ * always comes out as (srclen < 2). \ @@ -33,40 +33,43 @@ do { \ * reading part of a match encoding. And in that case, there \ * damn well ought to be an end marker (7 more bits) after \ * what we're reading now, so it's perfectly OK to use \ - * (srclen < 2) in that case too. And a *lot* cheaper. */ \ - if (srclen < 2) \ - return -EINVAL; \ - /* Explicit comparison with 8 to optimise it into a tautology \ + * (srclen < 2) in that case too. And a *lot* cheaper. */ \ + if (srclen < 2) \ + return -EINVAL; \ + /* Explicit comparison with 8 to optimise it into a tautology \ * in the bits == 9 case, because the compiler doesn't - * know that bits_left can never be larger than 8. */ \ - if (bits >= 8 || bits >= bits_left) { \ - /* We need *all* the bits that are left in the current \ - * byte. Take them and bump the input pointer. */ \ - data = (src[0] << (bits - bits_left)) & ((1 << bits) - 1); \ - src++; \ - srclen--; \ - bits_left += 8 - bits; \ - if (bits > 8 || bits_left < 8) { \ - /* We need bits from the next byte too... */ \ - data |= src[0] >> bits_left; \ - /* ...if we used *all* of them then (which can \ + * know that bits_left can never be larger than 8. */ \ + if (bits >= 8 || bits >= bits_left) { \ + /* We need *all* the bits that are left in the current \ + * byte. Take them and bump the input pointer. */ \ + data = (src[0] << (bits - bits_left)) & \ + ((1 << bits) - 1); \ + src++; \ + srclen--; \ + bits_left += 8 - bits; \ + if (bits > 8 || bits_left < 8) { \ + /* We need bits from the next byte too... */ \ + data |= src[0] >> bits_left; \ + /* ...if we used *all* of them then (which can \ * only happen if bits > 8), then bump the \ * input pointer again so we never leave \ - * bits_left == 0. */ \ - if (bits > 8 && !bits_left) { \ - bits_left = 8; \ - src++; \ - srclen--; \ - } \ - } \ - } else { \ - /* We need fewer bits than are left in the current byte */ \ - data = (src[0] >> (bits_left - bits)) & ((1ULL << bits) - 1); \ - bits_left -= bits; \ - } \ -} while (0) + * bits_left == 0. */ \ + if (bits > 8 && !bits_left) { \ + bits_left = 8; \ + src++; \ + srclen--; \ + } \ + } \ + } else { \ + /* We need fewer bits than are left in the current byte */ \ + data = (src[0] >> (bits_left - bits)) & \ + ((1ULL << bits) - 1); \ + bits_left -= bits; \ + } \ + } while (0) -int lzs_decompress(unsigned char *dst, int dstlen, const unsigned char *src, int srclen) +int lzs_decompress(unsigned char *dst, int dstlen, const unsigned char *src, + int srclen) { int outlen = 0; int bits_left = 8; /* Bits left in the current byte at *src */ @@ -140,24 +143,24 @@ int lzs_decompress(unsigned char *dst, int dstlen, const unsigned char *src, int return -EINVAL; } -#define PUT_BITS(nr, bits) \ -do { \ - outbits <<= (nr); \ - outbits |= (bits); \ - nr_outbits += (nr); \ - if ((nr) > 8) { \ - nr_outbits -= 8; \ - if (outpos == dstlen) \ - return -EFBIG; \ - dst[outpos++] = outbits >> nr_outbits; \ - } \ - if (nr_outbits >= 8) { \ - nr_outbits -= 8; \ - if (outpos == dstlen) \ - return -EFBIG; \ - dst[outpos++] = outbits >> nr_outbits; \ - } \ -} while (0) +#define PUT_BITS(nr, bits) \ + do { \ + outbits <<= (nr); \ + outbits |= (bits); \ + nr_outbits += (nr); \ + if ((nr) > 8) { \ + nr_outbits -= 8; \ + if (outpos == dstlen) \ + return -EFBIG; \ + dst[outpos++] = outbits >> nr_outbits; \ + } \ + if (nr_outbits >= 8) { \ + nr_outbits -= 8; \ + if (outpos == dstlen) \ + return -EFBIG; \ + dst[outpos++] = outbits >> nr_outbits; \ + } \ + } while (0) struct oc_packed_uint16_t { uint16_t d; @@ -167,7 +170,8 @@ struct oc_packed_uint16_t { * Much of the compression algorithm used here is based very loosely on ideas * from isdn_lzscomp.c by Andre Beck: http://micky.ibh.de/~beck/stuff/lzs4i4l/ */ -int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int srclen) +int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, + int srclen) { int length, offset; int inpos = 0, outpos = 0; @@ -203,7 +207,7 @@ int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int s * offset will yield the previous offset at which the same data hash * value was found. */ -#define MAX_HISTORY (1<<11) /* Highest offset LZS can represent is 11 bits */ +#define MAX_HISTORY (1 << 11) /* Highest offset LZS can represent is 11 bits */ uint16_t hash_chain[MAX_HISTORY]; /* Just in case anyone tries to use this in a more general-purpose @@ -234,10 +238,10 @@ int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int s for (; hofs != INVALID_OFS && hofs + MAX_HISTORY > inpos; hofs = hash_chain[hofs & (MAX_HISTORY - 1)]) { - /* We only get here if longest_match_len is >= 2. We need to find a match of longest_match_len + 1 for it to be interesting. */ - if (!memcmp(src + hofs + 2, src + inpos + 2, longest_match_len - 1)) { + if (!memcmp(src + hofs + 2, src + inpos + 2, + longest_match_len - 1)) { longest_match_ofs = hofs; do { @@ -248,7 +252,8 @@ int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int s if (longest_match_len + inpos == srclen) goto got_match; - } while (src[longest_match_len + inpos] == src[longest_match_len + hofs]); + } while (src[longest_match_len + inpos] == + src[longest_match_len + hofs]); } /* Typical compressor tuning would have a break out of the loop @@ -261,7 +266,7 @@ int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int s something. Anyway, we currently don't give up until we run out of reachable history — maximal compression. */ } - got_match: +got_match: /* Output offset, as 7-bit or 11-bit as appropriate */ offset = inpos - longest_match_ofs; length = longest_match_len; @@ -298,7 +303,8 @@ int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int s inpos++; while (--longest_match_len) { hash = HASH(src + inpos); - hash_chain[inpos & (MAX_HISTORY - 1)] = hash_table[hash]; + hash_chain[inpos & (MAX_HISTORY - 1)] = + hash_table[hash]; hash_table[hash] = inpos++; } } diff --git a/src/lzs.h b/src/lzs.h index 61dee2ee..6d8ea7a9 100644 --- a/src/lzs.h +++ b/src/lzs.h @@ -16,9 +16,11 @@ */ #ifndef OC_LZS_H -# define OC_LZS_H +#define OC_LZS_H -int lzs_decompress(unsigned char *dst, int dstlen, const unsigned char *src, int srclen); -int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, int srclen); +int lzs_decompress(unsigned char *dst, int dstlen, const unsigned char *src, + int srclen); +int lzs_compress(unsigned char *dst, int dstlen, const unsigned char *src, + int srclen); #endif diff --git a/src/main-auth.c b/src/main-auth.c index 199edd29..17644fe4 100644 --- a/src/main-auth.c +++ b/src/main-auth.c @@ -46,7 +46,7 @@ #include /* Puts the provided PIN into the config's cgroup */ -void put_into_cgroup(main_server_st * s, const char *_cgroup, pid_t pid) +void put_into_cgroup(main_server_st *s, const char *_cgroup, pid_t pid) { #ifdef __linux__ char *name, *p, *savep; @@ -72,8 +72,8 @@ void put_into_cgroup(main_server_st * s, const char *_cgroup, pid_t pid) p = strtok_r(cgroup, ",", &savep); while (p != NULL) { mslog(s, NULL, LOG_DEBUG, - "putting process %u to cgroup '%s:%s'", (unsigned)pid, p, - name); + "putting process %u to cgroup '%s:%s'", (unsigned int)pid, + p, name); snprintf(file, sizeof(file), "/sys/fs/cgroup/%s/%s/tasks", p, name); @@ -84,7 +84,7 @@ void put_into_cgroup(main_server_st * s, const char *_cgroup, pid_t pid) return; } - if (fprintf(fd, "%u", (unsigned)pid) <= 0) { + if (fprintf(fd, "%u", (unsigned int)pid) <= 0) { mslog(s, NULL, LOG_ERR, "could not write to: %s", file); } fclose(fd); @@ -99,8 +99,7 @@ void put_into_cgroup(main_server_st * s, const char *_cgroup, pid_t pid) #endif } -int send_cookie_auth_reply(main_server_st* s, struct proc_st* proc, - AUTHREP r) +int send_cookie_auth_reply(main_server_st *s, struct proc_st *proc, AUTHREP r) { AuthCookieReplyMsg msg = AUTH_COOKIE_REPLY_MSG__INIT; int ret; @@ -126,36 +125,43 @@ int send_cookie_auth_reply(main_server_st* s, struct proc_st* proc, msg.group_name = proc->groupname; if (proc->ipv4 && proc->ipv4->rip_len > 0) { - msg.ipv4 = human_addr2((struct sockaddr*)&proc->ipv4->rip, proc->ipv4->rip_len, - ipv4, sizeof(ipv4), 0); - msg.ipv4_local = human_addr2((struct sockaddr*)&proc->ipv4->lip, proc->ipv4->lip_len, - ipv4_local, sizeof(ipv4_local), 0); + msg.ipv4 = human_addr2( + (struct sockaddr *)&proc->ipv4->rip, + proc->ipv4->rip_len, ipv4, sizeof(ipv4), 0); + msg.ipv4_local = + human_addr2((struct sockaddr *)&proc->ipv4->lip, + proc->ipv4->lip_len, ipv4_local, + sizeof(ipv4_local), 0); } if (proc->ipv6 && proc->ipv6->rip_len > 0) { - msg.ipv6 = human_addr2((struct sockaddr*)&proc->ipv6->rip, proc->ipv6->rip_len, - ipv6, sizeof(ipv6), 0); - msg.ipv6_local = human_addr2((struct sockaddr*)&proc->ipv6->lip, proc->ipv6->lip_len, - ipv6_local, sizeof(ipv6_local), 0); + msg.ipv6 = human_addr2( + (struct sockaddr *)&proc->ipv6->rip, + proc->ipv6->rip_len, ipv6, sizeof(ipv6), 0); + msg.ipv6_local = + human_addr2((struct sockaddr *)&proc->ipv6->lip, + proc->ipv6->lip_len, ipv6_local, + sizeof(ipv6_local), 0); } msg.config = proc->config; - ret = send_socket_msg_to_worker(s, proc, AUTH_COOKIE_REP, proc->tun_lease.fd, - &msg, - (pack_size_func)auth_cookie_reply_msg__get_packed_size, - (pack_func)auth_cookie_reply_msg__pack); + ret = send_socket_msg_to_worker( + s, proc, AUTH_COOKIE_REP, proc->tun_lease.fd, &msg, + (pack_size_func)auth_cookie_reply_msg__get_packed_size, + (pack_func)auth_cookie_reply_msg__pack); } else { msg.reply = AUTH__REP__FAILED; - ret = send_msg_to_worker(s, proc, AUTH_COOKIE_REP, - &msg, - (pack_size_func)auth_cookie_reply_msg__get_packed_size, - (pack_func)auth_cookie_reply_msg__pack); + ret = send_msg_to_worker( + s, proc, AUTH_COOKIE_REP, &msg, + (pack_size_func)auth_cookie_reply_msg__get_packed_size, + (pack_func)auth_cookie_reply_msg__pack); } if (ret < 0) { int e = errno; + mslog(s, proc, LOG_ERR, "send_msg: %s", strerror(e)); return ret; } @@ -163,10 +169,11 @@ int send_cookie_auth_reply(main_server_st* s, struct proc_st* proc, return 0; } -int handle_auth_cookie_req(sec_mod_instance_st * sec_mod_instance, struct proc_st* proc, - const AuthCookieRequestMsg * req) +int handle_auth_cookie_req(sec_mod_instance_st *sec_mod_instance, + struct proc_st *proc, + const AuthCookieRequestMsg *req) { - main_server_st * s = sec_mod_instance->server; + main_server_st *s = sec_mod_instance->server; int ret; struct proc_st *old_proc; @@ -175,7 +182,8 @@ int handle_auth_cookie_req(sec_mod_instance_st * sec_mod_instance, struct proc_s /* generate a new DTLS session ID for each connection, to allow * openconnect of distinguishing when the DTLS key has switched. */ - ret = gnutls_rnd(GNUTLS_RND_NONCE, proc->dtls_session_id, sizeof(proc->dtls_session_id)); + ret = gnutls_rnd(GNUTLS_RND_NONCE, proc->dtls_session_id, + sizeof(proc->dtls_session_id)); if (ret < 0) return -1; proc->dtls_session_id_size = sizeof(proc->dtls_session_id); @@ -184,13 +192,15 @@ int handle_auth_cookie_req(sec_mod_instance_st * sec_mod_instance, struct proc_s old_proc = proc_search_sid(s, req->cookie.data); if (old_proc != NULL) { if (old_proc->invalidated != 0) { - mslog(s, proc, LOG_ERR, "the reused session has been invalidated"); + mslog(s, proc, LOG_ERR, + "the reused session has been invalidated"); return -1; } } /* loads sup config and basic proc info (e.g., username) */ - ret = session_open(sec_mod_instance, proc, req->cookie.data, req->cookie.len); + ret = session_open(sec_mod_instance, proc, req->cookie.data, + req->cookie.len); if (ret < 0) { mslog(s, proc, LOG_INFO, "could not open session"); return -1; @@ -204,12 +214,14 @@ int handle_auth_cookie_req(sec_mod_instance_st * sec_mod_instance, struct proc_s /* disconnect and reuse previous session's IPs*/ if (old_proc != NULL) { if (strcmp(proc->username, old_proc->username) != 0) { - mslog(s, old_proc, LOG_ERR, "the user of the new session doesn't match the old (new: %s)", + mslog(s, old_proc, LOG_ERR, + "the user of the new session doesn't match the old (new: %s)", proc->username); return -1; } - mslog(s, old_proc, LOG_INFO, "disconnecting previous user session due to session reuse"); + mslog(s, old_proc, LOG_INFO, + "disconnecting previous user session due to session reuse"); /* steal its leases */ steal_ip_leases(old_proc, proc); @@ -248,20 +260,22 @@ int handle_auth_cookie_req(sec_mod_instance_st * sec_mod_instance, struct proc_s * used had been reused before, and then disconnect the old session * (cookies are unique). */ -int check_multiple_users(main_server_st *s, struct proc_st* proc) +int check_multiple_users(main_server_st *s, struct proc_st *proc) { struct proc_st *ctmp = NULL, *cpos; unsigned int entries = 1; /* that one */ - unsigned max; + unsigned int max; max = proc->config->max_same_clients; if (max == 0) return 0; - list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) { + list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) + { if (ctmp != proc && ctmp->pid != -1) { - if (!ctmp->pid_killed && strcmp(proc->username, ctmp->username) == 0) { + if (!ctmp->pid_killed && + strcmp(proc->username, ctmp->username) == 0) { entries++; if (entries > max) diff --git a/src/main-ban.c b/src/main-ban.c index e7c7dc9c..05ea63f5 100644 --- a/src/main-ban.c +++ b/src/main-ban.c @@ -45,11 +45,13 @@ #include #include -static bool if_address_test_local(main_server_st * s, struct sockaddr_storage *addr); +static bool if_address_test_local(main_server_st *s, + struct sockaddr_storage *addr); static size_t rehash(const void *_e, void *unused) { - ban_entry_st *e = (void*)_e; + ban_entry_st *e = (void *)_e; + return hash_any(e->ip.ip, e->ip.size, 0); } @@ -61,15 +63,16 @@ static bool ban_entry_cmp(const void *_c1, void *_c2) const struct ban_entry_st *c1 = _c1; struct ban_entry_st *c2 = _c2; - if (c1->ip.size == c2->ip.size && memcmp(c1->ip.ip, c2->ip.ip, c1->ip.size) == 0) + if (c1->ip.size == c2->ip.size && + memcmp(c1->ip.ip, c2->ip.ip, c1->ip.size) == 0) return 1; return 0; } - void *main_ban_db_init(main_server_st *s) { struct htable *db = talloc(s, struct htable); + if (db == NULL) { oc_syslog(LOG_ERR, "error initializing ban DB\n"); exit(EXIT_FAILURE); @@ -93,13 +96,13 @@ void main_ban_db_deinit(main_server_st *s) #define IS_BANNED(main, entry) (entry->score >= GETCONFIG(main)->max_ban_score) -unsigned main_ban_db_elems(main_server_st *s) +unsigned int main_ban_db_elems(main_server_st *s) { struct htable *db = s->ban_db; ban_entry_st *t; struct htable_iter iter; time_t now = time(NULL); - unsigned banned = 0; + unsigned int banned = 0; if (db == NULL || GETCONFIG(s)->max_ban_score == 0) return 0; @@ -122,8 +125,8 @@ static void massage_ipv6_address(ban_entry_st *t) } /* returns -1 if the user is already banned, and zero otherwise */ -static -int add_ip_to_ban_list(main_server_st *s, const unsigned char *ip, unsigned ip_size, unsigned score) +static int add_ip_to_ban_list(main_server_st *s, const unsigned char *ip, + unsigned int ip_size, unsigned int score) { struct htable *db = s->ban_db; struct ban_entry_st *e; @@ -133,9 +136,10 @@ int add_ip_to_ban_list(main_server_st *s, const unsigned char *ip, unsigned ip_s int ret = 0; char str_ip[MAX_IP_STR]; const char *p_str_ip = NULL; - unsigned print_msg; + unsigned int print_msg; - if (db == NULL || GETCONFIG(s)->max_ban_score == 0 || ip == NULL || (ip_size != 4 && ip_size != 16)) + if (db == NULL || GETCONFIG(s)->max_ban_score == 0 || ip == NULL || + (ip_size != 4 && ip_size != 16)) return 0; memcpy(t.ip.ip, ip, ip_size); @@ -156,7 +160,7 @@ int add_ip_to_ban_list(main_server_st *s, const unsigned char *ip, unsigned ip_s if (htable_add(db, rehash(e, NULL), e) == 0) { mslog(s, NULL, LOG_INFO, - "could not add ban entry to hash table"); + "could not add ban entry to hash table"); goto fail; } } else { @@ -176,7 +180,8 @@ int add_ip_to_ban_list(main_server_st *s, const unsigned char *ip, unsigned ip_s print_msg = 0; /* prevent overflow */ - e->score = (e->score + score) > e->score ? (e->score + score) : (e->score); + e->score = (e->score + score) > e->score ? (e->score + score) : + (e->score); if (ip_size == 4) p_str_ip = inet_ntop(AF_INET, ip, str_ip, sizeof(str_ip)); @@ -187,32 +192,41 @@ int add_ip_to_ban_list(main_server_st *s, const unsigned char *ip, unsigned ip_s if (print_msg && p_str_ip) { char date[256]; struct tm tm; - if ((localtime_r(&e->expires, &tm) == NULL) || (strftime(date, sizeof(date), "%a %b %e %H:%M:%S %Y", &tm) == 0)) { + + if ((localtime_r(&e->expires, &tm) == NULL) || + (strftime(date, sizeof(date), + "%a %b %e %H:%M:%S %Y", &tm) == 0)) { date[0] = 0; } - mslog(s, NULL, LOG_INFO, "added IP '%s' (with score %d) to ban list, will be reset at: %s", str_ip, e->score, date); + mslog(s, NULL, LOG_INFO, + "added IP '%s' (with score %d) to ban list, will be reset at: %s", + str_ip, e->score, date); } ret = -1; } else { if (p_str_ip) { - mslog(s, NULL, LOG_DEBUG, "added %d points (total %d) for IP '%s' to ban list", score, e->score, str_ip); + mslog(s, NULL, LOG_DEBUG, + "added %d points (total %d) for IP '%s' to ban list", + score, e->score, str_ip); } ret = 0; } return ret; - fail: +fail: talloc_free(e); return ret; } -int add_str_ip_to_ban_list(main_server_st *s, const char *ip, unsigned score) +int add_str_ip_to_ban_list(main_server_st *s, const char *ip, + unsigned int score) { struct htable *db = s->ban_db; ban_entry_st t; int ret = 0; - if (db == NULL || GETCONFIG(s)->max_ban_score == 0 || ip == NULL || ip[0] == 0) + if (db == NULL || GETCONFIG(s)->max_ban_score == 0 || ip == NULL || + ip[0] == 0) return 0; if (strchr(ip, ':') != 0) { @@ -223,8 +237,7 @@ int add_str_ip_to_ban_list(main_server_st *s, const char *ip, unsigned score) t.ip.size = 4; } if (ret != 1) { - mslog(s, NULL, LOG_INFO, - "could not read IP: %s", ip); + mslog(s, NULL, LOG_INFO, "could not read IP: %s", ip); return 0; } @@ -232,7 +245,8 @@ int add_str_ip_to_ban_list(main_server_st *s, const char *ip, unsigned score) } /* returns non-zero if there is an IP removed */ -int remove_ip_from_ban_list(main_server_st *s, const uint8_t *ip, unsigned size) +int remove_ip_from_ban_list(main_server_st *s, const uint8_t *ip, + unsigned int size) { struct htable *db = s->ban_db; struct ban_entry_st *e; @@ -243,9 +257,9 @@ int remove_ip_from_ban_list(main_server_st *s, const uint8_t *ip, unsigned size) return 0; if (size == 4 || size == 16) { - if (inet_ntop(size==16?AF_INET6:AF_INET, ip, txt_ip, sizeof(txt_ip)) != NULL) { - mslog(s, NULL, LOG_INFO, - "unbanning IP '%s'", txt_ip); + if (inet_ntop(size == 16 ? AF_INET6 : AF_INET, ip, txt_ip, + sizeof(txt_ip)) != NULL) { + mslog(s, NULL, LOG_INFO, "unbanning IP '%s'", txt_ip); } t.ip.size = size; @@ -265,12 +279,13 @@ int remove_ip_from_ban_list(main_server_st *s, const uint8_t *ip, unsigned size) return 0; } -unsigned check_if_banned(main_server_st *s, struct sockaddr_storage *addr, socklen_t addr_size) +unsigned int check_if_banned(main_server_st *s, struct sockaddr_storage *addr, + socklen_t addr_size) { struct htable *db = s->ban_db; time_t now; ban_entry_st t, *e; - unsigned in_size; + unsigned int in_size; char txt[MAX_IP_STR]; if (db == NULL || GETCONFIG(s)->max_ban_score == 0) @@ -279,24 +294,30 @@ unsigned check_if_banned(main_server_st *s, struct sockaddr_storage *addr, sockl (void)(txt); if (if_address_test_local(s, addr)) { - mslog(s, NULL, LOG_DEBUG, "Not applying ban to local IP: %s", human_addr2((struct sockaddr*)addr, addr_size, txt, sizeof(txt), 0)); + mslog(s, NULL, LOG_DEBUG, "Not applying ban to local IP: %s", + human_addr2((struct sockaddr *)addr, addr_size, txt, + sizeof(txt), 0)); return 0; } in_size = SA_IN_SIZE(addr_size); if (in_size != 4 && in_size != 16) { - mslog(s, NULL, LOG_ERR, "unknown address type for %s", human_addr2((struct sockaddr*)addr, addr_size, txt, sizeof(txt), 0)); + mslog(s, NULL, LOG_ERR, "unknown address type for %s", + human_addr2((struct sockaddr *)addr, addr_size, txt, + sizeof(txt), 0)); return 0; } - memcpy(t.ip.ip, SA_IN_P_GENERIC(addr, addr_size), SA_IN_SIZE(addr_size)); + memcpy(t.ip.ip, SA_IN_P_GENERIC(addr, addr_size), + SA_IN_SIZE(addr_size)); t.ip.size = SA_IN_SIZE(addr_size); /* In IPv6 treat a /64 as a single address */ massage_ipv6_address(&t); /* add its current connection points */ - add_ip_to_ban_list(s, t.ip.ip, t.ip.size, GETCONFIG(s)->ban_points_connect); + add_ip_to_ban_list(s, t.ip.ip, t.ip.size, + GETCONFIG(s)->ban_points_connect); now = time(NULL); e = htable_get(db, rehash(&t, NULL), ban_entry_cmp, &t); @@ -305,7 +326,10 @@ unsigned check_if_banned(main_server_st *s, struct sockaddr_storage *addr, sockl return 0; if (e->score >= GETCONFIG(s)->max_ban_score) { - mslog(s, NULL, LOG_INFO, "rejected connection from banned IP: %s", human_addr2((struct sockaddr*)addr, addr_size, txt, sizeof(txt), 0)); + mslog(s, NULL, LOG_INFO, + "rejected connection from banned IP: %s", + human_addr2((struct sockaddr *)addr, addr_size, + txt, sizeof(txt), 0)); return 1; } } @@ -324,27 +348,30 @@ void cleanup_banned_entries(main_server_st *s) t = htable_first(db, &iter); while (t != NULL) { - if (now >= t->expires && now > t->last_reset + GETCONFIG(s)->ban_reset_time) { + if (now >= t->expires && + now > t->last_reset + GETCONFIG(s)->ban_reset_time) { htable_delval(db, &iter); talloc_free(t); } t = htable_next(db, &iter); - } } int if_address_init(main_server_st *s) { - struct ifaddrs * ifaddr = NULL, *ifa; - if_address_st * local_if_addresses = NULL; + struct ifaddrs *ifaddr = NULL, *ifa; + if_address_st *local_if_addresses = NULL; int retval = 0; - unsigned count = 0; + unsigned int count = 0; + s->if_addresses_count = 0; s->if_addresses = NULL; if (getifaddrs(&ifaddr) < 0) { int err = errno; - oc_syslog(LOG_ERR, "Failed to read local if address list: %s", strerror(err)); + + oc_syslog(LOG_ERR, "Failed to read local if address list: %s", + strerror(err)); goto cleanup; } @@ -352,7 +379,7 @@ int if_address_init(main_server_st *s) if (ifa->ifa_addr == NULL) { continue; } - count ++; + count++; } local_if_addresses = talloc_array(s, if_address_st, count); @@ -365,13 +392,16 @@ int if_address_init(main_server_st *s) for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { sa_family_t family; + if (ifa->ifa_addr == NULL) { continue; } family = ifa->ifa_addr->sa_family; if (family == AF_INET || family == AF_INET6) { - memcpy(&local_if_addresses[count].if_addr, ifa->ifa_addr, sizeof(struct sockaddr)); - memcpy(&local_if_addresses[count].if_netmask, ifa->ifa_netmask, sizeof(struct sockaddr)); + memcpy(&local_if_addresses[count].if_addr, + ifa->ifa_addr, sizeof(struct sockaddr)); + memcpy(&local_if_addresses[count].if_netmask, + ifa->ifa_netmask, sizeof(struct sockaddr)); count++; } } @@ -392,45 +422,61 @@ cleanup: return retval; } -static bool test_local_ipv4(struct sockaddr_in * remote, struct sockaddr_in * local, struct sockaddr_in * network) +static bool test_local_ipv4(struct sockaddr_in *remote, + struct sockaddr_in *local, + struct sockaddr_in *network) { uint32_t l = local->sin_addr.s_addr & network->sin_addr.s_addr; uint32_t r = remote->sin_addr.s_addr & network->sin_addr.s_addr; + if (l != r) return false; else return true; } -static bool test_local_ipv6(struct sockaddr_in6 * remote, struct sockaddr_in6 * local, struct sockaddr_in6 * network) +static bool test_local_ipv6(struct sockaddr_in6 *remote, + struct sockaddr_in6 *local, + struct sockaddr_in6 *network) { - unsigned index = 0; + unsigned int index = 0; + + for (index = 0; index < 4; index++) { + uint32_t l = local->sin6_addr.s6_addr32[index] & + network->sin6_addr.s6_addr32[index]; + uint32_t r = remote->sin6_addr.s6_addr32[index] & + network->sin6_addr.s6_addr32[index]; - for (index = 0; index < 4; index ++) { - uint32_t l = local->sin6_addr.s6_addr32[index] & network->sin6_addr.s6_addr32[index]; - uint32_t r = remote->sin6_addr.s6_addr32[index] & network->sin6_addr.s6_addr32[index]; if (l != r) return false; } return true; } -static bool if_address_test_local(main_server_st * s, struct sockaddr_storage *addr) +static bool if_address_test_local(main_server_st *s, + struct sockaddr_storage *addr) { - unsigned index; - for (index = 0; index < s->if_addresses_count; index ++) - { - if_address_st * ifa = &s->if_addresses[index]; + unsigned int index; + + for (index = 0; index < s->if_addresses_count; index++) { + if_address_st *ifa = &s->if_addresses[index]; + if (ifa->if_addr.sa_family != addr->ss_family) continue; switch (addr->ss_family) { case AF_INET: - if (test_local_ipv4((struct sockaddr_in *)addr, (struct sockaddr_in *)&ifa->if_addr, (struct sockaddr_in *)&ifa->if_netmask)) + if (test_local_ipv4( + (struct sockaddr_in *)addr, + (struct sockaddr_in *)&ifa->if_addr, + (struct sockaddr_in *)&ifa->if_netmask)) return true; break; case AF_INET6: - if (test_local_ipv6((struct sockaddr_in6 *)addr, (struct sockaddr_in6 *)&ifa->if_addr, (struct sockaddr_in6 *)&ifa->if_netmask)) + if (test_local_ipv6( + (struct sockaddr_in6 *)addr, + (struct sockaddr_in6 *)&ifa->if_addr, + (struct sockaddr_in6 *)&ifa->if_netmask)) return true; break; default: @@ -440,7 +486,7 @@ static bool if_address_test_local(main_server_st * s, struct sockaddr_storage *a return false; } -void if_address_cleanup(main_server_st * s) +void if_address_cleanup(main_server_st *s) { if (s->if_addresses) talloc_free(s->if_addresses); diff --git a/src/main-ban.h b/src/main-ban.h index 35921155..08dd520c 100644 --- a/src/main-ban.h +++ b/src/main-ban.h @@ -19,32 +19,35 @@ * along with this program. If not, see */ #ifndef OC_MAIN_BAN_H -# define OC_MAIN_BAN_H +#define OC_MAIN_BAN_H -# include "main.h" +#include "main.h" typedef struct inaddr_st { uint8_t ip[16]; - unsigned size; /* 4 or 16 */ + unsigned int size; /* 4 or 16 */ } inaddr_st; typedef struct ban_entry_st { inaddr_st ip; - unsigned score; + unsigned int score; time_t last_reset; /* the time its score counting started */ time_t expires; /* the time after the client is allowed to login */ } ban_entry_st; void cleanup_banned_entries(main_server_st *s); -unsigned check_if_banned(main_server_st *s, struct sockaddr_storage *addr, socklen_t addr_size); -int add_str_ip_to_ban_list(main_server_st *s, const char *ip, unsigned score); -int remove_ip_from_ban_list(main_server_st *s, const uint8_t *ip, unsigned size); -unsigned main_ban_db_elems(main_server_st *s); +unsigned int check_if_banned(main_server_st *s, struct sockaddr_storage *addr, + socklen_t addr_size); +int add_str_ip_to_ban_list(main_server_st *s, const char *ip, + unsigned int score); +int remove_ip_from_ban_list(main_server_st *s, const uint8_t *ip, + unsigned int size); +unsigned int main_ban_db_elems(main_server_st *s); void main_ban_db_deinit(main_server_st *s); void *main_ban_db_init(main_server_st *s); int if_address_init(main_server_st *s); -void if_address_cleanup(main_server_st * s); +void if_address_cleanup(main_server_st *s); #endif diff --git a/src/main-ctl-unix.c b/src/main-ctl-unix.c index 1354bee6..3b5563e8 100644 --- a/src/main-ctl-unix.c +++ b/src/main-ctl-unix.c @@ -45,46 +45,44 @@ typedef struct method_ctx { void *pool; } method_ctx; -static void method_top(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_status(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_list_users(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_disconnect_user_name(method_ctx *ctx, int cfd, - uint8_t * msg, unsigned msg_size); -static void method_disconnect_user_id(method_ctx *ctx, int cfd, - uint8_t * msg, unsigned msg_size); -static void method_unban_ip(method_ctx *ctx, int cfd, - uint8_t * msg, unsigned msg_size); -static void method_stop(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_reload(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_user_info(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_id_info(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_list_banned(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); -static void method_list_cookies(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); +static void method_top(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_status(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_list_users(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_disconnect_user_name(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_disconnect_user_id(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_unban_ip(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_stop(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_reload(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_user_info(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_id_info(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_list_banned(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); +static void method_list_cookies(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); -typedef void (*method_func) (method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size); +typedef void (*method_func)(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size); typedef struct { char *name; - unsigned cmd; + unsigned int cmd; method_func func; - unsigned indefinite; /* session remains open */ + unsigned int indefinite; /* session remains open */ } ctl_method_st; -#define ENTRY(cmd, func) \ - {#cmd, cmd, func, 0} +#define ENTRY(cmd, func) { #cmd, cmd, func, 0 } -#define ENTRY_INDEF(cmd, func) \ - {#cmd, cmd, func, 1} +#define ENTRY_INDEF(cmd, func) { #cmd, cmd, func, 1 } static const ctl_method_st methods[] = { ENTRY_INDEF(CTL_CMD_TOP, method_top), @@ -99,10 +97,10 @@ static const ctl_method_st methods[] = { ENTRY(CTL_CMD_UNBAN_IP, method_unban_ip), ENTRY(CTL_CMD_DISCONNECT_NAME, method_disconnect_user_name), ENTRY(CTL_CMD_DISCONNECT_ID, method_disconnect_user_id), - {NULL, 0, NULL} + { NULL, 0, NULL } }; -void ctl_handler_deinit(main_server_st * s) +void ctl_handler_deinit(main_server_st *s) { if (GETCONFIG(s)->use_occtl == 0) return; @@ -116,21 +114,24 @@ void ctl_handler_deinit(main_server_st * s) /* Initializes unix socket and stores the fd. */ -int ctl_handler_init(main_server_st * s) +int ctl_handler_init(main_server_st *s) { int ret; struct sockaddr_un sa; int sd, e; - if (GETCONFIG(s)->use_occtl == 0 || GETPCONFIG(s)->occtl_socket_file == NULL) { + if (GETCONFIG(s)->use_occtl == 0 || + GETPCONFIG(s)->occtl_socket_file == NULL) { mslog(s, NULL, LOG_INFO, "not using control unix socket"); return 0; } - mslog(s, NULL, LOG_DEBUG, "initializing control unix socket: %s", GETPCONFIG(s)->occtl_socket_file); + mslog(s, NULL, LOG_DEBUG, "initializing control unix socket: %s", + GETPCONFIG(s)->occtl_socket_file); memset(&sa, 0, sizeof(sa)); sa.sun_family = AF_UNIX; - strlcpy(sa.sun_path, GETPCONFIG(s)->occtl_socket_file, sizeof(sa.sun_path)); + strlcpy(sa.sun_path, GETPCONFIG(s)->occtl_socket_file, + sizeof(sa.sun_path)); ret = remove(GETPCONFIG(s)->occtl_socket_file); if (ret != 0) { e = errno; @@ -156,7 +157,8 @@ int ctl_handler_init(main_server_st * s) return -1; } - ret = chown(GETPCONFIG(s)->occtl_socket_file, GETPCONFIG(s)->uid, GETPCONFIG(s)->gid); + ret = chown(GETPCONFIG(s)->occtl_socket_file, GETPCONFIG(s)->uid, + GETPCONFIG(s)->gid); if (ret == -1) { e = errno; mslog(s, NULL, LOG_ERR, "could not chown socket '%s': %s", @@ -176,18 +178,20 @@ int ctl_handler_init(main_server_st * s) return sd; } -static void method_status(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_status(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { StatusRep rep = STATUS_REP__INIT; int ret; unsigned int i; - uint32_t * sec_mod_pids; + uint32_t *sec_mod_pids; - sec_mod_pids = talloc_array(ctx->pool, uint32_t, ctx->s->sec_mod_instance_count); + sec_mod_pids = talloc_array(ctx->pool, uint32_t, + ctx->s->sec_mod_instance_count); if (sec_mod_pids) { - for (i = 0; i < ctx->s->sec_mod_instance_count; i ++) { - sec_mod_pids[i] = ctx->s->sec_mod_instances[i].sec_mod_pid; + for (i = 0; i < ctx->s->sec_mod_instance_count; i++) { + sec_mod_pids[i] = + ctx->s->sec_mod_instances[i].sec_mod_pid; } } @@ -205,10 +209,14 @@ static void method_status(method_ctx *ctx, int cfd, uint8_t * msg, rep.stored_tls_sessions = 0; rep.max_auth_time = 0; rep.avg_auth_time = 0; - for (i = 0; i < ctx->s->sec_mod_instance_count; i ++) { - rep.secmod_client_entries += ctx->s->sec_mod_instances[i].secmod_client_entries; - rep.stored_tls_sessions += ctx->s->sec_mod_instances[i].tlsdb_entries; - rep.max_auth_time = MAX(rep.max_auth_time, ctx->s->sec_mod_instances[i].max_auth_time); + for (i = 0; i < ctx->s->sec_mod_instance_count; i++) { + rep.secmod_client_entries += + ctx->s->sec_mod_instances[i].secmod_client_entries; + rep.stored_tls_sessions += + ctx->s->sec_mod_instances[i].tlsdb_entries; + rep.max_auth_time = + MAX(rep.max_auth_time, + ctx->s->sec_mod_instances[i].max_auth_time); rep.avg_auth_time = ctx->s->sec_mod_instances[i].avg_auth_time; } if (ctx->s->sec_mod_instance_count != 0) { @@ -232,65 +240,66 @@ static void method_status(method_ctx *ctx, int cfd, uint8_t * msg, rep.total_auth_failures = ctx->s->stats.total_auth_failures; rep.total_sessions_closed = ctx->s->stats.total_sessions_closed; #if defined(CAPTURE_LATENCY_SUPPORT) - rep.latency_median_total = ctx->s->stats.current_latency_stats.median_total; + rep.latency_median_total = + ctx->s->stats.current_latency_stats.median_total; rep.has_latency_median_total = true; rep.latency_rms_total = ctx->s->stats.current_latency_stats.rms_total; rep.has_latency_rms_total = true; - rep.latency_sample_count = ctx->s->stats.current_latency_stats.sample_count; + rep.latency_sample_count = + ctx->s->stats.current_latency_stats.sample_count; rep.has_latency_sample_count = true; #endif ret = send_msg(ctx->pool, cfd, CTL_CMD_STATUS_REP, &rep, - (pack_size_func) status_rep__get_packed_size, - (pack_func) status_rep__pack); + (pack_size_func)status_rep__get_packed_size, + (pack_func)status_rep__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } } -static void method_reload(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_reload(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { BoolMsg rep = BOOL_MSG__INIT; int ret; mslog(ctx->s, NULL, LOG_DEBUG, "ctl: reload"); - ev_feed_signal_event (main_loop, SIGHUP); + ev_feed_signal_event(main_loop, SIGHUP); rep.status = 1; ret = send_msg(ctx->pool, cfd, CTL_CMD_RELOAD_REP, &rep, - (pack_size_func) bool_msg__get_packed_size, - (pack_func) bool_msg__pack); + (pack_size_func)bool_msg__get_packed_size, + (pack_func)bool_msg__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } } -static void method_stop(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_stop(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { BoolMsg rep = BOOL_MSG__INIT; int ret; mslog(ctx->s, NULL, LOG_DEBUG, "ctl: stop"); - ev_feed_signal_event (main_loop, SIGTERM); + ev_feed_signal_event(main_loop, SIGTERM); rep.status = 1; ret = send_msg(ctx->pool, cfd, CTL_CMD_STOP_REP, &rep, - (pack_size_func) bool_msg__get_packed_size, - (pack_func) bool_msg__pack); + (pack_size_func)bool_msg__get_packed_size, + (pack_func)bool_msg__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } } #define IPBUF_SIZE 64 -static int append_user_info(method_ctx *ctx, - UserListRep * list, +static int append_user_info(method_ctx *ctx, UserListRep *list, struct proc_st *ctmp) { uint32_t tmp; @@ -299,8 +308,8 @@ static int append_user_info(method_ctx *ctx, UserInfoRep *rep; char *safe_id; - list->user = - talloc_realloc(ctx->pool, list->user, UserInfoRep *, (1 + list->n_user)); + list->user = talloc_realloc(ctx->pool, list->user, UserInfoRep *, + (1 + list->n_user)); if (list->user == NULL) return -1; @@ -327,9 +336,8 @@ static int append_user_info(method_ctx *ctx, if (ipbuf == NULL) return -1; - strtmp = - human_addr2((struct sockaddr *)&ctmp->remote_addr, - ctmp->remote_addr_len, ipbuf, IPBUF_SIZE, 0); + strtmp = human_addr2((struct sockaddr *)&ctmp->remote_addr, + ctmp->remote_addr_len, ipbuf, IPBUF_SIZE, 0); if (strtmp == NULL) strtmp = ""; rep->ip = strtmp; @@ -338,9 +346,8 @@ static int append_user_info(method_ctx *ctx, if (ipbuf == NULL) return -1; - strtmp = - human_addr2((struct sockaddr *)&ctmp->our_addr, - ctmp->our_addr_len, ipbuf, IPBUF_SIZE, 0); + strtmp = human_addr2((struct sockaddr *)&ctmp->our_addr, + ctmp->our_addr_len, ipbuf, IPBUF_SIZE, 0); if (strtmp == NULL) strtmp = ""; rep->local_dev_ip = strtmp; @@ -353,9 +360,8 @@ static int append_user_info(method_ctx *ctx, strtmp = NULL; if (ctmp->ipv4 != NULL) - strtmp = - human_addr2((struct sockaddr *)&ctmp->ipv4->rip, - ctmp->ipv4->rip_len, ipbuf, IPBUF_SIZE, 0); + strtmp = human_addr2((struct sockaddr *)&ctmp->ipv4->rip, + ctmp->ipv4->rip_len, ipbuf, IPBUF_SIZE, 0); if (strtmp == NULL) strtmp = ""; rep->local_ip = strtmp; @@ -366,9 +372,8 @@ static int append_user_info(method_ctx *ctx, strtmp = NULL; if (ctmp->ipv4 != NULL) - strtmp = - human_addr2((struct sockaddr *)&ctmp->ipv4->lip, - ctmp->ipv4->lip_len, ipbuf, IPBUF_SIZE, 0); + strtmp = human_addr2((struct sockaddr *)&ctmp->ipv4->lip, + ctmp->ipv4->lip_len, ipbuf, IPBUF_SIZE, 0); if (strtmp == NULL) strtmp = ""; rep->remote_ip = strtmp; @@ -381,9 +386,8 @@ static int append_user_info(method_ctx *ctx, strtmp = NULL; if (ctmp->ipv6 != NULL) - strtmp = - human_addr2((struct sockaddr *)&ctmp->ipv6->rip, - ctmp->ipv6->rip_len, ipbuf, IPBUF_SIZE, 0); + strtmp = human_addr2((struct sockaddr *)&ctmp->ipv6->rip, + ctmp->ipv6->rip_len, ipbuf, IPBUF_SIZE, 0); if (strtmp == NULL) strtmp = ""; rep->local_ip6 = strtmp; @@ -394,9 +398,8 @@ static int append_user_info(method_ctx *ctx, strtmp = NULL; if (ctmp->ipv6 != NULL) - strtmp = - human_addr2((struct sockaddr *)&ctmp->ipv6->lip, - ctmp->ipv6->lip_len, ipbuf, IPBUF_SIZE, 0); + strtmp = human_addr2((struct sockaddr *)&ctmp->ipv6->lip, + ctmp->ipv6->lip_len, ipbuf, IPBUF_SIZE, 0); if (strtmp == NULL) strtmp = ""; rep->remote_ip6 = strtmp; @@ -411,7 +414,7 @@ static int append_user_info(method_ctx *ctx, rep->dtls_ciphersuite = ctmp->dtls_ciphersuite; calc_safe_id(ctmp->sid, sizeof(ctmp->sid), safe_id, SAFE_ID_SIZE); - rep->safe_id.data = (unsigned char*)safe_id; + rep->safe_id.data = (unsigned char *)safe_id; rep->safe_id.len = SAFE_ID_SIZE; rep->cstp_compr = ctmp->cstp_compr; @@ -438,8 +441,10 @@ static int append_user_info(method_ctx *ctx, rep->keepalive = ctmp->config->keepalive; if (ctmp->vhost) { - rep->domains = ctmp->vhost->perm_config.config->split_dns; - rep->n_domains = ctmp->vhost->perm_config.config->split_dns_size; + rep->domains = + ctmp->vhost->perm_config.config->split_dns; + rep->n_domains = + ctmp->vhost->perm_config.config->split_dns_size; } rep->dns = ctmp->config->dns; @@ -464,8 +469,8 @@ static int append_user_info(method_ctx *ctx, return 0; } -static void method_list_users(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_list_users(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { UserListRep rep = USER_LIST_REP__INIT; struct proc_st *ctmp = NULL; @@ -473,7 +478,8 @@ static void method_list_users(method_ctx *ctx, int cfd, uint8_t * msg, mslog(ctx->s, NULL, LOG_DEBUG, "ctl: list-users"); - list_for_each(&ctx->s->proc_list.head, ctmp, list) { + list_for_each(&ctx->s->proc_list.head, ctmp, list) + { ret = append_user_info(ctx, &rep, ctmp); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, @@ -483,15 +489,15 @@ static void method_list_users(method_ctx *ctx, int cfd, uint8_t * msg, } ret = send_msg(ctx->pool, cfd, CTL_CMD_LIST_REP, &rep, - (pack_size_func) user_list_rep__get_packed_size, - (pack_func) user_list_rep__pack); + (pack_size_func)user_list_rep__get_packed_size, + (pack_func)user_list_rep__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } } -static void method_top(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_top(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { /* we send the initial user list, and the we send a TOP reply message * once a user connects/disconnects. */ @@ -505,15 +511,14 @@ static void method_top(method_ctx *ctx, int cfd, uint8_t * msg, method_list_users(ctx, cfd, msg, msg_size); } -static int append_ban_info(method_ctx *ctx, - BanListRep *list, +static int append_ban_info(method_ctx *ctx, BanListRep *list, struct ban_entry_st *e) { BanInfoRep *rep; main_server_st *s = ctx->s; - list->info = - talloc_realloc(ctx->pool, list->info, BanInfoRep *, (1 + list->n_info)); + list->info = talloc_realloc(ctx->pool, list->info, BanInfoRep *, + (1 + list->n_info)); if (list->info == NULL) return -1; @@ -528,7 +533,8 @@ static int append_ban_info(method_ctx *ctx, rep->ip.len = e->ip.size; rep->score = e->score; - if (GETCONFIG(s)->max_ban_score > 0 && e->score >= GETCONFIG(s)->max_ban_score) { + if (GETCONFIG(s)->max_ban_score > 0 && + e->score >= GETCONFIG(s)->max_ban_score) { rep->expires = e->expires; rep->has_expires = 1; } @@ -536,8 +542,8 @@ static int append_ban_info(method_ctx *ctx, return 0; } -static void method_list_banned(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_list_banned(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { BanListRep rep = BAN_LIST_REP__INIT; struct ban_entry_st *e = NULL; @@ -559,19 +565,21 @@ static void method_list_banned(method_ctx *ctx, int cfd, uint8_t * msg, } ret = send_msg(ctx->pool, cfd, CTL_CMD_LIST_BANNED_REP, &rep, - (pack_size_func) ban_list_rep__get_packed_size, - (pack_func) ban_list_rep__pack); + (pack_size_func)ban_list_rep__get_packed_size, + (pack_func)ban_list_rep__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ban list reply"); } } -static void method_list_cookies(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_list_cookies(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { SecmListCookiesReplyMsg reply = SECM_LIST_COOKIES_REPLY_MSG__INIT; - SecmListCookiesReplyMsg ** sub_replies = NULL; - CookieIntMsg ** cookies = NULL; + SecmListCookiesReplyMsg **sub_replies = NULL; + + CookieIntMsg **cookies = NULL; + PROTOBUF_ALLOCATOR(pa, ctx->pool); size_t total_cookies = 0; @@ -582,23 +590,31 @@ static void method_list_cookies(method_ctx *ctx, int cfd, uint8_t * msg, mslog(ctx->s, NULL, LOG_DEBUG, "ctl: list-cookies"); - sub_replies = talloc_zero_array(ctx->pool, SecmListCookiesReplyMsg*, ctx->s->sec_mod_instance_count); + sub_replies = talloc_zero_array(ctx->pool, SecmListCookiesReplyMsg *, + ctx->s->sec_mod_instance_count); if (!sub_replies) { goto reply_and_exit; } for (i = 0; i < ctx->s->sec_mod_instance_count; i++) { - SecmListCookiesReplyMsg * sub_reply = NULL; - ret = send_msg(ctx->pool, ctx->s->sec_mod_instances[i].sec_mod_fd_sync, CMD_SECM_LIST_COOKIES, - NULL, NULL, NULL); + SecmListCookiesReplyMsg *sub_reply = NULL; + + ret = send_msg(ctx->pool, + ctx->s->sec_mod_instances[i].sec_mod_fd_sync, + CMD_SECM_LIST_COOKIES, NULL, NULL, NULL); if (ret < 0) { - mslog(ctx->s, NULL, LOG_ERR, "error sending list cookies to sec-mod!"); + mslog(ctx->s, NULL, LOG_ERR, + "error sending list cookies to sec-mod!"); continue; } - ret = recv_msg(ctx->pool, ctx->s->sec_mod_instances[i].sec_mod_fd_sync, CMD_SECM_LIST_COOKIES_REPLY, - (void*)&sub_reply, (unpack_func)secm_list_cookies_reply_msg__unpack, MAIN_SEC_MOD_TIMEOUT); + ret = recv_msg(ctx->pool, + ctx->s->sec_mod_instances[i].sec_mod_fd_sync, + CMD_SECM_LIST_COOKIES_REPLY, (void *)&sub_reply, + (unpack_func)secm_list_cookies_reply_msg__unpack, + MAIN_SEC_MOD_TIMEOUT); if (ret < 0) { - mslog(ctx->s, NULL, LOG_ERR, "error receiving list cookies reply"); + mslog(ctx->s, NULL, LOG_ERR, + "error receiving list cookies reply"); continue; } @@ -608,7 +624,7 @@ static void method_list_cookies(method_ctx *ctx, int cfd, uint8_t * msg, } } - cookies = talloc_zero_array(ctx->pool, CookieIntMsg*, total_cookies); + cookies = talloc_zero_array(ctx->pool, CookieIntMsg *, total_cookies); if (!cookies) { goto reply_and_exit; } @@ -628,11 +644,13 @@ reply_and_exit: reply.cookies = cookies; reply.n_cookies = total_cookies; - ret = send_msg(ctx->pool, cfd, CTL_CMD_LIST_COOKIES_REP, &reply, - (pack_size_func) secm_list_cookies_reply_msg__get_packed_size, - (pack_func) secm_list_cookies_reply_msg__pack); + ret = send_msg( + ctx->pool, cfd, CTL_CMD_LIST_COOKIES_REP, &reply, + (pack_size_func)secm_list_cookies_reply_msg__get_packed_size, + (pack_func)secm_list_cookies_reply_msg__pack); if (ret < 0) { - mslog(ctx->s, NULL, LOG_ERR, "error sending list cookies reply"); + mslog(ctx->s, NULL, LOG_ERR, + "error sending list cookies reply"); } if (sub_replies) { @@ -640,7 +658,8 @@ reply_and_exit: if (sub_replies[i] == NULL) { continue; } - secm_list_cookies_reply_msg__free_unpacked(sub_replies[i], &pa); + secm_list_cookies_reply_msg__free_unpacked( + sub_replies[i], &pa); } talloc_free(sub_replies); } @@ -650,25 +669,28 @@ reply_and_exit: } } -static void single_info_common(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size, const char *user, unsigned id) +static void single_info_common(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size, const char *user, + unsigned int id) { UserListRep rep = USER_LIST_REP__INIT; int ret; - unsigned found_user = 0; + unsigned int found_user = 0; struct proc_st *ctmp = NULL; if (user != NULL) - mslog(ctx->s, NULL, LOG_INFO, "providing info for user '%s'", user); + mslog(ctx->s, NULL, LOG_INFO, "providing info for user '%s'", + user); else mslog(ctx->s, NULL, LOG_INFO, "providing info for ID '%u'", id); - list_for_each(&ctx->s->proc_list.head, ctmp, list) { - if (user == NULL) { /* id */ + list_for_each(&ctx->s->proc_list.head, ctmp, list) + { + if (user == NULL) { /* id */ if (id == 0 || id == -1 || id != ctmp->pid) { continue; } - } else { /* username */ + } else { /* username */ if (strcmp(ctmp->username, user) != 0) { continue; } @@ -683,28 +705,29 @@ static void single_info_common(method_ctx *ctx, int cfd, uint8_t * msg, found_user = 1; - if (id != 0) /* id -> one a single element */ + if (id != 0) /* id -> one a single element */ break; } if (found_user == 0) { if (user != NULL) - mslog(ctx->s, NULL, LOG_INFO, "could not find user '%s'", - user); + mslog(ctx->s, NULL, LOG_INFO, + "could not find user '%s'", user); else - mslog(ctx->s, NULL, LOG_INFO, "could not find ID '%u'", id); + mslog(ctx->s, NULL, LOG_INFO, "could not find ID '%u'", + id); } ret = send_msg(ctx->pool, cfd, CTL_CMD_LIST_REP, &rep, - (pack_size_func) user_list_rep__get_packed_size, - (pack_func) user_list_rep__pack); + (pack_size_func)user_list_rep__get_packed_size, + (pack_func)user_list_rep__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } } -static void method_user_info(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_user_info(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { UsernameReq *req; @@ -720,8 +743,8 @@ static void method_user_info(method_ctx *ctx, int cfd, uint8_t * msg, username_req__free_unpacked(req, NULL); } -static void method_id_info(method_ctx *ctx, int cfd, uint8_t * msg, - unsigned msg_size) +static void method_id_info(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { IdReq *req; @@ -737,9 +760,8 @@ static void method_id_info(method_ctx *ctx, int cfd, uint8_t * msg, id_req__free_unpacked(req, NULL); } -static void method_unban_ip(method_ctx *ctx, - int cfd, uint8_t * msg, - unsigned msg_size) +static void method_unban_ip(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { UnbanReq *req; BoolMsg rep = BOOL_MSG__INIT; @@ -749,8 +771,7 @@ static void method_unban_ip(method_ctx *ctx, req = unban_req__unpack(NULL, msg_size, msg); if (req == NULL) { - mslog(ctx->s, NULL, LOG_ERR, - "error parsing unban IP request"); + mslog(ctx->s, NULL, LOG_ERR, "error parsing unban IP request"); return; } @@ -761,16 +782,16 @@ static void method_unban_ip(method_ctx *ctx, unban_req__free_unpacked(req, NULL); ret = send_msg(ctx->pool, cfd, CTL_CMD_UNBAN_IP_REP, &rep, - (pack_size_func) bool_msg__get_packed_size, - (pack_func) bool_msg__pack); + (pack_size_func)bool_msg__get_packed_size, + (pack_func)bool_msg__pack); if (ret < 0) { - mslog(ctx->s, NULL, LOG_ERR, "error sending unban IP ctl reply"); + mslog(ctx->s, NULL, LOG_ERR, + "error sending unban IP ctl reply"); } } -static void method_disconnect_user_name(method_ctx *ctx, - int cfd, uint8_t * msg, - unsigned msg_size) +static void method_disconnect_user_name(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { UsernameReq *req; BoolMsg rep = BOOL_MSG__INIT; @@ -788,7 +809,8 @@ static void method_disconnect_user_name(method_ctx *ctx, } /* got the name. Try to disconnect */ - list_for_each_safe(&ctx->s->proc_list.head, ctmp, cpos, list) { + list_for_each_safe(&ctx->s->proc_list.head, ctmp, cpos, list) + { if (strcmp(ctmp->username, req->username) == 0) { disconnect_proc(ctx->s, ctmp); rep.status = 1; @@ -798,15 +820,15 @@ static void method_disconnect_user_name(method_ctx *ctx, username_req__free_unpacked(req, NULL); ret = send_msg(ctx->pool, cfd, CTL_CMD_DISCONNECT_NAME_REP, &rep, - (pack_size_func) bool_msg__get_packed_size, - (pack_func) bool_msg__pack); + (pack_size_func)bool_msg__get_packed_size, + (pack_func)bool_msg__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } } -static void method_disconnect_user_id(method_ctx *ctx, int cfd, - uint8_t * msg, unsigned msg_size) +static void method_disconnect_user_id(method_ctx *ctx, int cfd, uint8_t *msg, + unsigned int msg_size) { IdReq *req; BoolMsg rep = BOOL_MSG__INIT; @@ -818,12 +840,14 @@ static void method_disconnect_user_id(method_ctx *ctx, int cfd, req = id_req__unpack(NULL, msg_size, msg); if (req == NULL) { - mslog(ctx->s, NULL, LOG_ERR, "error parsing disconnect_id request"); + mslog(ctx->s, NULL, LOG_ERR, + "error parsing disconnect_id request"); return; } /* got the ID. Try to disconnect */ - list_for_each_safe(&ctx->s->proc_list.head, ctmp, cpos, list) { + list_for_each_safe(&ctx->s->proc_list.head, ctmp, cpos, list) + { if (ctmp->pid == req->id) { disconnect_proc(ctx->s, ctmp); rep.status = 1; @@ -837,8 +861,8 @@ static void method_disconnect_user_id(method_ctx *ctx, int cfd, id_req__free_unpacked(req, NULL); ret = send_msg(ctx->pool, cfd, CTL_CMD_DISCONNECT_ID_REP, &rep, - (pack_size_func) bool_msg__get_packed_size, - (pack_func) bool_msg__pack); + (pack_size_func)bool_msg__get_packed_size, + (pack_func)bool_msg__pack); if (ret < 0) { mslog(ctx->s, NULL, LOG_ERR, "error sending ctl reply"); } @@ -857,8 +881,9 @@ static void ctl_cmd_wacher_cb(EV_P_ ev_io *w, int revents) uint8_t cmd; uint8_t buffer[256]; method_ctx ctx; - struct ctl_watcher_st *wst = container_of(w, struct ctl_watcher_st, ctl_cmd_io); - unsigned i, indef = 0; + struct ctl_watcher_st *wst = + container_of(w, struct ctl_watcher_st, ctl_cmd_io); + unsigned int i, indef = 0; ctx.s = s; ctx.pool = talloc_new(wst); @@ -879,7 +904,7 @@ static void ctl_cmd_wacher_cb(EV_P_ ev_io *w, int revents) if (methods[i].cmd == 0) { mslog(s, NULL, LOG_INFO, "unknown unix ctl message: 0x%.1x", - (unsigned)cmd); + (unsigned int)cmd); break; } else if (methods[i].cmd == cmd) { indef = methods[i].indefinite; @@ -892,7 +917,7 @@ static void ctl_cmd_wacher_cb(EV_P_ ev_io *w, int revents) talloc_free(ctx.pool); return; } - fail: +fail: if (s->top_fd == wst->fd) s->top_fd = -1; close(wst->fd); @@ -900,7 +925,7 @@ static void ctl_cmd_wacher_cb(EV_P_ ev_io *w, int revents) talloc_free(wst); } -static void ctl_handle_commands(main_server_st * s) +static void ctl_handle_commands(main_server_st *s) { int cfd = -1, e, ret; struct sockaddr_un sa; @@ -916,7 +941,8 @@ static void ctl_handle_commands(main_server_st * s) goto fail; } - ret = check_upeer_id("ctl", GETPCONFIG(s)->log_level, cfd, 0, 0, NULL, NULL); + ret = check_upeer_id("ctl", GETPCONFIG(s)->log_level, cfd, 0, 0, NULL, + NULL); if (ret < 0) { mslog(s, NULL, LOG_ERR, "ctl: unauthorized connection"); goto fail; @@ -934,12 +960,12 @@ static void ctl_handle_commands(main_server_st * s) ev_io_start(main_loop, &wst->ctl_cmd_io); return; - fail: +fail: if (cfd != -1) close(cfd); } -void ctl_handler_set_fds(main_server_st * s, ev_io *watcher) +void ctl_handler_set_fds(main_server_st *s, ev_io *watcher) { if (GETCONFIG(s)->use_occtl == 0) return; @@ -947,7 +973,7 @@ void ctl_handler_set_fds(main_server_st * s, ev_io *watcher) ev_io_set(watcher, s->ctl_fd, EV_READ); } -void ctl_handler_run_pending(main_server_st* s, ev_io *watcher) +void ctl_handler_run_pending(main_server_st *s, ev_io *watcher) { if (GETCONFIG(s)->use_occtl == 0) return; @@ -955,7 +981,8 @@ void ctl_handler_run_pending(main_server_st* s, ev_io *watcher) ctl_handle_commands(s); } -void ctl_handler_notify (main_server_st* s, struct proc_st *proc, unsigned connect) +void ctl_handler_notify(main_server_st *s, struct proc_st *proc, + unsigned int connect) { TopUpdateRep rep = TOP_UPDATE_REP__INIT; UserListRep list = USER_LIST_REP__INIT; @@ -979,20 +1006,20 @@ void ctl_handler_notify (main_server_st* s, struct proc_st *proc, unsigned conne if (connect == 0 && proc->discon_reason) { rep.has_discon_reason = 1; rep.discon_reason = proc->discon_reason; - rep.discon_reason_txt = (char*)discon_reason_to_str(proc->discon_reason); + rep.discon_reason_txt = + (char *)discon_reason_to_str(proc->discon_reason); } ret = append_user_info(&ctx, &list, proc); if (ret < 0) { - mslog(s, NULL, LOG_ERR, - "error appending user info to reply"); + mslog(s, NULL, LOG_ERR, "error appending user info to reply"); goto fail; } rep.user = &list; ret = send_msg(pool, s->top_fd, CTL_CMD_TOP_UPDATE_REP, &rep, - (pack_size_func) top_update_rep__get_packed_size, - (pack_func) top_update_rep__pack); + (pack_size_func)top_update_rep__get_packed_size, + (pack_func)top_update_rep__pack); if (ret < 0) { mslog(s, NULL, LOG_ERR, "error sending ctl reply"); goto fail; @@ -1000,7 +1027,7 @@ void ctl_handler_notify (main_server_st* s, struct proc_st *proc, unsigned conne talloc_free(pool); return; - fail: +fail: talloc_free(pool); s->top_fd = -1; } diff --git a/src/main-ctl.h b/src/main-ctl.h index c05a11a7..a39c4427 100644 --- a/src/main-ctl.h +++ b/src/main-ctl.h @@ -1,14 +1,15 @@ #ifndef OC_MAIN_CTL_H -# define OC_MAIN_CTL_H +#define OC_MAIN_CTL_H #include #include -int ctl_handler_init(main_server_st* s); -void ctl_handler_deinit(main_server_st* s); +int ctl_handler_init(main_server_st *s); +void ctl_handler_deinit(main_server_st *s); -void ctl_handler_set_fds(main_server_st* s, ev_io *watcher); -void ctl_handler_run_pending(main_server_st* s, ev_io *watcher); -void ctl_handler_notify (main_server_st* s, struct proc_st *proc, unsigned connect); +void ctl_handler_set_fds(main_server_st *s, ev_io *watcher); +void ctl_handler_run_pending(main_server_st *s, ev_io *watcher); +void ctl_handler_notify(main_server_st *s, struct proc_st *proc, + unsigned int connect); #endif diff --git a/src/main-limits.c b/src/main-limits.c index a5ba647f..28690808 100644 --- a/src/main-limits.c +++ b/src/main-limits.c @@ -22,14 +22,14 @@ #include #include - #include #include -void init_fd_limits_default(main_server_st * s) +void init_fd_limits_default(main_server_st *s) { #ifdef RLIMIT_NOFILE int ret = getrlimit(RLIMIT_NOFILE, &s->fd_limits_default_set); + if (ret < 0) { oc_syslog(LOG_ERR, "error in getrlimit: %s\n", strerror(errno)); exit(EXIT_FAILURE); @@ -46,11 +46,11 @@ void init_fd_limits_default(main_server_st * s) /* Adjusts the file descriptor limits for the main or worker processes */ -void set_main_fd_limits(main_server_st * s) +void set_main_fd_limits(main_server_st *s) { #ifdef RLIMIT_NOFILE struct rlimit new_set; - unsigned max; + unsigned int max; int ret; if (GETCONFIG(s)->max_clients > 0) @@ -66,19 +66,19 @@ void set_main_fd_limits(main_server_st * s) ret = setrlimit(RLIMIT_NOFILE, &new_set); if (ret < 0) { fprintf(stderr, - "error in setrlimit(%u): %s (cur: %u)\n", - max, strerror(errno), - (unsigned)s->fd_limits_default_set. - rlim_cur); + "error in setrlimit(%u): %s (cur: %u)\n", max, + strerror(errno), + (unsigned int)s->fd_limits_default_set.rlim_cur); } } #endif } -void set_self_oom_score_adj(main_server_st * s) +void set_self_oom_score_adj(main_server_st *s) { #ifdef __linux__ - static const char proc_self_oom_adj_score_path[] = "/proc/self/oom_score_adj"; + static const char proc_self_oom_adj_score_path[] = + "/proc/self/oom_score_adj"; static const char oom_adj_score_value[] = "1000"; size_t written = 0; int fd; @@ -87,6 +87,7 @@ void set_self_oom_score_adj(main_server_st * s) S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { int e = errno; + mslog(s, NULL, LOG_ERR, "cannot open %s: %s", proc_self_oom_adj_score_path, strerror(e)); goto cleanup; @@ -95,12 +96,13 @@ void set_self_oom_score_adj(main_server_st * s) written = write(fd, oom_adj_score_value, sizeof(oom_adj_score_value)); if (written != sizeof(oom_adj_score_value)) { int e = errno; + mslog(s, NULL, LOG_ERR, "cannot write %s: %s", proc_self_oom_adj_score_path, strerror(e)); goto cleanup; } - cleanup: +cleanup: if (fd >= 0) { close(fd); } diff --git a/src/main-limits.h b/src/main-limits.h index edb9e5e8..316a8c24 100644 --- a/src/main-limits.h +++ b/src/main-limits.h @@ -17,15 +17,14 @@ */ #ifndef MAIN_LIMITS_H -# define MAIN_LIMITS_H +#define MAIN_LIMITS_H - -void init_fd_limits_default(struct main_server_st * s); +void init_fd_limits_default(struct main_server_st *s); /* Adjusts the file descriptor limits for the main or worker processes */ -void set_main_fd_limits(struct main_server_st * s); +void set_main_fd_limits(struct main_server_st *s); -void set_self_oom_score_adj(struct main_server_st * s); +void set_self_oom_score_adj(struct main_server_st *s); #endif diff --git a/src/main-log.c b/src/main-log.c index 2fc963a9..8cbcb468 100644 --- a/src/main-log.c +++ b/src/main-log.c @@ -32,17 +32,18 @@ #include "log.h" /* proc is optional */ -void __attribute__ ((format(printf, 4, 5))) -_mslog(const main_server_st * s, const struct proc_st* proc, - int priority, const char *fmt, ...) +void __attribute__((format(printf, 4, 5))) _mslog(const main_server_st *s, + const struct proc_st *proc, + int priority, const char *fmt, + ...) { char buf[512]; char ipbuf[128]; - char name[MAX_USERNAME_SIZE+MAX_HOSTNAME_SIZE+3]; - const char* ip = NULL; + char name[MAX_USERNAME_SIZE + MAX_HOSTNAME_SIZE + 3]; + const char *ip = NULL; va_list args; int log_prio = DEFAULT_LOG_LEVEL; - unsigned have_vhosts; + unsigned int have_vhosts; int syslog_prio; if (s) @@ -52,8 +53,8 @@ _mslog(const main_server_st * s, const struct proc_st* proc, return; if (proc) { - ip = human_addr((void*)&proc->remote_addr, proc->remote_addr_len, - ipbuf, sizeof(ipbuf)); + ip = human_addr((void *)&proc->remote_addr, + proc->remote_addr_len, ipbuf, sizeof(ipbuf)); } else { ip = ""; } @@ -62,27 +63,32 @@ _mslog(const main_server_st * s, const struct proc_st* proc, vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); - have_vhosts = s?HAVE_VHOSTS(s):0; + have_vhosts = s ? HAVE_VHOSTS(s) : 0; if (have_vhosts && proc && proc->username[0] != 0) { - snprintf(name, sizeof(name), "[%s%s]", PREFIX_VHOST(proc->vhost), proc->username); - } else if (have_vhosts && proc && proc->username[0] == 0 && proc->vhost && proc->vhost->name) { - snprintf(name, sizeof(name), "[vhost:%s]", VHOSTNAME(proc->vhost)); + snprintf(name, sizeof(name), "[%s%s]", + PREFIX_VHOST(proc->vhost), proc->username); + } else if (have_vhosts && proc && proc->username[0] == 0 && + proc->vhost && proc->vhost->name) { + snprintf(name, sizeof(name), "[vhost:%s]", + VHOSTNAME(proc->vhost)); } else if (proc && proc->username[0] != 0) { snprintf(name, sizeof(name), "[%s]", proc->username); } else name[0] = 0; - _oc_syslog(syslog_prio, "main%s:%s %s", name, ip?ip:"[unknown]", buf); + _oc_syslog(syslog_prio, "main%s:%s %s", name, ip ? ip : "[unknown]", + buf); } -void mslog_hex(const main_server_st * s, const struct proc_st* proc, - int priority, const char *prefix, uint8_t* bin, unsigned bin_size, unsigned b64) +void mslog_hex(const main_server_st *s, const struct proc_st *proc, + int priority, const char *prefix, uint8_t *bin, + unsigned int bin_size, unsigned int b64) { char buf[512]; int ret; size_t buf_size; - gnutls_datum_t data = {bin, bin_size}; + gnutls_datum_t data = { bin, bin_size }; int log_prio = DEFAULT_LOG_LEVEL; if (s) @@ -92,7 +98,8 @@ void mslog_hex(const main_server_st * s, const struct proc_st* proc, return; if (b64) { - oc_base64_encode((char*)bin, bin_size, (char*)buf, sizeof(buf)); + oc_base64_encode((char *)bin, bin_size, (char *)buf, + sizeof(buf)); } else { buf_size = sizeof(buf); ret = gnutls_hex_encode(&data, buf, &buf_size); @@ -103,13 +110,13 @@ void mslog_hex(const main_server_st * s, const struct proc_st* proc, _mslog(s, proc, priority, "%s %s", prefix, buf); } -void seclog_hex(const struct sec_mod_st* sec, int priority, - const char *prefix, uint8_t* bin, unsigned bin_size, unsigned b64) +void seclog_hex(const struct sec_mod_st *sec, int priority, const char *prefix, + uint8_t *bin, unsigned int bin_size, unsigned int b64) { char buf[512]; int ret; size_t buf_size; - gnutls_datum_t data = {bin, bin_size}; + gnutls_datum_t data = { bin, bin_size }; int log_prio; log_prio = GETPCONFIG(sec)->log_level; @@ -118,7 +125,8 @@ void seclog_hex(const struct sec_mod_st* sec, int priority, return; if (b64) { - oc_base64_encode((char*)bin, bin_size, (char*)buf, sizeof(buf)); + oc_base64_encode((char *)bin, bin_size, (char *)buf, + sizeof(buf)); } else { buf_size = sizeof(buf); ret = gnutls_hex_encode(&data, buf, &buf_size); @@ -129,8 +137,8 @@ void seclog_hex(const struct sec_mod_st* sec, int priority, seclog(sec, priority, "%s %s", prefix, buf); } -void __attribute__ ((format(printf, 3, 4))) - _seclog(const sec_mod_st* sec, int priority, const char *fmt, ...) +void __attribute__((format(printf, 3, 4))) +_seclog(const sec_mod_st *sec, int priority, const char *fmt, ...) { char buf[512]; va_list args; diff --git a/src/main-proc.c b/src/main-proc.c index f060d171..922455bc 100644 --- a/src/main-proc.c +++ b/src/main-proc.c @@ -56,10 +56,11 @@ #include #include -struct proc_st *new_proc(main_server_st * s, pid_t pid, int cmd_fd, - struct sockaddr_storage *remote_addr, socklen_t remote_addr_len, - struct sockaddr_storage *our_addr, socklen_t our_addr_len, - uint8_t *sid, size_t sid_size) +struct proc_st *new_proc(main_server_st *s, pid_t pid, int cmd_fd, + struct sockaddr_storage *remote_addr, + socklen_t remote_addr_len, + struct sockaddr_storage *our_addr, + socklen_t our_addr_len, uint8_t *sid, size_t sid_size) { struct proc_st *ctmp; @@ -70,7 +71,7 @@ struct proc_st *new_proc(main_server_st * s, pid_t pid, int cmd_fd, ctmp->pid = pid; ctmp->tun_lease.fd = -1; ctmp->fd = cmd_fd; - set_cloexec_flag (cmd_fd, 1); + set_cloexec_flag(cmd_fd, 1); ctmp->conn_time = time(NULL); memcpy(&ctmp->remote_addr, remote_addr, remote_addr_len); @@ -92,7 +93,7 @@ struct proc_st *new_proc(main_server_st * s, pid_t pid, int cmd_fd, /* k: whether to kill the process */ -void remove_proc(main_server_st * s, struct proc_st *proc, unsigned flags) +void remove_proc(main_server_st *s, struct proc_st *proc, unsigned int flags) { pid_t pid; @@ -102,19 +103,25 @@ void remove_proc(main_server_st * s, struct proc_st *proc, unsigned flags) list_del(&proc->list); s->stats.active_clients--; - if ((flags&RPROC_KILL) && proc->pid != -1 && proc->pid != 0) + if ((flags & RPROC_KILL) && proc->pid != -1 && proc->pid != 0) kill(proc->pid, SIGTERM); /* close any pending sessions */ if (proc->active_sid && !(flags & RPROC_QUIT)) { - if (session_close(&(s->sec_mod_instances[proc->sec_mod_instance_index]), proc) < 0) { - mslog(s, proc, LOG_ERR, "error closing session (communication with sec-mod issue)"); + if (session_close( + &(s->sec_mod_instances[proc->sec_mod_instance_index]), + proc) < 0) { + mslog(s, proc, LOG_ERR, + "error closing session (communication with sec-mod issue)"); exit(EXIT_FAILURE); } } - mslog(s, proc, discon_reason_to_log_level(proc->discon_reason), "user disconnected (reason: %s, rx: %"PRIu64", tx: %"PRIu64")", - discon_reason_to_str(proc->discon_reason), proc->bytes_in, proc->bytes_out); + mslog(s, proc, discon_reason_to_log_level(proc->discon_reason), + "user disconnected (reason: %s, rx: %" PRIu64 ", tx: %" PRIu64 + ")", + discon_reason_to_str(proc->discon_reason), proc->bytes_in, + proc->bytes_out); pid = remove_from_script_list(s, proc); if (proc->status == PS_AUTH_COMPLETED || pid > 0) { @@ -128,8 +135,8 @@ void remove_proc(main_server_st * s, struct proc_st *proc, unsigned flags) user_disconnected(s, proc); } } else { /* pid > 0 or status == PS_AUTH_COMPLETED are mutually exclusive - * since PS_AUTH_COMPLETED is set only after a successful script run. - */ + * since PS_AUTH_COMPLETED is set only after a successful script run. + */ user_disconnected(s, proc); } } diff --git a/src/main-sec-mod-cmd.c b/src/main-sec-mod-cmd.c index d0edf9af..e337e57c 100644 --- a/src/main-sec-mod-cmd.c +++ b/src/main-sec-mod-cmd.c @@ -52,13 +52,14 @@ #include #ifdef HAVE_MALLOC_TRIM -# include +#include #endif -static void update_auth_failures(main_server_st * s, uint64_t auth_failures) +static void update_auth_failures(main_server_st *s, uint64_t auth_failures) { if (s->stats.auth_failures + auth_failures < s->stats.auth_failures) { - mslog(s, NULL, LOG_INFO, "overflow on updating authentication failures; resetting"); + mslog(s, NULL, LOG_INFO, + "overflow on updating authentication failures; resetting"); s->stats.auth_failures = 0; return; } @@ -66,9 +67,9 @@ static void update_auth_failures(main_server_st * s, uint64_t auth_failures) s->stats.total_auth_failures += auth_failures; } -int handle_sec_mod_commands(sec_mod_instance_st * sec_mod_instance) +int handle_sec_mod_commands(sec_mod_instance_st *sec_mod_instance) { - struct main_server_st * s = sec_mod_instance->server; + struct main_server_st *s = sec_mod_instance->server; struct iovec iov[3]; uint8_t cmd; struct msghdr hdr; @@ -76,6 +77,7 @@ int handle_sec_mod_commands(sec_mod_instance_st * sec_mod_instance) uint8_t *raw; int ret, raw_len, e; void *pool = talloc_new(s); + PROTOBUF_ALLOCATOR(pa, pool); BanIpMsg *tmsg = NULL; @@ -108,14 +110,17 @@ int handle_sec_mod_commands(sec_mod_instance_st * sec_mod_instance) return ERR_BAD_COMMAND; } - if (ret < 5 || cmd <= MIN_SECM_CMD || cmd >= MAX_SECM_CMD || (int)length < 0) { - mslog(s, NULL, LOG_ERR, "main received invalid message from sec-mod of %d bytes (cmd: %u)\n", - (int)length, (unsigned)cmd); + if (ret < 5 || cmd <= MIN_SECM_CMD || cmd >= MAX_SECM_CMD || + (int)length < 0) { + mslog(s, NULL, LOG_ERR, + "main received invalid message from sec-mod of %d bytes (cmd: %u)\n", + (int)length, (unsigned int)cmd); return ERR_BAD_COMMAND; } - mslog(s, NULL, LOG_DEBUG, "main received message '%s' from sec-mod of %u bytes\n", - cmd_request_to_str(cmd), (unsigned)length); + mslog(s, NULL, LOG_DEBUG, + "main received message '%s' from sec-mod of %u bytes\n", + cmd_request_to_str(cmd), (unsigned int)length); raw = talloc_size(pool, length); if (raw == NULL) { @@ -123,86 +128,90 @@ int handle_sec_mod_commands(sec_mod_instance_st * sec_mod_instance) return ERR_MEM; } - raw_len = force_read_timeout(sec_mod_instance->sec_mod_fd, raw, length, MAIN_SEC_MOD_TIMEOUT); + raw_len = force_read_timeout(sec_mod_instance->sec_mod_fd, raw, length, + MAIN_SEC_MOD_TIMEOUT); if (raw_len != length) { e = errno; mslog(s, NULL, LOG_ERR, "cannot obtain data of cmd %u with length %u from sec-mod socket: %s", - (unsigned)cmd, (unsigned)length, strerror(e)); + (unsigned int)cmd, (unsigned int)length, strerror(e)); ret = ERR_BAD_COMMAND; goto cleanup; } switch (cmd) { - case CMD_SECM_BAN_IP:{ - BanIpReplyMsg reply = BAN_IP_REPLY_MSG__INIT; + case CMD_SECM_BAN_IP: { + BanIpReplyMsg reply = BAN_IP_REPLY_MSG__INIT; - tmsg = ban_ip_msg__unpack(&pa, raw_len, raw); - if (tmsg == NULL) { - mslog(s, NULL, LOG_ERR, "error unpacking sec-mod data"); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - /* No need to authenticate tmsg->ip as sec-mod is trusted */ - ret = add_str_ip_to_ban_list(s, tmsg->ip, tmsg->score); - if (ret < 0) { - reply.reply = - AUTH__REP__FAILED; - } else { - /* no need to send a reply at all */ - ret = 0; - goto cleanup; - } - - reply.sid.data = tmsg->sid.data; - reply.sid.len = tmsg->sid.len; - reply.has_sid = tmsg->has_sid; - - mslog(s, NULL, LOG_DEBUG, "sending msg %s to sec-mod", cmd_request_to_str(CMD_SECM_BAN_IP_REPLY)); - - ret = send_msg(NULL, sec_mod_instance->sec_mod_fd, CMD_SECM_BAN_IP_REPLY, - &reply, (pack_size_func)ban_ip_reply_msg__get_packed_size, - (pack_func)ban_ip_reply_msg__pack); - if (ret < 0) { - mslog(s, NULL, LOG_ERR, - "could not send reply cmd %d.", - (unsigned)cmd); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - safe_memset(tmsg->sid.data, 0, tmsg->sid.len); - safe_memset(raw, 0, raw_len); + tmsg = ban_ip_msg__unpack(&pa, raw_len, raw); + if (tmsg == NULL) { + mslog(s, NULL, LOG_ERR, "error unpacking sec-mod data"); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + /* No need to authenticate tmsg->ip as sec-mod is trusted */ + ret = add_str_ip_to_ban_list(s, tmsg->ip, tmsg->score); + if (ret < 0) { + reply.reply = AUTH__REP__FAILED; + } else { + /* no need to send a reply at all */ + ret = 0; + goto cleanup; } - break; - case CMD_SECM_STATS:{ - SecmStatsMsg *smsg = NULL; + reply.sid.data = tmsg->sid.data; + reply.sid.len = tmsg->sid.len; + reply.has_sid = tmsg->has_sid; - smsg = secm_stats_msg__unpack(&pa, raw_len, raw); - if (smsg == NULL) { - mslog(s, NULL, LOG_ERR, "error unpacking sec-mod data"); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - sec_mod_instance->secmod_client_entries = smsg->secmod_client_entries; - sec_mod_instance->tlsdb_entries = smsg->secmod_tlsdb_entries; - sec_mod_instance->max_auth_time = smsg->secmod_max_auth_time; - sec_mod_instance->avg_auth_time = smsg->secmod_avg_auth_time; - update_auth_failures(s, smsg->secmod_auth_failures); + mslog(s, NULL, LOG_DEBUG, "sending msg %s to sec-mod", + cmd_request_to_str(CMD_SECM_BAN_IP_REPLY)); + ret = send_msg( + NULL, sec_mod_instance->sec_mod_fd, + CMD_SECM_BAN_IP_REPLY, &reply, + (pack_size_func)ban_ip_reply_msg__get_packed_size, + (pack_func)ban_ip_reply_msg__pack); + if (ret < 0) { + mslog(s, NULL, LOG_ERR, "could not send reply cmd %d.", + (unsigned int)cmd); + ret = ERR_BAD_COMMAND; + goto cleanup; } - break; + safe_memset(tmsg->sid.data, 0, tmsg->sid.len); + safe_memset(raw, 0, raw_len); + } + + break; + case CMD_SECM_STATS: { + SecmStatsMsg *smsg = NULL; + + smsg = secm_stats_msg__unpack(&pa, raw_len, raw); + if (smsg == NULL) { + mslog(s, NULL, LOG_ERR, "error unpacking sec-mod data"); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + + sec_mod_instance->secmod_client_entries = + smsg->secmod_client_entries; + sec_mod_instance->tlsdb_entries = smsg->secmod_tlsdb_entries; + sec_mod_instance->max_auth_time = smsg->secmod_max_auth_time; + sec_mod_instance->avg_auth_time = smsg->secmod_avg_auth_time; + update_auth_failures(s, smsg->secmod_auth_failures); + + } + + break; default: - mslog(s, NULL, LOG_ERR, "unknown CMD from sec-mod 0x%x.", (unsigned)cmd); + mslog(s, NULL, LOG_ERR, "unknown CMD from sec-mod 0x%x.", + (unsigned int)cmd); ret = ERR_BAD_COMMAND; goto cleanup; } ret = 0; - cleanup: +cleanup: if (tmsg != NULL) ban_ip_msg__free_unpacked(tmsg, &pa); talloc_free(raw); @@ -211,25 +220,29 @@ int handle_sec_mod_commands(sec_mod_instance_st * sec_mod_instance) return ret; } -static void append_routes(sec_mod_instance_st * sec_mod_instance, proc_st *proc, GroupCfgSt *gc) +static void append_routes(sec_mod_instance_st *sec_mod_instance, proc_st *proc, + GroupCfgSt *gc) { vhost_cfg_st *vhost = proc->vhost; /* if we have known_iroutes, we must append them to the routes list */ - if (vhost->perm_config.config->known_iroutes_size > 0 || vhost->perm_config.config->append_routes) { + if (vhost->perm_config.config->known_iroutes_size > 0 || + vhost->perm_config.config->append_routes) { char **old_routes = gc->routes; - unsigned old_routes_size = gc->n_routes; - unsigned i, j, append; - unsigned to_append = 0; + unsigned int old_routes_size = gc->n_routes; + unsigned int i, j, append; + unsigned int to_append = 0; to_append = vhost->perm_config.config->known_iroutes_size; if (vhost->perm_config.config->append_routes) - to_append += vhost->perm_config.config->network.routes_size; + to_append += + vhost->perm_config.config->network.routes_size; gc->n_routes = 0; - gc->routes = talloc_size(proc, sizeof(char*)*(old_routes_size+to_append)); + gc->routes = talloc_size( + proc, sizeof(char *) * (old_routes_size + to_append)); - for (i=0;iroutes[i] = talloc_strdup(proc, old_routes[i]); if (gc->routes[i] == NULL) break; @@ -238,17 +251,25 @@ static void append_routes(sec_mod_instance_st * sec_mod_instance, proc_st *proc, if (gc->routes) { /* Append any iroutes that are known and don't match the client's */ - for (i=0;iperm_config.config->known_iroutes_size;i++) { + for (i = 0; + i < vhost->perm_config.config->known_iroutes_size; + i++) { append = 1; - for (j=0;jn_iroutes;j++) { - if (strcmp(gc->iroutes[j], vhost->perm_config.config->known_iroutes[i]) == 0) { + for (j = 0; j < gc->n_iroutes; j++) { + if (strcmp(gc->iroutes[j], + vhost->perm_config.config + ->known_iroutes[i]) == + 0) { append = 0; break; } } if (append) { - gc->routes[gc->n_routes] = talloc_strdup(proc, vhost->perm_config.config->known_iroutes[i]); + gc->routes[gc->n_routes] = talloc_strdup( + proc, + vhost->perm_config.config + ->known_iroutes[i]); if (gc->routes[gc->n_routes] == NULL) break; gc->n_routes++; @@ -259,8 +280,13 @@ static void append_routes(sec_mod_instance_st * sec_mod_instance, proc_st *proc, if (vhost->perm_config.config->append_routes) { /* Append all global routes */ if (gc->routes) { - for (i=0;iperm_config.config->network.routes_size;i++) { - gc->routes[gc->n_routes] = talloc_strdup(proc, vhost->perm_config.config->network.routes[i]); + for (i = 0; i < vhost->perm_config.config + ->network.routes_size; + i++) { + gc->routes[gc->n_routes] = talloc_strdup( + proc, + vhost->perm_config.config + ->network.routes[i]); if (gc->routes[gc->n_routes] == NULL) break; gc->n_routes++; @@ -268,24 +294,36 @@ static void append_routes(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } /* Append no-routes */ - if (vhost->perm_config.config->network.no_routes_size == 0) + if (vhost->perm_config.config->network.no_routes_size == + 0) return; old_routes = gc->no_routes; old_routes_size = gc->n_no_routes; gc->n_no_routes = 0; - gc->no_routes = talloc_size(proc, sizeof(char*)*(old_routes_size+vhost->perm_config.config->network.no_routes_size)); + gc->no_routes = talloc_size( + proc, + sizeof(char *) * + (old_routes_size + + vhost->perm_config.config->network + .no_routes_size)); - for (i=0;ino_routes[i] = talloc_strdup(proc, old_routes[i]); + for (i = 0; i < old_routes_size; i++) { + gc->no_routes[i] = + talloc_strdup(proc, old_routes[i]); if (gc->no_routes[i] == NULL) break; gc->n_no_routes++; } - for (i=0;iperm_config.config->network.no_routes_size;i++) { - gc->no_routes[gc->n_no_routes] = talloc_strdup(proc, vhost->perm_config.config->network.no_routes[i]); + for (i = 0; + i < + vhost->perm_config.config->network.no_routes_size; + i++) { + gc->no_routes[gc->n_no_routes] = talloc_strdup( + proc, vhost->perm_config.config->network + .no_routes[i]); if (gc->no_routes[gc->n_no_routes] == NULL) break; gc->n_no_routes++; @@ -294,13 +332,13 @@ static void append_routes(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } } -static -void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, GroupCfgSt *gc) +static void apply_default_config(sec_mod_instance_st *sec_mod_instance, + proc_st *proc, GroupCfgSt *gc) { vhost_cfg_st *vhost = proc->vhost; if (!gc->has_no_udp) { - gc->no_udp = (vhost->perm_config.udp_port!=0)?0:1; + gc->no_udp = (vhost->perm_config.udp_port != 0) ? 0 : 1; gc->has_no_udp = 1; } @@ -313,7 +351,8 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, if (gc->no_routes == NULL) { gc->no_routes = vhost->perm_config.config->network.no_routes; - gc->n_no_routes = vhost->perm_config.config->network.no_routes_size; + gc->n_no_routes = + vhost->perm_config.config->network.no_routes_size; } if (gc->dns == NULL) { @@ -332,12 +371,14 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } if (!gc->has_interim_update_secs) { - gc->interim_update_secs = vhost->perm_config.config->stats_report_time; + gc->interim_update_secs = + vhost->perm_config.config->stats_report_time; gc->has_interim_update_secs = 1; } if (!gc->has_session_timeout_secs) { - gc->session_timeout_secs = vhost->perm_config.config->session_timeout; + gc->session_timeout_secs = + vhost->perm_config.config->session_timeout; gc->has_session_timeout_secs = 1; } @@ -351,7 +392,8 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } if (!gc->ipv4_netmask) { - gc->ipv4_netmask = vhost->perm_config.config->network.ipv4_netmask; + gc->ipv4_netmask = + vhost->perm_config.config->network.ipv4_netmask; } if (!gc->ipv6_net) { @@ -359,12 +401,14 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } if (!gc->has_ipv6_prefix) { - gc->ipv6_prefix = vhost->perm_config.config->network.ipv6_prefix; + gc->ipv6_prefix = + vhost->perm_config.config->network.ipv6_prefix; gc->has_ipv6_prefix = 1; } if (!gc->has_ipv6_subnet_prefix) { - gc->ipv6_subnet_prefix = vhost->perm_config.config->network.ipv6_subnet_prefix; + gc->ipv6_subnet_prefix = + vhost->perm_config.config->network.ipv6_subnet_prefix; gc->has_ipv6_subnet_prefix = 1; } @@ -374,12 +418,14 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, #ifdef ANYCONNECT_CLIENT_COMPAT if (!gc->xml_config_file) { - gc->xml_config_file = vhost->perm_config.config->xml_config_file; + gc->xml_config_file = + vhost->perm_config.config->xml_config_file; } #endif if (!gc->has_client_bypass_protocol) { - gc->client_bypass_protocol = vhost->perm_config.config->client_bypass_protocol; + gc->client_bypass_protocol = + vhost->perm_config.config->client_bypass_protocol; gc->has_client_bypass_protocol = 1; } @@ -414,7 +460,8 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } if (!gc->has_max_same_clients) { - gc->max_same_clients = vhost->perm_config.config->max_same_clients; + gc->max_same_clients = + vhost->perm_config.config->max_same_clients; gc->has_max_same_clients = 1; } @@ -424,7 +471,8 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } if (!gc->has_restrict_user_to_routes) { - gc->restrict_user_to_routes = vhost->perm_config.config->restrict_user_to_routes; + gc->restrict_user_to_routes = + vhost->perm_config.config->restrict_user_to_routes; gc->has_restrict_user_to_routes = 1; } @@ -439,7 +487,8 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, } if (!gc->has_mobile_idle_timeout) { - gc->mobile_idle_timeout = vhost->perm_config.config->mobile_idle_timeout; + gc->mobile_idle_timeout = + vhost->perm_config.config->mobile_idle_timeout; gc->has_mobile_idle_timeout = 1; } @@ -453,10 +502,11 @@ void apply_default_config(sec_mod_instance_st * sec_mod_instance, proc_st *proc, (*proc->config_usage_count)++; } -int session_open(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc, const uint8_t *cookie, unsigned cookie_size) +int session_open(sec_mod_instance_st *sec_mod_instance, struct proc_st *proc, + const uint8_t *cookie, unsigned int cookie_size) { int ret, e; - main_server_st * s = sec_mod_instance->server; + main_server_st *s = sec_mod_instance->server; SecmSessionOpenMsg ireq = SECM_SESSION_OPEN_MSG__INIT; SecmSessionReplyMsg *msg = NULL; char str_ipv4[MAX_IP_STR]; @@ -466,37 +516,43 @@ int session_open(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc, c if (cookie == NULL || cookie_size != SID_SIZE) return -1; - ireq.sid.data = (void*)cookie; + ireq.sid.data = (void *)cookie; ireq.sid.len = cookie_size; - if (proc->ipv4 && - human_addr2((struct sockaddr *)&proc->ipv4->rip, proc->ipv4->rip_len, - str_ipv4, sizeof(str_ipv4), 0) != NULL) { + if (proc->ipv4 && human_addr2((struct sockaddr *)&proc->ipv4->rip, + proc->ipv4->rip_len, str_ipv4, + sizeof(str_ipv4), 0) != NULL) { ireq.ipv4 = str_ipv4; } - if (proc->ipv6 && - human_addr2((struct sockaddr *)&proc->ipv6->rip, proc->ipv6->rip_len, - str_ipv6, sizeof(str_ipv6), 0) != NULL) { + if (proc->ipv6 && human_addr2((struct sockaddr *)&proc->ipv6->rip, + proc->ipv6->rip_len, str_ipv6, + sizeof(str_ipv6), 0) != NULL) { ireq.ipv6 = str_ipv6; } - mslog(s, proc, LOG_DEBUG, "sending msg %s to sec-mod", cmd_request_to_str(CMD_SECM_SESSION_OPEN)); + mslog(s, proc, LOG_DEBUG, "sending msg %s to sec-mod", + cmd_request_to_str(CMD_SECM_SESSION_OPEN)); - ret = send_msg(proc, sec_mod_instance->sec_mod_fd_sync, CMD_SECM_SESSION_OPEN, - &ireq, (pack_size_func)secm_session_open_msg__get_packed_size, - (pack_func)secm_session_open_msg__pack); + ret = send_msg(proc, sec_mod_instance->sec_mod_fd_sync, + CMD_SECM_SESSION_OPEN, &ireq, + (pack_size_func)secm_session_open_msg__get_packed_size, + (pack_func)secm_session_open_msg__pack); if (ret < 0) { mslog(s, proc, LOG_ERR, "error sending message to sec-mod cmd socket"); return -1; } - ret = recv_msg(proc, sec_mod_instance->sec_mod_fd_sync, CMD_SECM_SESSION_REPLY, - (void *)&msg, (unpack_func) secm_session_reply_msg__unpack, MAIN_SEC_MOD_TIMEOUT); + ret = recv_msg(proc, sec_mod_instance->sec_mod_fd_sync, + CMD_SECM_SESSION_REPLY, (void *)&msg, + (unpack_func)secm_session_reply_msg__unpack, + MAIN_SEC_MOD_TIMEOUT); if (ret < 0) { e = errno; - mslog(s, proc, LOG_ERR, "error receiving auth reply message from sec-mod cmd socket: %s", strerror(e)); + mslog(s, proc, LOG_ERR, + "error receiving auth reply message from sec-mod cmd socket: %s", + strerror(e)); return ret; } @@ -507,30 +563,37 @@ int session_open(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc, c } if (msg->username == NULL) { - mslog(s, proc, LOG_INFO, "no username present in session reply"); + mslog(s, proc, LOG_INFO, + "no username present in session reply"); return -1; } strlcpy(proc->username, msg->username, sizeof(proc->username)); if (msg->user_agent != NULL) { - strlcpy(proc->user_agent, msg->user_agent, sizeof(proc->user_agent)); + strlcpy(proc->user_agent, msg->user_agent, + sizeof(proc->user_agent)); } if (msg->device_type != NULL) { - strlcpy(proc->device_type, msg->device_type, sizeof(proc->device_type)); + strlcpy(proc->device_type, msg->device_type, + sizeof(proc->device_type)); } if (msg->device_platform != NULL) { - strlcpy(proc->device_platform, msg->device_platform, sizeof(proc->device_platform)); + strlcpy(proc->device_platform, msg->device_platform, + sizeof(proc->device_platform)); } /* override the group name in order to load the correct configuration in * case his group is specified in the certificate */ if (msg->groupname) - strlcpy(proc->groupname, msg->groupname, sizeof(proc->groupname)); + strlcpy(proc->groupname, msg->groupname, + sizeof(proc->groupname)); if (msg->config == NULL) { - mslog(s, proc, LOG_INFO, "received invalid configuration for '%s'; could not initiate session", proc->username); + mslog(s, proc, LOG_INFO, + "received invalid configuration for '%s'; could not initiate session", + proc->username); return -1; } @@ -548,13 +611,15 @@ int session_open(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc, c return -1; } - if (human_addr2((struct sockaddr *)&proc->remote_addr, proc->remote_addr_len, - str_ip, sizeof(str_ip), 0) == NULL) + if (human_addr2((struct sockaddr *)&proc->remote_addr, + proc->remote_addr_len, str_ip, + sizeof(str_ip), 0) == NULL) return -1; if (strcmp(str_ip, msg->ip) != 0) { - mslog(s, proc, LOG_INFO, "user '%s' is re-using cookie from different IP (prev: %s, current: %s); rejecting", - proc->username, msg->ip, str_ip); + mslog(s, proc, LOG_INFO, + "user '%s' is re-using cookie from different IP (prev: %s, current: %s); rejecting", + proc->username, msg->ip, str_ip); return -1; } } @@ -568,8 +633,10 @@ static void reset_stats(main_server_st *s, time_t now) unsigned int i; unsigned long max_auth_time = 0; unsigned long avg_auth_time = 0; - for (i = 0; i < s->sec_mod_instance_count; i ++) { - max_auth_time = MAX(max_auth_time, s->sec_mod_instances[i].max_auth_time); + + for (i = 0; i < s->sec_mod_instance_count; i++) { + max_auth_time = MAX(max_auth_time, + s->sec_mod_instances[i].max_auth_time); s->sec_mod_instances[i].max_auth_time = 0; avg_auth_time += s->sec_mod_instances[i].avg_auth_time; s->sec_mod_instances[i].avg_auth_time = 0; @@ -577,20 +644,34 @@ static void reset_stats(main_server_st *s, time_t now) if (s->sec_mod_instance_count != 0) avg_auth_time /= s->sec_mod_instance_count; mslog(s, NULL, LOG_INFO, "Start statistics block"); - mslog(s, NULL, LOG_INFO, "Total sessions handled: %lu", (unsigned long)s->stats.total_sessions_closed); - mslog(s, NULL, LOG_INFO, "Sessions handled: %lu", (unsigned long)s->stats.sessions_closed); - mslog(s, NULL, LOG_INFO, "Maximum session time: %lu min", (unsigned long)s->stats.max_session_mins); - mslog(s, NULL, LOG_INFO, "Average session time: %lu min", (unsigned long)s->stats.avg_session_mins); - mslog(s, NULL, LOG_INFO, "Closed due to timeout sessions: %lu", (unsigned long)s->stats.session_timeouts); - mslog(s, NULL, LOG_INFO, "Closed due to timeout (idle) sessions: %lu", (unsigned long)s->stats.session_idle_timeouts); - mslog(s, NULL, LOG_INFO, "Closed due to error sessions: %lu", (unsigned long)s->stats.session_errors); + mslog(s, NULL, LOG_INFO, "Total sessions handled: %lu", + (unsigned long)s->stats.total_sessions_closed); + mslog(s, NULL, LOG_INFO, "Sessions handled: %lu", + (unsigned long)s->stats.sessions_closed); + mslog(s, NULL, LOG_INFO, "Maximum session time: %lu min", + (unsigned long)s->stats.max_session_mins); + mslog(s, NULL, LOG_INFO, "Average session time: %lu min", + (unsigned long)s->stats.avg_session_mins); + mslog(s, NULL, LOG_INFO, "Closed due to timeout sessions: %lu", + (unsigned long)s->stats.session_timeouts); + mslog(s, NULL, LOG_INFO, "Closed due to timeout (idle) sessions: %lu", + (unsigned long)s->stats.session_idle_timeouts); + mslog(s, NULL, LOG_INFO, "Closed due to error sessions: %lu", + (unsigned long)s->stats.session_errors); - mslog(s, NULL, LOG_INFO, "Total authentication failures: %lu", (unsigned long)s->stats.total_auth_failures); - mslog(s, NULL, LOG_INFO, "Authentication failures: %lu", (unsigned long)s->stats.auth_failures); - mslog(s, NULL, LOG_INFO, "Maximum authentication time: %lu sec", max_auth_time); - mslog(s, NULL, LOG_INFO, "Average authentication time: %lu sec", avg_auth_time); - mslog(s, NULL, LOG_INFO, "Data in: %lu, out: %lu kbytes", (unsigned long)s->stats.kbytes_in, (unsigned long)s->stats.kbytes_out); - mslog(s, NULL, LOG_INFO, "End of statistics block; resetting non-total stats"); + mslog(s, NULL, LOG_INFO, "Total authentication failures: %lu", + (unsigned long)s->stats.total_auth_failures); + mslog(s, NULL, LOG_INFO, "Authentication failures: %lu", + (unsigned long)s->stats.auth_failures); + mslog(s, NULL, LOG_INFO, "Maximum authentication time: %lu sec", + max_auth_time); + mslog(s, NULL, LOG_INFO, "Average authentication time: %lu sec", + avg_auth_time); + mslog(s, NULL, LOG_INFO, "Data in: %lu, out: %lu kbytes", + (unsigned long)s->stats.kbytes_in, + (unsigned long)s->stats.kbytes_out); + mslog(s, NULL, LOG_INFO, + "End of statistics block; resetting non-total stats"); s->stats.session_idle_timeouts = 0; s->stats.session_timeouts = 0; @@ -601,10 +682,9 @@ static void reset_stats(main_server_st *s, time_t now) s->stats.kbytes_in = 0; s->stats.kbytes_out = 0; s->stats.max_session_mins = 0; - } -static void update_main_stats(main_server_st * s, struct proc_st *proc) +static void update_main_stats(main_server_st *s, struct proc_st *proc) { uint64_t kb_in, kb_out; time_t now = time(NULL), stime; @@ -629,13 +709,13 @@ static void update_main_stats(main_server_st * s, struct proc_st *proc) goto reset; } - kb_in = proc->bytes_in/1000; - kb_out = proc->bytes_out/1000; + kb_in = proc->bytes_in / 1000; + kb_out = proc->bytes_out / 1000; - if (s->stats.kbytes_in + kb_in < s->stats.kbytes_in) + if (s->stats.kbytes_in + kb_in < s->stats.kbytes_in) goto reset; - if (s->stats.kbytes_out + kb_out < s->stats.kbytes_out) + if (s->stats.kbytes_out + kb_out < s->stats.kbytes_out) goto reset; s->stats.kbytes_in += kb_in; @@ -647,25 +727,30 @@ static void update_main_stats(main_server_st * s, struct proc_st *proc) s->stats.max_mtu = proc->mtu; /* connection time in minutes */ - stime = (now - proc->conn_time)/60; + stime = (now - proc->conn_time) / 60; if (stime > 0) { - s->stats.avg_session_mins = ((s->stats.sessions_closed-1) * s->stats.avg_session_mins + stime) / s->stats.sessions_closed; + s->stats.avg_session_mins = ((s->stats.sessions_closed - 1) * + s->stats.avg_session_mins + + stime) / + s->stats.sessions_closed; if (stime > s->stats.max_session_mins) s->stats.max_session_mins = stime; } return; - reset: - mslog(s, NULL, LOG_INFO, "overflow on updating server statistics, resetting stats"); +reset: + mslog(s, NULL, LOG_INFO, + "overflow on updating server statistics, resetting stats"); reset_stats(s, now); } -int session_close(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc) +int session_close(sec_mod_instance_st *sec_mod_instance, struct proc_st *proc) { - main_server_st * s = sec_mod_instance->server; + main_server_st *s = sec_mod_instance->server; int ret, e; SecmSessionCloseMsg ireq = SECM_SESSION_CLOSE_MSG__INIT; CliStatsMsg *msg = NULL; + PROTOBUF_ALLOCATOR(pa, proc); ireq.uptime = time(NULL) - proc->conn_time; @@ -680,22 +765,28 @@ int session_close(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc) if (proc->invalidated) ireq.server_disconnected = 1; - mslog(s, proc, LOG_DEBUG, "sending msg %s to sec-mod", cmd_request_to_str(CMD_SECM_SESSION_CLOSE)); + mslog(s, proc, LOG_DEBUG, "sending msg %s to sec-mod", + cmd_request_to_str(CMD_SECM_SESSION_CLOSE)); - ret = send_msg(proc, sec_mod_instance->sec_mod_fd_sync, CMD_SECM_SESSION_CLOSE, - &ireq, (pack_size_func)secm_session_close_msg__get_packed_size, - (pack_func)secm_session_close_msg__pack); + ret = send_msg(proc, sec_mod_instance->sec_mod_fd_sync, + CMD_SECM_SESSION_CLOSE, &ireq, + (pack_size_func)secm_session_close_msg__get_packed_size, + (pack_func)secm_session_close_msg__pack); if (ret < 0) { mslog(s, proc, LOG_ERR, "error sending message to sec-mod cmd socket"); return -1; } - ret = recv_msg(proc, sec_mod_instance->sec_mod_fd_sync, CMD_SECM_CLI_STATS, - (void *)&msg, (unpack_func) cli_stats_msg__unpack, MAIN_SEC_MOD_TIMEOUT); + ret = recv_msg(proc, sec_mod_instance->sec_mod_fd_sync, + CMD_SECM_CLI_STATS, (void *)&msg, + (unpack_func)cli_stats_msg__unpack, + MAIN_SEC_MOD_TIMEOUT); if (ret < 0) { e = errno; - mslog(s, proc, LOG_ERR, "error receiving auth cli stats message from sec-mod cmd socket: %s", strerror(e)); + mslog(s, proc, LOG_ERR, + "error receiving auth cli stats message from sec-mod cmd socket: %s", + strerror(e)); return ret; } @@ -712,26 +803,29 @@ int session_close(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc) return 0; } -int secmod_reload(sec_mod_instance_st * sec_mod_instance) +int secmod_reload(sec_mod_instance_st *sec_mod_instance) { - main_server_st * s = sec_mod_instance->server; + main_server_st *s = sec_mod_instance->server; int ret, e; - mslog(s, NULL, LOG_DEBUG, "sending msg %s to sec-mod", cmd_request_to_str(CMD_SECM_RELOAD)); + mslog(s, NULL, LOG_DEBUG, "sending msg %s to sec-mod", + cmd_request_to_str(CMD_SECM_RELOAD)); - ret = send_msg(s->main_pool, sec_mod_instance->sec_mod_fd_sync, CMD_SECM_RELOAD, - NULL, NULL, NULL); + ret = send_msg(s->main_pool, sec_mod_instance->sec_mod_fd_sync, + CMD_SECM_RELOAD, NULL, NULL, NULL); if (ret < 0) { mslog(s, NULL, LOG_ERR, "error sending message to sec-mod cmd socket"); return -1; } - ret = recv_msg(s->main_pool, sec_mod_instance->sec_mod_fd_sync, CMD_SECM_RELOAD_REPLY, - NULL, NULL, MAIN_SEC_MOD_TIMEOUT); + ret = recv_msg(s->main_pool, sec_mod_instance->sec_mod_fd_sync, + CMD_SECM_RELOAD_REPLY, NULL, NULL, MAIN_SEC_MOD_TIMEOUT); if (ret < 0) { e = errno; - mslog(s, NULL, LOG_ERR, "error receiving reload reply message from sec-mod cmd socket: %s", strerror(e)); + mslog(s, NULL, LOG_ERR, + "error receiving reload reply message from sec-mod cmd socket: %s", + strerror(e)); return ret; } @@ -743,7 +837,8 @@ static void clear_unneeded_mem(struct list_head *vconfig) vhost_cfg_st *vhost = NULL; /* deinitialize certificate credentials etc. */ - list_for_each_rev(vconfig, vhost, list) { + list_for_each_rev(vconfig, vhost, list) + { tls_vhost_deinit(vhost); } } @@ -752,47 +847,59 @@ static void clear_unneeded_mem(struct list_head *vconfig) * The sync_fd is used by main to send synchronous commands- commands which * expect a reply immediately. */ -void run_sec_mod(sec_mod_instance_st * sec_mod_instance, unsigned int instance_index) +void run_sec_mod(sec_mod_instance_st *sec_mod_instance, + unsigned int instance_index) { int e, fd[2], ret; int sfd[2]; pid_t pid; const char *p; - main_server_st * s = sec_mod_instance->server; + main_server_st *s = sec_mod_instance->server; /* fills sec_mod_instance->socket_file */ - snprintf(sec_mod_instance->socket_file, sizeof(sec_mod_instance->socket_file), "%s.%d", secmod_socket_file_name(GETPCONFIG(s)), instance_index); - mslog(s, NULL, LOG_DEBUG, "created sec-mod socket file (%s)", sec_mod_instance->socket_file); + snprintf(sec_mod_instance->socket_file, + sizeof(sec_mod_instance->socket_file), "%s.%d", + secmod_socket_file_name(GETPCONFIG(s)), instance_index); + mslog(s, NULL, LOG_DEBUG, "created sec-mod socket file (%s)", + sec_mod_instance->socket_file); if (GETPCONFIG(s)->chroot_dir != NULL) { - ret = snprintf(sec_mod_instance->full_socket_file, sizeof(sec_mod_instance->full_socket_file), "%s/%s", - GETPCONFIG(s)->chroot_dir, sec_mod_instance->socket_file); + ret = snprintf(sec_mod_instance->full_socket_file, + sizeof(sec_mod_instance->full_socket_file), + "%s/%s", GETPCONFIG(s)->chroot_dir, + sec_mod_instance->socket_file); if (ret != strlen(sec_mod_instance->full_socket_file)) { - mslog(s, NULL, LOG_ERR, "too long chroot path; cannot create socket: %s", sec_mod_instance->full_socket_file); + mslog(s, NULL, LOG_ERR, + "too long chroot path; cannot create socket: %s", + sec_mod_instance->full_socket_file); exit(EXIT_FAILURE); } } else { - strlcpy(sec_mod_instance->full_socket_file, sec_mod_instance->socket_file, sizeof(sec_mod_instance->full_socket_file)); + strlcpy(sec_mod_instance->full_socket_file, + sec_mod_instance->socket_file, + sizeof(sec_mod_instance->full_socket_file)); } p = sec_mod_instance->full_socket_file; ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd); if (ret < 0) { - mslog(s, NULL, LOG_ERR, "error creating sec-mod command socket"); + mslog(s, NULL, LOG_ERR, + "error creating sec-mod command socket"); exit(EXIT_FAILURE); } ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sfd); if (ret < 0) { - mslog(s, NULL, LOG_ERR, "error creating sec-mod sync command socket"); + mslog(s, NULL, LOG_ERR, + "error creating sec-mod sync command socket"); exit(EXIT_FAILURE); } pid = fork(); - if (pid == 0) { /* child */ + if (pid == 0) { /* child */ clear_lists(s); kill_on_parent_kill(SIGTERM); @@ -804,17 +911,19 @@ void run_sec_mod(sec_mod_instance_st * sec_mod_instance, unsigned int instance_i setproctitle(PACKAGE "-sm"); close(fd[1]); close(sfd[1]); - set_cloexec_flag (fd[0], 1); - set_cloexec_flag (sfd[0], 1); + set_cloexec_flag(fd[0], 1); + set_cloexec_flag(sfd[0], 1); clear_unneeded_mem(s->vconfig); - sec_mod_server(s->main_pool, s->config_pool, s->vconfig, p, fd[0], sfd[0], sizeof(s->hmac_key), s->hmac_key, instance_index); + sec_mod_server(s->main_pool, s->config_pool, s->vconfig, p, + fd[0], sfd[0], sizeof(s->hmac_key), s->hmac_key, + instance_index); exit(EXIT_SUCCESS); - } else if (pid > 0) { /* parent */ + } else if (pid > 0) { /* parent */ close(fd[0]); close(sfd[0]); sec_mod_instance->sec_mod_pid = pid; - set_cloexec_flag (fd[1], 1); - set_cloexec_flag (sfd[1], 1); + set_cloexec_flag(fd[1], 1); + set_cloexec_flag(sfd[1], 1); sec_mod_instance->sec_mod_fd_sync = sfd[1]; sec_mod_instance->sec_mod_fd = fd[1]; return; diff --git a/src/main-user.c b/src/main-user.c index 38292b88..1fcc1e1c 100644 --- a/src/main-user.c +++ b/src/main-user.c @@ -34,7 +34,7 @@ #include #include #ifdef HAVE_LIBUTIL -# include +#include #endif #include @@ -49,13 +49,14 @@ #define OCSERV_FW_SCRIPT "/usr/libexec/ocserv-fw" -#define APPEND_TO_STR(str, val) \ - do { \ - ret = str_append_str(str, val); \ - if (ret < 0) { \ - mslog(s, proc, LOG_ERR, "could not append value to environment\n"); \ - exit(EXIT_FAILURE); \ - } \ +#define APPEND_TO_STR(str, val) \ + do { \ + ret = str_append_str(str, val); \ + if (ret < 0) { \ + mslog(s, proc, LOG_ERR, \ + "could not append value to environment\n"); \ + exit(EXIT_FAILURE); \ + } \ } while (0) typedef enum script_type_t { @@ -64,14 +65,14 @@ typedef enum script_type_t { SCRIPT_DISCONNECT } script_type_t; -static const char * const type_name[] = {"up", "host-update", "down"}; +static const char *const type_name[] = { "up", "host-update", "down" }; -static void export_fw_info(main_server_st *s, struct proc_st* proc) +static void export_fw_info(main_server_st *s, struct proc_st *proc) { str_st str4; str_st str6; str_st str_common; - unsigned i, negate = 0; + unsigned int i, negate = 0; int ret; str_init(&str4, proc); @@ -82,7 +83,7 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) * with legacy software such as iptables and ip6tables. */ /* append custom routes to str */ - for (i=0;iconfig->n_routes;i++) { + for (i = 0; i < proc->config->n_routes; i++) { APPEND_TO_STR(&str_common, proc->config->routes[i]); APPEND_TO_STR(&str_common, " "); @@ -95,17 +96,20 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) } } - if (str4.length > 0 && setenv("OCSERV_ROUTES4", (char*)str4.data, 1) == -1) { + if (str4.length > 0 && + setenv("OCSERV_ROUTES4", (char *)str4.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export routes\n"); exit(EXIT_FAILURE); } - if (str6.length > 0 && setenv("OCSERV_ROUTES6", (char*)str6.data, 1) == -1) { + if (str6.length > 0 && + setenv("OCSERV_ROUTES6", (char *)str6.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export routes\n"); exit(EXIT_FAILURE); } - if (str_common.length > 0 && setenv("OCSERV_ROUTES", (char*)str_common.data, 1) == -1) { + if (str_common.length > 0 && + setenv("OCSERV_ROUTES", (char *)str_common.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export routes\n"); exit(EXIT_FAILURE); } @@ -117,7 +121,7 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) str_reset(&str_common); /* append custom no_routes to str */ - for (i=0;iconfig->n_no_routes;i++) { + for (i = 0; i < proc->config->n_no_routes; i++) { APPEND_TO_STR(&str_common, proc->config->no_routes[i]); APPEND_TO_STR(&str_common, " "); @@ -130,24 +134,28 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) } } - if (str4.length > 0 && setenv("OCSERV_NO_ROUTES4", (char*)str4.data, 1) == -1) { + if (str4.length > 0 && + setenv("OCSERV_NO_ROUTES4", (char *)str4.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export no-routes\n"); exit(EXIT_FAILURE); } - if (str6.length > 0 && setenv("OCSERV_NO_ROUTES6", (char*)str6.data, 1) == -1) { + if (str6.length > 0 && + setenv("OCSERV_NO_ROUTES6", (char *)str6.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export no-routes\n"); exit(EXIT_FAILURE); } - if (str_common.length > 0 && setenv("OCSERV_NO_ROUTES", (char*)str_common.data, 1) == -1) { + if (str_common.length > 0 && + setenv("OCSERV_NO_ROUTES", (char *)str_common.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export no-routes\n"); exit(EXIT_FAILURE); } if (proc->config->restrict_user_to_routes) { if (setenv("OCSERV_RESTRICT_TO_ROUTES", "1", 1) == -1) { - mslog(s, proc, LOG_ERR, "could not export OCSERV_RESTRICT_TO_ROUTES\n"); + mslog(s, proc, LOG_ERR, + "could not export OCSERV_RESTRICT_TO_ROUTES\n"); exit(EXIT_FAILURE); } } @@ -158,7 +166,7 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) str_reset(&str_common); if (proc->config->n_dns > 0) { - for (i=0;iconfig->n_dns;i++) { + for (i = 0; i < proc->config->n_dns; i++) { APPEND_TO_STR(&str_common, proc->config->dns[i]); APPEND_TO_STR(&str_common, " "); @@ -172,17 +180,20 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) } } - if (str4.length > 0 && setenv("OCSERV_DNS4", (char*)str4.data, 1) == -1) { + if (str4.length > 0 && + setenv("OCSERV_DNS4", (char *)str4.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export DNS servers\n"); exit(EXIT_FAILURE); } - if (str6.length > 0 && setenv("OCSERV_DNS6", (char*)str6.data, 1) == -1) { + if (str6.length > 0 && + setenv("OCSERV_DNS6", (char *)str6.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export DNS servers\n"); exit(EXIT_FAILURE); } - if (str_common.length > 0 && setenv("OCSERV_DNS", (char*)str_common.data, 1) == -1) { + if (str_common.length > 0 && + setenv("OCSERV_DNS", (char *)str_common.data, 1) == -1) { mslog(s, proc, LOG_ERR, "could not export DNS servers\n"); exit(EXIT_FAILURE); } @@ -196,35 +207,45 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) str_reset(&str_common); if (proc->config->n_fw_ports > 0) { - for (i=0;iconfig->n_fw_ports;i++) { + for (i = 0; i < proc->config->n_fw_ports; i++) { if (proc->config->fw_ports[i]->negate) negate = 1; switch (proc->config->fw_ports[i]->proto) { case PROTO_UDP: - ret = str_append_printf(&str_common, "udp %u ", proc->config->fw_ports[i]->port); + ret = str_append_printf( + &str_common, "udp %u ", + proc->config->fw_ports[i]->port); break; case PROTO_TCP: - ret = str_append_printf(&str_common, "tcp %u ", proc->config->fw_ports[i]->port); + ret = str_append_printf( + &str_common, "tcp %u ", + proc->config->fw_ports[i]->port); break; case PROTO_SCTP: - ret = str_append_printf(&str_common, "sctp %u ", proc->config->fw_ports[i]->port); + ret = str_append_printf( + &str_common, "sctp %u ", + proc->config->fw_ports[i]->port); break; case PROTO_ICMP: - ret = str_append_printf(&str_common, "icmp all "); + ret = str_append_printf(&str_common, + "icmp all "); break; case PROTO_ESP: - ret = str_append_printf(&str_common, "esp all "); + ret = str_append_printf(&str_common, + "esp all "); break; case PROTO_ICMPv6: - ret = str_append_printf(&str_common, "icmpv6 all "); + ret = str_append_printf(&str_common, + "icmpv6 all "); break; default: ret = -1; } if (ret < 0) { - mslog(s, proc, LOG_ERR, "could not append value to environment\n"); + mslog(s, proc, LOG_ERR, + "could not append value to environment\n"); exit(EXIT_FAILURE); } } @@ -232,13 +253,17 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) if (str_common.length > 0) { if (negate) { - if (setenv("OCSERV_DENY_PORTS", (char*)str_common.data, 1) == -1) { - mslog(s, proc, LOG_ERR, "could not export DENY_PORTS\n"); + if (setenv("OCSERV_DENY_PORTS", (char *)str_common.data, + 1) == -1) { + mslog(s, proc, LOG_ERR, + "could not export DENY_PORTS\n"); exit(EXIT_FAILURE); } } else { - if (setenv("OCSERV_ALLOW_PORTS", (char*)str_common.data, 1) == -1) { - mslog(s, proc, LOG_ERR, "could not export ALLOW_PORTS\n"); + if (setenv("OCSERV_ALLOW_PORTS", + (char *)str_common.data, 1) == -1) { + mslog(s, proc, LOG_ERR, + "could not export ALLOW_PORTS\n"); exit(EXIT_FAILURE); } } @@ -247,12 +272,12 @@ static void export_fw_info(main_server_st *s, struct proc_st* proc) str_clear(&str_common); } -static -int call_script(main_server_st *s, struct proc_st* proc, script_type_t type) +static int call_script(main_server_st *s, struct proc_st *proc, + script_type_t type) { -pid_t pid; -int ret; -const char* script, *next_script = NULL; + pid_t pid; + int ret; + const char *script, *next_script = NULL; if (type == SCRIPT_CONNECT) script = GETCONFIG(s)->connect_script; @@ -262,7 +287,8 @@ const char* script, *next_script = NULL; script = GETCONFIG(s)->disconnect_script; if (type != SCRIPT_HOST_UPDATE) { - if (proc->config->restrict_user_to_routes || proc->config->n_fw_ports > 0) { + if (proc->config->restrict_user_to_routes || + proc->config->n_fw_ports > 0) { next_script = script; script = OCSERV_FW_SCRIPT; } @@ -279,20 +305,32 @@ const char* script, *next_script = NULL; sigprocmask(SIG_SETMASK, &sig_default_set, NULL); - snprintf(real, sizeof(real), "%u", (unsigned)proc->pid); + snprintf(real, sizeof(real), "%u", (unsigned int)proc->pid); setenv("ID", real, 1); if (proc->remote_addr_len > 0) { - if ((ret=getnameinfo((void*)&proc->remote_addr, proc->remote_addr_len, real, sizeof(real), NULL, 0, NI_NUMERICHOST)) != 0) { - mslog(s, proc, LOG_DEBUG, "cannot determine peer address: %s; script failed", gai_strerror(ret)); + ret = getnameinfo((void *)&proc->remote_addr, + proc->remote_addr_len, real, + sizeof(real), NULL, 0, + NI_NUMERICHOST); + if (ret != 0) { + mslog(s, proc, LOG_DEBUG, + "cannot determine peer address: %s; script failed", + gai_strerror(ret)); exit(EXIT_FAILURE); } setenv("IP_REAL", real, 1); } if (proc->our_addr_len > 0) { - if ((ret=getnameinfo((void*)&proc->our_addr, proc->our_addr_len, real, sizeof(real), NULL, 0, NI_NUMERICHOST)) != 0) { - mslog(s, proc, LOG_DEBUG, "cannot determine our address: %s", gai_strerror(ret)); + ret = getnameinfo((void *)&proc->our_addr, + proc->our_addr_len, real, + sizeof(real), NULL, 0, + NI_NUMERICHOST); + if (ret != 0) { + mslog(s, proc, LOG_DEBUG, + "cannot determine our address: %s", + gai_strerror(ret)); } else { setenv("IP_REAL_LOCAL", real, 1); } @@ -300,16 +338,24 @@ const char* script, *next_script = NULL; if (proc->ipv4 != NULL || proc->ipv6 != NULL) { if (proc->ipv4 && proc->ipv4->lip_len > 0) { - if (getnameinfo((void*)&proc->ipv4->lip, proc->ipv4->lip_len, local, sizeof(local), NULL, 0, NI_NUMERICHOST) != 0) { - mslog(s, proc, LOG_DEBUG, "cannot determine local VPN address; script failed"); + if (getnameinfo((void *)&proc->ipv4->lip, + proc->ipv4->lip_len, local, + sizeof(local), NULL, 0, + NI_NUMERICHOST) != 0) { + mslog(s, proc, LOG_DEBUG, + "cannot determine local VPN address; script failed"); exit(EXIT_FAILURE); } setenv("IP_LOCAL", local, 1); } if (proc->ipv6 && proc->ipv6->lip_len > 0) { - if (getnameinfo((void*)&proc->ipv6->lip, proc->ipv6->lip_len, local, sizeof(local), NULL, 0, NI_NUMERICHOST) != 0) { - mslog(s, proc, LOG_DEBUG, "cannot determine local VPN PtP address; script failed"); + if (getnameinfo((void *)&proc->ipv6->lip, + proc->ipv6->lip_len, local, + sizeof(local), NULL, 0, + NI_NUMERICHOST) != 0) { + mslog(s, proc, LOG_DEBUG, + "cannot determine local VPN PtP address; script failed"); exit(EXIT_FAILURE); } if (local[0] == 0) @@ -318,22 +364,31 @@ const char* script, *next_script = NULL; } if (proc->ipv4 && proc->ipv4->rip_len > 0) { - if (getnameinfo((void*)&proc->ipv4->rip, proc->ipv4->rip_len, remote, sizeof(remote), NULL, 0, NI_NUMERICHOST) != 0) { - mslog(s, proc, LOG_DEBUG, "cannot determine local VPN address; script failed"); + if (getnameinfo((void *)&proc->ipv4->rip, + proc->ipv4->rip_len, remote, + sizeof(remote), NULL, 0, + NI_NUMERICHOST) != 0) { + mslog(s, proc, LOG_DEBUG, + "cannot determine local VPN address; script failed"); exit(EXIT_FAILURE); } setenv("IP_REMOTE", remote, 1); } if (proc->ipv6 && proc->ipv6->rip_len > 0) { - if (getnameinfo((void*)&proc->ipv6->rip, proc->ipv6->rip_len, remote, sizeof(remote), NULL, 0, NI_NUMERICHOST) != 0) { - mslog(s, proc, LOG_DEBUG, "cannot determine local VPN PtP address; script failed"); + if (getnameinfo((void *)&proc->ipv6->rip, + proc->ipv6->rip_len, remote, + sizeof(remote), NULL, 0, + NI_NUMERICHOST) != 0) { + mslog(s, proc, LOG_DEBUG, + "cannot determine local VPN PtP address; script failed"); exit(EXIT_FAILURE); } if (remote[0] == 0) setenv("IP_REMOTE", remote, 1); setenv("IPV6_REMOTE", remote, 1); - snprintf(remote, sizeof(remote), "%u", proc->ipv6->prefix); + snprintf(remote, sizeof(remote), "%u", + proc->ipv6->prefix); setenv("IPV6_PREFIX", remote, 1); } } @@ -355,12 +410,16 @@ const char* script, *next_script = NULL; setenv("REASON", "host-update", 1); } else if (type == SCRIPT_DISCONNECT) { /* use remote as temp buffer */ - snprintf(remote, sizeof(remote), "%lu", (unsigned long)proc->bytes_in); + snprintf(remote, sizeof(remote), "%lu", + (unsigned long)proc->bytes_in); setenv("STATS_BYTES_IN", remote, 1); - snprintf(remote, sizeof(remote), "%lu", (unsigned long)proc->bytes_out); + snprintf(remote, sizeof(remote), "%lu", + (unsigned long)proc->bytes_out); setenv("STATS_BYTES_OUT", remote, 1); if (proc->conn_time > 0) { - snprintf(remote, sizeof(remote), "%lu", (unsigned long)(time(NULL)-proc->conn_time)); + snprintf(remote, sizeof(remote), "%lu", + (unsigned long)(time(NULL) - + proc->conn_time)); setenv("STATS_DURATION", remote, 1); } setenv("REASON", "disconnect", 1); @@ -372,18 +431,25 @@ const char* script, *next_script = NULL; /* set stdout to be stderr to avoid confusing scripts - note we have stdout closed */ if (dup2(STDERR_FILENO, STDOUT_FILENO) < 0) { int e = errno; - mslog(s, proc, LOG_INFO, "cannot dup2(STDERR_FILENO, STDOUT_FILENO): %s", strerror(e)); + + mslog(s, proc, LOG_INFO, + "cannot dup2(STDERR_FILENO, STDOUT_FILENO): %s", + strerror(e)); } if (next_script) { setenv("OCSERV_NEXT_SCRIPT", next_script, 1); - mslog(s, proc, LOG_DEBUG, "executing script %s %s (next: %s)", type_name[type], script, next_script); + mslog(s, proc, LOG_DEBUG, + "executing script %s %s (next: %s)", + type_name[type], script, next_script); } else - mslog(s, proc, LOG_DEBUG, "executing script %s %s", type_name[type], script); + mslog(s, proc, LOG_DEBUG, "executing script %s %s", + type_name[type], script); ret = execl(script, script, NULL); if (ret == -1) { - mslog(s, proc, LOG_ERR, "Could not execute script %s", script); + mslog(s, proc, LOG_ERR, "Could not execute script %s", + script); exit(EXIT_FAILURE); } @@ -404,8 +470,7 @@ const char* script, *next_script = NULL; } } -static void -add_utmp_entry(main_server_st *s, struct proc_st* proc) +static void add_utmp_entry(main_server_st *s, struct proc_st *proc) { #ifdef HAVE_LIBUTIL struct utmpx entry; @@ -421,15 +486,19 @@ add_utmp_entry(main_server_st *s, struct proc_st* proc) strlcpy(entry.ut_user, proc->username, sizeof(entry.ut_user)); #ifdef __linux__ if (proc->remote_addr_len == sizeof(struct sockaddr_in)) - memcpy(entry.ut_addr_v6, SA_IN_P(&proc->remote_addr), sizeof(struct in_addr)); + memcpy(entry.ut_addr_v6, SA_IN_P(&proc->remote_addr), + sizeof(struct in_addr)); else - memcpy(entry.ut_addr_v6, SA_IN6_P(&proc->remote_addr), sizeof(struct in6_addr)); + memcpy(entry.ut_addr_v6, SA_IN6_P(&proc->remote_addr), + sizeof(struct in6_addr)); #endif gettime(&tv); entry.ut_tv.tv_sec = tv.tv_sec; entry.ut_tv.tv_usec = tv.tv_nsec / 1000; - getnameinfo((void*)&proc->remote_addr, proc->remote_addr_len, entry.ut_host, sizeof(entry.ut_host), NULL, 0, NI_NUMERICHOST); + getnameinfo((void *)&proc->remote_addr, proc->remote_addr_len, + entry.ut_host, sizeof(entry.ut_host), NULL, 0, + NI_NUMERICHOST); setutxent(); pututxline(&entry); @@ -443,7 +512,7 @@ add_utmp_entry(main_server_st *s, struct proc_st* proc) #endif } -static void remove_utmp_entry(main_server_st *s, struct proc_st* proc) +static void remove_utmp_entry(main_server_st *s, struct proc_st *proc) { #ifdef HAVE_LIBUTIL struct utmpx entry; @@ -457,7 +526,8 @@ static void remove_utmp_entry(main_server_st *s, struct proc_st* proc) memset(&entry, 0, sizeof(entry)); entry.ut_type = DEAD_PROCESS; if (proc->tun_lease.name[0] != 0) - strlcpy(entry.ut_line, proc->tun_lease.name, sizeof(entry.ut_line)); + strlcpy(entry.ut_line, proc->tun_lease.name, + sizeof(entry.ut_line)); entry.ut_pid = proc->pid; setutxent(); @@ -474,11 +544,11 @@ static void remove_utmp_entry(main_server_st *s, struct proc_st* proc) #endif } -int user_connected(main_server_st *s, struct proc_st* proc) +int user_connected(main_server_st *s, struct proc_st *proc) { -int ret; + int ret; - ctl_handler_notify(s,proc, 1); + ctl_handler_notify(s, proc, 1); add_utmp_entry(s, proc); ret = call_script(s, proc, SCRIPT_CONNECT); @@ -488,7 +558,7 @@ int ret; return 0; } -void user_hostname_update(main_server_st *s, struct proc_st* proc) +void user_hostname_update(main_server_st *s, struct proc_st *proc) { if (proc->host_updated != 0) return; @@ -496,9 +566,9 @@ void user_hostname_update(main_server_st *s, struct proc_st* proc) proc->host_updated = 1; } -void user_disconnected(main_server_st *s, struct proc_st* proc) +void user_disconnected(main_server_st *s, struct proc_st *proc) { - ctl_handler_notify(s,proc, 0); + ctl_handler_notify(s, proc, 0); remove_utmp_entry(s, proc); call_script(s, proc, SCRIPT_DISCONNECT); } diff --git a/src/main-worker-cmd.c b/src/main-worker-cmd.c index c1e9f8ac..0d01a7f9 100644 --- a/src/main-worker-cmd.c +++ b/src/main-worker-cmd.c @@ -56,7 +56,7 @@ #include #include -int set_tun_mtu(main_server_st * s, struct proc_st *proc, unsigned mtu) +int set_tun_mtu(main_server_st *s, struct proc_st *proc, unsigned int mtu) { int fd, ret, e; struct ifreq ifr; @@ -79,15 +79,15 @@ int set_tun_mtu(main_server_st * s, struct proc_st *proc, unsigned mtu) ret = ioctl(fd, SIOCSIFMTU, &ifr); if (ret != 0) { e = errno; - mslog(s, proc, LOG_INFO, "ioctl SIOCSIFMTU(%d) error: %s", - mtu, strerror(e)); + mslog(s, proc, LOG_INFO, "ioctl SIOCSIFMTU(%d) error: %s", mtu, + strerror(e)); ret = -1; goto fail; } proc->mtu = mtu; ret = 0; - fail: +fail: close(fd); return ret; } @@ -119,8 +119,7 @@ int handle_script_exit(main_server_st *s, struct proc_st *proc, int code) mslog(s, proc, LOG_INFO, "failed authentication attempt for user '%s'", proc->username); - ret = - send_cookie_auth_reply(s, proc, AUTH__REP__FAILED); + ret = send_cookie_auth_reply(s, proc, AUTH__REP__FAILED); if (ret < 0) { mslog(s, proc, LOG_ERR, "could not send reply auth cmd."); @@ -130,7 +129,7 @@ int handle_script_exit(main_server_st *s, struct proc_st *proc, int code) } ret = 0; - fail: +fail: /* we close the lease tun fd both on success and failure. * The parent doesn't need to keep the tunfd, and if it does, * it causes issues to client. @@ -143,7 +142,8 @@ int handle_script_exit(main_server_st *s, struct proc_st *proc, int code) } /* This is the function after which proc is populated */ -static int accept_user(main_server_st * s, struct proc_st *proc, unsigned cmd) +static int accept_user(main_server_st *s, struct proc_st *proc, + unsigned int cmd) { int ret; const char *group; @@ -169,8 +169,7 @@ static int accept_user(main_server_st * s, struct proc_st *proc, unsigned cmd) if (cmd == AUTH_COOKIE_REQ) { mslog(s, proc, LOG_DEBUG, - "user of group '%s' authenticated (using cookie)", - group); + "user of group '%s' authenticated (using cookie)", group); } else { mslog(s, proc, LOG_INFO, "user of group '%s' authenticated but from unknown state! rejecting.", @@ -194,7 +193,7 @@ static int accept_user(main_server_st * s, struct proc_st *proc, unsigned cmd) * @result: the auth result */ static int handle_cookie_auth_res(main_server_st *s, struct proc_st *proc, - unsigned cmd, int result) + unsigned int cmd, int result) { int ret; @@ -214,7 +213,7 @@ static int handle_cookie_auth_res(main_server_st *s, struct proc_st *proc, ret = ERR_BAD_COMMAND; } - finished: +finished: if (ret == ERR_WAIT_FOR_SCRIPT) { /* we will wait for script termination to send our reply. * The notification of peer will be done in handle_script_exit(). @@ -230,20 +229,20 @@ static int handle_cookie_auth_res(main_server_st *s, struct proc_st *proc, return ret; } -int handle_worker_commands(main_server_st * s, struct proc_st *proc) +int handle_worker_commands(main_server_st *s, struct proc_st *proc) { uint8_t cmd; AuthCookieRequestMsg *auth_cookie_req; size_t length; uint8_t *raw; int ret, raw_len, e; + PROTOBUF_ALLOCATOR(pa, proc); ret = recv_msg_headers(proc->fd, &cmd, MAX_WAIT_SECS); if (ret < 0) { if (ret == ERR_PEER_TERMINATED) - mslog(s, proc, LOG_DEBUG, - "worker terminated"); + mslog(s, proc, LOG_DEBUG, "worker terminated"); else mslog(s, proc, LOG_DEBUG, "cannot obtain metadata from worker's command socket"); @@ -253,14 +252,15 @@ int handle_worker_commands(main_server_st * s, struct proc_st *proc) length = ret; if (length > MAX_MSG_SIZE) { - mslog(s, proc, LOG_DEBUG, - "received too big message (%d)", (int)length); + mslog(s, proc, LOG_DEBUG, "received too big message (%d)", + (int)length); ret = ERR_BAD_COMMAND; return ret; } - mslog(s, proc, LOG_DEBUG, "main received worker's message '%s' of %u bytes\n", - cmd_request_to_str(cmd), (unsigned)length); + mslog(s, proc, LOG_DEBUG, + "main received worker's message '%s' of %u bytes\n", + cmd_request_to_str(cmd), (unsigned int)length); raw = talloc_size(proc, length); if (raw == NULL) { @@ -279,138 +279,145 @@ int handle_worker_commands(main_server_st * s, struct proc_st *proc) } switch (cmd) { - case CMD_BAN_IP:{ - BanIpMsg *tmsg; - BanIpReplyMsg reply = BAN_IP_REPLY_MSG__INIT; - char remote_address[MAX_IP_STR]; + case CMD_BAN_IP: { + BanIpMsg *tmsg; + BanIpReplyMsg reply = BAN_IP_REPLY_MSG__INIT; + char remote_address[MAX_IP_STR]; - tmsg = ban_ip_msg__unpack(&pa, raw_len, raw); - if (tmsg == NULL) { - mslog(s, NULL, LOG_ERR, "error unpacking worker data"); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - human_addr2((struct sockaddr *)&proc->remote_addr, proc->remote_addr_len, remote_address, sizeof(remote_address), 0); - - ret = add_str_ip_to_ban_list(s, remote_address, tmsg->score); - - if (tmsg->has_discon_reason) { - proc->discon_reason = tmsg->discon_reason; - } - - ban_ip_msg__free_unpacked(tmsg, &pa); - - if (ret < 0) { - reply.reply = - AUTH__REP__FAILED; - } else { - reply.reply = - AUTH__REP__OK; - } - - ret = - send_msg_to_worker(s, proc, CMD_BAN_IP_REPLY, &reply, - (pack_size_func) - ban_ip_reply_msg__get_packed_size, - (pack_func) - ban_ip_reply_msg__pack); - - if (ret < 0) { - mslog(s, NULL, LOG_ERR, - "could not send reply cmd %d.", - (unsigned)cmd); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - } - break; - case CMD_TUN_MTU:{ - TunMtuMsg *tmsg; - unsigned minimum_mtu = RFC_791_MTU; - unsigned maximum_mtu = - proc->vhost->perm_config.config->default_mtu != 0 ? - proc->vhost->perm_config.config->default_mtu : - MAX_DTLS_MTU; - - if (proc->status != PS_AUTH_COMPLETED) { - mslog(s, proc, LOG_ERR, - "received TUN MTU in unauthenticated state."); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - tmsg = tun_mtu_msg__unpack(&pa, raw_len, raw); - if (tmsg == NULL) { - mslog(s, proc, LOG_ERR, "error unpacking data"); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - if (tmsg->mtu < minimum_mtu || tmsg->mtu > maximum_mtu) { - mslog(s, proc, LOG_ERR, - "worker process invalid MTU %d", (int)tmsg->mtu); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - set_tun_mtu(s, proc, tmsg->mtu); - - tun_mtu_msg__free_unpacked(tmsg, &pa); + tmsg = ban_ip_msg__unpack(&pa, raw_len, raw); + if (tmsg == NULL) { + mslog(s, NULL, LOG_ERR, "error unpacking worker data"); + ret = ERR_BAD_COMMAND; + goto cleanup; } - break; - case CMD_SESSION_INFO:{ - SessionInfoMsg *tmsg; + human_addr2((struct sockaddr *)&proc->remote_addr, + proc->remote_addr_len, remote_address, + sizeof(remote_address), 0); - tmsg = session_info_msg__unpack(&pa, raw_len, raw); - if (tmsg == NULL) { - mslog(s, proc, LOG_ERR, "error unpacking session info data"); - ret = ERR_BAD_COMMAND; - goto cleanup; - } + ret = add_str_ip_to_ban_list(s, remote_address, tmsg->score); - if (tmsg->tls_ciphersuite) - strlcpy(proc->tls_ciphersuite, tmsg->tls_ciphersuite, - sizeof(proc->tls_ciphersuite)); - if (tmsg->dtls_ciphersuite) - strlcpy(proc->dtls_ciphersuite, tmsg->dtls_ciphersuite, - sizeof(proc->dtls_ciphersuite)); - if (tmsg->cstp_compr) - strlcpy(proc->cstp_compr, tmsg->cstp_compr, - sizeof(proc->cstp_compr)); - if (tmsg->dtls_compr) - strlcpy(proc->dtls_compr, tmsg->dtls_compr, - sizeof(proc->dtls_compr)); + if (tmsg->has_discon_reason) { + proc->discon_reason = tmsg->discon_reason; + } - if (proc->hostname[0] != 0) { - user_hostname_update(s, proc); - } + ban_ip_msg__free_unpacked(tmsg, &pa); - if (GETCONFIG(s)->listen_proxy_proto) { - if (tmsg->has_remote_addr && tmsg->remote_addr.len <= sizeof(struct sockaddr_storage)) { - proc_table_update_ip(s, proc, (struct sockaddr_storage*)tmsg->remote_addr.data, tmsg->remote_addr.len); + if (ret < 0) { + reply.reply = AUTH__REP__FAILED; + } else { + reply.reply = AUTH__REP__OK; + } - /* If the address is in the BAN list, terminate it */ - if (check_if_banned(s, &proc->remote_addr, proc->remote_addr_len) != 0) { - if (proc->pid != -1 && proc->pid != 0) { - kill_proc(proc); - } + ret = send_msg_to_worker( + s, proc, CMD_BAN_IP_REPLY, &reply, + (pack_size_func)ban_ip_reply_msg__get_packed_size, + (pack_func)ban_ip_reply_msg__pack); + + if (ret < 0) { + mslog(s, NULL, LOG_ERR, "could not send reply cmd %d.", + (unsigned int)cmd); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + } break; + case CMD_TUN_MTU: { + TunMtuMsg *tmsg; + unsigned int minimum_mtu = RFC_791_MTU; + unsigned int maximum_mtu = + proc->vhost->perm_config.config->default_mtu != 0 ? + proc->vhost->perm_config.config->default_mtu : + MAX_DTLS_MTU; + + if (proc->status != PS_AUTH_COMPLETED) { + mslog(s, proc, LOG_ERR, + "received TUN MTU in unauthenticated state."); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + + tmsg = tun_mtu_msg__unpack(&pa, raw_len, raw); + if (tmsg == NULL) { + mslog(s, proc, LOG_ERR, "error unpacking data"); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + + if (tmsg->mtu < minimum_mtu || tmsg->mtu > maximum_mtu) { + mslog(s, proc, LOG_ERR, "worker process invalid MTU %d", + (int)tmsg->mtu); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + + set_tun_mtu(s, proc, tmsg->mtu); + + tun_mtu_msg__free_unpacked(tmsg, &pa); + } + + break; + case CMD_SESSION_INFO: { + SessionInfoMsg *tmsg; + + tmsg = session_info_msg__unpack(&pa, raw_len, raw); + if (tmsg == NULL) { + mslog(s, proc, LOG_ERR, + "error unpacking session info data"); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + + if (tmsg->tls_ciphersuite) + strlcpy(proc->tls_ciphersuite, tmsg->tls_ciphersuite, + sizeof(proc->tls_ciphersuite)); + if (tmsg->dtls_ciphersuite) + strlcpy(proc->dtls_ciphersuite, tmsg->dtls_ciphersuite, + sizeof(proc->dtls_ciphersuite)); + if (tmsg->cstp_compr) + strlcpy(proc->cstp_compr, tmsg->cstp_compr, + sizeof(proc->cstp_compr)); + if (tmsg->dtls_compr) + strlcpy(proc->dtls_compr, tmsg->dtls_compr, + sizeof(proc->dtls_compr)); + + if (proc->hostname[0] != 0) { + user_hostname_update(s, proc); + } + + if (GETCONFIG(s)->listen_proxy_proto) { + if (tmsg->has_remote_addr && + tmsg->remote_addr.len <= + sizeof(struct sockaddr_storage)) { + proc_table_update_ip( + s, proc, + (struct sockaddr_storage *) + tmsg->remote_addr.data, + tmsg->remote_addr.len); + + /* If the address is in the BAN list, terminate it */ + if (check_if_banned(s, &proc->remote_addr, + proc->remote_addr_len) != + 0) { + if (proc->pid != -1 && proc->pid != 0) { + kill_proc(proc); } } - - if (tmsg->has_our_addr && tmsg->our_addr.len <= sizeof(struct sockaddr_storage) && - tmsg->our_addr.len > 0) { - memcpy(&proc->our_addr, tmsg->our_addr.data, tmsg->our_addr.len); - proc->our_addr_len = tmsg->our_addr.len; - } - } - session_info_msg__free_unpacked(tmsg, &pa); + if (tmsg->has_our_addr && + tmsg->our_addr.len <= + sizeof(struct sockaddr_storage) && + tmsg->our_addr.len > 0) { + memcpy(&proc->our_addr, tmsg->our_addr.data, + tmsg->our_addr.len); + proc->our_addr_len = tmsg->our_addr.len; + } } - break; + session_info_msg__free_unpacked(tmsg, &pa); + } + + break; case AUTH_COOKIE_REQ: if (proc->status != PS_AUTH_INACTIVE) { mslog(s, proc, LOG_ERR, @@ -420,19 +427,23 @@ int handle_worker_commands(main_server_st * s, struct proc_st *proc) } auth_cookie_req = - auth_cookie_request_msg__unpack(&pa, raw_len, raw); + auth_cookie_request_msg__unpack(&pa, raw_len, raw); if (auth_cookie_req == NULL) { mslog(s, proc, LOG_ERR, "error unpacking cookie data"); ret = ERR_BAD_COMMAND; goto cleanup; } - proc->sec_mod_instance_index = auth_cookie_req->cookie.data[0] % s->sec_mod_instance_count; + proc->sec_mod_instance_index = auth_cookie_req->cookie.data[0] % + s->sec_mod_instance_count; - ret = handle_auth_cookie_req(&s->sec_mod_instances[proc->sec_mod_instance_index], proc, auth_cookie_req); + ret = handle_auth_cookie_req( + &s->sec_mod_instances[proc->sec_mod_instance_index], + proc, auth_cookie_req); safe_memset(raw, 0, raw_len); - safe_memset(auth_cookie_req->cookie.data, 0, auth_cookie_req->cookie.len); + safe_memset(auth_cookie_req->cookie.data, 0, + auth_cookie_req->cookie.len); auth_cookie_request_msg__free_unpacked(auth_cookie_req, &pa); @@ -444,39 +455,41 @@ int handle_worker_commands(main_server_st * s, struct proc_st *proc) break; #if defined(CAPTURE_LATENCY_SUPPORT) - case CMD_LATENCY_STATS_DELTA:{ - LatencyStatsDelta * tmsg; + case CMD_LATENCY_STATS_DELTA: { + LatencyStatsDelta *tmsg; - if (proc->status != PS_AUTH_COMPLETED) { - mslog(s, proc, LOG_ERR, - "received LATENCY STATS DELTA in unauthenticated state."); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - tmsg = latency_stats_delta__unpack(&pa, raw_len, raw); - if (tmsg == NULL) { - mslog(s, proc, LOG_ERR, "error unpacking latency stats delta data"); - ret = ERR_BAD_COMMAND; - goto cleanup; - } - - s->stats.delta_latency_stats.median_total += tmsg->median_delta; - s->stats.delta_latency_stats.rms_total += tmsg->rms_delta; - s->stats.delta_latency_stats.sample_count += tmsg->sample_count_delta; - - latency_stats_delta__free_unpacked(tmsg, &pa); + if (proc->status != PS_AUTH_COMPLETED) { + mslog(s, proc, LOG_ERR, + "received LATENCY STATS DELTA in unauthenticated state."); + ret = ERR_BAD_COMMAND; + goto cleanup; } - break; + + tmsg = latency_stats_delta__unpack(&pa, raw_len, raw); + if (tmsg == NULL) { + mslog(s, proc, LOG_ERR, + "error unpacking latency stats delta data"); + ret = ERR_BAD_COMMAND; + goto cleanup; + } + + s->stats.delta_latency_stats.median_total += tmsg->median_delta; + s->stats.delta_latency_stats.rms_total += tmsg->rms_delta; + s->stats.delta_latency_stats.sample_count += + tmsg->sample_count_delta; + + latency_stats_delta__free_unpacked(tmsg, &pa); + } break; #endif default: - mslog(s, proc, LOG_ERR, "unknown CMD from worker: 0x%x", (unsigned)cmd); + mslog(s, proc, LOG_ERR, "unknown CMD from worker: 0x%x", + (unsigned int)cmd); ret = ERR_BAD_COMMAND; goto cleanup; } ret = 0; - cleanup: +cleanup: talloc_free(raw); return ret; diff --git a/src/main.c b/src/main.c index cf1da4cb..7347581f 100644 --- a/src/main.c +++ b/src/main.c @@ -42,13 +42,13 @@ #include #include "setproctitle.h" #ifdef HAVE_LIBWRAP -# include +#include #endif #include #include #ifdef HAVE_LIBSYSTEMD -# include +#include #endif #include #include @@ -68,24 +68,24 @@ #include #ifdef HAVE_GSSAPI -# include +#include extern const asn1_static_node kkdcp_asn1_tab[]; -asn1_node _kkdcp_pkix1_asn = NULL; +asn1_node _kkdcp_pkix1_asn; #endif -extern struct snapshot_t * config_snapshot; +extern struct snapshot_t *config_snapshot; -int worker_argc = 0; -char **worker_argv = NULL; +int worker_argc; +char **worker_argv; -static void listen_watcher_cb (EV_P_ ev_io *w, int revents); -static void resume_accept_cb (EV_P_ ev_timer *w, int revents); +static void listen_watcher_cb(EV_P_ ev_io *w, int revents); +static void resume_accept_cb(EV_P_ ev_timer *w, int revents); -int syslog_open = 0; +int syslog_open; sigset_t sig_default_set; -struct ev_loop *main_loop = NULL; -static unsigned allow_broken_clients = 0; +struct ev_loop *main_loop; +static unsigned int allow_broken_clients; typedef struct sec_mod_watcher_st { ev_io sec_mod_watcher; @@ -95,7 +95,7 @@ typedef struct sec_mod_watcher_st { /* EV watchers */ ev_io ctl_watcher; -sec_mod_watcher_st * sec_mod_watchers = NULL; +sec_mod_watcher_st *sec_mod_watchers; ev_timer maintenance_watcher; ev_timer graceful_shutdown_watcher; ev_signal maintenance_sig_watcher; @@ -106,11 +106,11 @@ ev_signal reload_sig_watcher; ev_timer latency_watcher; #endif -static bool set_env_from_ws(main_server_st * ws); +static bool set_env_from_ws(main_server_st *ws); -static void add_listener(void *pool, struct listen_list_st *list, - int fd, int family, int socktype, int protocol, - struct sockaddr* addr, socklen_t addr_len) +static void add_listener(void *pool, struct listen_list_st *list, int fd, + int family, int socktype, int protocol, + struct sockaddr *addr, socklen_t addr_len) { struct listener_st *tmp; @@ -132,22 +132,22 @@ static void add_listener(void *pool, struct listen_list_st *list, list->total++; } -static void set_udp_socket_options(struct perm_cfg_st* config, int fd, int family) +static void set_udp_socket_options(struct perm_cfg_st *config, int fd, + int family) { -int y; + int y; if (config->config->try_mtu) { set_mtu_disc(fd, family, 1); } #if defined(IP_PKTINFO) y = 1; - if (setsockopt(fd, SOL_IP, IP_PKTINFO, - (const void *)&y, sizeof(y)) < 0) + if (setsockopt(fd, SOL_IP, IP_PKTINFO, (const void *)&y, sizeof(y)) < 0) perror("setsockopt(IP_PKTINFO) failed"); #elif defined(IP_RECVDSTADDR) /* *BSD */ if (family == AF_INET) { y = 1; - if (setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, - (const void *)&y, sizeof(y)) < 0) + if (setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, (const void *)&y, + sizeof(y)) < 0) perror("setsockopt(IP_RECVDSTADDR) failed"); } #endif @@ -164,16 +164,16 @@ int y; static void set_common_socket_options(int fd) { set_non_block(fd); - set_cloexec_flag (fd, 1); + set_cloexec_flag(fd, 1); } -static -int _listen_ports(void *pool, struct perm_cfg_st* config, struct addrinfo *res, - struct listen_list_st *list, struct netns_fds *netns) +static int _listen_ports(void *pool, struct perm_cfg_st *config, + struct addrinfo *res, struct listen_list_st *list, + struct netns_fds *netns) { struct addrinfo *ptr; int s, y; - const char* type = NULL; + const char *type = NULL; char buf[512]; for (ptr = res; ptr != NULL; ptr = ptr->ai_next) { @@ -188,12 +188,12 @@ int _listen_ports(void *pool, struct perm_cfg_st* config, struct addrinfo *res, continue; if (config->foreground != 0) - fprintf(stderr, "listening (%s) on %s...\n", - type, human_addr(ptr->ai_addr, ptr->ai_addrlen, - buf, sizeof(buf))); + fprintf(stderr, "listening (%s) on %s...\n", type, + human_addr(ptr->ai_addr, ptr->ai_addrlen, buf, + sizeof(buf))); s = socket_netns(netns, ptr->ai_family, ptr->ai_socktype, - ptr->ai_protocol); + ptr->ai_protocol); if (s < 0) { perror("socket() failed"); continue; @@ -205,15 +205,15 @@ int _listen_ports(void *pool, struct perm_cfg_st* config, struct addrinfo *res, /* avoid listen on ipv6 addresses failing * because already listening on ipv4 addresses: */ if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, - (const void *) &y, sizeof(y)) < 0) { + (const void *)&y, sizeof(y)) < 0) { perror("setsockopt(IPV6_V6ONLY) failed"); } } #endif y = 1; - if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, - (const void *) &y, sizeof(y)) < 0) { + if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const void *)&y, + sizeof(y)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } @@ -221,7 +221,6 @@ int _listen_ports(void *pool, struct perm_cfg_st* config, struct addrinfo *res, set_udp_socket_options(config, s, ptr->ai_family); } - if (bind(s, ptr->ai_addr, ptr->ai_addrlen) < 0) { perror("bind() failed"); close(s); @@ -238,9 +237,10 @@ int _listen_ports(void *pool, struct perm_cfg_st* config, struct addrinfo *res, set_common_socket_options(s); - add_listener(pool, list, s, ptr->ai_family, ptr->ai_socktype==SOCK_STREAM?SOCK_TYPE_TCP:SOCK_TYPE_UDP, - ptr->ai_protocol, ptr->ai_addr, ptr->ai_addrlen); - + add_listener(pool, list, s, ptr->ai_family, + ptr->ai_socktype == SOCK_STREAM ? SOCK_TYPE_TCP : + SOCK_TYPE_UDP, + ptr->ai_protocol, ptr->ai_addr, ptr->ai_addrlen); } fflush(stderr); @@ -250,10 +250,8 @@ int _listen_ports(void *pool, struct perm_cfg_st* config, struct addrinfo *res, /* Returns 0 on success or negative value on error. */ -static int -listen_ports(void *pool, struct perm_cfg_st* config, - struct listen_list_st *list, - struct netns_fds *netns) +static int listen_ports(void *pool, struct perm_cfg_st *config, + struct listen_list_st *list, struct netns_fds *netns) { struct addrinfo hints, *res; char portname[6]; @@ -267,22 +265,24 @@ listen_ports(void *pool, struct perm_cfg_st* config, #ifdef HAVE_LIBSYSTEMD /* Support for systemd socket-activatable service */ - if ((fds=sd_listen_fds(0)) > 0) { + fds = sd_listen_fds(0); + if (fds > 0) { /* if we get our fds from systemd */ - unsigned i; + unsigned int i; int family, type, fd; struct sockaddr_storage tmp_sock; socklen_t tmp_sock_len; - for (i=0;iport = ntohs(((struct sockaddr_in*)&tmp_sock)->sin_port); + config->port = ntohs( + ((struct sockaddr_in *)&tmp_sock) + ->sin_port); else - config->port = ntohs(((struct sockaddr_in6*)&tmp_sock)->sin6_port); + config->port = + ntohs(((struct sockaddr_in6 + *)&tmp_sock) + ->sin6_port); } else if (type == SOCK_DGRAM) { if (family == AF_INET) - config->udp_port = ntohs(((struct sockaddr_in*)&tmp_sock)->sin_port); + config->udp_port = ntohs( + ((struct sockaddr_in *)&tmp_sock) + ->sin_port); else - config->udp_port = ntohs(((struct sockaddr_in6*)&tmp_sock)->sin6_port); + config->udp_port = + ntohs(((struct sockaddr_in6 + *)&tmp_sock) + ->sin6_port); } - add_listener(pool, list, fd, family, type==SOCK_STREAM?SOCK_TYPE_TCP:SOCK_TYPE_UDP, 0, (struct sockaddr*)&tmp_sock, tmp_sock_len); + add_listener(pool, list, fd, family, + type == SOCK_STREAM ? SOCK_TYPE_TCP : + SOCK_TYPE_UDP, + 0, (struct sockaddr *)&tmp_sock, + tmp_sock_len); } if (list->total == 0) { - fprintf(stderr, "no useful sockets were provided by systemd\n"); + fprintf(stderr, + "no useful sockets were provided by systemd\n"); exit(EXIT_FAILURE); } if (config->foreground != 0) - fprintf(stderr, "listening on %d systemd sockets...\n", list->total); + fprintf(stderr, "listening on %d systemd sockets...\n", + list->total); return 0; } @@ -347,9 +365,9 @@ listen_ports(void *pool, struct perm_cfg_st* config, hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE #ifdef AI_ADDRCONFIG - | AI_ADDRCONFIG + | AI_ADDRCONFIG #endif - ; + ; ret = getaddrinfo(config->listen_host, portname, &hints, &res); if (ret != 0) { @@ -364,7 +382,6 @@ listen_ports(void *pool, struct perm_cfg_st* config, if (ret < 0) { return -1; } - } if (list->total == 0) { @@ -379,11 +396,12 @@ listen_ports(void *pool, struct perm_cfg_st* config, hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE #ifdef AI_ADDRCONFIG - | AI_ADDRCONFIG + | AI_ADDRCONFIG #endif - ; + ; - ret = getaddrinfo(config->udp_listen_host, portname, &hints, &res); + ret = getaddrinfo(config->udp_listen_host, portname, &hints, + &res); if (ret != 0) { fprintf(stderr, "getaddrinfo() failed: %s\n", gai_strerror(ret)); @@ -403,32 +421,32 @@ listen_ports(void *pool, struct perm_cfg_st* config, /* Sets the options needed in the UDP socket we forward to * worker */ -static -void set_worker_udp_opts(main_server_st *s, int fd, int family) +static void set_worker_udp_opts(main_server_st *s, int fd, int family) { -int y; + int y; #ifdef IPV6_V6ONLY if (family == AF_INET6) { y = 1; /* avoid listen on ipv6 addresses failing * because already listening on ipv4 addresses: */ - if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, - (const void *) &y, sizeof(y)) < 0) { + if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const void *)&y, + sizeof(y)) < 0) { perror("setsockopt(IPV6_V6ONLY) failed"); } } #endif y = 1; - if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &y, sizeof(y)) < 0) { + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&y, + sizeof(y)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } if (GETCONFIG(s)->try_mtu) { set_mtu_disc(fd, family, 1); } - set_cloexec_flag (fd, 1); + set_cloexec_flag(fd, 1); } /* clears the server listen_list and proc_list. To be used after fork(). @@ -441,14 +459,16 @@ void clear_lists(main_server_st *s) struct proc_st *ctmp = NULL, *cpos; struct script_wait_st *script_tmp = NULL, *script_pos; - list_for_each_safe(&s->listen_list.head, ltmp, lpos, list) { + list_for_each_safe(&s->listen_list.head, ltmp, lpos, list) + { close(ltmp->fd); list_del(<mp->list); talloc_free(ltmp); s->listen_list.total--; } - list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) { + list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) + { if (ctmp->fd >= 0) close(ctmp->fd); if (ctmp->tun_lease.fd >= 0) @@ -461,7 +481,8 @@ void clear_lists(main_server_st *s) s->proc_list.total--; } - list_for_each_safe(&s->script_list.head, script_tmp, script_pos, list) { + list_for_each_safe(&s->script_list.head, script_tmp, script_pos, list) + { list_del(&script_tmp->list); ev_child_stop(main_loop, &script_tmp->ev_child); talloc_free(script_tmp); @@ -475,34 +496,42 @@ void clear_lists(main_server_st *s) /* clear libev state */ if (main_loop) { - ev_io_stop (main_loop, &ctl_watcher); + ev_io_stop(main_loop, &ctl_watcher); for (i = 0; i < s->sec_mod_instance_count; i++) { - ev_io_stop (main_loop, &sec_mod_watchers[i].sec_mod_watcher); - ev_child_stop (main_loop, &sec_mod_watchers[i].child_watcher); + ev_io_stop(main_loop, + &sec_mod_watchers[i].sec_mod_watcher); + ev_child_stop(main_loop, + &sec_mod_watchers[i].child_watcher); } ev_timer_stop(main_loop, &maintenance_watcher); #if defined(CAPTURE_LATENCY_SUPPORT) ev_timer_stop(main_loop, &latency_watcher); #endif /* free memory and descriptors by the event loop */ - ev_loop_destroy (main_loop); + ev_loop_destroy(main_loop); } } -#define SKIP16(pos, total) { \ - uint16_t _s; \ - if (pos+2 > total) goto fallback; \ - _s = (buffer[pos] << 8) | buffer[pos+1]; \ - if ((size_t)(pos+2+_s) > total) goto fallback; \ - pos += 2+_s; \ +#define SKIP16(pos, total) \ + { \ + uint16_t _s; \ + if (pos + 2 > total) \ + goto fallback; \ + _s = (buffer[pos] << 8) | buffer[pos + 1]; \ + if ((size_t)(pos + 2 + _s) > total) \ + goto fallback; \ + pos += 2 + _s; \ } -#define SKIP8(pos, total) { \ - uint8_t _s; \ - if (pos+1 > total) goto fallback; \ - _s = buffer[pos]; \ - if ((size_t)(pos+1+_s) > total) goto fallback; \ - pos += 1+_s; \ +#define SKIP8(pos, total) \ + { \ + uint8_t _s; \ + if (pos + 1 > total) \ + goto fallback; \ + _s = buffer[pos]; \ + if ((size_t)(pos + 1 + _s) > total) \ + goto fallback; \ + pos += 1 + _s; \ } #define TLS_EXT_APP_ID 48018 @@ -532,14 +561,16 @@ void clear_lists(main_server_st *s) * Extension server_hello_extension_list<0..2^16-1>; * } ServerHello; */ -static -unsigned get_session_id(main_server_st* s, uint8_t *buffer, size_t buffer_size, uint8_t **id, int *id_size) +static unsigned int get_session_id(main_server_st *s, uint8_t *buffer, + size_t buffer_size, uint8_t **id, + int *id_size) { size_t pos; /* A client hello packet. We can get the session ID and figure * the associated connection. */ - if (buffer_size < RECORD_PAYLOAD_POS+HANDSHAKE_SESSION_ID_POS+GNUTLS_MAX_SESSION_ID+2) { + if (buffer_size < RECORD_PAYLOAD_POS + HANDSHAKE_SESSION_ID_POS + + GNUTLS_MAX_SESSION_ID + 2) { return 0; } @@ -547,7 +578,7 @@ unsigned get_session_id(main_server_st* s, uint8_t *buffer, size_t buffer_size, goto fallback; /* try to read the extension data */ - pos = RECORD_PAYLOAD_POS+HANDSHAKE_SESSION_ID_POS; + pos = RECORD_PAYLOAD_POS + HANDSHAKE_SESSION_ID_POS; SKIP8(pos, buffer_size); /* Cookie */ @@ -560,33 +591,33 @@ unsigned get_session_id(main_server_st* s, uint8_t *buffer, size_t buffer_size, SKIP8(pos, buffer_size); - if (pos+2 > buffer_size) + if (pos + 2 > buffer_size) goto fallback; - pos+=2; + pos += 2; /* Extension(s) */ while (pos < buffer_size) { uint16_t type; uint16_t len; - if (pos+4 > buffer_size) + if (pos + 4 > buffer_size) goto fallback; - type = (buffer[pos] << 8) | buffer[pos+1]; - pos+=2; + type = (buffer[pos] << 8) | buffer[pos + 1]; + pos += 2; if (type != TLS_EXT_APP_ID) { SKIP16(pos, buffer_size); } else { /* found */ - if (pos+2 > buffer_size) + if (pos + 2 > buffer_size) return 0; /* invalid format */ - len = (buffer[pos] << 8) | buffer[pos+1]; - if ((size_t)(pos+2+len) > buffer_size) + len = (buffer[pos] << 8) | buffer[pos + 1]; + if ((size_t)(pos + 2 + len) > buffer_size) return 0; /* invalid format */ - pos+=2; + pos += 2; len = buffer[pos]; - if ((size_t)(pos+1+len) > buffer_size) + if ((size_t)(pos + 1 + len) > buffer_size) return 0; /* invalid format */ pos++; *id_size = len; @@ -595,32 +626,32 @@ unsigned get_session_id(main_server_st* s, uint8_t *buffer, size_t buffer_size, } } - fallback: +fallback: /* read session_id */ - *id_size = buffer[RECORD_PAYLOAD_POS+HANDSHAKE_SESSION_ID_POS]; - *id = &buffer[RECORD_PAYLOAD_POS+HANDSHAKE_SESSION_ID_POS+1]; + *id_size = buffer[RECORD_PAYLOAD_POS + HANDSHAKE_SESSION_ID_POS]; + *id = &buffer[RECORD_PAYLOAD_POS + HANDSHAKE_SESSION_ID_POS + 1]; return 1; } -static -unsigned has_broken_random(main_server_st* s, uint8_t *buffer, size_t buffer_size) +static unsigned int has_broken_random(main_server_st *s, uint8_t *buffer, + size_t buffer_size) { - size_t pos,i; + size_t pos, i; if (allow_broken_clients) return 0; - if (buffer_size < RECORD_PAYLOAD_POS+HANDSHAKE_RANDOM_POS+32) + if (buffer_size < RECORD_PAYLOAD_POS + HANDSHAKE_RANDOM_POS + 32) return 0; /* check whether the client hello contains a random value of all zeros; * if that's the case it indicates a broken DTLS client. Relates to: * https://gitlab.com/gnutls/gnutls/-/issues/960 */ - pos = RECORD_PAYLOAD_POS+HANDSHAKE_RANDOM_POS; + pos = RECORD_PAYLOAD_POS + HANDSHAKE_RANDOM_POS; - for (i=0;i<32;i++) { - if (buffer[pos+i] != 0) + for (i = 0; i < 32; i++) { + if (buffer[pos + i] != 0) return 0; } @@ -632,28 +663,28 @@ unsigned has_broken_random(main_server_st* s, uint8_t *buffer, size_t buffer_siz */ #define UDP_FD_RESEND_TIME 3 -static int forward_udp_to_owner(main_server_st* s, struct listener_st *listener) +static int forward_udp_to_owner(main_server_st *s, struct listener_st *listener) { -int ret, e; -struct sockaddr_storage cli_addr; -struct sockaddr_storage our_addr; -struct proc_st *proc_to_send = NULL; -socklen_t cli_addr_size, our_addr_size; -char tbuf[64]; -uint8_t *session_id = NULL; -int session_id_size = 0; -ssize_t buffer_size; -int match_ip_only = 0; -time_t now; -int sfd = -1; + int ret, e; + struct sockaddr_storage cli_addr; + struct sockaddr_storage our_addr; + struct proc_st *proc_to_send; + socklen_t cli_addr_size, our_addr_size; + char tbuf[64]; + uint8_t *session_id; + int session_id_size = 0; + ssize_t buffer_size; + int match_ip_only = 0; + time_t now; + int sfd = -1; /* first receive from the correct client and connect socket */ cli_addr_size = sizeof(cli_addr); our_addr_size = sizeof(our_addr); - ret = oc_recvfrom_at(listener->fd, s->msg_buffer, sizeof(s->msg_buffer), 0, - (struct sockaddr*)&cli_addr, &cli_addr_size, - (struct sockaddr*)&our_addr, &our_addr_size, - GETPCONFIG(s)->udp_port); + ret = oc_recvfrom_at(listener->fd, s->msg_buffer, sizeof(s->msg_buffer), + 0, (struct sockaddr *)&cli_addr, &cli_addr_size, + (struct sockaddr *)&our_addr, &our_addr_size, + GETPCONFIG(s)->udp_port); if (ret < 0) { mslog(s, NULL, LOG_INFO, "error receiving in UDP socket"); return -1; @@ -666,29 +697,42 @@ int sfd = -1; if (buffer_size < RECORD_PAYLOAD_POS) { mslog(s, NULL, LOG_INFO, "%s: too short UDP packet", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf))); + human_addr((struct sockaddr *)&cli_addr, cli_addr_size, + tbuf, sizeof(tbuf))); goto fail; } /* check version */ if (s->msg_buffer[0] == 22) { - mslog(s, NULL, LOG_DEBUG, "new DTLS session from %s (record v%u.%u, hello v%u.%u)", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf)), - (unsigned int)s->msg_buffer[1], (unsigned int)s->msg_buffer[2], - (unsigned int)s->msg_buffer[RECORD_PAYLOAD_POS], (unsigned int)s->msg_buffer[RECORD_PAYLOAD_POS+1]); + mslog(s, NULL, LOG_DEBUG, + "new DTLS session from %s (record v%u.%u, hello v%u.%u)", + human_addr((struct sockaddr *)&cli_addr, cli_addr_size, + tbuf, sizeof(tbuf)), + (unsigned int)s->msg_buffer[1], + (unsigned int)s->msg_buffer[2], + (unsigned int)s->msg_buffer[RECORD_PAYLOAD_POS], + (unsigned int)s->msg_buffer[RECORD_PAYLOAD_POS + 1]); } - if (s->msg_buffer[1] != 254 && (s->msg_buffer[1] != 1 && s->msg_buffer[2] != 0) && - s->msg_buffer[RECORD_PAYLOAD_POS] != 254 && (s->msg_buffer[RECORD_PAYLOAD_POS] != 0 && s->msg_buffer[RECORD_PAYLOAD_POS+1] != 0)) { - mslog(s, NULL, LOG_INFO, "%s: unknown DTLS record version: %u.%u", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf)), - (unsigned)s->msg_buffer[1], (unsigned)s->msg_buffer[2]); + if (s->msg_buffer[1] != 254 && + (s->msg_buffer[1] != 1 && s->msg_buffer[2] != 0) && + s->msg_buffer[RECORD_PAYLOAD_POS] != 254 && + (s->msg_buffer[RECORD_PAYLOAD_POS] != 0 && + s->msg_buffer[RECORD_PAYLOAD_POS + 1] != 0)) { + mslog(s, NULL, LOG_INFO, + "%s: unknown DTLS record version: %u.%u", + human_addr((struct sockaddr *)&cli_addr, cli_addr_size, + tbuf, sizeof(tbuf)), + (unsigned int)s->msg_buffer[1], + (unsigned int)s->msg_buffer[2]); goto fail; } if (s->msg_buffer[0] != 22) { - mslog(s, NULL, LOG_DEBUG, "%s: unexpected DTLS content type: %u; possibly a firewall disassociated a UDP session", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf)), + mslog(s, NULL, LOG_DEBUG, + "%s: unexpected DTLS content type: %u; possibly a firewall disassociated a UDP session", + human_addr((struct sockaddr *)&cli_addr, cli_addr_size, + tbuf, sizeof(tbuf)), (unsigned int)s->msg_buffer[0]); /* Here we received a non-client-hello packet. It may be that * the client's NAT changed its UDP source port and the previous @@ -698,20 +742,28 @@ int sfd = -1; match_ip_only = 1; } else { if (has_broken_random(s, s->msg_buffer, buffer_size)) { - mslog(s, NULL, LOG_INFO, "%s: detected broken DTLS client hello (no randomness); ignoring", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf))); + mslog(s, NULL, LOG_INFO, + "%s: detected broken DTLS client hello (no randomness); ignoring", + human_addr((struct sockaddr *)&cli_addr, + cli_addr_size, tbuf, sizeof(tbuf))); goto fail; } - if (!get_session_id(s, s->msg_buffer, buffer_size, &session_id, &session_id_size)) { - mslog(s, NULL, LOG_INFO, "%s: too short handshake packet", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf))); + if (!get_session_id(s, s->msg_buffer, buffer_size, &session_id, + &session_id_size)) { + mslog(s, NULL, LOG_INFO, + "%s: too short handshake packet", + human_addr((struct sockaddr *)&cli_addr, + cli_addr_size, tbuf, sizeof(tbuf))); goto fail; } - if (session_id_size <= 0 || session_id_size > GNUTLS_MAX_SESSION_ID) { - mslog(s, NULL, LOG_INFO, "%s: invalid session ID size (%d)", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf)), + if (session_id_size <= 0 || + session_id_size > GNUTLS_MAX_SESSION_ID) { + mslog(s, NULL, LOG_INFO, + "%s: invalid session ID size (%d)", + human_addr((struct sockaddr *)&cli_addr, + cli_addr_size, tbuf, sizeof(tbuf)), session_id_size); goto fail; } @@ -721,45 +773,58 @@ int sfd = -1; now = time(NULL); if (match_ip_only == 0) { - proc_to_send = proc_search_dtls_id(s, session_id, session_id_size); + proc_to_send = + proc_search_dtls_id(s, session_id, session_id_size); } else { - proc_to_send = proc_search_single_ip(s, &cli_addr, cli_addr_size); + proc_to_send = + proc_search_single_ip(s, &cli_addr, cli_addr_size); } if (proc_to_send != 0) { UdpFdMsg msg = UDP_FD_MSG__INIT; - if (now - proc_to_send->udp_fd_receive_time <= UDP_FD_RESEND_TIME) { - mslog(s, proc_to_send, LOG_DEBUG, "received UDP connection too soon from %s", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf))); + if (now - proc_to_send->udp_fd_receive_time <= + UDP_FD_RESEND_TIME) { + mslog(s, proc_to_send, LOG_DEBUG, + "received UDP connection too soon from %s", + human_addr((struct sockaddr *)&cli_addr, + cli_addr_size, tbuf, sizeof(tbuf))); goto fail; } - sfd = socket_netns(&s->netns, listener->family, SOCK_DGRAM, listener->protocol); + sfd = socket_netns(&s->netns, listener->family, SOCK_DGRAM, + listener->protocol); if (sfd < 0) { e = errno; - mslog(s, proc_to_send, LOG_ERR, "new UDP socket failed: %s", - strerror(e)); + mslog(s, proc_to_send, LOG_ERR, + "new UDP socket failed: %s", strerror(e)); goto fail; } set_worker_udp_opts(s, sfd, listener->family); if (our_addr_size > 0) { - ret = bind(sfd, (struct sockaddr *)&our_addr, our_addr_size); + ret = bind(sfd, (struct sockaddr *)&our_addr, + our_addr_size); if (ret == -1) { e = errno; - mslog(s, proc_to_send, LOG_INFO, "bind UDP to %s: %s", - human_addr((struct sockaddr*)&listener->addr, listener->addr_len, tbuf, sizeof(tbuf)), + mslog(s, proc_to_send, LOG_INFO, + "bind UDP to %s: %s", + human_addr( + (struct sockaddr *)&listener->addr, + listener->addr_len, tbuf, + sizeof(tbuf)), strerror(e)); } } - ret = connect(sfd, (void*)&cli_addr, cli_addr_size); + ret = connect(sfd, (void *)&cli_addr, cli_addr_size); if (ret == -1) { e = errno; - mslog(s, proc_to_send, LOG_ERR, "connect UDP socket from %s: %s", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf)), + mslog(s, proc_to_send, LOG_ERR, + "connect UDP socket from %s: %s", + human_addr((struct sockaddr *)&cli_addr, + cli_addr_size, tbuf, sizeof(tbuf)), strerror(e)); goto fail; } @@ -768,24 +833,27 @@ int sfd = -1; msg.hello = 0; /* by default this is one */ } else { /* a new DTLS session, store the DTLS IPs into proc and add it into hash table */ - proc_table_update_dtls_ip(s, proc_to_send, &cli_addr, cli_addr_size); + proc_table_update_dtls_ip(s, proc_to_send, &cli_addr, + cli_addr_size); } msg.data.data = s->msg_buffer; msg.data.len = buffer_size; - ret = send_socket_msg_to_worker(s, proc_to_send, CMD_UDP_FD, - sfd, - &msg, + ret = send_socket_msg_to_worker( + s, proc_to_send, CMD_UDP_FD, sfd, &msg, (pack_size_func)udp_fd_msg__get_packed_size, (pack_func)udp_fd_msg__pack); if (ret < 0) { - mslog(s, proc_to_send, LOG_ERR, "error passing UDP socket from %s", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf))); + mslog(s, proc_to_send, LOG_ERR, + "error passing UDP socket from %s", + human_addr((struct sockaddr *)&cli_addr, + cli_addr_size, tbuf, sizeof(tbuf))); goto fail; } mslog(s, proc_to_send, LOG_DEBUG, "passed UDP socket from %s", - human_addr((struct sockaddr*)&cli_addr, cli_addr_size, tbuf, sizeof(tbuf))); + human_addr((struct sockaddr *)&cli_addr, cli_addr_size, + tbuf, sizeof(tbuf))); proc_to_send->udp_fd_receive_time = now; } @@ -794,7 +862,6 @@ fail: close(sfd); return 0; - } #ifdef HAVE_LIBWRAP @@ -812,40 +879,47 @@ static int check_tcp_wrapper(int fd) return 0; } #else -# define check_tcp_wrapper(x) 0 +#define check_tcp_wrapper(x) 0 #endif -static void sec_mod_child_watcher_cb(struct ev_loop *loop, ev_child *w, int revents) +static void sec_mod_child_watcher_cb(struct ev_loop *loop, ev_child *w, + int revents) { main_server_st *s = ev_userdata(loop); if (WIFSIGNALED(w->rstatus)) { if (WTERMSIG(w->rstatus) == SIGSEGV) - mslog(s, NULL, LOG_ERR, "Sec-mod %u died with sigsegv\n", (unsigned)w->pid); + mslog(s, NULL, LOG_ERR, + "Sec-mod %u died with sigsegv\n", + (unsigned int)w->pid); else if (WTERMSIG(w->rstatus) == SIGSYS) - mslog(s, NULL, LOG_ERR, "Sec-mod %u died with sigsys\n", (unsigned)w->pid); + mslog(s, NULL, LOG_ERR, "Sec-mod %u died with sigsys\n", + (unsigned int)w->pid); else - mslog(s, NULL, LOG_ERR, "Sec-mod %u died with signal %d\n", (unsigned)w->pid, (int)WTERMSIG(w->rstatus)); + mslog(s, NULL, LOG_ERR, + "Sec-mod %u died with signal %d\n", + (unsigned int)w->pid, (int)WTERMSIG(w->rstatus)); } ev_child_stop(loop, w); mslog(s, NULL, LOG_ERR, "ocserv-secmod died unexpectedly"); - ev_feed_signal_event (loop, SIGTERM); + ev_feed_signal_event(loop, SIGTERM); } void script_child_watcher_cb(struct ev_loop *loop, ev_child *w, int revents) { main_server_st *s = ev_userdata(loop); int ret; - struct script_wait_st *stmp = (struct script_wait_st*)w; - unsigned estatus; + struct script_wait_st *stmp = (struct script_wait_st *)w; + unsigned int estatus; estatus = WEXITSTATUS(w->rstatus); if (WIFSIGNALED(w->rstatus)) estatus = 1; /* check if someone was waiting for that pid */ - mslog(s, stmp->proc, LOG_DEBUG, "connect-script exit status: %u", estatus); + mslog(s, stmp->proc, LOG_DEBUG, "connect-script exit status: %u", + estatus); list_del(&stmp->list); ev_child_stop(loop, &stmp->ev_child); @@ -858,39 +932,45 @@ void script_child_watcher_cb(struct ev_loop *loop, ev_child *w, int revents) } } -static void worker_child_watcher_cb(struct ev_loop *loop, ev_child *w, int revents) +static void worker_child_watcher_cb(struct ev_loop *loop, ev_child *w, + int revents) { main_server_st *s = ev_userdata(loop); if (WIFSIGNALED(w->rstatus)) { if (WTERMSIG(w->rstatus) == SIGSEGV) - mslog(s, NULL, LOG_ERR, "Child %u died with sigsegv\n", (unsigned)w->pid); + mslog(s, NULL, LOG_ERR, "Child %u died with sigsegv\n", + (unsigned int)w->pid); else if (WTERMSIG(w->rstatus) == SIGSYS) - mslog(s, NULL, LOG_ERR, "Child %u died with sigsys\n", (unsigned)w->pid); + mslog(s, NULL, LOG_ERR, "Child %u died with sigsys\n", + (unsigned int)w->pid); else - mslog(s, NULL, LOG_ERR, "Child %u died with signal %d\n", (unsigned)w->pid, (int)WTERMSIG(w->rstatus)); + mslog(s, NULL, LOG_ERR, + "Child %u died with signal %d\n", + (unsigned int)w->pid, (int)WTERMSIG(w->rstatus)); } ev_child_stop(loop, w); } /* Returns the number of processes to wait */ -static unsigned kill_children(main_server_st* s) +static unsigned int kill_children(main_server_st *s) { struct proc_st *ctmp = NULL, *cpos; int i; - unsigned nproc = 0; + unsigned int nproc = 0; /* Kill the worker processes first */ - list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) { + list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) + { if (ctmp->pid != -1) { - remove_proc(s, ctmp, RPROC_KILL|RPROC_QUIT); + remove_proc(s, ctmp, RPROC_KILL | RPROC_QUIT); nproc++; } } /* kill the security module server */ - for (i = 0; i < s->sec_mod_instance_count; i ++) { + for (i = 0; i < s->sec_mod_instance_count; i++) { kill(s->sec_mod_instances[i].sec_mod_pid, SIGTERM); nproc++; } @@ -898,47 +978,52 @@ static unsigned kill_children(main_server_st* s) return nproc; } -static void kill_children_auth_timeout(main_server_st* s) +static void kill_children_auth_timeout(main_server_st *s) { struct proc_st *ctmp = NULL, *cpos; - time_t oldest_permitted_session = time(NULL) - GETCONFIG(s)->auth_timeout; + time_t oldest_permitted_session = + time(NULL) - GETCONFIG(s)->auth_timeout; /* kill the security module server */ - list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) { + list_for_each_safe(&s->proc_list.head, ctmp, cpos, list) + { /* If the worker has not completed it's auth within auth_timeout seconds, kill it */ if ((ctmp->status < PS_AUTH_COMPLETED) && (ctmp->conn_time < oldest_permitted_session) && - (ctmp->pid != -1)) { + (ctmp->pid != -1)) { remove_proc(s, ctmp, RPROC_KILL); } } } -static void terminate_server(main_server_st * s) +static void terminate_server(main_server_st *s) { - unsigned remain; + unsigned int remain; int ret; struct timespec start; struct timespec now; - mslog(s, NULL, LOG_INFO, "termination request received; waiting for sessions to terminate"); + mslog(s, NULL, LOG_INFO, + "termination request received; waiting for sessions to terminate"); remain = kill_children(s); gettime(&start); - while ((ret=waitpid(-1, NULL, WNOHANG)) >= 0 && remain > 0) { + while ((ret = waitpid(-1, NULL, WNOHANG)) >= 0 && remain > 0) { if (ret > 0 && remain > 0) remain--; gettime(&now); if (timespec_sub_ms(&now, &start) > 5000) { - mslog(s, NULL, LOG_INFO, "not all sessions were terminated (%u remain); forcing termination", remain); + mslog(s, NULL, LOG_INFO, + "not all sessions were terminated (%u remain); forcing termination", + remain); kill(0, SIGKILL); break; } ms_sleep(1); } - ev_break (main_loop, EVBREAK_ALL); + ev_break(main_loop, EVBREAK_ALL); } static void graceful_shutdown_watcher_cb(EV_P_ ev_timer *w, int revents) @@ -956,17 +1041,21 @@ static void term_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revents) if (server_drain_ms == 0) { terminate_server(s); - } - else - { + } else { if (!ev_is_active(&graceful_shutdown_watcher)) { - mslog(s, NULL, LOG_INFO, "termination request received; stopping new connections"); - graceful_shutdown_watcher.repeat = ((ev_tstamp)(server_drain_ms)) / 1000.; - mslog(s, NULL, LOG_INFO, "termination request received; waiting %d ms", server_drain_ms); + mslog(s, NULL, LOG_INFO, + "termination request received; stopping new connections"); + graceful_shutdown_watcher.repeat = + ((ev_tstamp)(server_drain_ms)) / 1000.; + mslog(s, NULL, LOG_INFO, + "termination request received; waiting %d ms", + server_drain_ms); ev_timer_again(loop, &graceful_shutdown_watcher); // Close the listening ports and stop the IO - list_for_each_safe(&s->listen_list.head, ltmp, lpos, list) { + list_for_each_safe(&s->listen_list.head, ltmp, lpos, + list) + { ev_io_stop(loop, <mp->io); close(ltmp->fd); list_del(<mp->list); @@ -977,14 +1066,15 @@ static void term_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revents) } } -static void reload_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revents) +static void reload_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, + int revents) { main_server_st *s = ev_userdata(loop); int ret; int i; mslog(s, NULL, LOG_INFO, "reloading configuration"); - for (i = 0; i < s->sec_mod_instance_count; i ++) { + for (i = 0; i < s->sec_mod_instance_count; i++) { kill(s->sec_mod_instances[i].sec_mod_pid, SIGHUP); /* Reload on main needs to happen later than sec-mod. @@ -993,41 +1083,45 @@ static void reload_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revent ret = secmod_reload(&s->sec_mod_instances[i]); if (ret < 0) { mslog(s, NULL, LOG_ERR, "could not reload sec-mod!\n"); - ev_feed_signal_event (loop, SIGTERM); + ev_feed_signal_event(loop, SIGTERM); } } reload_cfg_file(s->config_pool, s->vconfig, 0); } -static void cmd_watcher_cb (EV_P_ ev_io *w, int revents) +static void cmd_watcher_cb(EV_P_ ev_io *w, int revents) { main_server_st *s = ev_userdata(loop); - struct proc_st *ctmp = (struct proc_st*)w; + struct proc_st *ctmp = (struct proc_st *)w; int ret; /* Check for any pending commands */ ret = handle_worker_commands(s, ctmp); if (ret < 0) { - remove_proc(s, ctmp, (ret!=ERR_WORKER_TERMINATED)?RPROC_KILL:0); + remove_proc(s, ctmp, + (ret != ERR_WORKER_TERMINATED) ? RPROC_KILL : 0); } } -static void resume_accept_cb (EV_P_ ev_timer *w, int revents) +static void resume_accept_cb(EV_P_ ev_timer *w, int revents) { main_server_st *s = ev_userdata(loop); - struct listener_st *ltmp = (struct listener_st *)((char*)w - offsetof(struct listener_st, resume_accept)); + struct listener_st *ltmp = + (struct listener_st *)((char *)w - offsetof(struct listener_st, + resume_accept)); // Add hysteresis to the pause/resume cycle to damp oscillations unsigned int resume_threshold = GETCONFIG(s)->max_clients * 9 / 10; // Only resume accepting connections if we are under the limit - if (resume_threshold == 0 || s->stats.active_clients < resume_threshold) { + if (resume_threshold == 0 || + s->stats.active_clients < resume_threshold) { // Clear the timer and resume accept ev_timer_stop(loop, <mp->resume_accept); ev_io_start(loop, <mp->io); } } -static void listen_watcher_cb (EV_P_ ev_io *w, int revents) +static void listen_watcher_cb(EV_P_ ev_io *w, int revents) { main_server_st *s = ev_userdata(loop); struct listener_st *ltmp = (struct listener_st *)w; @@ -1040,42 +1134,51 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) hmac_component_st hmac_components[3]; char worker_path[_POSIX_PATH_MAX]; - if (ltmp->sock_type == SOCK_TYPE_TCP || ltmp->sock_type == SOCK_TYPE_UNIX) { + if (ltmp->sock_type == SOCK_TYPE_TCP || + ltmp->sock_type == SOCK_TYPE_UNIX) { /* connection on TCP port */ int stype = ltmp->sock_type; ws->remote_addr_len = sizeof(ws->remote_addr); - fd = accept(ltmp->fd, (void*)&ws->remote_addr, &ws->remote_addr_len); + fd = accept(ltmp->fd, (void *)&ws->remote_addr, + &ws->remote_addr_len); if (fd < 0) { - mslog(s, NULL, LOG_ERR, - "error in accept(): %s", strerror(errno)); + mslog(s, NULL, LOG_ERR, "error in accept(): %s", + strerror(errno)); return; } - set_cloexec_flag (fd, 1); + set_cloexec_flag(fd, 1); #ifndef __linux__ /* OpenBSD sets the non-blocking flag if accept's fd is non-blocking */ set_block(fd); #endif - if (GETCONFIG(s)->max_clients > 0 && s->stats.active_clients >= GETCONFIG(s)->max_clients) { + if (GETCONFIG(s)->max_clients > 0 && + s->stats.active_clients >= GETCONFIG(s)->max_clients) { close(fd); - mslog(s, NULL, LOG_INFO, "reached maximum client limit (active: %u)", s->stats.active_clients); + mslog(s, NULL, LOG_INFO, + "reached maximum client limit (active: %u)", + s->stats.active_clients); return; } if (check_tcp_wrapper(fd) < 0) { close(fd); - mslog(s, NULL, LOG_INFO, "TCP wrappers rejected the connection (see /etc/hosts->[allow|deny])"); + mslog(s, NULL, LOG_INFO, + "TCP wrappers rejected the connection (see /etc/hosts->[allow|deny])"); return; } - if (ws->conn_type != SOCK_TYPE_UNIX && !GETCONFIG(s)->listen_proxy_proto) { + if (ws->conn_type != SOCK_TYPE_UNIX && + !GETCONFIG(s)->listen_proxy_proto) { memset(&ws->our_addr, 0, sizeof(ws->our_addr)); ws->our_addr_len = sizeof(ws->our_addr); - if (getsockname(fd, (struct sockaddr*)&ws->our_addr, &ws->our_addr_len) < 0) + if (getsockname(fd, (struct sockaddr *)&ws->our_addr, + &ws->our_addr_len) < 0) ws->our_addr_len = 0; - if (check_if_banned(s, &ws->remote_addr, ws->remote_addr_len) != 0) { + if (check_if_banned(s, &ws->remote_addr, + ws->remote_addr_len) != 0) { close(fd); return; } @@ -1084,13 +1187,14 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) /* Create a command socket */ ret = socketpair(AF_UNIX, SOCK_STREAM, 0, cmd_fd); if (ret < 0) { - mslog(s, NULL, LOG_ERR, "error creating command socket"); + mslog(s, NULL, LOG_ERR, + "error creating command socket"); close(fd); return; } pid = fork(); - if (pid == 0) { /* child */ + if (pid == 0) { /* child */ unsigned int sec_mod_instance_index; /* close any open descriptors, and erase * sensitive data before running the worker @@ -1098,13 +1202,14 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) sigprocmask(SIG_SETMASK, &sig_default_set, NULL); close(cmd_fd[0]); clear_lists(s); - if (s->top_fd != -1) close(s->top_fd); - for (i = 0; i < s->sec_mod_instance_count; i ++) { + if (s->top_fd != -1) + close(s->top_fd); + for (i = 0; i < s->sec_mod_instance_count; i++) { close(s->sec_mod_instances[i].sec_mod_fd); close(s->sec_mod_instances[i].sec_mod_fd_sync); } - setproctitle(PACKAGE"-worker"); + setproctitle(PACKAGE "-worker"); kill_on_parent_kill(SIGTERM); set_self_oom_score_adj(s); @@ -1112,14 +1217,21 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) /* Each cookie is valid for its IP address and when resuming it must * reach the same sec-mod process that contains the corresponding * session information under the SID. */ - sec_mod_instance_index = hash_any( - SA_IN_P_GENERIC(&ws->remote_addr, ws->remote_addr_len), - SA_IN_SIZE(ws->remote_addr_len), 0) % s->sec_mod_instance_count; + sec_mod_instance_index = + hash_any(SA_IN_P_GENERIC(&ws->remote_addr, + ws->remote_addr_len), + SA_IN_SIZE(ws->remote_addr_len), 0) % + s->sec_mod_instance_count; /* write sec-mod's address */ - memcpy(&ws->secmod_addr, &s->sec_mod_instances[sec_mod_instance_index].secmod_addr, s->sec_mod_instances[sec_mod_instance_index].secmod_addr_len); - ws->secmod_addr_len = s->sec_mod_instances[sec_mod_instance_index].secmod_addr_len; - + memcpy(&ws->secmod_addr, + &s->sec_mod_instances[sec_mod_instance_index] + .secmod_addr, + s->sec_mod_instances[sec_mod_instance_index] + .secmod_addr_len); + ws->secmod_addr_len = + s->sec_mod_instances[sec_mod_instance_index] + .secmod_addr_len; ws->main_pool = s->main_pool; @@ -1132,20 +1244,29 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) ws->conn_type = stype; ws->session_start_time = time(NULL); - human_addr2((const struct sockaddr *)&ws->remote_addr, ws->remote_addr_len, ws->remote_ip_str, sizeof(ws->remote_ip_str), 0); - human_addr2((const struct sockaddr *)&ws->our_addr, ws->our_addr_len, ws->our_ip_str, sizeof(ws->our_ip_str), 0); + human_addr2((const struct sockaddr *)&ws->remote_addr, + ws->remote_addr_len, ws->remote_ip_str, + sizeof(ws->remote_ip_str), 0); + human_addr2((const struct sockaddr *)&ws->our_addr, + ws->our_addr_len, ws->our_ip_str, + sizeof(ws->our_ip_str), 0); hmac_components[0].data = ws->remote_ip_str; hmac_components[0].length = strlen(ws->remote_ip_str); hmac_components[1].data = ws->our_ip_str; hmac_components[1].length = strlen(ws->our_ip_str); hmac_components[2].data = &ws->session_start_time; - hmac_components[2].length = sizeof(ws->session_start_time); + hmac_components[2].length = + sizeof(ws->session_start_time); - generate_hmac(sizeof(s->hmac_key), s->hmac_key, ARRAY_SIZE(hmac_components), hmac_components, (uint8_t*) ws->sec_auth_init_hmac); + generate_hmac(sizeof(s->hmac_key), s->hmac_key, + ARRAY_SIZE(hmac_components), + hmac_components, + (uint8_t *)ws->sec_auth_init_hmac); // Clear the HMAC key - safe_memset((uint8_t*)s->hmac_key, 0, sizeof(s->hmac_key)); + safe_memset((uint8_t *)s->hmac_key, 0, + sizeof(s->hmac_key)); if (!set_env_from_ws(s)) exit(EXIT_FAILURE); @@ -1154,20 +1275,32 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) { char path[_POSIX_PATH_MAX]; size_t path_length; - path_length = readlink("/proc/self/exe", path, sizeof(path)-1); + + path_length = readlink("/proc/self/exe", path, + sizeof(path) - 1); if (path_length == -1) { - mslog(s, NULL, LOG_ERR, "readlink failed %s", strerror(ret)); + mslog(s, NULL, LOG_ERR, + "readlink failed %s", + strerror(ret)); exit(EXIT_FAILURE); } path[path_length] = '\0'; - if (snprintf(worker_path, sizeof(worker_path), "%s-worker", path) >= sizeof(worker_path)) { - mslog(s, NULL, LOG_ERR, "snprint of path %s and ocserv-worker failed", path); + if (snprintf(worker_path, sizeof(worker_path), + "%s-worker", + path) >= sizeof(worker_path)) { + mslog(s, NULL, LOG_ERR, + "snprint of path %s and ocserv-worker failed", + path); exit(EXIT_FAILURE); } } #else - if (snprintf(worker_path, sizeof(worker_path), "%s-worker", worker_argv[0]) >= sizeof(worker_path)) { - mslog(s, NULL, LOG_ERR, "snprint of path %s and ocserv-worker failed", worker_argv[0]); + if (snprintf(worker_path, sizeof(worker_path), + "%s-worker", + worker_argv[0]) >= sizeof(worker_path)) { + mslog(s, NULL, LOG_ERR, + "snprint of path %s and ocserv-worker failed", + worker_argv[0]); exit(EXIT_FAILURE); } #endif @@ -1175,7 +1308,8 @@ static void listen_watcher_cb (EV_P_ ev_io *w, int revents) worker_argv[0] = worker_path; execv(worker_path, worker_argv); ret = errno; - mslog(s, NULL, LOG_ERR, "exec %s failed %s", worker_path, strerror(ret)); + mslog(s, NULL, LOG_ERR, "exec %s failed %s", + worker_path, strerror(ret)); exit(EXIT_FAILURE); } else if (pid == -1) { fork_failed: @@ -1183,19 +1317,21 @@ fork_failed: close(cmd_fd[0]); } else { /* parent */ /* add_proc */ - ctmp = new_proc(s, pid, cmd_fd[0], - &ws->remote_addr, ws->remote_addr_len, - &ws->our_addr, ws->our_addr_len, - ws->sid, sizeof(ws->sid)); + ctmp = new_proc(s, pid, cmd_fd[0], &ws->remote_addr, + ws->remote_addr_len, &ws->our_addr, + ws->our_addr_len, ws->sid, + sizeof(ws->sid)); if (ctmp == NULL) { kill(pid, SIGTERM); goto fork_failed; } - ev_io_init(&ctmp->io, cmd_watcher_cb, cmd_fd[0], EV_READ); + ev_io_init(&ctmp->io, cmd_watcher_cb, cmd_fd[0], + EV_READ); ev_io_start(loop, &ctmp->io); - ev_child_init(&ctmp->ev_child, worker_child_watcher_cb, pid, 0); + ev_child_init(&ctmp->ev_child, worker_child_watcher_cb, + pid, 0); ev_child_start(loop, &ctmp->ev_child); } close(cmd_fd[1]); @@ -1205,7 +1341,8 @@ fork_failed: forward_udp_to_owner(s, ltmp); } - if (GETCONFIG(s)->max_clients > 0 && s->stats.active_clients >= GETCONFIG(s)->max_clients) { + if (GETCONFIG(s)->max_clients > 0 && + s->stats.active_clients >= GETCONFIG(s)->max_clients) { ltmp->resume_accept.repeat = ((ev_tstamp)(1)); ev_io_stop(loop, <mp->io); ev_timer_again(loop, <mp->resume_accept); @@ -1219,34 +1356,42 @@ fork_failed: if (GETCONFIG(s)->rate_limit_ms > 0) { int rqueue = 0; int wqueue = 0; - int retval = sockdiag_query_unix_domain_socket_queue_length(s->sec_mod_instances[0].secmod_addr.sun_path, &rqueue, &wqueue); - mslog(s, NULL, LOG_DEBUG, "queue_length retval:%d rqueue:%d wqueue:%d", retval, rqueue, wqueue); + int retval = sockdiag_query_unix_domain_socket_queue_length( + s->sec_mod_instances[0].secmod_addr.sun_path, &rqueue, + &wqueue); + + mslog(s, NULL, LOG_DEBUG, + "queue_length retval:%d rqueue:%d wqueue:%d", retval, + rqueue, wqueue); if (retval || rqueue > wqueue / 2) { - mslog(s, NULL, LOG_INFO, "delaying accepts for %d ms", GETCONFIG(s)->rate_limit_ms); + mslog(s, NULL, LOG_INFO, "delaying accepts for %d ms", + GETCONFIG(s)->rate_limit_ms); // Arm the timer and pause accept - ltmp->resume_accept.repeat = ((ev_tstamp)(GETCONFIG(s)->rate_limit_ms)) / 1000.; + ltmp->resume_accept.repeat = + ((ev_tstamp)(GETCONFIG(s)->rate_limit_ms)) / + 1000.; ev_io_stop(loop, <mp->io); ev_timer_again(loop, <mp->resume_accept); } } } -static void sec_mod_watcher_cb (EV_P_ ev_io *w, int revents) +static void sec_mod_watcher_cb(EV_P_ ev_io *w, int revents) { sec_mod_watcher_st *sec_mod = (sec_mod_watcher_st *)w; main_server_st *s = ev_userdata(loop); int ret; - ret = handle_sec_mod_commands(&s->sec_mod_instances[sec_mod->sec_mod_instance_index]); + ret = handle_sec_mod_commands( + &s->sec_mod_instances[sec_mod->sec_mod_instance_index]); if (ret < 0) { /* bad commands from sec-mod are unacceptable */ - mslog(s, NULL, LOG_ERR, - "error in command from sec-mod"); + mslog(s, NULL, LOG_ERR, "error in command from sec-mod"); ev_io_stop(loop, w); - ev_feed_signal_event (loop, SIGTERM); + ev_feed_signal_event(loop, SIGTERM); } } -static void ctl_watcher_cb (EV_P_ ev_io *w, int revents) +static void ctl_watcher_cb(EV_P_ ev_io *w, int revents) { main_server_st *s = ev_userdata(loop); @@ -1264,7 +1409,8 @@ static void perform_maintenance(main_server_st *s) kill_children_auth_timeout(s); - list_for_each_rev(s->vconfig, vhost, list) { + list_for_each_rev(s->vconfig, vhost, list) + { tls_reload_crl(s, vhost, 0); } } @@ -1280,22 +1426,21 @@ static void maintenance_watcher_cb(EV_P_ ev_timer *w, int revents) static void latency_watcher_cb(EV_P_ ev_timer *w, int revents) { main_server_st *s = ev_userdata(loop); + s->stats.current_latency_stats = s->stats.delta_latency_stats; s->stats.delta_latency_stats.median_total = 0; s->stats.delta_latency_stats.rms_total = 0; s->stats.delta_latency_stats.sample_count = 0; - mslog( - s, - NULL, - LOG_DEBUG, - "Latency: Median Total %ld RMS Total %ld Sample Count %ld", - s->stats.current_latency_stats.median_total, - s->stats.current_latency_stats.rms_total, - s->stats.current_latency_stats.sample_count); + mslog(s, NULL, LOG_DEBUG, + "Latency: Median Total %ld RMS Total %ld Sample Count %ld", + s->stats.current_latency_stats.median_total, + s->stats.current_latency_stats.rms_total, + s->stats.current_latency_stats.sample_count); } #endif -static void maintenance_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revents) +static void maintenance_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, + int revents) { main_server_st *s = ev_userdata(loop); @@ -1303,8 +1448,7 @@ static void maintenance_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int r perform_maintenance(s); } - -static void syserr_cb (const char *msg) +static void syserr_cb(const char *msg) { main_server_st *s = ev_userdata(main_loop); @@ -1314,7 +1458,7 @@ static void syserr_cb (const char *msg) extern char secmod_socket_file_name_socket_file[_POSIX_PATH_MAX]; -int main(int argc, char** argv) +int main(int argc, char **argv) { int e; struct listener_st *ltmp = NULL; @@ -1373,19 +1517,19 @@ int main(int argc, char** argv) s->netns.default_fd = -1; s->netns.listen_fd = -1; - if (!hmac_init_key(sizeof(s->hmac_key), (uint8_t*)(s->hmac_key))) { + if (!hmac_init_key(sizeof(s->hmac_key), (uint8_t *)(s->hmac_key))) { fprintf(stderr, "unable to generate hmac key\n"); exit(EXIT_FAILURE); } // getopt processing mutates argv. Save a copy to pass to the child. worker_argc = argc; - worker_argv = talloc_zero_array(main_pool, char*, worker_argc + 1); + worker_argv = talloc_zero_array(main_pool, char *, worker_argc + 1); if (!worker_argv) { fprintf(stderr, "memory error\n"); exit(EXIT_FAILURE); } - for (i = 0; i < argc; i ++) { + for (i = 0; i < argc; i++) { worker_argv[i] = talloc_strdup(main_pool, argv[i]); if (!worker_argv[i]) { fprintf(stderr, "memory error\n"); @@ -1404,8 +1548,7 @@ int main(int argc, char** argv) ip_lease_init(&s->ip_leases); proc_table_init(s); main_ban_db_init(s); - if (if_address_init(s) == 0) - { + if (if_address_init(s) == 0) { fprintf(stderr, "failed to initialize local addresses\n"); exit(EXIT_FAILURE); } @@ -1431,14 +1574,16 @@ int main(int argc, char** argv) exit(EXIT_FAILURE); } - setproctitle(PACKAGE"-main"); + setproctitle(PACKAGE "-main"); if (getuid() != 0) { - fprintf(stderr, "This server requires root access to operate.\n"); + fprintf(stderr, + "This server requires root access to operate.\n"); exit(EXIT_FAILURE); } - if (GETPCONFIG(s)->listen_netns_name && open_namespaces(&s->netns, GETPCONFIG(s)) < 0) { + if (GETPCONFIG(s)->listen_netns_name && + open_namespaces(&s->netns, GETPCONFIG(s)) < 0) { fprintf(stderr, "cannot init listen namespaces\n"); exit(EXIT_FAILURE); } @@ -1450,7 +1595,7 @@ int main(int argc, char** argv) } if (GETPCONFIG(s)->syslog) { - flags = LOG_PID|LOG_NDELAY; + flags = LOG_PID | LOG_NDELAY; #ifdef LOG_PERROR if (GETPCONFIG(s)->log_stderr && GETPCONFIG(s)->syslog) flags |= LOG_PERROR; @@ -1460,8 +1605,8 @@ int main(int argc, char** argv) } #ifdef HAVE_LIBWRAP - allow_severity = LOG_DAEMON|LOG_INFO; - deny_severity = LOG_DAEMON|LOG_WARNING; + allow_severity = LOG_DAEMON | LOG_INFO; + deny_severity = LOG_DAEMON | LOG_WARNING; #endif if (GETPCONFIG(s)->foreground == 0) { @@ -1484,23 +1629,30 @@ int main(int argc, char** argv) // Start the configured number of ocserv-sm processes s->sec_mod_instance_count = GETPCONFIG(s)->sec_mod_scale; - if (s->sec_mod_instance_count == 0) { + if (s->sec_mod_instance_count == 0) { if (GETCONFIG(s)->max_clients != 0) { // Compute ideal number of clients per sec-mod - unsigned int sec_mod_count_for_users = GETCONFIG(s)->max_clients / MINIMUM_USERS_PER_SEC_MOD + 1; + unsigned int sec_mod_count_for_users = + GETCONFIG(s)->max_clients / + MINIMUM_USERS_PER_SEC_MOD + + 1; // Limit it to number of processors. - s->sec_mod_instance_count = MIN(processor_count,sec_mod_count_for_users); + s->sec_mod_instance_count = + MIN(processor_count, sec_mod_count_for_users); } else { // If it's unlimited, the use processor count. s->sec_mod_instance_count = processor_count; } } - s->sec_mod_instances = talloc_zero_array(s, sec_mod_instance_st, s->sec_mod_instance_count); - sec_mod_watchers = talloc_zero_array(s, sec_mod_watcher_st, s->sec_mod_instance_count); + s->sec_mod_instances = talloc_zero_array(s, sec_mod_instance_st, + s->sec_mod_instance_count); + sec_mod_watchers = talloc_zero_array(s, sec_mod_watcher_st, + s->sec_mod_instance_count); - mslog(s, NULL, LOG_INFO, "Starting %d instances of ocserv-sm", s->sec_mod_instance_count); - for (i = 0; i < s->sec_mod_instance_count; i ++) { + mslog(s, NULL, LOG_INFO, "Starting %d instances of ocserv-sm", + s->sec_mod_instance_count); + for (i = 0; i < s->sec_mod_instance_count; i++) { s->sec_mod_instances[i].server = s; run_sec_mod(&s->sec_mod_instances[i], i); } @@ -1524,19 +1676,24 @@ int main(int argc, char** argv) if (GETPCONFIG(s)->chroot_dir) { if (chdir(GETPCONFIG(s)->chroot_dir) != 0) { e = errno; - mslog(s, NULL, LOG_ERR, "cannot chdir to %s: %s", GETPCONFIG(s)->chroot_dir, strerror(e)); + mslog(s, NULL, LOG_ERR, "cannot chdir to %s: %s", + GETPCONFIG(s)->chroot_dir, strerror(e)); exit(EXIT_FAILURE); } } ms_sleep(100); /* give some time for sec-mod to initialize */ - for (i = 0; i < s->sec_mod_instance_count; i ++) { + for (i = 0; i < s->sec_mod_instance_count; i++) { s->sec_mod_instances[i].secmod_addr.sun_family = AF_UNIX; p = s->sec_mod_instances[i].socket_file; - if (GETPCONFIG(s)->chroot_dir) /* if we are on chroot make the socket file path relative */ - while (*p == '/') p++; - strlcpy(s->sec_mod_instances[i].secmod_addr.sun_path, p, sizeof(s->sec_mod_instances[i].secmod_addr.sun_path)); - s->sec_mod_instances[i].secmod_addr_len = SUN_LEN(&s->sec_mod_instances[i].secmod_addr); + if (GETPCONFIG(s) + ->chroot_dir) /* if we are on chroot make the socket file path relative */ + while (*p == '/') + p++; + strlcpy(s->sec_mod_instances[i].secmod_addr.sun_path, p, + sizeof(s->sec_mod_instances[i].secmod_addr.sun_path)); + s->sec_mod_instances[i].secmod_addr_len = + SUN_LEN(&s->sec_mod_instances[i].secmod_addr); } /* initialize memory for worker process */ @@ -1566,72 +1723,80 @@ int main(int argc, char** argv) /* increase the number of our allowed file descriptors */ set_main_fd_limits(s); - ev_set_userdata (main_loop, s); + ev_set_userdata(main_loop, s); ev_set_syserr_cb(syserr_cb); ev_init(&ctl_watcher, ctl_watcher_cb); - for (i = 0; i < s->sec_mod_instance_count; i ++) { - ev_init(&sec_mod_watchers[i].sec_mod_watcher, sec_mod_watcher_cb); + for (i = 0; i < s->sec_mod_instance_count; i++) { + ev_init(&sec_mod_watchers[i].sec_mod_watcher, + sec_mod_watcher_cb); sec_mod_watchers[i].sec_mod_instance_index = i; } - ev_init (&int_sig_watcher, term_sig_watcher_cb); - ev_signal_set (&int_sig_watcher, SIGINT); - ev_signal_start (main_loop, &int_sig_watcher); + ev_init(&int_sig_watcher, term_sig_watcher_cb); + ev_signal_set(&int_sig_watcher, SIGINT); + ev_signal_start(main_loop, &int_sig_watcher); - ev_init (&term_sig_watcher, term_sig_watcher_cb); - ev_signal_set (&term_sig_watcher, SIGTERM); - ev_signal_start (main_loop, &term_sig_watcher); + ev_init(&term_sig_watcher, term_sig_watcher_cb); + ev_signal_set(&term_sig_watcher, SIGTERM); + ev_signal_start(main_loop, &term_sig_watcher); - ev_init (&reload_sig_watcher, reload_sig_watcher_cb); - ev_signal_set (&reload_sig_watcher, SIGHUP); - ev_signal_start (main_loop, &reload_sig_watcher); + ev_init(&reload_sig_watcher, reload_sig_watcher_cb); + ev_signal_set(&reload_sig_watcher, SIGHUP); + ev_signal_start(main_loop, &reload_sig_watcher); /* set the standard fds we watch */ - list_for_each(&s->listen_list.head, ltmp, list) { - if (ltmp->fd == -1) continue; + list_for_each(&s->listen_list.head, ltmp, list) + { + if (ltmp->fd == -1) + continue; - ev_io_start (main_loop, <mp->io); + ev_io_start(main_loop, <mp->io); } - for (i = 0; i < s->sec_mod_instance_count; i ++) { - ev_io_set(&sec_mod_watchers[i].sec_mod_watcher, s->sec_mod_instances[i].sec_mod_fd, EV_READ); - ev_io_start (main_loop, &sec_mod_watchers[i].sec_mod_watcher); + for (i = 0; i < s->sec_mod_instance_count; i++) { + ev_io_set(&sec_mod_watchers[i].sec_mod_watcher, + s->sec_mod_instances[i].sec_mod_fd, EV_READ); + ev_io_start(main_loop, &sec_mod_watchers[i].sec_mod_watcher); } ctl_handler_set_fds(s, &ctl_watcher); - ev_io_start (main_loop, &ctl_watcher); + ev_io_start(main_loop, &ctl_watcher); - for (i = 0; i < s->sec_mod_instance_count; i ++) { - ev_child_init(&sec_mod_watchers[i].child_watcher, sec_mod_child_watcher_cb, s->sec_mod_instances[i].sec_mod_pid, 0); - ev_child_start (main_loop, &sec_mod_watchers[i].child_watcher); + for (i = 0; i < s->sec_mod_instance_count; i++) { + ev_child_init(&sec_mod_watchers[i].child_watcher, + sec_mod_child_watcher_cb, + s->sec_mod_instances[i].sec_mod_pid, 0); + ev_child_start(main_loop, &sec_mod_watchers[i].child_watcher); } ev_init(&maintenance_watcher, maintenance_watcher_cb); - ev_timer_set(&maintenance_watcher, MAIN_MAINTENANCE_TIME, MAIN_MAINTENANCE_TIME); + ev_timer_set(&maintenance_watcher, MAIN_MAINTENANCE_TIME, + MAIN_MAINTENANCE_TIME); ev_timer_start(main_loop, &maintenance_watcher); ev_init(&graceful_shutdown_watcher, graceful_shutdown_watcher_cb); #if defined(CAPTURE_LATENCY_SUPPORT) ev_init(&latency_watcher, latency_watcher_cb); - ev_timer_set(&latency_watcher, LATENCY_AGGREGATION_TIME, LATENCY_AGGREGATION_TIME); + ev_timer_set(&latency_watcher, LATENCY_AGGREGATION_TIME, + LATENCY_AGGREGATION_TIME); ev_timer_start(main_loop, &latency_watcher); #endif /* allow forcing maintenance with SIGUSR2 */ - ev_init (&maintenance_sig_watcher, maintenance_sig_watcher_cb); - ev_signal_set (&maintenance_sig_watcher, SIGUSR2); - ev_signal_start (main_loop, &maintenance_sig_watcher); + ev_init(&maintenance_sig_watcher, maintenance_sig_watcher_cb); + ev_signal_set(&maintenance_sig_watcher, SIGUSR2); + ev_signal_start(main_loop, &maintenance_sig_watcher); /* Main server loop */ - ev_run (main_loop, 0); + ev_run(main_loop, 0); /* try to clean-up everything allocated to ease checks * for memory leaks. */ - for (i = 0; i < s->sec_mod_instance_count; i ++) { + for (i = 0; i < s->sec_mod_instance_count; i++) { remove(s->sec_mod_instances[i].full_socket_file); } remove(GETPCONFIG(s)->occtl_socket_file); @@ -1639,7 +1804,8 @@ int main(int argc, char** argv) snapshot_terminate(config_snapshot); - if (GETPCONFIG(s)->listen_netns_name && close_namespaces(&s->netns) < 0) { + if (GETPCONFIG(s)->listen_netns_name && + close_namespaces(&s->netns) < 0) { fprintf(stderr, "cannot close listen namespaces\n"); exit(EXIT_FAILURE); } @@ -1652,12 +1818,12 @@ int main(int argc, char** argv) return 0; } -extern char ** pam_auth_group_list; -extern char ** gssapi_auth_group_list; -extern char ** plain_auth_group_list; -extern unsigned pam_auth_group_list_size; -extern unsigned gssapi_auth_group_list_size; -extern unsigned plain_auth_group_list_size; +extern char **pam_auth_group_list; +extern char **gssapi_auth_group_list; +extern char **plain_auth_group_list; +extern unsigned int pam_auth_group_list_size; +extern unsigned int gssapi_auth_group_list_size; +extern unsigned int plain_auth_group_list_size; static bool set_env_from_ws(main_server_st *s) { @@ -1668,6 +1834,7 @@ static bool set_env_from_ws(main_server_st *s) size_t string_size = 0; char *string_buffer = NULL; int ret = 0; + SnapshotEntryMsg **entries = NULL; SnapshotEntryMsg entry_template = SNAPSHOT_ENTRY_MSG__INIT; size_t entry_count; @@ -1698,13 +1865,17 @@ static bool set_env_from_ws(main_server_st *s) for (index = 0; index < entry_count; index++) { int fd, rr; const char *file_name; + if (index == 0) { - rr = snapshot_first(config_snapshot, &iter, &fd, &file_name); + rr = snapshot_first(config_snapshot, &iter, &fd, + &file_name); } else { - rr = snapshot_next(config_snapshot, &iter, &fd, &file_name); + rr = snapshot_next(config_snapshot, &iter, &fd, + &file_name); } if (rr < 0) { - mslog(s, NULL, LOG_ERR, "snapshot restoration failed (%d)\n", ret); + mslog(s, NULL, LOG_ERR, + "snapshot restoration failed (%d)\n", ret); goto cleanup; } @@ -1726,7 +1897,8 @@ static bool set_env_from_ws(main_server_st *s) msg_size = worker_startup_msg__get_packed_size(&msg); if (msg_size == 0) { - mslog(s, NULL, LOG_ERR, "worker_startup_msg__get_packed_size failed\n"); + mslog(s, NULL, LOG_ERR, + "worker_startup_msg__get_packed_size failed\n"); goto cleanup; } @@ -1747,7 +1919,8 @@ static bool set_env_from_ws(main_server_st *s) goto cleanup; } - oc_base64_encode((const char *)msg_buffer, msg_size, string_buffer, string_size); + oc_base64_encode((const char *)msg_buffer, msg_size, string_buffer, + string_size); if (setenv(OCSERV_ENV_WORKER_STARTUP_MSG, string_buffer, 1)) { mslog(s, NULL, LOG_ERR, "setenv failed\n"); goto cleanup; diff --git a/src/main.h b/src/main.h index 32f767da..a3897d6a 100644 --- a/src/main.h +++ b/src/main.h @@ -20,7 +20,7 @@ * along with this program. If not, see */ #ifndef OC_MAIN_H -# define OC_MAIN_H +#define OC_MAIN_H #include #include @@ -40,8 +40,8 @@ #include #if defined(__FreeBSD__) || defined(__OpenBSD__) -# include -# define SOL_IP IPPROTO_IP +#include +#define SOL_IP IPPROTO_IP #endif #define COOKIE_KEY_SIZE 16 @@ -56,7 +56,8 @@ extern ev_timer maintainance_watcher; #define MAIN_MAINTENANCE_TIME (900) -int cmd_parser (void *pool, int argc, char **argv, struct list_head *head, bool worker); +int cmd_parser(void *pool, int argc, char **argv, struct list_head *head, + bool worker); #if defined(CAPTURE_LATENCY_SUPPORT) #define LATENCY_AGGREGATION_TIME (60) @@ -89,7 +90,7 @@ struct script_wait_st { struct list_node list; pid_t pid; - struct proc_st* proc; + struct proc_st *proc; }; /* Each worker process maps to a unique proc_st structure. @@ -102,7 +103,7 @@ typedef struct proc_st { struct list_node list; int fd; /* the command file descriptor */ pid_t pid; - unsigned pid_killed; /* if explicitly disconnected */ + unsigned int pid_killed; /* if explicitly disconnected */ time_t udp_fd_receive_time; /* when the corresponding process has received a UDP fd */ @@ -112,7 +113,7 @@ typedef struct proc_st { struct tun_lease_st tun_lease; struct ip_lease_st *ipv4; struct ip_lease_st *ipv6; - unsigned leases_in_use; /* someone else got our IP leases */ + unsigned int leases_in_use; /* someone else got our IP leases */ struct sockaddr_storage remote_addr; /* peer address (CSTP) */ socklen_t remote_addr_len; @@ -125,20 +126,21 @@ typedef struct proc_st { /* The SID which acts as a cookie */ uint8_t sid[SID_SIZE]; - unsigned active_sid; + unsigned int active_sid; /* non zero if the sid has been invalidated and must not be allowed * to reconnect. */ - unsigned invalidated; + unsigned int invalidated; /* whether the host-update script has already been called */ - unsigned host_updated; + unsigned int host_updated; /* The DTLS session ID associated with the TLS session * it is either generated or restored from a cookie. */ uint8_t dtls_session_id[GNUTLS_MAX_SESSION_ID]; - unsigned dtls_session_id_size; /* would act as a flag if session_id is set */ + unsigned int + dtls_session_id_size; /* would act as a flag if session_id is set */ /* The following are set by the worker process (or by a stored cookie) */ char username[MAX_USERNAME_SIZE]; /* the owner */ @@ -154,7 +156,7 @@ typedef struct proc_st { char dtls_ciphersuite[MAX_CIPHERSUITE_NAME]; char cstp_compr[8]; char dtls_compr[8]; - unsigned mtu; + unsigned int mtu; unsigned int sec_mod_instance_index; /* if the session is initiated by a cookie the following two are set @@ -163,7 +165,7 @@ typedef struct proc_st { */ uint8_t ipv4_seed[4]; - unsigned status; /* PS_AUTH_ */ + unsigned int status; /* PS_AUTH_ */ /* these are filled in after the worker process dies, using the * Cli stats message. */ @@ -171,7 +173,8 @@ typedef struct proc_st { uint64_t bytes_out; uint32_t discon_reason; /* filled on session close */ - unsigned applied_iroutes; /* whether the iroutes in the config have been successfully applied */ + unsigned int + applied_iroutes; /* whether the iroutes in the config have been successfully applied */ /* The following we rely on talloc for deallocation */ GroupCfgSt *config; /* custom user/group config */ @@ -205,7 +208,7 @@ struct proc_hash_db_st { struct htable *db_dtls_ip; struct htable *db_dtls_id; struct htable *db_sid; - unsigned total; + unsigned int total; }; #if defined(CAPTURE_LATENCY_SUPPORT) @@ -223,10 +226,10 @@ struct main_stats_st { uint64_t sessions_closed; /* sessions closed since last reset */ uint64_t kbytes_in; uint64_t kbytes_out; - unsigned min_mtu; - unsigned max_mtu; + unsigned int min_mtu; + unsigned int max_mtu; - unsigned active_clients; + unsigned int active_clients; time_t start_time; time_t last_reset; @@ -245,20 +248,20 @@ struct main_stats_st { }; typedef struct sec_mod_instance_st { - struct main_server_st * server; + struct main_server_st *server; char socket_file[_POSIX_PATH_MAX]; char full_socket_file[_POSIX_PATH_MAX]; pid_t sec_mod_pid; struct sockaddr_un secmod_addr; - unsigned secmod_addr_len; + unsigned int secmod_addr_len; int sec_mod_fd; /* messages are sent and received async */ int sec_mod_fd_sync; /* messages are send in a sync order (ping-pong). Only main sends. */ /* updated on the cli_stats_msg from sec-mod. * Holds the number of entries in secmod list of users */ - unsigned secmod_client_entries; - unsigned tlsdb_entries; + unsigned int secmod_client_entries; + unsigned int tlsdb_entries; uint32_t avg_auth_time; /* in seconds */ uint32_t max_auth_time; /* in seconds */ @@ -285,13 +288,13 @@ typedef struct main_server_st { struct main_stats_st stats; - void * auth_extra; + void *auth_extra; /* This one is on worker pool */ struct worker_st *ws; unsigned int sec_mod_instance_count; - sec_mod_instance_st * sec_mod_instances; + sec_mod_instance_st *sec_mod_instances; int top_fd; int ctl_fd; @@ -310,52 +313,55 @@ typedef struct main_server_st { struct rlimit fd_limits_default_set; #endif - struct if_address_st * if_addresses; + struct if_address_st *if_addresses; unsigned int if_addresses_count; } main_server_st; void clear_lists(main_server_st *s); -int handle_worker_commands(main_server_st *s, struct proc_st* cur); -int handle_sec_mod_commands(sec_mod_instance_st * sec_mod_instances); +int handle_worker_commands(main_server_st *s, struct proc_st *cur); +int handle_sec_mod_commands(sec_mod_instance_st *sec_mod_instances); -int user_connected(main_server_st *s, struct proc_st* cur); -void user_hostname_update(main_server_st *s, struct proc_st* cur); -void user_disconnected(main_server_st *s, struct proc_st* cur); +int user_connected(main_server_st *s, struct proc_st *cur); +void user_hostname_update(main_server_st *s, struct proc_st *cur); +void user_disconnected(main_server_st *s, struct proc_st *cur); -int send_udp_fd(main_server_st* s, struct proc_st * proc, int fd); +int send_udp_fd(main_server_st *s, struct proc_st *proc, int fd); -int session_open(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc, const uint8_t *cookie, unsigned cookie_size); -int session_close(sec_mod_instance_st * sec_mod_instance, struct proc_st *proc); +int session_open(sec_mod_instance_st *sec_mod_instance, struct proc_st *proc, + const uint8_t *cookie, unsigned int cookie_size); +int session_close(sec_mod_instance_st *sec_mod_instance, struct proc_st *proc); -int open_tun(main_server_st* s, struct proc_st* proc); -void close_tun(main_server_st* s, struct proc_st* proc); -void reset_tun(struct proc_st* proc); -int set_tun_mtu(main_server_st* s, struct proc_st * proc, unsigned mtu); +int open_tun(main_server_st *s, struct proc_st *proc); +void close_tun(main_server_st *s, struct proc_st *proc); +void reset_tun(struct proc_st *proc); +int set_tun_mtu(main_server_st *s, struct proc_st *proc, unsigned int mtu); -int send_cookie_auth_reply(main_server_st* s, struct proc_st* proc, - AUTHREP r); +int send_cookie_auth_reply(main_server_st *s, struct proc_st *proc, AUTHREP r); -int handle_auth_cookie_req(sec_mod_instance_st * sec_mod_instance, struct proc_st* proc, - const AuthCookieRequestMsg * req); +int handle_auth_cookie_req(sec_mod_instance_st *sec_mod_instance, + struct proc_st *proc, + const AuthCookieRequestMsg *req); -int check_multiple_users(main_server_st *s, struct proc_st* proc); -int handle_script_exit(main_server_st *s, struct proc_st* proc, int code); +int check_multiple_users(main_server_st *s, struct proc_st *proc); +int handle_script_exit(main_server_st *s, struct proc_st *proc, int code); -void run_sec_mod(sec_mod_instance_st * sec_mod_instance, unsigned int instance_index); +void run_sec_mod(sec_mod_instance_st *sec_mod_instance, + unsigned int instance_index); -struct proc_st *new_proc(main_server_st * s, pid_t pid, int cmd_fd, - struct sockaddr_storage *remote_addr, socklen_t remote_addr_len, - struct sockaddr_storage *our_addr, socklen_t our_addr_len, - uint8_t *sid, size_t sid_size); +struct proc_st *new_proc(main_server_st *s, pid_t pid, int cmd_fd, + struct sockaddr_storage *remote_addr, + socklen_t remote_addr_len, + struct sockaddr_storage *our_addr, + socklen_t our_addr_len, uint8_t *sid, size_t sid_size); /* kill the pid */ #define RPROC_KILL 1 /* we are on shutdown, don't wait for anything */ -#define RPROC_QUIT (1<<1) +#define RPROC_QUIT (1 << 1) -void remove_proc(main_server_st* s, struct proc_st *proc, unsigned flags); -void proc_to_zombie(main_server_st* s, struct proc_st *proc); +void remove_proc(main_server_st *s, struct proc_st *proc, unsigned int flags); +void proc_to_zombie(main_server_st *s, struct proc_st *proc); inline static void disconnect_proc(main_server_st *s, proc_st *proc) { @@ -365,34 +371,39 @@ inline static void disconnect_proc(main_server_st *s, proc_st *proc) /* if it has a PID, send a signal so that we cleanup * and sec-mod gets stats orderly */ if (proc->pid != -1 && proc->pid != 0) { - kill(proc->pid, SIGTERM); + kill(proc->pid, SIGTERM); } else { remove_proc(s, proc, RPROC_KILL); } } -void put_into_cgroup(main_server_st * s, const char* cgroup, pid_t pid); +void put_into_cgroup(main_server_st *s, const char *cgroup, pid_t pid); -inline static -int send_msg_to_worker(main_server_st* s, struct proc_st* proc, uint8_t cmd, - const void* msg, pack_size_func get_size, pack_func pack) +inline static int send_msg_to_worker(main_server_st *s, struct proc_st *proc, + uint8_t cmd, const void *msg, + pack_size_func get_size, pack_func pack) { - mslog(s, proc, LOG_DEBUG, "sending message '%s' to worker", cmd_request_to_str(cmd)); + mslog(s, proc, LOG_DEBUG, "sending message '%s' to worker", + cmd_request_to_str(cmd)); return send_msg(proc, proc->fd, cmd, msg, get_size, pack); } -inline static -int send_socket_msg_to_worker(main_server_st* s, struct proc_st* proc, uint8_t cmd, - int socketfd, const void* msg, pack_size_func get_size, pack_func pack) +inline static int send_socket_msg_to_worker(main_server_st *s, + struct proc_st *proc, uint8_t cmd, + int socketfd, const void *msg, + pack_size_func get_size, + pack_func pack) { - mslog(s, proc, LOG_DEBUG, "sending (socket) message %u to worker", (unsigned)cmd); - return send_socket_msg(proc, proc->fd, cmd, socketfd, msg, get_size, pack); + mslog(s, proc, LOG_DEBUG, "sending (socket) message %u to worker", + (unsigned int)cmd); + return send_socket_msg(proc, proc->fd, cmd, socketfd, msg, get_size, + pack); } -int secmod_reload(sec_mod_instance_st * sec_mod_instance); +int secmod_reload(sec_mod_instance_st *sec_mod_instance); const char *secmod_socket_file_name(struct perm_cfg_st *perm_config); -void restore_secmod_socket_file_name(const char * save_path); +void restore_secmod_socket_file_name(const char *save_path); void clear_vhosts(struct list_head *head); void request_reload(int signo); diff --git a/src/namespace.c b/src/namespace.c index f437a0b7..6b88bb0a 100644 --- a/src/namespace.c +++ b/src/namespace.c @@ -15,7 +15,6 @@ * along with this program. If not, see . */ - #include #if defined(LINUX_NAMESPACES) @@ -45,7 +44,8 @@ static int init_default_namespace(void) int fd; pid = getpid(); - if (snprintf(netns_path, sizeof(netns_path), "/proc/%d/ns/net", pid) < 0) + if (snprintf(netns_path, sizeof(netns_path), "/proc/%d/ns/net", pid) < + 0) return -1; fd = open(netns_path, O_RDONLY | O_CLOEXEC); @@ -64,7 +64,8 @@ static int init_listen_namespace(const char *ns_name) int error; int fd; - if (snprintf(netns_path, sizeof(netns_path), "/var/run/netns/%s", ns_name) < 0) + if (snprintf(netns_path, sizeof(netns_path), "/var/run/netns/%s", + ns_name) < 0) return -1; fd = open(netns_path, O_RDONLY | O_CLOEXEC); @@ -101,16 +102,19 @@ int close_namespaces(struct netns_fds *netns) } /* opens a socket in the namespace described by */ -int socket_netns(const struct netns_fds *fds, int domain, int type, int protocol) +int socket_netns(const struct netns_fds *fds, int domain, int type, + int protocol) { int sock; - if (fds->default_fd >= 0 && fds->listen_fd && setns(fds->listen_fd, CLONE_NEWNET) == -1) + if (fds->default_fd >= 0 && fds->listen_fd && + setns(fds->listen_fd, CLONE_NEWNET) == -1) return -1; sock = socket(domain, type, protocol); - if (fds->default_fd >= 0 && fds->listen_fd && setns(fds->default_fd, CLONE_NEWNET) == -1) { + if (fds->default_fd >= 0 && fds->listen_fd && + setns(fds->default_fd, CLONE_NEWNET) == -1) { if (sock >= 0) close(sock); return -1; diff --git a/src/namespace.h b/src/namespace.h index 8dd1e71d..b2f00f2f 100644 --- a/src/namespace.h +++ b/src/namespace.h @@ -16,7 +16,7 @@ */ #ifndef OC_NAMESPACE_H -# define OC_NAMESPACE_H +#define OC_NAMESPACE_H #include @@ -27,7 +27,7 @@ struct netns_fds { #if defined(LINUX_NAMESPACES) -int socket_netns(const struct netns_fds*, int domain, int type, int protocol); +int socket_netns(const struct netns_fds *, int domain, int type, int protocol); int open_namespaces(struct netns_fds *netns, struct perm_cfg_st *config); int close_namespaces(struct netns_fds *netns); @@ -36,10 +36,11 @@ int close_namespaces(struct netns_fds *netns); #define open_namespaces(netns, config) (-1) #define close_namespaces(netns) (-1) -static inline int socket_netns(__attribute__((unused)) const struct netns_fds* fds, +static inline int socket_netns(__attribute__((unused)) + const struct netns_fds *fds, int domain, int type, int protocol) { - return socket(domain, type, protocol); + return socket(domain, type, protocol); } #endif /* __linux__ */ diff --git a/src/occtl/cache.c b/src/occtl/cache.c index 7b13eb2b..f98b2adc 100644 --- a/src/occtl/cache.c +++ b/src/occtl/cache.c @@ -26,52 +26,57 @@ #include typedef struct uid_entries_st { - char* user; - unsigned user_size; + char *user; + unsigned int user_size; char id[8]; - unsigned id_size; + unsigned int id_size; } uid_entries_st; -static uid_entries_st *entries = NULL; -static unsigned entries_size = 0; -static unsigned max_entries_size = 0; +static uid_entries_st *entries; +static unsigned int entries_size; +static unsigned int max_entries_size; void entries_clear(void) { -unsigned i; + unsigned int i; - for (i=0;i max_entries_size) { + if (entries_size + 1 > max_entries_size) { max_entries_size += 128; - entries = talloc_realloc_size(pool, entries, sizeof(uid_entries_st)*max_entries_size); + entries = talloc_realloc_size(pool, entries, + sizeof(uid_entries_st) * + max_entries_size); } entries[entries_size].user = talloc_strdup(pool, user); entries[entries_size].user_size = user_size; entries[entries_size].id_size = - snprintf(entries[entries_size].id, sizeof(entries[entries_size].id), "%u", id); + snprintf(entries[entries_size].id, + sizeof(entries[entries_size].id), "%u", id); entries_size++; } -char* search_for_user(unsigned idx, const char* match, int match_size) +char *search_for_user(unsigned int idx, const char *match, int match_size) { -unsigned i; + unsigned int i; if (idx >= entries_size) return NULL; - for (i=idx;i= entries_size) return NULL; - for (i=idx;i -# include +#include +#include extern void _GeoIP_setup_dbfilename(void); -# define p_GeoIP_setup_dbfilename _GeoIP_setup_dbfilename -# define pGeoIP_open_type GeoIP_open_type -# define pGeoIP_country_name_by_id GeoIP_country_name_by_id -# define pGeoIP_delete GeoIP_delete -# define pGeoIP_record_by_ipnum GeoIP_record_by_ipnum -# define pGeoIP_id_by_ipnum GeoIP_id_by_ipnum -# define pGeoIP_id_by_ipnum_v6 GeoIP_id_by_ipnum_v6 -# define pGeoIP_record_by_ipnum_v6 GeoIP_record_by_ipnum_v6 -# define pGeoIP_code_by_id GeoIP_code_by_id +#define p_GeoIP_setup_dbfilename _GeoIP_setup_dbfilename +#define pGeoIP_open_type GeoIP_open_type +#define pGeoIP_country_name_by_id GeoIP_country_name_by_id +#define pGeoIP_delete GeoIP_delete +#define pGeoIP_record_by_ipnum GeoIP_record_by_ipnum +#define pGeoIP_id_by_ipnum GeoIP_id_by_ipnum +#define pGeoIP_id_by_ipnum_v6 GeoIP_id_by_ipnum_v6 +#define pGeoIP_record_by_ipnum_v6 GeoIP_record_by_ipnum_v6 +#define pGeoIP_code_by_id GeoIP_code_by_id int geo_setup(void) { - static unsigned init = 0; + static unsigned int init; if (init == 0) { p_GeoIP_setup_dbfilename(); @@ -56,7 +56,8 @@ int geo_setup(void) return 0; } -void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, char **coord) +void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, + char **coord) { GeoIP *gi; GeoIPRecord *gir; @@ -68,7 +69,8 @@ void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, char **coor ip.s_addr = ntohl(ip.s_addr); - gi = pGeoIP_open_type(GEOIP_COUNTRY_EDITION, GEOIP_STANDARD | GEOIP_SILENCE); + gi = pGeoIP_open_type(GEOIP_COUNTRY_EDITION, + GEOIP_STANDARD | GEOIP_SILENCE); if (gi != NULL) { gi->charset = GEOIP_CHARSET_UTF8; @@ -83,7 +85,8 @@ void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, char **coor pGeoIP_delete(gi); } - gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV1, GEOIP_STANDARD | GEOIP_SILENCE); + gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV1, + GEOIP_STANDARD | GEOIP_SILENCE); if (gi != NULL) { gi->charset = GEOIP_CHARSET_UTF8; @@ -93,12 +96,14 @@ void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, char **coor *city = strdup(gir->city); if (gir && gir->longitude != 0 && gir->longitude != 0) - if (asprintf(coord, "%f,%f", gir->latitude, gir->longitude) < 0) + if (asprintf(coord, "%f,%f", gir->latitude, + gir->longitude) < 0) *coord = NULL; pGeoIP_delete(gi); } else { - gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV0, GEOIP_STANDARD | GEOIP_SILENCE); + gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV0, + GEOIP_STANDARD | GEOIP_SILENCE); if (gi != NULL) { gi->charset = GEOIP_CHARSET_UTF8; @@ -108,7 +113,8 @@ void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, char **coor *city = strdup(gir->city); if (gir && gir->longitude != 0 && gir->longitude != 0) - if (asprintf(coord, "%f,%f", gir->latitude, gir->longitude) < 0) + if (asprintf(coord, "%f,%f", gir->latitude, + gir->longitude) < 0) *coord = NULL; pGeoIP_delete(gi); @@ -116,7 +122,8 @@ void geo_ipv4_lookup(struct in_addr ip, char **country, char **city, char **coor } } -void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, char **coord) +void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, + char **coord) { GeoIP *gi; GeoIPRecord *gir; @@ -126,7 +133,8 @@ void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, char **co if (geo_setup() != 0) return; - gi = pGeoIP_open_type(GEOIP_COUNTRY_EDITION_V6, GEOIP_STANDARD | GEOIP_SILENCE); + gi = pGeoIP_open_type(GEOIP_COUNTRY_EDITION_V6, + GEOIP_STANDARD | GEOIP_SILENCE); if (gi != NULL) { gi->charset = GEOIP_CHARSET_UTF8; @@ -141,7 +149,8 @@ void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, char **co pGeoIP_delete(gi); } - gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV1_V6, GEOIP_STANDARD | GEOIP_SILENCE); + gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV1_V6, + GEOIP_STANDARD | GEOIP_SILENCE); if (gi != NULL) { gi->charset = GEOIP_CHARSET_UTF8; @@ -151,12 +160,14 @@ void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, char **co *city = strdup(gir->city); if (gir && gir->longitude != 0 && gir->longitude != 0) - if (asprintf(coord, "%f,%f", gir->latitude, gir->longitude) < 0) + if (asprintf(coord, "%f,%f", gir->latitude, + gir->longitude) < 0) *coord = NULL; pGeoIP_delete(gi); } else { - gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV0_V6, GEOIP_STANDARD | GEOIP_SILENCE); + gi = pGeoIP_open_type(GEOIP_CITY_EDITION_REV0_V6, + GEOIP_STANDARD | GEOIP_SILENCE); if (gi != NULL) { gi->charset = GEOIP_CHARSET_UTF8; @@ -166,7 +177,8 @@ void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, char **co *city = strdup(gir->city); if (gir && gir->longitude != 0 && gir->longitude != 0) - if (asprintf(coord, "%f,%f", gir->latitude, gir->longitude) < 0) + if (asprintf(coord, "%f,%f", gir->latitude, + gir->longitude) < 0) *coord = NULL; pGeoIP_delete(gi); @@ -174,7 +186,7 @@ void geo_ipv6_lookup(struct in6_addr *ip, char **country, char **city, char **co } } -char *geo_lookup(const char *ip, char *buf, unsigned buf_size) +char *geo_lookup(const char *ip, char *buf, unsigned int buf_size) { char *country = NULL; char *city = NULL; @@ -209,7 +221,7 @@ char *geo_lookup(const char *ip, char *buf, unsigned buf_size) return buf; - fail: +fail: free(country); free(city); free(coord); @@ -218,7 +230,7 @@ char *geo_lookup(const char *ip, char *buf, unsigned buf_size) } #else -char * geo_lookup(const char *ip, char *buf, unsigned buf_size) +char *geo_lookup(const char *ip, char *buf, unsigned int buf_size) { return "unknown"; } diff --git a/src/occtl/geoip.h b/src/occtl/geoip.h index 8f25a992..124a6be3 100644 --- a/src/occtl/geoip.h +++ b/src/occtl/geoip.h @@ -18,8 +18,8 @@ */ #ifndef GEOIP_H -# define GEOIP_H +#define GEOIP_H -char * geo_lookup(const char *ip, char *buf, unsigned buf_size); +char *geo_lookup(const char *ip, char *buf, unsigned int buf_size); #endif diff --git a/src/occtl/ip-cache.c b/src/occtl/ip-cache.c index 5c47cded..f0570523 100644 --- a/src/occtl/ip-cache.c +++ b/src/occtl/ip-cache.c @@ -28,45 +28,49 @@ typedef struct ip_entries_st { char ip[MAX_IP_STR]; - unsigned ip_size; + unsigned int ip_size; } ip_entries_st; -static ip_entries_st *ip_entries = NULL; -static unsigned ip_entries_size = 0; -static unsigned max_ip_entries_size = 0; +static ip_entries_st *ip_entries; +static unsigned int ip_entries_size; +static unsigned int max_ip_entries_size; void ip_entries_clear(void) { -unsigned i; + unsigned int i; - for (i=0;i max_ip_entries_size) { + if (ip_entries_size + 1 > max_ip_entries_size) { max_ip_entries_size += 128; - ip_entries = talloc_realloc_size(pool, ip_entries, sizeof(ip_entries_st)*max_ip_entries_size); + ip_entries = talloc_realloc_size(pool, ip_entries, + sizeof(ip_entries_st) * + max_ip_entries_size); } - strlcpy(ip_entries[ip_entries_size].ip, ip, sizeof(ip_entries[ip_entries_size].ip)); + strlcpy(ip_entries[ip_entries_size].ip, ip, + sizeof(ip_entries[ip_entries_size].ip)); ip_entries[ip_entries_size].ip_size = ip_size; ip_entries_size++; } -char* search_for_ip(unsigned idx, const char* match, int match_size) +char *search_for_ip(unsigned int idx, const char *match, int match_size) { -unsigned i; + unsigned int i; if (idx >= ip_entries_size) return NULL; - for (i=idx;i= tmp_size) return "(invalid)"; if (val[i] == '"' || val[i] == '\\') { - snprintf(&tmp[j], 3, "\\%c", val[i]); - j+=2; + snprintf(&tmp[j], 3, "\\%c", val[i]); + j += 2; } else if (val[i] <= 0x1F) { - snprintf(&tmp[j], 7, "\\u00%02x", (unsigned)val[i]); - j+=6; - } else tmp[j++] = val[i]; + snprintf(&tmp[j], 7, "\\u00%02x", (unsigned int)val[i]); + j += 6; + } else + tmp[j++] = val[i]; } tmp[j] = 0; diff --git a/src/occtl/json.h b/src/occtl/json.h index f228f65c..b546ecd7 100644 --- a/src/occtl/json.h +++ b/src/occtl/json.h @@ -20,7 +20,7 @@ */ #ifndef JSON_H -# define JSON_H -char *json_escape_val(char *tmp, unsigned tmp_size, const char *val); +#define JSON_H +char *json_escape_val(char *tmp, unsigned int tmp_size, const char *val); #endif diff --git a/src/occtl/maxmind.c b/src/occtl/maxmind.c index 3214d2e3..724e121a 100644 --- a/src/occtl/maxmind.c +++ b/src/occtl/maxmind.c @@ -38,21 +38,21 @@ #define MAXMINDDB_LOCATION_CITY "/usr/share/GeoIP/GeoLite2-City.mmdb" #endif -#define pMMDB_close MMDB_close -#define pMMDB_get_value MMDB_get_value +#define pMMDB_close MMDB_close +#define pMMDB_get_value MMDB_get_value #define pMMDB_lookup_string MMDB_lookup_string -#define pMMDB_open MMDB_open +#define pMMDB_open MMDB_open -void process_result_from_mmdb_lookup(MMDB_entry_data_s * entry_data, int status, +void process_result_from_mmdb_lookup(MMDB_entry_data_s *entry_data, int status, char **output) { - if (MMDB_SUCCESS == status) { + if (status == MMDB_SUCCESS) { if (entry_data->has_data) { if (entry_data->type == MMDB_DATA_TYPE_UTF8_STRING) { - *output = - (char *)calloc(entry_data->data_size + 1, - sizeof(char)); - if (NULL != *output) { + *output = (char *)calloc(entry_data->data_size + + 1, + sizeof(char)); + if (*output != NULL) { memcpy(*output, entry_data->utf8_string, entry_data->data_size); } else { @@ -66,7 +66,7 @@ void process_result_from_mmdb_lookup(MMDB_entry_data_s * entry_data, int status, /* Else fail silently */ } -char *geo_lookup(const char *ip, char *buf, unsigned buf_size) +char *geo_lookup(const char *ip, char *buf, unsigned int buf_size) { MMDB_s mmdb; MMDB_entry_data_s entry_data; @@ -74,33 +74,30 @@ char *geo_lookup(const char *ip, char *buf, unsigned buf_size) double latitude, longitude; char *country = NULL, *ccode = NULL; char *coord = NULL; - unsigned found = 0; + unsigned int found = 0; /* Open the system maxmind database with countries */ status = pMMDB_open(MAXMINDDB_LOCATION_COUNTRY, MMDB_MODE_MMAP, &mmdb); - if (MMDB_SUCCESS == status) { + if (status == MMDB_SUCCESS) { /* Lookup IP address in the database */ MMDB_lookup_result_s result = - pMMDB_lookup_string(&mmdb, ip, &gai_error, &mmdb_error); - if (MMDB_SUCCESS == mmdb_error) { + pMMDB_lookup_string(&mmdb, ip, &gai_error, &mmdb_error); + if (mmdb_error == MMDB_SUCCESS) { /* If the lookup was successful and an entry was found */ if (result.found_entry) { memset(&entry_data, 0, sizeof(MMDB_entry_data_s)); /* Travel the path in the tree like structure of the MMDB and store the value if found */ - status = - pMMDB_get_value(&result.entry, &entry_data, - "country", "names", "en", - NULL); - process_result_from_mmdb_lookup(&entry_data, - status, - &country); + status = pMMDB_get_value(&result.entry, + &entry_data, "country", + "names", "en", NULL); + process_result_from_mmdb_lookup( + &entry_data, status, &country); memset(&entry_data, 0, sizeof(MMDB_entry_data_s)); - status = - pMMDB_get_value(&result.entry, &entry_data, - "country", "iso_code", - NULL); + status = pMMDB_get_value(&result.entry, + &entry_data, "country", + "iso_code", NULL); process_result_from_mmdb_lookup(&entry_data, status, &ccode); } @@ -112,11 +109,11 @@ char *geo_lookup(const char *ip, char *buf, unsigned buf_size) /* Open the system maxmind database with cities - which actually does not contain names of the cities */ status = pMMDB_open(MAXMINDDB_LOCATION_CITY, MMDB_MODE_MMAP, &mmdb); - if (MMDB_SUCCESS == status) { + if (status == MMDB_SUCCESS) { /* Lookup IP address in the database */ MMDB_lookup_result_s result = - pMMDB_lookup_string(&mmdb, ip, &gai_error, &mmdb_error); - if (MMDB_SUCCESS == mmdb_error) { + pMMDB_lookup_string(&mmdb, ip, &gai_error, &mmdb_error); + if (mmdb_error == MMDB_SUCCESS) { /* If the lookup was successful and an entry was found */ if (result.found_entry) { memset(&entry_data, 0, @@ -124,32 +121,32 @@ char *geo_lookup(const char *ip, char *buf, unsigned buf_size) // NOTE: Information about the city is not available in the free database, so there is not way // for me to implement this functionality right now, but it should be easy to add for anyone with // access to the paid databases. - status = - pMMDB_get_value(&result.entry, &entry_data, - "location", "latitude", - NULL); - if (MMDB_SUCCESS == status) { + status = pMMDB_get_value(&result.entry, + &entry_data, + "location", "latitude", + NULL); + if (status == MMDB_SUCCESS) { if (entry_data.has_data) { if (entry_data.type == MMDB_DATA_TYPE_DOUBLE) { latitude = - entry_data. - double_value; + entry_data + .double_value; ++coordinates; } } } - status = - pMMDB_get_value(&result.entry, &entry_data, - "location", "longitude", - NULL); - if (MMDB_SUCCESS == status) { + status = pMMDB_get_value(&result.entry, + &entry_data, + "location", + "longitude", NULL); + if (status == MMDB_SUCCESS) { if (entry_data.has_data) { if (entry_data.type == MMDB_DATA_TYPE_DOUBLE) { longitude = - entry_data. - double_value; + entry_data + .double_value; ++coordinates; } } @@ -161,7 +158,6 @@ char *geo_lookup(const char *ip, char *buf, unsigned buf_size) } } } - } pMMDB_close(&mmdb); } diff --git a/src/occtl/nl.c b/src/occtl/nl.c index 985890c2..03c985f1 100644 --- a/src/occtl/nl.c +++ b/src/occtl/nl.c @@ -33,12 +33,12 @@ #include #include -static struct nl_sock *sock = NULL; -static int nl_failed = 0; +static struct nl_sock *sock; +static int nl_failed; static int open_netlink(void) { -int err; + int err; if (sock != NULL) return 0; @@ -52,7 +52,8 @@ int err; goto error; } - if ((err = nl_connect(sock, NETLINK_ROUTE)) < 0) { + err = nl_connect(sock, NETLINK_ROUTE); + if (err < 0) { fprintf(stderr, "nl: error in nl_connect (%d)", err); goto error; } @@ -68,8 +69,8 @@ error: return -1; } -static void -value2speed(unsigned long bytes, time_t time, char* output, unsigned output_size) +static void value2speed(unsigned long bytes, time_t time, char *output, + unsigned int output_size) { unsigned long speed; @@ -80,7 +81,8 @@ value2speed(unsigned long bytes, time_t time, char* output, unsigned output_size bytes2human(speed, output, output_size, "/s"); } -void print_iface_stats(const char *iface, time_t since, FILE * out, cmd_params_st *params, unsigned have_more) +void print_iface_stats(const char *iface, time_t since, FILE *out, + cmd_params_st *params, unsigned int have_more) { uint64_t tx, rx; char buf1[32], buf2[32]; @@ -106,21 +108,30 @@ void print_iface_stats(const char *iface, time_t since, FILE * out, cmd_params_s bytes2human(rx, buf1, sizeof(buf1), NULL); bytes2human(tx, buf2, sizeof(buf2), NULL); if (HAVE_JSON(params)) { - fprintf(out, " \"RX\": \"%"PRIu64"\",\n \"TX\": \"%"PRIu64"\",\n", rx, tx); - fprintf(out, " \"_RX\": \"%s\",\n \"_TX\": \"%s\",\n", buf1, buf2); + fprintf(out, + " \"RX\": \"%" PRIu64 "\",\n \"TX\": \"%" PRIu64 + "\",\n", + rx, tx); + fprintf(out, " \"_RX\": \"%s\",\n \"_TX\": \"%s\",\n", + buf1, buf2); } else - fprintf(out, "\tRX: %"PRIu64" (%s) TX: %"PRIu64" (%s)\n", rx, buf1, tx, buf2); + fprintf(out, "\tRX: %" PRIu64 " (%s) TX: %" PRIu64 " (%s)\n", + rx, buf1, tx, buf2); value2speed(rx, diff, buf1, sizeof(buf1)); value2speed(tx, diff, buf2, sizeof(buf2)); if (HAVE_JSON(params)) - fprintf(out, " \"Average RX\": \"%s\",\n \"Average TX\": \"%s\"%s\n", buf1, buf2, have_more?",":""); + fprintf(out, + " \"Average RX\": \"%s\",\n \"Average TX\": \"%s\"%s\n", + buf1, buf2, have_more ? "," : ""); else - fprintf(out, "\tAverage bandwidth RX: %s TX: %s\n", buf1, buf2); + fprintf(out, "\tAverage bandwidth RX: %s TX: %s\n", buf1, + buf2); } #else -void print_iface_stats(const char *iface, time_t since, FILE * out, cmd_params_st *params, unsigned have_more) +void print_iface_stats(const char *iface, time_t since, FILE *out, + cmd_params_st *params, unsigned int have_more) { } #endif diff --git a/src/occtl/occtl.c b/src/occtl/occtl.c index 1279a257..f4263603 100644 --- a/src/occtl/occtl.c +++ b/src/occtl/occtl.c @@ -30,15 +30,18 @@ #include #include -int syslog_open = 0; +int syslog_open; -static int handle_reset_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -static int handle_help_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -static int handle_exit_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); +static int handle_reset_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +static int handle_help_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +static int handle_exit_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); typedef struct { char *name; - unsigned name_size; + unsigned int name_size; char *arg; cmd_func func; char *doc; @@ -47,15 +50,15 @@ typedef struct { } commands_st; #define ENTRY(name, arg, func, doc, show, npc) \ - {name, sizeof(name)-1, arg, func, doc, show, npc} + { name, sizeof(name) - 1, arg, func, doc, show, npc } static const commands_st commands[] = { ENTRY("disconnect user", "[NAME]", handle_disconnect_user_cmd, "Disconnect the specified user", 1, 1), ENTRY("disconnect id", "[ID]", handle_disconnect_id_cmd, "Disconnect the specified ID", 1, 1), - ENTRY("unban ip", "[IP]", handle_unban_ip_cmd, - "Unban the specified IP", 1, 1), + ENTRY("unban ip", "[IP]", handle_unban_ip_cmd, "Unban the specified IP", + 1, 1), ENTRY("reload", NULL, handle_reload_cmd, "Reloads the server configuration", 1, 1), ENTRY("show status", NULL, handle_status_cmd, @@ -80,8 +83,7 @@ static const commands_st commands[] = { "Prints information on the specified ID", 1, 1), ENTRY("show events", NULL, handle_events_cmd, "Provides information about connecting users", 1, 1), - ENTRY("stop", "now", handle_stop_cmd, - "Terminates the server", 1, 1), + ENTRY("stop", "now", handle_stop_cmd, "Terminates the server", 1, 1), ENTRY("reset", NULL, handle_reset_cmd, "Resets the screen and terminal", 0, 0), ENTRY("help", "or ?", handle_help_cmd, "Prints this help", 0, 0), @@ -93,10 +95,10 @@ static const commands_st commands[] = { "Alias for show sessions all", -1, 1), ENTRY("show cookies valid", NULL, handle_list_valid_sessions_cmd, "Alias for show sessions valid", -1, 1), - {NULL, 0, NULL, NULL} + { NULL, 0, NULL, NULL } }; -static void print_commands(unsigned interactive) +static void print_commands(unsigned int interactive) { unsigned int i; @@ -121,10 +123,10 @@ static void print_commands(unsigned interactive) } #ifndef HAVE_ORIG_READLINE -# define whitespace(x) c_isspace(x) +#define whitespace(x) c_isspace(x) #endif -unsigned need_help(const char *arg) +unsigned int need_help(const char *arg) { while (whitespace(*arg)) arg++; @@ -135,11 +137,11 @@ unsigned need_help(const char *arg) return 0; } -unsigned check_cmd_help(const char *line) +unsigned int check_cmd_help(const char *line) { unsigned int i; - unsigned len = (line!=NULL)?strlen(line):0; - unsigned status = 0, tlen; + unsigned len = (line != NULL) ? strlen(line) : 0; + unsigned int status = 0, tlen; while (len > 0 && (line[len - 1] == '?' || whitespace(line[len - 1]))) len--; @@ -167,8 +169,7 @@ unsigned check_cmd_help(const char *line) return status; } -static -void usage(void) +static void usage(void) { printf("occtl: [OPTIONS...] {COMMAND}\n\n"); printf(" -s --socket-file Specify the server's occtl socket file\n"); @@ -181,18 +182,16 @@ void usage(void) printf("\n"); } -static -void version(void) +static void version(void) { - fprintf(stderr, - "OpenConnect server control (occtl) version %s\n", VERSION); + fprintf(stderr, "OpenConnect server control (occtl) version %s\n", + VERSION); fprintf(stderr, "Copyright (C) 2014-2017 Red Hat and others.\n"); fprintf(stderr, "ocserv comes with ABSOLUTELY NO WARRANTY. This is free software,\n"); fprintf(stderr, "and you are welcome to redistribute it under the conditions of the\n"); - fprintf(stderr, - "GNU General Public License version 2.\n"); + fprintf(stderr, "GNU General Public License version 2.\n"); fprintf(stderr, "\nFor help type ? or 'help'\n"); fprintf(stderr, "==================================================================\n"); @@ -217,47 +216,50 @@ static char *rl_gets(char *line_read) return line_read; } -void -bytes2human(unsigned long bytes, char* output, unsigned output_size, const char* suffix) +void bytes2human(unsigned long bytes, char *output, unsigned int output_size, + const char *suffix) { -double data; + double data; if (suffix == NULL) suffix = ""; if (bytes > 1000 && bytes < 1000 * 1000) { - data = ((double) bytes) / 1000; + data = ((double)bytes) / 1000; snprintf(output, output_size, "%.1f kB%s", data, suffix); } else if (bytes >= 1000 * 1000 && bytes < 1000 * 1000 * 1000) { - data = ((double) bytes) / (1000 * 1000); + data = ((double)bytes) / (1000 * 1000); snprintf(output, output_size, "%.1f MB%s", data, suffix); } else if (bytes >= 1000 * 1000 * 1000) { - data = ((double) bytes) / (1000 * 1000 * 1000); + data = ((double)bytes) / (1000 * 1000 * 1000); snprintf(output, output_size, "%.1f GB%s", data, suffix); } else { snprintf(output, output_size, "%lu bytes%s", bytes, suffix); } } -void -time2human(uint64_t microseconds, char* output, unsigned output_size) +void time2human(uint64_t microseconds, char *output, unsigned int output_size) { if (microseconds < 1000) { snprintf(output, output_size, "<1ms"); } else if (microseconds < 1000000) { - snprintf(output, output_size, "%" PRIu64 "ms", microseconds / 1000); + snprintf(output, output_size, "%" PRIu64 "ms", + microseconds / 1000); } else { - snprintf(output, output_size, "%" PRIu64 "s", microseconds / 1000000); + snprintf(output, output_size, "%" PRIu64 "s", + microseconds / 1000000); } } -static int handle_help_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params) +static int handle_help_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params) { print_commands(1); return 0; } -static int handle_reset_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params) +static int handle_reset_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params) { rl_reset_terminal(NULL); #ifdef HAVE_ORIG_READLINE @@ -267,7 +269,8 @@ static int handle_reset_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *pa return 0; } -static int handle_exit_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params) +static int handle_exit_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params) { exit(EXIT_SUCCESS); } @@ -275,14 +278,13 @@ static int handle_exit_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *par /* checks whether an input command of type " list users" matches * the given cmd (e.g., "list users"). If yes it executes func() and returns true. */ -static -unsigned check_cmd(const char *cmd, const char *input, - CONN_TYPE * conn, int need_preconn, cmd_func func, int *status, - cmd_params_st *params) +static unsigned int check_cmd(const char *cmd, const char *input, + CONN_TYPE *conn, int need_preconn, cmd_func func, + int *status, cmd_params_st *params) { char *t, *p; - unsigned len, tlen; - unsigned i, ret = 0; + unsigned int len, tlen; + unsigned int i, ret = 0; char prev; while (whitespace(*input)) @@ -310,7 +312,8 @@ unsigned check_cmd(const char *cmd, const char *input, if (len == 0) goto cleanup; - if (tlen >= len && strncasecmp(cmd, t, len) == 0 && cmd[len] == 0) { /* match */ + if (tlen >= len && strncasecmp(cmd, t, len) == 0 && + cmd[len] == 0) { /* match */ p = t + len; while (whitespace(*p)) p++; @@ -331,7 +334,7 @@ unsigned check_cmd(const char *cmd, const char *input, conn_posthandle(conn); } - cleanup: +cleanup: talloc_free(t); return ret; @@ -341,7 +344,8 @@ char *stripwhite(char *string) { register char *s, *t; - for (s = string; whitespace(*s); s++) ; + for (s = string; whitespace(*s); s++) + ; if (*s == 0) return (s); @@ -354,8 +358,7 @@ char *stripwhite(char *string) return s; } -static -int handle_cmd(CONN_TYPE * conn, char *line, cmd_params_st *params) +static int handle_cmd(CONN_TYPE *conn, char *line, cmd_params_st *params) { char *cline; unsigned int i; @@ -370,17 +373,15 @@ int handle_cmd(CONN_TYPE * conn, char *line, cmd_params_st *params) if (commands[i].name == NULL) goto error; - if (check_cmd - (commands[i].name, cline, conn, - commands[i].need_preconn, - commands[i].func, - &status, params) != 0) + if (check_cmd(commands[i].name, cline, conn, + commands[i].need_preconn, commands[i].func, + &status, params) != 0) break; } return status; - error: +error: if (check_cmd_help(line) == 0) { fprintf(stderr, "unknown command: %s\n", line); fprintf(stderr, @@ -394,9 +395,9 @@ int handle_cmd(CONN_TYPE * conn, char *line, cmd_params_st *params) */ static char *merge_args(int argc, char **argv) { - unsigned size = 0; + unsigned int size = 0; char *data, *p; - unsigned i, len; + unsigned int i, len; for (i = 1; i < argc; i++) { size += strlen(argv[i]) + 1; @@ -423,12 +424,12 @@ static char *merge_args(int argc, char **argv) return data; } -static unsigned int cmd_start = 0; +static unsigned int cmd_start; static char *command_generator(const char *text, int state) { static int list_index, len; static int entries_idx; - unsigned name_size; + unsigned int name_size; char *name, *arg; char *ret; @@ -450,35 +451,29 @@ static char *command_generator(const char *text, int state) if (cmd_start > name_size) { /* check for user or ID options */ if (rl_line_buffer != NULL && - strncasecmp(rl_line_buffer, name, name_size) == 0 - && + strncasecmp(rl_line_buffer, name, name_size) == 0 && /* make sure only one argument is appended */ rl_line_buffer[name_size] != 0 && - strchr(&rl_line_buffer[name_size + 1], - ' ') == NULL) { - + strchr(&rl_line_buffer[name_size + 1], ' ') == + NULL) { if (arg != NULL) { ret = NULL; if (strcmp(arg, "[NAME]") == 0) - ret = - search_for_user(entries_idx, - text, len); + ret = search_for_user( + entries_idx, text, len); else if (strcmp(arg, "[ID]") == 0) - ret = - search_for_id(entries_idx, - text, len); + ret = search_for_id(entries_idx, + text, len); else if (strcmp(arg, "[IP]") == 0) - ret = - search_for_ip(entries_idx, - text, len); + ret = search_for_ip(entries_idx, + text, len); else if (strcmp(arg, "[SID]") == 0) - ret = - search_for_session(entries_idx, - text, len); + ret = search_for_session( + entries_idx, text, len); if (ret != NULL) { entries_idx++; } - list_index--; /* restart at the same cmd */ + list_index--; /* restart at the same cmd */ return ret; } } @@ -489,8 +484,8 @@ static char *command_generator(const char *text, int state) if (cmd_start > 0 && name[cmd_start - 1] != ' ') continue; - if (rl_line_buffer != NULL - && strncasecmp(rl_line_buffer, name, cmd_start) != 0) + if (rl_line_buffer != NULL && + strncasecmp(rl_line_buffer, name, cmd_start) != 0) continue; name += cmd_start; @@ -530,7 +525,8 @@ void initialize_readline(void) ocsignal(SIGINT, handle_sigint); } -static int single_cmd(int argc, char **argv, void *pool, const char *file, cmd_params_st *params) +static int single_cmd(int argc, char **argv, void *pool, const char *file, + cmd_params_st *params) { CONN_TYPE *conn; char *line; @@ -545,7 +541,6 @@ static int single_cmd(int argc, char **argv, void *pool, const char *file, cmd_p return ret; } - int main(int argc, char **argv) { char *line = NULL; @@ -573,14 +568,14 @@ int main(int argc, char **argv) if (argc > 1) { while (argc > 1 && argv[1][0] == '-') { - if (argv[1][1] == 'j' - || (argv[1][1] == '-' && argv[1][2] == 'j')) { + if (argv[1][1] == 'j' || + (argv[1][1] == '-' && argv[1][2] == 'j')) { params.json = 1; argv += 1; argc -= 1; - } else if (argv[1][1] == 'n' - || (argv[1][1] == '-' && argv[1][2] == 'n')) { + } else if (argv[1][1] == 'n' || + (argv[1][1] == '-' && argv[1][2] == 'n')) { params.no_pager = 1; argv += 1; @@ -595,12 +590,13 @@ int main(int argc, char **argv) params.json = 0; goto interactive; } - } else if (argv[1][1] == 'v' - || (argv[1][1] == '-' && argv[1][2] == 'v')) { + } else if (argv[1][1] == 'v' || + (argv[1][1] == '-' && argv[1][2] == 'v')) { version(); exit(EXIT_SUCCESS); - } else if (argc > 2 && (argv[1][1] == 's' - || (argv[1][1] == '-' && argv[1][2] == 's'))) { + } else if (argc > 2 && + (argv[1][1] == 's' || + (argv[1][1] == '-' && argv[1][2] == 's'))) { file = talloc_strdup(gl_pool, argv[2]); if (argc == 3) { @@ -622,7 +618,7 @@ int main(int argc, char **argv) exit(ret); } - interactive: +interactive: conn = conn_init(gl_pool, file); initialize_readline(); diff --git a/src/occtl/occtl.h b/src/occtl/occtl.h index c57783ed..f96c9311 100644 --- a/src/occtl/occtl.h +++ b/src/occtl/occtl.h @@ -1,15 +1,15 @@ #ifndef OCCTL_H -# define OCCTL_H +#define OCCTL_H #include #include #include "common.h" #ifdef HAVE_ORIG_READLINE -# include -# include +#include +#include #else -# include +#include #endif #define DATE_TIME_FMT "%Y-%m-%d %H:%M" @@ -19,87 +19,110 @@ #define HAVE_JSON(params) (params && params->json) typedef struct cmd_params_st { - unsigned json; - unsigned no_pager; - unsigned debug; + unsigned int json; + unsigned int no_pager; + unsigned int debug; } cmd_params_st; -FILE* pager_start(cmd_params_st *params); -void pager_stop(FILE* fp); +FILE *pager_start(cmd_params_st *params); +void pager_stop(FILE *fp); void print_time_ival7(char output[MAX_TMPSTR_SIZE], time_t t1, time_t t2); -void print_iface_stats(const char *iface, time_t since, FILE * out, cmd_params_st *params, unsigned have_more); -int print_list_entries(FILE* out, cmd_params_st *params, const char* name, char **val, unsigned vsize, unsigned have_more); -int print_fwport_entries(FILE* out, cmd_params_st *params, const char* name, FwPortSt **val, unsigned vsize, unsigned have_more); +void print_iface_stats(const char *iface, time_t since, FILE *out, + cmd_params_st *params, unsigned int have_more); +int print_list_entries(FILE *out, cmd_params_st *params, const char *name, + char **val, unsigned int vsize, unsigned int have_more); +int print_fwport_entries(FILE *out, cmd_params_st *params, const char *name, + FwPortSt **val, unsigned int vsize, + unsigned int have_more); void print_start_block(FILE *out, cmd_params_st *params); -void print_end_block(FILE *out, cmd_params_st *params, unsigned have_more); +void print_end_block(FILE *out, cmd_params_st *params, unsigned int have_more); void print_array_block(FILE *out, cmd_params_st *params); void print_end_array_block(FILE *out, cmd_params_st *params); void print_separator(FILE *out, cmd_params_st *params); -void print_single_value(FILE *out, cmd_params_st *params, const char *name, const char *value, unsigned have_more); -void print_single_value_int(FILE *out, cmd_params_st *params, const char *name, long i, unsigned have_more); -void print_single_value_ex(FILE *out, cmd_params_st *params, const char *name, const char *value, const char *ex, unsigned have_more); -void print_pair_value(FILE *out, cmd_params_st *params, const char *name1, const char *value1, const char *name2, const char *value2, unsigned have_more); +void print_single_value(FILE *out, cmd_params_st *params, const char *name, + const char *value, unsigned int have_more); +void print_single_value_int(FILE *out, cmd_params_st *params, const char *name, + long i, unsigned int have_more); +void print_single_value_ex(FILE *out, cmd_params_st *params, const char *name, + const char *value, const char *ex, + unsigned int have_more); +void print_pair_value(FILE *out, cmd_params_st *params, const char *name1, + const char *value1, const char *name2, const char *value2, + unsigned int have_more); +void bytes2human(unsigned long bytes, char *output, unsigned int output_size, + const char *suffix); -void -bytes2human(unsigned long bytes, char* output, unsigned output_size, const char* suffix); +void time2human(uint64_t microseconds, char *output, unsigned int output_size); -void -time2human(uint64_t microseconds, char* output, unsigned output_size); - -char* search_for_id(unsigned idx, const char* match, int match_size); -char* search_for_user(unsigned idx, const char* match, int match_size); -void entries_add(void *pool, const char* user, unsigned user_size, unsigned id); +char *search_for_id(unsigned int idx, const char *match, int match_size); +char *search_for_user(unsigned int idx, const char *match, int match_size); +void entries_add(void *pool, const char *user, unsigned int user_size, + unsigned int id); void entries_clear(void); -void session_entries_add(void *pool, const char* session); +void session_entries_add(void *pool, const char *session); void session_entries_clear(void); -char* search_for_session(unsigned idx, const char* match, int match_size); +char *search_for_session(unsigned int idx, const char *match, int match_size); -char* search_for_ip(unsigned idx, const char* match, int match_size); -void ip_entries_add(void *pool, const char* ip, unsigned ip_size); +char *search_for_ip(unsigned int idx, const char *match, int match_size); +void ip_entries_add(void *pool, const char *ip, unsigned int ip_size); void ip_entries_clear(void); -#define DEFAULT_TIMEOUT (10*1000) +#define DEFAULT_TIMEOUT (10 * 1000) #define NO_GROUP "(none)" #define NO_USER "(none)" -#define ERR_SERVER_UNREACHABLE "could not send message; possibly insufficient permissions or server is offline.\n" +#define ERR_SERVER_UNREACHABLE \ + "could not send message; possibly insufficient permissions or server is offline.\n" -unsigned need_help(const char *arg); -unsigned check_cmd_help(const char *line); +unsigned int need_help(const char *arg); +unsigned int check_cmd_help(const char *line); #ifdef HAVE_DBUS -# include -# define CONN_TYPE struct dbus_ctx +#include +#define CONN_TYPE struct dbus_ctx #else -# define CONN_TYPE struct unix_ctx +#define CONN_TYPE struct unix_ctx #endif CONN_TYPE *conn_init(void *pool, const char *socket_file); -void conn_close(CONN_TYPE*); +void conn_close(CONN_TYPE *); int conn_prehandle(CONN_TYPE *ctx); void conn_posthandle(CONN_TYPE *ctx); -typedef int (*cmd_func) (CONN_TYPE * conn, const char *arg, cmd_params_st *params); +typedef int (*cmd_func)(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); -int handle_status_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_list_users_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_list_iroutes_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_list_banned_ips_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_list_all_sessions_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_list_valid_sessions_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_show_session_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); +int handle_status_cmd(CONN_TYPE *conn, const char *arg, cmd_params_st *params); +int handle_list_users_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_list_iroutes_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_list_banned_ips_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_list_all_sessions_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_list_valid_sessions_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_show_session_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); -int handle_list_banned_points_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_show_user_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_show_id_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_disconnect_user_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_unban_ip_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_disconnect_id_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_reload_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_stop_cmd(CONN_TYPE * conn, const char *arg, cmd_params_st *params); -int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params); +int handle_list_banned_points_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_show_user_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_show_id_cmd(CONN_TYPE *conn, const char *arg, cmd_params_st *params); +int handle_disconnect_user_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_unban_ip_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_disconnect_id_cmd(CONN_TYPE *conn, const char *arg, + cmd_params_st *params); +int handle_reload_cmd(CONN_TYPE *conn, const char *arg, cmd_params_st *params); +int handle_stop_cmd(CONN_TYPE *conn, const char *arg, cmd_params_st *params); +int handle_events_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params); #endif diff --git a/src/occtl/pager.c b/src/occtl/pager.c index db7be5ce..13682dc4 100644 --- a/src/occtl/pager.c +++ b/src/occtl/pager.c @@ -26,9 +26,9 @@ #include #include -static const char* get_pager(void) +static const char *get_pager(void) { - char* pager; + char *pager; pager = getenv("OCCTL_PAGER"); if (pager == NULL) @@ -40,7 +40,7 @@ static const char* get_pager(void) } /* Always succeeds */ -FILE* pager_start(cmd_params_st *params) +FILE *pager_start(cmd_params_st *params) { FILE *fp; const char *pager; @@ -64,14 +64,15 @@ FILE* pager_start(cmd_params_st *params) fp = popen(pager, "w"); if (fp == NULL) { /* no pager */ - fprintf(stderr, "unable to start pager; check your $PAGER environment variable\n"); + fprintf(stderr, + "unable to start pager; check your $PAGER environment variable\n"); fp = stdout; } return fp; } -void pager_stop(FILE* fp) +void pager_stop(FILE *fp) { if (fp != stdout) pclose(fp); diff --git a/src/occtl/print.c b/src/occtl/print.c index 5b1a14b9..ae68e039 100644 --- a/src/occtl/print.c +++ b/src/occtl/print.c @@ -36,28 +36,29 @@ #define escape_val json_escape_val -int print_list_entries(FILE* out, cmd_params_st *params, const char* name, char **val, unsigned vsize, unsigned have_more) +int print_list_entries(FILE *out, cmd_params_st *params, const char *name, + char **val, unsigned int vsize, unsigned int have_more) { - const char * tmp; + const char *tmp; unsigned int i = 0; if (HAVE_JSON(params)) { fprintf(out, " \"%s\":\t[", name); - for (i=0;iport) - snprintf(tmp, sizeof(tmp), "%s%s(%d)", val[i]->negate?"!":"", proto_to_str(val[i]->proto), val[i]->port); + snprintf(tmp, sizeof(tmp), "%s%s(%d)", + val[i]->negate ? "!" : "", + proto_to_str(val[i]->proto), + val[i]->port); else - snprintf(tmp, sizeof(tmp), "%s%s()", val[i]->negate?"!":"", proto_to_str(val[i]->proto)); + snprintf(tmp, sizeof(tmp), "%s%s()", + val[i]->negate ? "!" : "", + proto_to_str(val[i]->proto)); - if (i==0) + if (i == 0) fprintf(out, "\"%s\"", tmp); else fprintf(out, ", \"%s\"", tmp); } - fprintf(out, "]%s\n", have_more?",":""); + fprintf(out, "]%s\n", have_more ? "," : ""); } else { - for (i=0;iport) - snprintf(tmp, sizeof(tmp), "%s%s(%d)", val[i]->negate?"!":"", proto_to_str(val[i]->proto), val[i]->port); + snprintf(tmp, sizeof(tmp), "%s%s(%d)", + val[i]->negate ? "!" : "", + proto_to_str(val[i]->proto), + val[i]->port); else - snprintf(tmp, sizeof(tmp), "%s%s()", val[i]->negate?"!":"", proto_to_str(val[i]->proto)); - if (i==0) + snprintf(tmp, sizeof(tmp), "%s%s()", + val[i]->negate ? "!" : "", + proto_to_str(val[i]->proto)); + if (i == 0) fprintf(out, "\t%s: %s", name, tmp); else fprintf(out, ", %s", tmp); @@ -110,10 +123,10 @@ void print_start_block(FILE *out, cmd_params_st *params) fprintf(out, " {\n"); } -void print_end_block(FILE *out, cmd_params_st *params, unsigned have_more) +void print_end_block(FILE *out, cmd_params_st *params, unsigned int have_more) { if (HAVE_JSON(params)) - fprintf(out, " }%s\n", have_more?",":""); + fprintf(out, " }%s\n", have_more ? "," : ""); } void print_array_block(FILE *out, cmd_params_st *params) @@ -134,53 +147,72 @@ void print_separator(FILE *out, cmd_params_st *params) fprintf(out, "\n"); } -void print_single_value(FILE *out, cmd_params_st *params, const char *name, const char *value, unsigned have_more) +void print_single_value(FILE *out, cmd_params_st *params, const char *name, + const char *value, unsigned int have_more) { char tmp[MAX_STR_SIZE]; + if (value[0] == 0) return; if (HAVE_JSON(params)) - fprintf(out, " \"%s\": \"%s\"%s\n", name, escape_val(tmp, sizeof(tmp), value), have_more?",":""); + fprintf(out, " \"%s\": \"%s\"%s\n", name, + escape_val(tmp, sizeof(tmp), value), + have_more ? "," : ""); else fprintf(out, "\t%s: %s\n", name, value); } -void print_single_value_int(FILE *out, cmd_params_st *params, const char *name, long i, unsigned have_more) +void print_single_value_int(FILE *out, cmd_params_st *params, const char *name, + long i, unsigned int have_more) { if (HAVE_JSON(params)) - fprintf(out, " \"%s\": \%lu%s\n", name, i, have_more?",":""); + fprintf(out, " \"%s\": \%lu%s\n", name, i, + have_more ? "," : ""); else fprintf(out, "\t%s: %lu\n", name, i); } -void print_single_value_ex(FILE *out, cmd_params_st *params, const char *name, const char *value, const char *ex, unsigned have_more) +void print_single_value_ex(FILE *out, cmd_params_st *params, const char *name, + const char *value, const char *ex, + unsigned int have_more) { char tmp[MAX_STR_SIZE]; + if (value[0] == 0) return; if (HAVE_JSON(params)) { - fprintf(out, " \"%s\": \"%s\",\n", name, escape_val(tmp, sizeof(tmp), value)); - fprintf(out, " \"_%s\": \"%s\"%s\n", name, escape_val(tmp, sizeof(tmp), ex), have_more?",":""); + fprintf(out, " \"%s\": \"%s\",\n", name, + escape_val(tmp, sizeof(tmp), value)); + fprintf(out, " \"_%s\": \"%s\"%s\n", name, + escape_val(tmp, sizeof(tmp), ex), have_more ? "," : ""); } else fprintf(out, "\t%s: %s (%s)\n", name, value, ex); } -void print_pair_value(FILE *out, cmd_params_st *params, const char *name1, const char *value1, const char *name2, const char *value2, unsigned have_more) +void print_pair_value(FILE *out, cmd_params_st *params, const char *name1, + const char *value1, const char *name2, const char *value2, + unsigned int have_more) { char tmp[MAX_STR_SIZE]; + if (HAVE_JSON(params)) { if (value1 && value1[0] != 0) - fprintf(out, " \"%s\": \"%s\"%s\n", name1, escape_val(tmp, sizeof(tmp), value1), have_more?",":""); + fprintf(out, " \"%s\": \"%s\"%s\n", name1, + escape_val(tmp, sizeof(tmp), value1), + have_more ? "," : ""); if (value2 && value2[0] != 0) - fprintf(out, " \"%s\": \"%s\"%s\n", name2, escape_val(tmp, sizeof(tmp), value2), have_more?",":""); + fprintf(out, " \"%s\": \"%s\"%s\n", name2, + escape_val(tmp, sizeof(tmp), value2), + have_more ? "," : ""); } else { if (value1 && value1[0] != 0) fprintf(out, "\t%s: %s", name1, value1); if (value2 && value2[0] != 0) { const char *sep; + if (name1) sep = " "; else diff --git a/src/occtl/session-cache.c b/src/occtl/session-cache.c index 2b12446a..5480d3b4 100644 --- a/src/occtl/session-cache.c +++ b/src/occtl/session-cache.c @@ -30,35 +30,39 @@ typedef struct session_entries_st { char session[SAFE_ID_SIZE]; } session_entries_st; -static session_entries_st *session_entries = NULL; -static unsigned session_entries_size = 0; -static unsigned max_session_entries_size = 0; +static session_entries_st *session_entries; +static unsigned int session_entries_size; +static unsigned int max_session_entries_size; void session_entries_clear(void) { session_entries_size = 0; } -void session_entries_add(void *pool, const char* session) +void session_entries_add(void *pool, const char *session) { - if (session_entries_size+1 > max_session_entries_size) { + if (session_entries_size + 1 > max_session_entries_size) { max_session_entries_size += 128; - session_entries = talloc_realloc_size(pool, session_entries, sizeof(session_entries_st)*max_session_entries_size); + session_entries = talloc_realloc_size( + pool, session_entries, + sizeof(session_entries_st) * max_session_entries_size); } - strlcpy(session_entries[session_entries_size].session, session, sizeof(session_entries[session_entries_size].session)); + strlcpy(session_entries[session_entries_size].session, session, + sizeof(session_entries[session_entries_size].session)); session_entries_size++; } -char* search_for_session(unsigned idx, const char* match, int match_size) +char *search_for_session(unsigned int idx, const char *match, int match_size) { -unsigned i; + unsigned int i; if (idx >= session_entries_size) return NULL; - for (i=idx;i= 48 * 60 * 60) /* 2 days or more */ - snprintf(output, MAX_TMPSTR_SIZE, _("%2ludays"), (long)t / (24 * 60 * 60)); + snprintf(output, MAX_TMPSTR_SIZE, _("%2ludays"), + (long)t / (24 * 60 * 60)); else if (t >= 60 * 60) /* 1 hour or more */ - /* Translation Hint: Hours:Minutes */ - snprintf(output, MAX_TMPSTR_SIZE, _("%2luh:%02um"), (long)t / (60 * 60), - (unsigned)((t / 60) % 60)); + /* Translation Hint: Hours:Minutes */ + snprintf(output, MAX_TMPSTR_SIZE, _("%2luh:%02um"), + (long)t / (60 * 60), (unsigned int)((t / 60) % 60)); else if (t > 60) /* 1 minute or more */ - /* Translation Hint: Minutes:Seconds */ - snprintf(output, MAX_TMPSTR_SIZE, "%2lum:%02us", (long)t / 60, (unsigned)t % 60); + /* Translation Hint: Minutes:Seconds */ + snprintf(output, MAX_TMPSTR_SIZE, "%2lum:%02us", (long)t / 60, + (unsigned int)t % 60); else - /* Translation Hint: Seconds:Centiseconds */ + /* Translation Hint: Seconds:Centiseconds */ snprintf(output, MAX_TMPSTR_SIZE, _("%5lus"), (long)t); } diff --git a/src/occtl/unix.c b/src/occtl/unix.c index 935c5c10..df0fbea6 100644 --- a/src/occtl/unix.c +++ b/src/occtl/unix.c @@ -52,12 +52,10 @@ */ #undef OCSERV_0_11_6_COMPAT -static -int common_info_cmd(UserListRep *args, FILE *out, cmd_params_st *params); -static -int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, - cmd_params_st *params, - const char *lsid, unsigned all); +static int common_info_cmd(UserListRep *args, FILE *out, cmd_params_st *params); +static int session_info_cmd(void *ctx, SecmListCookiesReplyMsg *args, FILE *out, + cmd_params_st *params, const char *lsid, + unsigned int all); struct unix_ctx { int fd; @@ -66,24 +64,24 @@ struct unix_ctx { }; static uint8_t msg_map[] = { - [CTL_CMD_STATUS] = CTL_CMD_STATUS_REP, - [CTL_CMD_RELOAD] = CTL_CMD_RELOAD_REP, - [CTL_CMD_STOP] = CTL_CMD_STOP_REP, - [CTL_CMD_LIST] = CTL_CMD_LIST_REP, - [CTL_CMD_LIST_COOKIES] = CTL_CMD_LIST_COOKIES_REP, - [CTL_CMD_LIST_BANNED] = CTL_CMD_LIST_BANNED_REP, - [CTL_CMD_USER_INFO] = CTL_CMD_LIST_REP, - [CTL_CMD_TOP] = CTL_CMD_LIST_REP, - [CTL_CMD_ID_INFO] = CTL_CMD_LIST_REP, - [CTL_CMD_DISCONNECT_NAME] = CTL_CMD_DISCONNECT_NAME_REP, - [CTL_CMD_DISCONNECT_ID] = CTL_CMD_DISCONNECT_ID_REP, - [CTL_CMD_UNBAN_IP] = CTL_CMD_UNBAN_IP_REP, + [CTL_CMD_STATUS] = CTL_CMD_STATUS_REP, + [CTL_CMD_RELOAD] = CTL_CMD_RELOAD_REP, + [CTL_CMD_STOP] = CTL_CMD_STOP_REP, + [CTL_CMD_LIST] = CTL_CMD_LIST_REP, + [CTL_CMD_LIST_COOKIES] = CTL_CMD_LIST_COOKIES_REP, + [CTL_CMD_LIST_BANNED] = CTL_CMD_LIST_BANNED_REP, + [CTL_CMD_USER_INFO] = CTL_CMD_LIST_REP, + [CTL_CMD_TOP] = CTL_CMD_LIST_REP, + [CTL_CMD_ID_INFO] = CTL_CMD_LIST_REP, + [CTL_CMD_DISCONNECT_NAME] = CTL_CMD_DISCONNECT_NAME_REP, + [CTL_CMD_DISCONNECT_ID] = CTL_CMD_DISCONNECT_ID_REP, + [CTL_CMD_UNBAN_IP] = CTL_CMD_UNBAN_IP_REP, }; struct cmd_reply_st { - unsigned cmd; + unsigned int cmd; uint8_t *data; - unsigned data_size; + unsigned int data_size; }; static void free_reply(struct cmd_reply_st *rep) @@ -98,10 +96,9 @@ static void init_reply(struct cmd_reply_st *rep) } /* sends a message and returns the reply */ -static -int send_cmd(struct unix_ctx *ctx, unsigned cmd, const void *data, - pack_size_func get_size, pack_func pack, - struct cmd_reply_st *rep) +static int send_cmd(struct unix_ctx *ctx, unsigned int cmd, const void *data, + pack_size_func get_size, pack_func pack, + struct cmd_reply_st *rep) { int e, ret; uint32_t length32 = 0; @@ -129,7 +126,9 @@ int send_cmd(struct unix_ctx *ctx, unsigned cmd, const void *data, length32 = ret; if (msg_map[cmd] != rep->cmd) { - fprintf(stderr, "Unexpected message '%d', expected '%d'\n", (int)rep->cmd, (int)msg_map[cmd]); + fprintf(stderr, + "Unexpected message '%d', expected '%d'\n", + (int)rep->cmd, (int)msg_map[cmd]); ret = -1; goto fail; } @@ -142,7 +141,8 @@ int send_cmd(struct unix_ctx *ctx, unsigned cmd, const void *data, goto fail; } - ret = force_read_timeout(ctx->fd, rep->data, length32, DEFAULT_TIMEOUT); + ret = force_read_timeout(ctx->fd, rep->data, length32, + DEFAULT_TIMEOUT); if (ret == -1) { e = errno; talloc_free(rep->data); @@ -154,13 +154,12 @@ int send_cmd(struct unix_ctx *ctx, unsigned cmd, const void *data, } ret = 0; - fail: +fail: talloc_free(packed); return ret; } -static -int connect_to_ocserv (const char *socket_file) +static int connect_to_ocserv(const char *socket_file) { int sd, ret, e; struct sockaddr_un sa; @@ -192,10 +191,10 @@ int connect_to_ocserv (const char *socket_file) error: close(sd); return ret; - } -int handle_status_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_status_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; @@ -204,6 +203,7 @@ int handle_status_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para char buf[MAX_TMPSTR_SIZE]; time_t t; struct tm *tm, _tm; + PROTOBUF_ALLOCATOR(pa, ctx); init_reply(&raw); @@ -223,52 +223,81 @@ int handle_status_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para if (rep == NULL) goto error_status; - if (rep->status) { print_separator(stdout, params); if (NO_JSON(params)) printf("General info:\n"); - print_single_value(stdout, params, "Status", rep->status != 0 ? "online" : "error", 1); - print_single_value_int(stdout, params, "Server PID", rep->pid, 1); - print_single_value_int(stdout, params, "Sec-mod PID", rep->sec_mod_pids[0], 1); - print_single_value_int(stdout, params, "Sec-mod instance count", rep->n_sec_mod_pids, 1); + print_single_value(stdout, params, "Status", + rep->status != 0 ? "online" : "error", 1); + print_single_value_int(stdout, params, "Server PID", rep->pid, + 1); + print_single_value_int(stdout, params, "Sec-mod PID", + rep->sec_mod_pids[0], 1); + print_single_value_int(stdout, params, "Sec-mod instance count", + rep->n_sec_mod_pids, 1); t = rep->start_time; tm = localtime_r(&t, &_tm); print_time_ival7(buf, time(NULL), t); strftime(str_since, sizeof(str_since), DATE_TIME_FMT, tm); - print_single_value_ex(stdout, params, "Up since", str_since, buf, 1); + print_single_value_ex(stdout, params, "Up since", str_since, + buf, 1); if (HAVE_JSON(params)) { - print_single_value_int(stdout, params, "raw_up_since", rep->start_time, 1); - print_single_value_int(stdout, params, "uptime", ((long)time(NULL)) - ((long)rep->start_time), 1); + print_single_value_int(stdout, params, "raw_up_since", + rep->start_time, 1); + print_single_value_int(stdout, params, "uptime", + ((long)time(NULL)) - + ((long)rep->start_time), + 1); } - print_single_value_int(stdout, params, "Active sessions", rep->active_clients, 1); - print_single_value_int(stdout, params, "Total sessions", rep->total_sessions_closed, 1); - print_single_value_int(stdout, params, "Total authentication failures", rep->total_auth_failures, 1); - print_single_value_int(stdout, params, "IPs in ban list", rep->banned_ips, 1); + print_single_value_int(stdout, params, "Active sessions", + rep->active_clients, 1); + print_single_value_int(stdout, params, "Total sessions", + rep->total_sessions_closed, 1); + print_single_value_int(stdout, params, + "Total authentication failures", + rep->total_auth_failures, 1); + print_single_value_int(stdout, params, "IPs in ban list", + rep->banned_ips, 1); if (params && params->debug) { - print_single_value_int(stdout, params, "Sec-mod client entries", rep->secmod_client_entries, 1); - print_single_value_int(stdout, params, "TLS DB entries", rep->stored_tls_sessions, 1); + print_single_value_int(stdout, params, + "Sec-mod client entries", + rep->secmod_client_entries, 1); + print_single_value_int(stdout, params, "TLS DB entries", + rep->stored_tls_sessions, 1); } #if defined(CAPTURE_LATENCY_SUPPORT) if (rep->has_latency_sample_count) { - unsigned int median_latency = (unsigned int)(rep->latency_sample_count ? rep->latency_median_total / rep->latency_sample_count : 0); - unsigned int stdev_latency = (unsigned int)(rep->latency_sample_count ? rep->latency_rms_total / rep->latency_sample_count : 0); + unsigned int median_latency = + (unsigned int)(rep->latency_sample_count ? + rep->latency_median_total / + rep->latency_sample_count : + 0); + unsigned int stdev_latency = + (unsigned int)(rep->latency_sample_count ? + rep->latency_rms_total / + rep->latency_sample_count : + 0); time2human(median_latency, buf, sizeof(buf)); - print_single_value(stdout, params, "Median latency", buf, 1); + print_single_value(stdout, params, "Median latency", + buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_median_latency", median_latency, 1); + print_single_value_int(stdout, params, + "raw_median_latency", + median_latency, 1); time2human(stdev_latency, buf, sizeof(buf)); - print_single_value(stdout, params, "STDEV latency", buf, 1); + print_single_value(stdout, params, "STDEV latency", buf, + 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_stdev_latency", stdev_latency, 1); - + print_single_value_int(stdout, params, + "raw_stdev_latency", + stdev_latency, 1); } #endif @@ -280,52 +309,78 @@ int handle_status_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para if (t > 0) { tm = localtime_r(&t, &_tm); print_time_ival7(buf, time(NULL), t); - strftime(str_since, sizeof(str_since), DATE_TIME_FMT, tm); + strftime(str_since, sizeof(str_since), DATE_TIME_FMT, + tm); - print_single_value_ex(stdout, params, "Last stats reset", str_since, buf, 1); + print_single_value_ex(stdout, params, + "Last stats reset", str_since, + buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_last_stats_reset", rep->last_reset, 1); + print_single_value_int(stdout, params, + "raw_last_stats_reset", + rep->last_reset, 1); } - print_single_value_int(stdout, params, "Sessions handled", rep->sessions_closed, 1); - print_single_value_int(stdout, params, "Timed out sessions", rep->session_timeouts, 1); - print_single_value_int(stdout, params, "Timed out (idle) sessions", rep->session_idle_timeouts, 1); - print_single_value_int(stdout, params, "Closed due to error sessions", rep->session_errors, 1); - print_single_value_int(stdout, params, "Authentication failures", rep->auth_failures, 1); + print_single_value_int(stdout, params, "Sessions handled", + rep->sessions_closed, 1); + print_single_value_int(stdout, params, "Timed out sessions", + rep->session_timeouts, 1); + print_single_value_int(stdout, params, + "Timed out (idle) sessions", + rep->session_idle_timeouts, 1); + print_single_value_int(stdout, params, + "Closed due to error sessions", + rep->session_errors, 1); + print_single_value_int(stdout, params, + "Authentication failures", + rep->auth_failures, 1); print_time_ival7(buf, rep->avg_auth_time, 0); print_single_value(stdout, params, "Average auth time", buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_avg_auth_time", rep->avg_auth_time, 1); + print_single_value_int(stdout, params, + "raw_avg_auth_time", + rep->avg_auth_time, 1); print_time_ival7(buf, rep->max_auth_time, 0); print_single_value(stdout, params, "Max auth time", buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_max_auth_time", rep->max_auth_time, 1); + print_single_value_int(stdout, params, + "raw_max_auth_time", + rep->max_auth_time, 1); - print_time_ival7(buf, rep->avg_session_mins*60, 0); - print_single_value(stdout, params, "Average session time", buf, 1); + print_time_ival7(buf, rep->avg_session_mins * 60, 0); + print_single_value(stdout, params, "Average session time", buf, + 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_avg_session_time", rep->avg_session_mins*60, 1); + print_single_value_int(stdout, params, + "raw_avg_session_time", + rep->avg_session_mins * 60, 1); - print_time_ival7(buf, rep->max_session_mins*60, 0); + print_time_ival7(buf, rep->max_session_mins * 60, 0); print_single_value(stdout, params, "Max session time", buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_max_session_time", rep->max_session_mins*60, 1); + print_single_value_int(stdout, params, + "raw_max_session_time", + rep->max_session_mins * 60, 1); if (rep->min_mtu > 0) - print_single_value_int(stdout, params, "Min MTU", rep->min_mtu, 1); + print_single_value_int(stdout, params, "Min MTU", + rep->min_mtu, 1); if (rep->max_mtu > 0) - print_single_value_int(stdout, params, "Max MTU", rep->max_mtu, 1); + print_single_value_int(stdout, params, "Max MTU", + rep->max_mtu, 1); - bytes2human(rep->kbytes_in*1000, buf, sizeof(buf), ""); + bytes2human(rep->kbytes_in * 1000, buf, sizeof(buf), ""); print_single_value(stdout, params, "RX", buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_rx", rep->kbytes_in*1000, 1); - bytes2human(rep->kbytes_out*1000, buf, sizeof(buf), ""); + print_single_value_int(stdout, params, "raw_rx", + rep->kbytes_in * 1000, 1); + bytes2human(rep->kbytes_out * 1000, buf, sizeof(buf), ""); print_single_value(stdout, params, "TX", buf, 1); if (HAVE_JSON(params)) - print_single_value_int(stdout, params, "raw_tx", rep->kbytes_out*1000, 0); + print_single_value_int(stdout, params, "raw_tx", + rep->kbytes_out * 1000, 0); } print_end_block(stdout, params, 0); @@ -335,22 +390,24 @@ int handle_status_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para ret = 0; goto cleanup; - error_status: +error_status: print_single_value(stdout, params, "Status", "offline", 0); print_end_block(stdout, params, 0); ret = 1; - cleanup: +cleanup: free_reply(&raw); return ret; } -int handle_reload_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_reload_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; BoolMsg *rep; - unsigned status; + unsigned int status; + PROTOBUF_ALLOCATOR(pa, ctx); init_reply(&raw); @@ -375,22 +432,24 @@ int handle_reload_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para ret = 0; goto cleanup; - error_status: +error_status: printf("Error scheduling reload\n"); ret = 1; - cleanup: +cleanup: free_reply(&raw); return ret; } -int handle_stop_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_stop_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; BoolMsg *rep; - unsigned status; + unsigned int status; + PROTOBUF_ALLOCATOR(pa, ctx); init_reply(&raw); @@ -415,25 +474,27 @@ int handle_stop_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params ret = 0; goto cleanup; - error_status: +error_status: printf("Error scheduling server stop\n"); ret = 1; goto cleanup; - cleanup: +cleanup: free_reply(&raw); return ret; } -int handle_unban_ip_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_unban_ip_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; BoolMsg *rep; - unsigned status; + unsigned int status; UnbanReq req = UNBAN_REQ__INIT; int af; unsigned char tmp[16]; + PROTOBUF_ALLOCATOR(pa, ctx); if (arg == NULL || need_help(arg)) { @@ -463,8 +524,8 @@ int handle_unban_ip_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *pa } ret = send_cmd(ctx, CTL_CMD_UNBAN_IP, &req, - (pack_size_func)unban_req__get_packed_size, - (pack_func)unban_req__pack, &raw); + (pack_size_func)unban_req__get_packed_size, + (pack_func)unban_req__pack, &raw); if (ret < 0) { goto error; } @@ -486,22 +547,24 @@ int handle_unban_ip_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *pa goto cleanup; - error: +error: fprintf(stderr, ERR_SERVER_UNREACHABLE); ret = 1; - cleanup: +cleanup: free_reply(&raw); return ret; } -int handle_disconnect_user_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_disconnect_user_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; BoolMsg *rep; - unsigned status; + unsigned int status; UsernameReq req = USERNAME_REQ__INIT; + PROTOBUF_ALLOCATOR(pa, ctx); if (arg == NULL || need_help(arg)) { @@ -511,11 +574,11 @@ int handle_disconnect_user_cmd(struct unix_ctx *ctx, const char *arg, cmd_params init_reply(&raw); - req.username = (void*)arg; + req.username = (void *)arg; ret = send_cmd(ctx, CTL_CMD_DISCONNECT_NAME, &req, - (pack_size_func)username_req__get_packed_size, - (pack_func)username_req__pack, &raw); + (pack_size_func)username_req__get_packed_size, + (pack_func)username_req__pack, &raw); if (ret < 0) { goto error; } @@ -537,23 +600,25 @@ int handle_disconnect_user_cmd(struct unix_ctx *ctx, const char *arg, cmd_params goto cleanup; - error: +error: fprintf(stderr, ERR_SERVER_UNREACHABLE); ret = 1; - cleanup: +cleanup: free_reply(&raw); return ret; } -int handle_disconnect_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_disconnect_id_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; BoolMsg *rep; - unsigned status; - unsigned id; + unsigned int status; + unsigned int id; IdReq req = ID_REQ__INIT; + PROTOBUF_ALLOCATOR(pa, ctx); if (arg != NULL) @@ -569,8 +634,8 @@ int handle_disconnect_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_s req.id = id; ret = send_cmd(ctx, CTL_CMD_DISCONNECT_ID, &req, - (pack_size_func)id_req__get_packed_size, - (pack_func)id_req__pack, &raw); + (pack_size_func)id_req__get_packed_size, + (pack_func)id_req__pack, &raw); if (ret < 0) { goto error; } @@ -592,10 +657,10 @@ int handle_disconnect_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_s goto cleanup; - error: +error: fprintf(stderr, ERR_SERVER_UNREACHABLE); ret = 1; - cleanup: +cleanup: free_reply(&raw); return ret; @@ -603,8 +668,10 @@ int handle_disconnect_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_s static const char *fix_ciphersuite(char *txt) { - if (txt != NULL && txt[0] != 0 && strlen(txt) > 16 && strncmp(txt, "(DTLS", 5) == 0) { - if (strncmp(&txt[8], ")-(RSA)-", 8) == 0 || strncmp(&txt[8], ")-(PSK)-", 8) == 0) { + if (txt != NULL && txt[0] != 0 && strlen(txt) > 16 && + strncmp(txt, "(DTLS", 5) == 0) { + if (strncmp(&txt[8], ")-(RSA)-", 8) == 0 || + strncmp(&txt[8], ")-(PSK)-", 8) == 0) { return txt + 16; } else if (strncmp(&txt[8], ")-(ECDHE-RSA)-", 14) == 0) { return txt + 22; @@ -624,9 +691,10 @@ static const char *get_ip(const char *ip1, const char *ip2) return ip2; } -void common_user_list(struct unix_ctx *ctx, UserListRep *rep, FILE *out, cmd_params_st *params) +void common_user_list(struct unix_ctx *ctx, UserListRep *rep, FILE *out, + cmd_params_st *params) { - unsigned i; + unsigned int i; const char *vpn_ip, *username; const char *dtls_ciphersuite; char tmpbuf[MAX_TMPSTR_SIZE]; @@ -636,43 +704,55 @@ void common_user_list(struct unix_ctx *ctx, UserListRep *rep, FILE *out, cmd_par if (HAVE_JSON(params)) { common_info_cmd(rep, out, params); - } else for (i=0;in_user;i++) { - username = rep->user[i]->username; - if (username == NULL || username[0] == 0) - username = NO_USER; + } else + for (i = 0; i < rep->n_user; i++) { + username = rep->user[i]->username; + if (username == NULL || username[0] == 0) + username = NO_USER; - vpn_ip = get_ip(rep->user[i]->local_ip, rep->user[i]->local_ip6); + vpn_ip = get_ip(rep->user[i]->local_ip, + rep->user[i]->local_ip6); - /* add header */ - if (i == 0) { - fprintf(out, "%8s %8s %8s %14s %14s %6s %7s %14s %9s\n", - "id", "user", "vhost", "ip", "vpn-ip", "device", - "since", "dtls-cipher", "status"); + /* add header */ + if (i == 0) { + fprintf(out, + "%8s %8s %8s %14s %14s %6s %7s %14s %9s\n", + "id", "user", "vhost", "ip", "vpn-ip", + "device", "since", "dtls-cipher", + "status"); + } + + t = rep->user[i]->conn_time; + tm = localtime_r(&t, &_tm); + strftime(str_since, sizeof(str_since), DATE_TIME_FMT, + tm); + + print_time_ival7(tmpbuf, time(NULL), t); + + fprintf(out, "%8d %8s %8s %14s %14s %6s ", + (int)rep->user[i]->id, username, + rep->user[i]->vhost, rep->user[i]->ip, vpn_ip, + rep->user[i]->tun); + + dtls_ciphersuite = + fix_ciphersuite(rep->user[i]->dtls_ciphersuite); + + fprintf(out, "%s %14s %9s\n", tmpbuf, dtls_ciphersuite, + ps_status_to_str(rep->user[i]->status, 0)); + + entries_add(ctx, username, strlen(username), + rep->user[i]->id); } - - t = rep->user[i]->conn_time; - tm = localtime_r(&t, &_tm); - strftime(str_since, sizeof(str_since), DATE_TIME_FMT, tm); - - print_time_ival7(tmpbuf, time(NULL), t); - - fprintf(out, "%8d %8s %8s %14s %14s %6s ", - (int)rep->user[i]->id, username, rep->user[i]->vhost, rep->user[i]->ip, vpn_ip, rep->user[i]->tun); - - dtls_ciphersuite = fix_ciphersuite(rep->user[i]->dtls_ciphersuite); - - fprintf(out, "%s %14s %9s\n", tmpbuf, dtls_ciphersuite, ps_status_to_str(rep->user[i]->status, 0)); - - entries_add(ctx, username, strlen(username), rep->user[i]->id); - } } -int handle_list_users_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_list_users_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; UserListRep *rep = NULL; FILE *out; + PROTOBUF_ALLOCATOR(pa, ctx); init_reply(&raw); @@ -695,11 +775,11 @@ int handle_list_users_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st * ret = 0; goto cleanup; - error: +error: ret = 1; fprintf(stderr, ERR_SERVER_UNREACHABLE); - cleanup: +cleanup: if (rep != NULL) user_list_rep__free_unpacked(rep, &pa); @@ -709,7 +789,8 @@ int handle_list_users_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st * return ret; } -static char *shorten(void *cookie, unsigned session_id_size, unsigned small) +static char *shorten(void *cookie, unsigned int session_id_size, + unsigned int small) { static char psid[SAFE_ID_SIZE]; @@ -719,16 +800,15 @@ static char *shorten(void *cookie, unsigned session_id_size, unsigned small) if (small) psid[6] = 0; else - psid[SAFE_ID_SIZE-1] = 0; + psid[SAFE_ID_SIZE - 1] = 0; return psid; } -static -void session_list(struct unix_ctx *ctx, SecmListCookiesReplyMsg *rep, FILE *out, cmd_params_st *params, - unsigned all) +static void session_list(struct unix_ctx *ctx, SecmListCookiesReplyMsg *rep, + FILE *out, cmd_params_st *params, unsigned int all) { - unsigned i; + unsigned int i; const char *username; char tmpbuf[MAX_TMPSTR_SIZE] = ""; time_t t; @@ -740,43 +820,51 @@ void session_list(struct unix_ctx *ctx, SecmListCookiesReplyMsg *rep, FILE *out, if (HAVE_JSON(params)) { session_info_cmd(ctx, rep, out, params, NULL, all); - } else for (i=0;in_cookies;i++) { - if (!all && rep->cookies[i]->status != PS_AUTH_COMPLETED) - continue; + } else + for (i = 0; i < rep->n_cookies; i++) { + if (!all && + rep->cookies[i]->status != PS_AUTH_COMPLETED) + continue; - username = rep->cookies[i]->username; - if (username == NULL || username[0] == 0) - username = NO_USER; + username = rep->cookies[i]->username; + if (username == NULL || username[0] == 0) + username = NO_USER; - /* add header */ - if (i == 0) { - fprintf(out, "%6s %8s %8s %14s %24s %8s %8s\n", - "session", "user", "vhost", "ip", "user agent", "created", "status"); + /* add header */ + if (i == 0) { + fprintf(out, "%6s %8s %8s %14s %24s %8s %8s\n", + "session", "user", "vhost", "ip", + "user agent", "created", "status"); + } + + t = rep->cookies[i]->created; + if (t > 0) { + tm = localtime_r(&t, &_tm); + strftime(str_since, sizeof(str_since), + DATE_TIME_FMT, tm); + print_time_ival7(tmpbuf, time(NULL), t); + } + + sid = shorten(rep->cookies[i]->safe_id.data, + rep->cookies[i]->safe_id.len, 1); + session_entries_add(ctx, sid); + + fprintf(out, "%.6s %8s %8s %14s %.24s %8s %8s\n", sid, + username, rep->cookies[i]->vhost, + rep->cookies[i]->remote_ip, + rep->cookies[i]->user_agent, tmpbuf, + ps_status_to_str(rep->cookies[i]->status, 1)); } - - t = rep->cookies[i]->created; - if (t > 0) { - tm = localtime_r(&t, &_tm); - strftime(str_since, sizeof(str_since), DATE_TIME_FMT, tm); - print_time_ival7(tmpbuf, time(NULL), t); - } - - sid = shorten(rep->cookies[i]->safe_id.data, rep->cookies[i]->safe_id.len, 1); - session_entries_add(ctx, sid); - - fprintf(out, "%.6s %8s %8s %14s %.24s %8s %8s\n", - sid, username, rep->cookies[i]->vhost, rep->cookies[i]->remote_ip, - rep->cookies[i]->user_agent, tmpbuf, ps_status_to_str(rep->cookies[i]->status, 1)); - } } -static -int handle_list_sessions_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params, unsigned all) +static int handle_list_sessions_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params, unsigned int all) { int ret; struct cmd_reply_st raw; SecmListCookiesReplyMsg *rep = NULL; FILE *out; + PROTOBUF_ALLOCATOR(pa, ctx); init_reply(&raw); @@ -799,11 +887,11 @@ int handle_list_sessions_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_s ret = 0; goto cleanup; - error: +error: ret = 1; fprintf(stderr, ERR_SERVER_UNREACHABLE); - cleanup: +cleanup: if (rep != NULL) secm_list_cookies_reply_msg__free_unpacked(rep, &pa); @@ -813,13 +901,15 @@ int handle_list_sessions_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_s return ret; } -int handle_show_session_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_show_session_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; SecmListCookiesReplyMsg *rep = NULL; FILE *out; - const char *sid = (void*)arg; + const char *sid = (void *)arg; + PROTOBUF_ALLOCATOR(pa, ctx); if (arg == NULL || need_help(arg)) { @@ -847,11 +937,11 @@ int handle_show_session_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st ret = 0; goto cleanup; - error: +error: ret = 1; fprintf(stderr, ERR_SERVER_UNREACHABLE); - cleanup: +cleanup: if (rep != NULL) secm_list_cookies_reply_msg__free_unpacked(rep, &pa); @@ -861,23 +951,27 @@ int handle_show_session_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st return ret; } -int handle_list_valid_sessions_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_list_valid_sessions_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { return handle_list_sessions_cmd(ctx, arg, params, 0); } -int handle_list_all_sessions_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_list_all_sessions_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { return handle_list_sessions_cmd(ctx, arg, params, 1); } -int handle_list_iroutes_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_list_iroutes_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; UserListRep *rep = NULL; FILE *out; - unsigned i, j; + unsigned int i, j; + PROTOBUF_ALLOCATOR(pa, ctx); init_reply(&raw); @@ -898,43 +992,53 @@ int handle_list_iroutes_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st /* print iroutes */ if (NO_JSON(params)) { - for (i=0;in_user;i++) { + for (i = 0; i < rep->n_user; i++) { const char *username, *vpn_ip; username = rep->user[i]->username; if (username == NULL || username[0] == 0) username = NO_USER; - vpn_ip = get_ip(rep->user[i]->local_ip, rep->user[i]->local_ip6); + vpn_ip = get_ip(rep->user[i]->local_ip, + rep->user[i]->local_ip6); /* add header */ if (i == 0) { fprintf(out, "%6s %8s %8s %6s %16s %28s\n", - "id", "user", "vhost", "device", "vpn-ip", "iroute"); + "id", "user", "vhost", "device", + "vpn-ip", "iroute"); } - for (j=0;juser[i]->n_iroutes;j++) + for (j = 0; j < rep->user[i]->n_iroutes; j++) fprintf(out, "%6d %8s %8s %6s %16s %28s\n", - (int)rep->user[i]->id, username, rep->user[i]->vhost, rep->user[i]->tun, vpn_ip, rep->user[i]->iroutes[j]); - + (int)rep->user[i]->id, username, + rep->user[i]->vhost, rep->user[i]->tun, + vpn_ip, rep->user[i]->iroutes[j]); } } else { print_start_block(out, params); - for (i=0;in_user;i++) { + for (i = 0; i < rep->n_user; i++) { const char *username, *vpn_ip; username = rep->user[i]->username; if (username == NULL || username[0] == 0) username = NO_USER; - vpn_ip = get_ip(rep->user[i]->local_ip, rep->user[i]->local_ip6); + vpn_ip = get_ip(rep->user[i]->local_ip, + rep->user[i]->local_ip6); - print_single_value_int(out, params, "ID", rep->user[i]->id, 1); - print_single_value(out, params, "Username", username, 1); - print_single_value(out, params, "vhost", rep->user[i]->vhost, 1); - print_single_value(out, params, "Device", rep->user[i]->tun, 1); + print_single_value_int(out, params, "ID", + rep->user[i]->id, 1); + print_single_value(out, params, "Username", username, + 1); + print_single_value(out, params, "vhost", + rep->user[i]->vhost, 1); + print_single_value(out, params, "Device", + rep->user[i]->tun, 1); print_single_value(out, params, "IP", vpn_ip, 1); - print_list_entries(out, params, "iRoutes", rep->user[i]->iroutes, rep->user[i]->n_iroutes, 1); + print_list_entries(out, params, "iRoutes", + rep->user[i]->iroutes, + rep->user[i]->n_iroutes, 1); print_single_value(out, params, "IP", vpn_ip, 0); } print_end_block(out, params, 0); @@ -943,11 +1047,11 @@ int handle_list_iroutes_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st ret = 0; goto cleanup; - error: +error: ret = 1; fprintf(stderr, ERR_SERVER_UNREACHABLE); - cleanup: +cleanup: if (rep != NULL) user_list_rep__free_unpacked(rep, &pa); @@ -957,18 +1061,19 @@ int handle_list_iroutes_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st return ret; } -static -int handle_list_banned_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params, unsigned points) +static int handle_list_banned_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params, unsigned int points) { int ret; struct cmd_reply_st raw; BanListRep *rep = NULL; - unsigned i; + unsigned int i; char str_since[64]; char tmpbuf[MAX_TMPSTR_SIZE]; FILE *out; struct tm *tm, _tm; time_t t; + PROTOBUF_ALLOCATOR(pa, ctx); char txt_ip[MAX_IP_STR]; const char *tmp_str; @@ -990,14 +1095,16 @@ int handle_list_banned_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st print_array_block(out, params); - for (i=0;in_info;i++) { + for (i = 0; i < rep->n_info; i++) { if (rep->info[i]->ip.len < 4) continue; if (rep->info[i]->ip.len == 16) - tmp_str = inet_ntop(AF_INET6, rep->info[i]->ip.data, txt_ip, sizeof(txt_ip)); + tmp_str = inet_ntop(AF_INET6, rep->info[i]->ip.data, + txt_ip, sizeof(txt_ip)); else - tmp_str = inet_ntop(AF_INET, rep->info[i]->ip.data, txt_ip, sizeof(txt_ip)); + tmp_str = inet_ntop(AF_INET, rep->info[i]->ip.data, + txt_ip, sizeof(txt_ip)); if (tmp_str == NULL) strlcpy(txt_ip, "(unknown)", sizeof(txt_ip)); @@ -1006,44 +1113,50 @@ int handle_list_banned_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st if (rep->info[i]->has_expires) { t = rep->info[i]->expires; tm = localtime_r(&t, &_tm); - strftime(str_since, sizeof(str_since), DATE_TIME_FMT, tm); + strftime(str_since, sizeof(str_since), + DATE_TIME_FMT, tm); } else { continue; } if (i == 0 && NO_JSON(params)) { - fprintf(out, "%14s %14s %30s\n", - "IP", "score", "expires"); + fprintf(out, "%14s %14s %30s\n", "IP", "score", + "expires"); } print_start_block(out, params); print_time_ival7(tmpbuf, t, time(NULL)); if (HAVE_JSON(params)) { - print_single_value(out, params, "IP", txt_ip, 1); - print_single_value_ex(out, params, "Since", str_since, tmpbuf, 1); - print_single_value_int(out, params, "Score", rep->info[i]->score, 0); + print_single_value(out, params, "IP", txt_ip, + 1); + print_single_value_ex(out, params, "Since", + str_since, tmpbuf, 1); + print_single_value_int(out, params, "Score", + rep->info[i]->score, 0); } else { - fprintf(out, "%14s %14u %30s (%s)\n", - txt_ip, (unsigned)rep->info[i]->score, str_since, tmpbuf); + fprintf(out, "%14s %14u %30s (%s)\n", txt_ip, + (unsigned int)rep->info[i]->score, + str_since, tmpbuf); } } else { if (i == 0 && NO_JSON(params)) { - fprintf(out, "%14s %14s\n", - "IP", "score"); + fprintf(out, "%14s %14s\n", "IP", "score"); } print_start_block(out, params); if (HAVE_JSON(params)) { - print_single_value(out, params, "IP", txt_ip, 1); - print_single_value_int(out, params, "Score", rep->info[i]->score, 0); + print_single_value(out, params, "IP", txt_ip, + 1); + print_single_value_int(out, params, "Score", + rep->info[i]->score, 0); } else { - fprintf(out, "%14s %14u\n", - txt_ip, (unsigned)rep->info[i]->score); + fprintf(out, "%14s %14u\n", txt_ip, + (unsigned int)rep->info[i]->score); } } - print_end_block(out, params, i<(rep->n_info-1)?1:0); + print_end_block(out, params, i < (rep->n_info - 1) ? 1 : 0); ip_entries_add(ctx, txt_ip, strlen(txt_ip)); } @@ -1053,11 +1166,11 @@ int handle_list_banned_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st ret = 0; goto cleanup; - error: +error: ret = 1; fprintf(stderr, ERR_SERVER_UNREACHABLE); - cleanup: +cleanup: if (rep != NULL) ban_list_rep__free_unpacked(rep, &pa); @@ -1067,17 +1180,18 @@ int handle_list_banned_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st return ret; } -int handle_list_banned_ips_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_list_banned_ips_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { return handle_list_banned_cmd(ctx, arg, params, 0); } -int handle_list_banned_points_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_list_banned_points_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { return handle_list_banned_cmd(ctx, arg, params, 1); } - static char *int2str(char tmpbuf[MAX_TMPSTR_SIZE], int i) { tmpbuf[0] = 0; @@ -1085,8 +1199,7 @@ static char *int2str(char tmpbuf[MAX_TMPSTR_SIZE], int i) return tmpbuf; } -static -int common_info_cmd(UserListRep * args, FILE *out, cmd_params_st *params) +static int common_info_cmd(UserListRep *args, FILE *out, cmd_params_st *params) { char *username; char *groupname; @@ -1095,10 +1208,10 @@ int common_info_cmd(UserListRep * args, FILE *out, cmd_params_st *params) char tmpbuf2[MAX_TMPSTR_SIZE]; struct tm *tm, _tm; time_t t; - unsigned at_least_one = 0; + unsigned int at_least_one = 0; int ret = 1, r; - unsigned i; - unsigned init_pager = 0; + unsigned int i; + unsigned int init_pager = 0; if (out == NULL) { out = pager_start(params); @@ -1108,7 +1221,7 @@ int common_info_cmd(UserListRep * args, FILE *out, cmd_params_st *params) if (HAVE_JSON(params)) fprintf(out, "[\n"); - for (i=0;in_user;i++) { + for (i = 0; i < args->n_user; i++) { if (at_least_one > 0) fprintf(out, "\n"); @@ -1124,105 +1237,177 @@ int common_info_cmd(UserListRep * args, FILE *out, cmd_params_st *params) if (username == NULL || username[0] == 0) username = NO_USER; - groupname = args->user[i]->groupname; if (groupname == NULL || groupname[0] == 0) groupname = NO_GROUP; - print_pair_value(out, params, "Username", username, "Groupname", groupname, 1); + print_pair_value(out, params, "Username", username, "Groupname", + groupname, 1); - print_single_value(out, params, "State", ps_status_to_str(args->user[i]->status, 0), 1); - print_single_value(out, params, "vhost", args->user[i]->vhost, 1); + print_single_value(out, params, "State", + ps_status_to_str(args->user[i]->status, 0), + 1); + print_single_value(out, params, "vhost", args->user[i]->vhost, + 1); if (args->user[i]->has_mtu != 0) - print_pair_value(out, params, "Device", args->user[i]->tun, "MTU", int2str(tmpbuf, args->user[i]->mtu), 1); + print_pair_value(out, params, "Device", + args->user[i]->tun, "MTU", + int2str(tmpbuf, args->user[i]->mtu), + 1); else - print_single_value(out, params, "Device", args->user[i]->tun, 1); - print_pair_value(out, params, "Remote IP", args->user[i]->ip, "Location", geo_lookup(args->user[i]->ip, tmpbuf, sizeof(tmpbuf)), 1); - print_single_value(out, params, "Local Device IP", args->user[i]->local_dev_ip, 1); + print_single_value(out, params, "Device", + args->user[i]->tun, 1); + print_pair_value( + out, params, "Remote IP", args->user[i]->ip, "Location", + geo_lookup(args->user[i]->ip, tmpbuf, sizeof(tmpbuf)), + 1); + print_single_value(out, params, "Local Device IP", + args->user[i]->local_dev_ip, 1); - if (args->user[i]->local_ip != NULL && args->user[i]->local_ip[0] != 0 && - args->user[i]->remote_ip != NULL && args->user[i]->remote_ip[0] != 0) { - print_pair_value(out, params, "IPv4", args->user[i]->local_ip, "P-t-P IPv4", args->user[i]->remote_ip, 1); + if (args->user[i]->local_ip != NULL && + args->user[i]->local_ip[0] != 0 && + args->user[i]->remote_ip != NULL && + args->user[i]->remote_ip[0] != 0) { + print_pair_value(out, params, "IPv4", + args->user[i]->local_ip, "P-t-P IPv4", + args->user[i]->remote_ip, 1); } - if (args->user[i]->local_ip6 != NULL && args->user[i]->local_ip6[0] != 0 && - args->user[i]->remote_ip6 != NULL && args->user[i]->remote_ip6[0] != 0) { - print_pair_value(out, params, "IPv6", args->user[i]->local_ip6, "P-t-P IPv6", args->user[i]->remote_ip6, 1); + if (args->user[i]->local_ip6 != NULL && + args->user[i]->local_ip6[0] != 0 && + args->user[i]->remote_ip6 != NULL && + args->user[i]->remote_ip6[0] != 0) { + print_pair_value(out, params, "IPv6", + args->user[i]->local_ip6, "P-t-P IPv6", + args->user[i]->remote_ip6, 1); } - print_single_value(out, params, "User-Agent", args->user[i]->user_agent, 1); + print_single_value(out, params, "User-Agent", + args->user[i]->user_agent, 1); - if (args->user[i]->rx_per_sec > 0 || args->user[i]->tx_per_sec > 0) { + if (args->user[i]->rx_per_sec > 0 || + args->user[i]->tx_per_sec > 0) { /* print limits */ char buf1[32]; char buf2[32]; - if (args->user[i]->rx_per_sec > 0 && args->user[i]->tx_per_sec > 0) { - bytes2human(args->user[i]->rx_per_sec, buf1, sizeof(buf1), "/s"); - bytes2human(args->user[i]->tx_per_sec, buf2, sizeof(buf2), "/s"); + if (args->user[i]->rx_per_sec > 0 && + args->user[i]->tx_per_sec > 0) { + bytes2human(args->user[i]->rx_per_sec, buf1, + sizeof(buf1), "/s"); + bytes2human(args->user[i]->tx_per_sec, buf2, + sizeof(buf2), "/s"); - print_pair_value(out, params, "Limit RX", buf1, "Limit TX", buf2, 1); + print_pair_value(out, params, "Limit RX", buf1, + "Limit TX", buf2, 1); } else if (args->user[i]->tx_per_sec > 0) { - bytes2human(args->user[i]->tx_per_sec, buf1, sizeof(buf1), "/s"); - print_single_value(out, params, "Limit TX", buf1, 1); + bytes2human(args->user[i]->tx_per_sec, buf1, + sizeof(buf1), "/s"); + print_single_value(out, params, "Limit TX", + buf1, 1); } else if (args->user[i]->rx_per_sec > 0) { - bytes2human(args->user[i]->rx_per_sec, buf1, sizeof(buf1), "/s"); - print_single_value(out, params, "Limit RX", buf1, 1); + bytes2human(args->user[i]->rx_per_sec, buf1, + sizeof(buf1), "/s"); + print_single_value(out, params, "Limit RX", + buf1, 1); } } - print_iface_stats(args->user[i]->tun, args->user[i]->conn_time, out, params, 1); + print_iface_stats(args->user[i]->tun, args->user[i]->conn_time, + out, params, 1); - print_pair_value(out, params, "DPD", int2str(tmpbuf, args->user[i]->dpd), "KeepAlive", int2str(tmpbuf2, args->user[i]->keepalive), 1); + print_pair_value(out, params, "DPD", + int2str(tmpbuf, args->user[i]->dpd), + "KeepAlive", + int2str(tmpbuf2, args->user[i]->keepalive), 1); - print_single_value(out, params, "Hostname", args->user[i]->hostname, 1); + print_single_value(out, params, "Hostname", + args->user[i]->hostname, 1); print_time_ival7(tmpbuf, time(NULL), t); - print_single_value_ex(out, params, "Connected at", str_since, tmpbuf, 1); + print_single_value_ex(out, params, "Connected at", str_since, + tmpbuf, 1); if (HAVE_JSON(params)) { - print_single_value_int(out, params, "raw_connected_at", t, 1); - print_single_value(out, params, "Full session", shorten(args->user[i]->safe_id.data, args->user[i]->safe_id.len, 0), 1); + print_single_value_int(out, params, "raw_connected_at", + t, 1); + print_single_value(out, params, "Full session", + shorten(args->user[i]->safe_id.data, + args->user[i]->safe_id.len, + 0), + 1); #ifdef OCSERV_0_11_6_COMPAT /* compat with previous versions */ - print_single_value(out, params, "Raw cookie", shorten(args->user[i]->safe_id.data, args->user[i]->safe_id.len, 0), 1); - print_single_value(out, params, "Cookie", shorten(args->user[i]->safe_id.data, args->user[i]->safe_id.len, 1), 1); + print_single_value(out, params, "Raw cookie", + shorten(args->user[i]->safe_id.data, + args->user[i]->safe_id.len, + 0), + 1); + print_single_value(out, params, "Cookie", + shorten(args->user[i]->safe_id.data, + args->user[i]->safe_id.len, + 1), + 1); #endif } - print_single_value(out, params, "Session", shorten(args->user[i]->safe_id.data, args->user[i]->safe_id.len, 1), 1); + print_single_value(out, params, "Session", + shorten(args->user[i]->safe_id.data, + args->user[i]->safe_id.len, 1), + 1); - print_single_value(out, params, "TLS ciphersuite", args->user[i]->tls_ciphersuite, 1); - print_single_value(out, params, "DTLS cipher", args->user[i]->dtls_ciphersuite, 1); - print_pair_value(out, params, "CSTP compression", args->user[i]->cstp_compr, "DTLS compression", args->user[i]->dtls_compr, 1); + print_single_value(out, params, "TLS ciphersuite", + args->user[i]->tls_ciphersuite, 1); + print_single_value(out, params, "DTLS cipher", + args->user[i]->dtls_ciphersuite, 1); + print_pair_value(out, params, "CSTP compression", + args->user[i]->cstp_compr, "DTLS compression", + args->user[i]->dtls_compr, 1); print_separator(out, params); /* user network info */ - if (print_list_entries(out, params, "DNS", args->user[i]->dns, args->user[i]->n_dns, 1) < 0) + if (print_list_entries(out, params, "DNS", args->user[i]->dns, + args->user[i]->n_dns, 1) < 0) goto error_parse; - if (print_list_entries(out, params, "NBNS", args->user[i]->nbns, args->user[i]->n_nbns, 1) < 0) + if (print_list_entries(out, params, "NBNS", args->user[i]->nbns, + args->user[i]->n_nbns, 1) < 0) goto error_parse; - if (print_list_entries(out, params, "Split-DNS-Domains", args->user[i]->domains, args->user[i]->n_domains, 1) < 0) + if (print_list_entries(out, params, "Split-DNS-Domains", + args->user[i]->domains, + args->user[i]->n_domains, 1) < 0) goto error_parse; - if ((r = print_list_entries(out, params, "Routes", args->user[i]->routes, args->user[i]->n_routes, 1)) < 0) + r = print_list_entries(out, params, "Routes", + args->user[i]->routes, + args->user[i]->n_routes, 1); + if (r < 0) goto error_parse; if (r == 0) { - print_single_value(out, params, "Routes", "defaultroute", 1); + print_single_value(out, params, "Routes", + "defaultroute", 1); } - if (print_list_entries(out, params, "No-routes", args->user[i]->no_routes, args->user[i]->n_no_routes, 1) < 0) + if (print_list_entries(out, params, "No-routes", + args->user[i]->no_routes, + args->user[i]->n_no_routes, 1) < 0) goto error_parse; - if (print_list_entries(out, params, "iRoutes", args->user[i]->iroutes, args->user[i]->n_iroutes, 1) < 0) + if (print_list_entries(out, params, "iRoutes", + args->user[i]->iroutes, + args->user[i]->n_iroutes, 1) < 0) goto error_parse; - print_single_value(out, params, "Restricted to routes", args->user[i]->restrict_to_routes?"True":"False", 1); + print_single_value(out, params, "Restricted to routes", + args->user[i]->restrict_to_routes ? "True" : + "False", + 1); - if (print_fwport_entries(out, params, "Restricted to ports", args->user[i]->fw_ports, args->user[i]->n_fw_ports, 0) < 0) + if (print_fwport_entries(out, params, "Restricted to ports", + args->user[i]->fw_ports, + args->user[i]->n_fw_ports, 0) < 0) goto error_parse; - print_end_block(out, params, i<(args->n_user-1)?1:0); + print_end_block(out, params, i < (args->n_user - 1) ? 1 : 0); at_least_one = 1; } @@ -1233,10 +1418,10 @@ int common_info_cmd(UserListRep * args, FILE *out, cmd_params_st *params) ret = 0; goto cleanup; - error_parse: +error_parse: fprintf(stderr, "%s: message parsing error\n", __func__); goto cleanup; - cleanup: +cleanup: if (at_least_one == 0) { if (NO_JSON(params)) fprintf(out, "user or ID not found\n"); @@ -1248,20 +1433,20 @@ int common_info_cmd(UserListRep * args, FILE *out, cmd_params_st *params) return ret; } -static -int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, - cmd_params_st *params, const char *lsid, unsigned all) +static int session_info_cmd(void *ctx, SecmListCookiesReplyMsg *args, FILE *out, + cmd_params_st *params, const char *lsid, + unsigned int all) { const char *username, *groupname; char str_since[65]; char str_since2[65]; struct tm *tm, _tm; time_t t; - unsigned at_least_one = 0; + unsigned int at_least_one = 0; int ret = 1; - unsigned i; + unsigned int i; const char *sid; - unsigned init_pager = 0; + unsigned int init_pager = 0; unsigned int match_len = 0; char tmpbuf[MAX_TMPSTR_SIZE]; @@ -1278,11 +1463,13 @@ int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, session_entries_clear(); - for (i=0;in_cookies;i++) { - if (!all && args->cookies[i]->status != PS_AUTH_COMPLETED && lsid == NULL) + for (i = 0; i < args->n_cookies; i++) { + if (!all && args->cookies[i]->status != PS_AUTH_COMPLETED && + lsid == NULL) continue; - sid = shorten(args->cookies[i]->safe_id.data, args->cookies[i]->safe_id.len, 1); + sid = shorten(args->cookies[i]->safe_id.data, + args->cookies[i]->safe_id.len, 1); session_entries_add(ctx, sid); if (lsid && strncmp(sid, lsid, match_len) != 0) @@ -1295,9 +1482,17 @@ int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, print_single_value(out, params, "Session", sid, 1); if (HAVE_JSON(params)) - print_single_value(out, params, "Full session", shorten(args->cookies[i]->safe_id.data, args->cookies[i]->safe_id.len, 0), 1); + print_single_value( + out, params, "Full session", + shorten(args->cookies[i]->safe_id.data, + args->cookies[i]->safe_id.len, 0), + 1); else - print_single_value(out, params, "Full session ID", shorten(args->cookies[i]->safe_id.data, args->cookies[i]->safe_id.len, 0), 1); + print_single_value( + out, params, "Full session ID", + shorten(args->cookies[i]->safe_id.data, + args->cookies[i]->safe_id.len, 0), + 1); t = args->cookies[i]->created; @@ -1306,18 +1501,23 @@ int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, if (t > 0) { tm = localtime_r(&t, &_tm); - strftime(str_since, sizeof(str_since), DATE_TIME_FMT, tm); + strftime(str_since, sizeof(str_since), DATE_TIME_FMT, + tm); } t = args->cookies[i]->expires; if (t > 0) { tm = localtime_r(&t, &_tm); - strftime(str_since2, sizeof(str_since2), DATE_TIME_FMT, tm); + strftime(str_since2, sizeof(str_since2), DATE_TIME_FMT, + tm); } - print_pair_value(out, params, "Created", str_since, "Expires", str_since2, 1); + print_pair_value(out, params, "Created", str_since, "Expires", + str_since2, 1); - print_single_value(out, params, "State", ps_status_to_str(args->cookies[i]->status, 1), 1); + print_single_value( + out, params, "State", + ps_status_to_str(args->cookies[i]->status, 1), 1); username = args->cookies[i]->username; if (username == NULL || username[0] == 0) @@ -1327,32 +1527,61 @@ int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, if (groupname == NULL || groupname[0] == 0) groupname = NO_GROUP; - print_pair_value(out, params, "Username", username, "Groupname", groupname, 1); - print_pair_value(out, params, "vhost", args->cookies[i]->vhost, "User-Agent", args->cookies[i]->user_agent, 1); - print_pair_value(out, params, "Remote IP", args->cookies[i]->remote_ip, "Location", geo_lookup(args->cookies[i]->remote_ip, tmpbuf, sizeof(tmpbuf)), 1); + print_pair_value(out, params, "Username", username, "Groupname", + groupname, 1); + print_pair_value(out, params, "vhost", args->cookies[i]->vhost, + "User-Agent", args->cookies[i]->user_agent, 1); + print_pair_value(out, params, "Remote IP", + args->cookies[i]->remote_ip, "Location", + geo_lookup(args->cookies[i]->remote_ip, tmpbuf, + sizeof(tmpbuf)), + 1); if (HAVE_JSON(params)) { /* old names for compatibility */ - print_single_value_int(out, params, "session_is_open", args->cookies[i]->session_is_open, 1); - print_single_value_int(out, params, "tls_auth_ok", args->cookies[i]->tls_auth_ok, 1); - print_single_value_int(out, params, "in_use", args->cookies[i]->in_use, 1); + print_single_value_int( + out, params, "session_is_open", + args->cookies[i]->session_is_open, 1); + print_single_value_int(out, params, "tls_auth_ok", + args->cookies[i]->tls_auth_ok, + 1); + print_single_value_int(out, params, "in_use", + args->cookies[i]->in_use, 1); } else { /* old names for compatibility */ - print_pair_value(out, params, "In use", args->cookies[i]->in_use?"True":"False", - "Activated", args->cookies[i]->session_is_open?"True":"False", 1); - print_single_value(out, params, "Certificate auth", args->cookies[i]->tls_auth_ok?"True":"False", 1); + print_pair_value( + out, params, "In use", + args->cookies[i]->in_use ? "True" : "False", + "Activated", + args->cookies[i]->session_is_open ? "True" : + "False", + 1); + print_single_value(out, params, "Certificate auth", + args->cookies[i]->tls_auth_ok ? + "True" : + "False", + 1); } #ifdef OCSERV_0_11_6_COMPAT if (HAVE_JSON(params)) { /* compat with previous versions */ - print_single_value(out, params, "Last Modified", str_since, 1); - print_single_value(out, params, "Raw cookie", shorten(args->cookies[i]->safe_id.data, args->cookies[i]->safe_id.len, 0), 1); - print_single_value(out, params, "Cookie", shorten(args->cookies[i]->safe_id.data, args->cookies[i]->safe_id.len, 1), 1); + print_single_value(out, params, "Last Modified", + str_since, 1); + print_single_value( + out, params, "Raw cookie", + shorten(args->cookies[i]->safe_id.data, + args->cookies[i]->safe_id.len, 0), + 1); + print_single_value( + out, params, "Cookie", + shorten(args->cookies[i]->safe_id.data, + args->cookies[i]->safe_id.len, 1), + 1); } #endif - print_end_block(out, params, i<(args->n_cookies-1)?1:0); + print_end_block(out, params, i < (args->n_cookies - 1) ? 1 : 0); at_least_one = 1; } @@ -1363,7 +1592,7 @@ int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, ret = 0; goto cleanup; - cleanup: +cleanup: if (at_least_one == 0) { if (NO_JSON(params)) fprintf(out, "Session ID not found or expired\n"); @@ -1375,12 +1604,14 @@ int session_info_cmd(void *ctx, SecmListCookiesReplyMsg * args, FILE *out, return ret; } -int handle_show_user_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_show_user_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; UserListRep *rep = NULL; UsernameReq req = USERNAME_REQ__INIT; + PROTOBUF_ALLOCATOR(pa, ctx); if (arg == NULL || need_help(arg)) { @@ -1390,11 +1621,11 @@ int handle_show_user_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *p init_reply(&raw); - req.username = (void*)arg; + req.username = (void *)arg; ret = send_cmd(ctx, CTL_CMD_USER_INFO, &req, - (pack_size_func)username_req__get_packed_size, - (pack_func)username_req__pack, &raw); + (pack_size_func)username_req__get_packed_size, + (pack_func)username_req__pack, &raw); if (ret < 0) { goto error; } @@ -1407,14 +1638,12 @@ int handle_show_user_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *p if (ret < 0) goto error; - - goto cleanup; - error: +error: fprintf(stderr, ERR_SERVER_UNREACHABLE); ret = 1; - cleanup: +cleanup: if (rep != NULL) user_list_rep__free_unpacked(rep, &pa); free_reply(&raw); @@ -1426,8 +1655,8 @@ static void dummy_sighandler(int signo) { } - -int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_events_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { uint8_t header[5]; int ret; @@ -1435,9 +1664,10 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para UserListRep *rep1 = NULL; TopUpdateRep *rep2 = NULL; uint32_t slength; - unsigned data_size; + unsigned int data_size; uint8_t *data = NULL; char tmpbuf[MAX_TMPSTR_SIZE]; + PROTOBUF_ALLOCATOR(pa, ctx); struct termios tio_old, tio_new; SIGHANDLER_T old_sighandler; @@ -1465,7 +1695,7 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para old_sighandler = ocsignal(SIGINT, dummy_sighandler); tcgetattr(STDIN_FILENO, &tio_old); tio_new = tio_old; - tio_new.c_lflag &= ~(ICANON|ECHO); + tio_new.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &tio_new); /* start listening for updates */ @@ -1477,7 +1707,8 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para #endif FD_SET(ctx->fd, &rfds); - ret = select(MAX(STDIN_FILENO,ctx->fd)+1, &rfds, NULL, NULL, NULL); + ret = select(MAX(STDIN_FILENO, ctx->fd) + 1, &rfds, NULL, NULL, + NULL); if (ret == -1 && errno == EINTR) { ret = 0; break; @@ -1485,6 +1716,7 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para if (ret == -1) { int e = errno; + fprintf(stderr, "events: select: %s\n", strerror(e)); ret = -1; break; @@ -1501,29 +1733,34 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para if (!FD_ISSET(ctx->fd, &rfds)) continue; - assert(sizeof(header) == 1+sizeof(slength)); - ret = force_read_timeout(ctx->fd, header, 1+sizeof(slength), DEFAULT_TIMEOUT); + assert(sizeof(header) == 1 + sizeof(slength)); + ret = force_read_timeout(ctx->fd, header, 1 + sizeof(slength), + DEFAULT_TIMEOUT); if (ret == -1) { int e = errno; + fprintf(stderr, "events: read1: %s\n", strerror(e)); ret = -1; break; } if (ret == 0) { - fprintf(stderr, "events: server closed the connection\n"); + fprintf(stderr, + "events: server closed the connection\n"); ret = 0; break; } - if (ret != 1+sizeof(slength)) { + if (ret != 1 + sizeof(slength)) { fprintf(stderr, "events: short read %d\n", ret); ret = -1; break; } if (header[0] != CTL_CMD_TOP_UPDATE_REP) { - fprintf(stderr, "events: Unexpected message '%d', expected '%d'\n", (int)header[0], (int)CTL_CMD_TOP_UPDATE_REP); + fprintf(stderr, + "events: Unexpected message '%d', expected '%d'\n", + (int)header[0], (int)CTL_CMD_TOP_UPDATE_REP); ret = -1; break; } @@ -1541,6 +1778,7 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para ret = force_read(ctx->fd, data, data_size); if (ret == -1) { int e = errno; + fprintf(stderr, "events: read: %s\n", strerror(e)); ret = -1; break; @@ -1556,25 +1794,33 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para } else { if (rep2->connected) { printf("%s: connected user '%s' (%u) from %s with IP %s\n", - rep2->user->user[0]->vhost, - rep2->user->user[0]->username, - rep2->user->user[0]->id, - rep2->user->user[0]->ip, - get_ip(rep2->user->user[0]->local_ip, - rep2->user->user[0]->local_ip6)); + rep2->user->user[0]->vhost, + rep2->user->user[0]->username, + rep2->user->user[0]->id, + rep2->user->user[0]->ip, + get_ip(rep2->user->user[0]->local_ip, + rep2->user->user[0]->local_ip6)); - entries_add(ctx, rep2->user->user[0]->username, strlen(rep2->user->user[0]->username), rep2->user->user[0]->id); + entries_add( + ctx, rep2->user->user[0]->username, + strlen(rep2->user->user[0]->username), + rep2->user->user[0]->id); } else { - print_time_ival7(tmpbuf, time(NULL), rep2->user->user[0]->conn_time); + print_time_ival7( + tmpbuf, time(NULL), + rep2->user->user[0]->conn_time); printf("%s: disconnect user '%s' (%u) from %s with IP %s (reason: %s, time: %s)\n", - rep2->user->user[0]->vhost, - rep2->user->user[0]->username, - rep2->user->user[0]->id, - rep2->user->user[0]->ip, - get_ip(rep2->user->user[0]->local_ip, rep2->user->user[0]->local_ip6), - rep2->discon_reason_txt?rep2->discon_reason_txt:"unknown", tmpbuf); + rep2->user->user[0]->vhost, + rep2->user->user[0]->username, + rep2->user->user[0]->id, + rep2->user->user[0]->ip, + get_ip(rep2->user->user[0]->local_ip, + rep2->user->user[0]->local_ip6), + rep2->discon_reason_txt ? + rep2->discon_reason_txt : + "unknown", + tmpbuf); } - } top_update_rep__free_unpacked(rep2, &pa); @@ -1585,10 +1831,10 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para ocsignal(SIGINT, old_sighandler); goto cleanup; - error: +error: fprintf(stderr, ERR_SERVER_UNREACHABLE); ret = 1; - cleanup: +cleanup: talloc_free(data); // These are indeed dead code but if removed a minor change // in the code above may result to either memory leak or @@ -1604,13 +1850,15 @@ int handle_events_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *para return ret; } -int handle_show_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *params) +int handle_show_id_cmd(struct unix_ctx *ctx, const char *arg, + cmd_params_st *params) { int ret; struct cmd_reply_st raw; UserListRep *rep = NULL; - unsigned id; + unsigned int id; IdReq req = ID_REQ__INIT; + PROTOBUF_ALLOCATOR(pa, ctx); if (arg != NULL) @@ -1626,8 +1874,8 @@ int handle_show_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *par req.id = id; ret = send_cmd(ctx, CTL_CMD_ID_INFO, &req, - (pack_size_func)id_req__get_packed_size, - (pack_func)id_req__pack, &raw); + (pack_size_func)id_req__get_packed_size, + (pack_func)id_req__pack, &raw); if (ret < 0) { goto error; } @@ -1642,10 +1890,10 @@ int handle_show_id_cmd(struct unix_ctx *ctx, const char *arg, cmd_params_st *par goto cleanup; - error: +error: fprintf(stderr, ERR_SERVER_UNREACHABLE); ret = 1; - cleanup: +cleanup: if (rep != NULL) user_list_rep__free_unpacked(rep, &pa); free_reply(&raw); @@ -1672,7 +1920,7 @@ void conn_posthandle(struct unix_ctx *ctx) struct unix_ctx *conn_init(void *pool, const char *file) { -struct unix_ctx *ctx; + struct unix_ctx *ctx; ctx = talloc_zero(pool, struct unix_ctx); if (ctx == NULL) return NULL; @@ -1681,7 +1929,7 @@ struct unix_ctx *ctx; return ctx; } -void conn_close(struct unix_ctx* conn) +void conn_close(struct unix_ctx *conn) { talloc_free(conn); } diff --git a/src/ocpasswd/ocpasswd.c b/src/ocpasswd/ocpasswd.c index da039d06..54cb9ab6 100644 --- a/src/ocpasswd/ocpasswd.c +++ b/src/ocpasswd/ocpasswd.c @@ -25,14 +25,14 @@ #include #include #include -#include /* for random */ +#include /* for random */ #include #include #include #ifdef HAVE_CRYPT_H - /* libcrypt in Fedora28 does not provide prototype +/* libcrypt in Fedora28 does not provide prototype * in unistd.h */ -# include +#include #endif #include @@ -42,18 +42,17 @@ static const char alphabet[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./"; #define SALT_SIZE 16 -static void -crypt_int(const char *fpasswd, const char *username, const char *groupname, - const char *passwd) +static void crypt_int(const char *fpasswd, const char *username, + const char *groupname, const char *passwd) { uint8_t _salt[SALT_SIZE]; - char salt[SALT_SIZE+16]; + char salt[SALT_SIZE + 16]; char *p, *cr_passwd; char *tmp_passwd; - unsigned i; - unsigned fpasswd_len = strlen(fpasswd); - unsigned tmp_passwd_len; - unsigned username_len = strlen(username); + unsigned int i; + unsigned int fpasswd_len = strlen(fpasswd); + unsigned int tmp_passwd_len; + unsigned int username_len = strlen(username); struct stat st; FILE *fd, *fd2; char *line = NULL; @@ -121,14 +120,17 @@ crypt_int(const char *fpasswd, const char *username, const char *groupname, fprintf(fd2, "%s:%s:%s\n", username, groupname, cr_passwd); } else { int found = 0; + while ((len = getline(&line, &line_size, fd)) > 0) { p = strchr(line, ':'); if (p == NULL) continue; - l = p-line; - if (l == username_len && strncmp(line, username, l) == 0) { - fprintf(fd2, "%s:%s:%s\n", username, groupname, cr_passwd); /* lgtm[cpp/cleartext-storage-file] */ + l = p - line; + if (l == username_len && + strncmp(line, username, l) == 0) { + fprintf(fd2, "%s:%s:%s\n", username, groupname, + cr_passwd); /* lgtm[cpp/cleartext-storage-file] */ found = 1; } else { fwrite(line, 1, len, fd2); @@ -138,7 +140,8 @@ crypt_int(const char *fpasswd, const char *username, const char *groupname, fclose(fd); if (found == 0) - fprintf(fd2, "%s:%s:%s\n", username, groupname, cr_passwd); /* lgtm[cpp/cleartext-storage-file] */ + fprintf(fd2, "%s:%s:%s\n", username, groupname, + cr_passwd); /* lgtm[cpp/cleartext-storage-file] */ } fclose(fd2); @@ -151,15 +154,14 @@ crypt_int(const char *fpasswd, const char *username, const char *groupname, free(tmp_passwd); } -static void -delete_user(const char *fpasswd, const char *username) +static void delete_user(const char *fpasswd, const char *username) { - FILE * fd, *fd2; + FILE *fd, *fd2; char *tmp_passwd; char *line, *p; - unsigned fpasswd_len = strlen(fpasswd); - unsigned tmp_passwd_len; - unsigned username_len = strlen(username); + unsigned int fpasswd_len = strlen(fpasswd); + unsigned int tmp_passwd_len; + unsigned int username_len = strlen(username); int ret; ssize_t len, l; size_t line_size; @@ -196,7 +198,7 @@ delete_user(const char *fpasswd, const char *username) if (p == NULL) continue; - l = p-line; + l = p - line; if (l == username_len && strncmp(line, username, l) == 0) { continue; } else { @@ -216,15 +218,14 @@ delete_user(const char *fpasswd, const char *username) free(tmp_passwd); } -static void -lock_user(const char *fpasswd, const char *username) +static void lock_user(const char *fpasswd, const char *username) { - FILE * fd, *fd2; + FILE *fd, *fd2; char *tmp_passwd; char *line, *p; - unsigned fpasswd_len = strlen(fpasswd); - unsigned tmp_passwd_len; - unsigned username_len = strlen(username); + unsigned int fpasswd_len = strlen(fpasswd); + unsigned int tmp_passwd_len; + unsigned int username_len = strlen(username); int ret; ssize_t len, l; size_t line_size; @@ -261,18 +262,18 @@ lock_user(const char *fpasswd, const char *username) if (p == NULL) continue; - l = p-line; + l = p - line; if (l == username_len && strncmp(line, username, l) == 0) { - p = strchr(p+1, ':'); + p = strchr(p + 1, ':'); if (p == NULL) continue; p++; if (*p != '!') { - l = p-line; + l = p - line; fwrite(line, 1, l, fd2); fputc('!', fd2); - fwrite(p, 1, len-l, fd2); + fwrite(p, 1, len - l, fd2); } else { fwrite(line, 1, len, fd2); } @@ -293,15 +294,14 @@ lock_user(const char *fpasswd, const char *username) free(tmp_passwd); } -static void -unlock_user(const char *fpasswd, const char *username) +static void unlock_user(const char *fpasswd, const char *username) { - FILE * fd, *fd2; + FILE *fd, *fd2; char *tmp_passwd; char *line, *p; - unsigned fpasswd_len = strlen(fpasswd); - unsigned tmp_passwd_len; - unsigned username_len = strlen(username); + unsigned int fpasswd_len = strlen(fpasswd); + unsigned int tmp_passwd_len; + unsigned int username_len = strlen(username); int ret; ssize_t len, l; size_t line_size; @@ -338,19 +338,20 @@ unlock_user(const char *fpasswd, const char *username) if (p == NULL) continue; - l = p-line; + l = p - line; if (l == username_len && strncmp(line, username, l) == 0) { - p = strchr(p+1, ':'); + p = strchr(p + 1, ':'); if (p == NULL) continue; p++; - l = p-line; + l = p - line; fwrite(line, 1, l, fd2); - if (*p=='!') p++; - l = p-line; - fwrite(p, 1, len-l, fd2); + if (*p == '!') + p++; + l = p - line; + fwrite(p, 1, len - l, fd2); } else { fwrite(line, 1, len, fd2); } @@ -369,63 +370,67 @@ unlock_user(const char *fpasswd, const char *username) } static const struct option long_options[] = { - {"passwd", 1, 0, 'c'}, - {"groupname", 1, 0, 'g'}, - {"delete", 0, 0, 'd'}, - {"lock", 0, 0, 'l'}, - {"unlock", 0, 0, 'u'}, - {"help", 0, 0, 'h'}, - {"version", 0, 0, 'v'}, - {NULL, 0, 0, 0} + { "passwd", 1, 0, 'c' }, { "groupname", 1, 0, 'g' }, + { "delete", 0, 0, 'd' }, { "lock", 0, 0, 'l' }, + { "unlock", 0, 0, 'u' }, { "help", 0, 0, 'h' }, + { "version", 0, 0, 'v' }, { NULL, 0, 0, 0 } }; -static -void usage(void) +static void usage(void) { fprintf(stderr, "ocpasswd - OpenConnect server password utility\n"); - fprintf(stderr, "Usage: ocpasswd [ - [] | --[{=| }] ]... [username]\n"); + fprintf(stderr, + "Usage: ocpasswd [ - [] | --[{=| }] ]... [username]\n"); fprintf(stderr, "\n"); fprintf(stderr, " -c, --passwd=file Password file\n"); fprintf(stderr, " -g, --groupname=str User's group name\n"); fprintf(stderr, " -d, --delete Delete user\n"); fprintf(stderr, " -l, --lock Lock user\n"); fprintf(stderr, " -u, --unlock Unlock user\n"); - fprintf(stderr, " -v, --version output version information and exit\n"); - fprintf(stderr, " -h, --help display extended usage information and exit\n"); + fprintf(stderr, + " -v, --version output version information and exit\n"); + fprintf(stderr, + " -h, --help display extended usage information and exit\n"); fprintf(stderr, "\n"); - fprintf(stderr, "Options are specified by doubled hyphens and their name or by a single\n"); + fprintf(stderr, + "Options are specified by doubled hyphens and their name or by a single\n"); fprintf(stderr, "hyphen and the flag character.\n\n"); - fprintf(stderr, "This program is openconnect password (ocpasswd) utility. It allows the\n"); - fprintf(stderr, "generation and handling of a 'plain' password file used by ocserv.\n\n"); - fprintf(stderr, "Please file bug reports at: "PACKAGE_BUGREPORT"\n"); + fprintf(stderr, + "This program is openconnect password (ocpasswd) utility. It allows the\n"); + fprintf(stderr, + "generation and handling of a 'plain' password file used by ocserv.\n\n"); + fprintf(stderr, "Please file bug reports at: " PACKAGE_BUGREPORT "\n"); } -static -void version(void) +static void version(void) { - fprintf(stderr, "ocpasswd - "VERSION"\n"); - fprintf(stderr, "Copyright (C) 2013-2017 Nikos Mavrogiannopoulos, all rights reserved.\n"); - fprintf(stderr, "This is free software. It is licensed for use, modification and\n"); - fprintf(stderr, "redistribution under the terms of the GNU General Public License,\n"); + fprintf(stderr, "ocpasswd - " VERSION "\n"); + fprintf(stderr, + "Copyright (C) 2013-2017 Nikos Mavrogiannopoulos, all rights reserved.\n"); + fprintf(stderr, + "This is free software. It is licensed for use, modification and\n"); + fprintf(stderr, + "redistribution under the terms of the GNU General Public License,\n"); fprintf(stderr, "version 2 \n\n"); - fprintf(stderr, "Please file bug reports at: "PACKAGE_BUGREPORT"\n"); + fprintf(stderr, "Please file bug reports at: " PACKAGE_BUGREPORT "\n"); } #define FLAG_DELETE 1 -#define FLAG_LOCK (1<<1) -#define FLAG_UNLOCK (1<<2) +#define FLAG_LOCK (1 << 1) +#define FLAG_UNLOCK (1 << 2) int main(int argc, char **argv) { int ret, c; const char *username = NULL; char *groupname = NULL, *fpasswd = NULL; - char* passwd = NULL; - unsigned free_passwd = 0; + char *passwd = NULL; + unsigned int free_passwd = 0; size_t l, i; - unsigned flags = 0; + unsigned int flags = 0; - if ((ret = gnutls_global_init()) < 0) { + ret = gnutls_global_init(); + if (ret < 0) { fprintf(stderr, "global_init: %s\n", gnutls_strerror(ret)); exit(EXIT_FAILURE); } @@ -440,14 +445,16 @@ int main(int argc, char **argv) switch (c) { case 'c': if (fpasswd) { - fprintf(stderr, "-c option cannot be specified multiple time\n"); + fprintf(stderr, + "-c option cannot be specified multiple time\n"); exit(EXIT_FAILURE); } fpasswd = strdup(optarg); break; case 'g': if (groupname) { - fprintf(stderr, "-g option cannot be specified multiple time\n"); + fprintf(stderr, + "-g option cannot be specified multiple time\n"); exit(EXIT_FAILURE); } groupname = strdup(optarg); @@ -482,7 +489,7 @@ int main(int argc, char **argv) } } - if (optind < argc && argc-optind == 1) { + if (optind < argc && argc - optind == 1) { username = argv[optind++]; } else { usage(); @@ -511,7 +518,7 @@ int main(int argc, char **argv) } else { /* set password */ if (isatty(STDIN_FILENO)) { - char* p2; + char *p2; passwd = getpass("Enter password: "); if (passwd == NULL) { @@ -519,7 +526,6 @@ int main(int argc, char **argv) exit(EXIT_FAILURE); } - p2 = strdup(passwd); passwd = getpass("Re-enter password: "); if (passwd == NULL) { @@ -541,8 +547,8 @@ int main(int argc, char **argv) } free_passwd = 1; - if (passwd[l-1] == '\n') - passwd[l-1] = 0; + if (passwd[l - 1] == '\n') + passwd[l - 1] = 0; } crypt_int(fpasswd, username, groupname, passwd); diff --git a/src/proc-search.c b/src/proc-search.c index 3346b3c4..df782c27 100644 --- a/src/proc-search.c +++ b/src/proc-search.c @@ -25,48 +25,47 @@ struct find_ip_st { struct sockaddr_storage *sockaddr; - unsigned sockaddr_size; - unsigned found_ips; + unsigned int sockaddr_size; + unsigned int found_ips; }; struct find_dtls_id_st { const uint8_t *dtls_id; - unsigned dtls_id_size; + unsigned int dtls_id_size; }; struct find_sid_st { const uint8_t *sid; }; - -static size_t rehash_ip(const void* _p, void* unused) +static size_t rehash_ip(const void *_p, void *unused) { - const struct proc_st * proc = _p; + const struct proc_st *proc = _p; - return hash_any( - SA_IN_P_GENERIC(&proc->remote_addr, proc->remote_addr_len), - SA_IN_SIZE(proc->remote_addr_len), 0); + return hash_any(SA_IN_P_GENERIC(&proc->remote_addr, + proc->remote_addr_len), + SA_IN_SIZE(proc->remote_addr_len), 0); } -static size_t rehash_dtls_ip(const void* _p, void* unused) +static size_t rehash_dtls_ip(const void *_p, void *unused) { - const struct proc_st * proc = _p; + const struct proc_st *proc = _p; - return hash_any( - SA_IN_P_GENERIC(&proc->dtls_remote_addr, proc->dtls_remote_addr_len), - SA_IN_SIZE(proc->dtls_remote_addr_len), 0); + return hash_any(SA_IN_P_GENERIC(&proc->dtls_remote_addr, + proc->dtls_remote_addr_len), + SA_IN_SIZE(proc->dtls_remote_addr_len), 0); } -static size_t rehash_dtls_id(const void* _p, void* unused) +static size_t rehash_dtls_id(const void *_p, void *unused) { - const struct proc_st * proc = _p; + const struct proc_st *proc = _p; return hash_any(proc->dtls_session_id, proc->dtls_session_id_size, 0); } -static size_t rehash_sid(const void* _p, void* unused) +static size_t rehash_sid(const void *_p, void *unused) { - const struct proc_st * proc = _p; + const struct proc_st *proc = _p; return hash_any(proc->sid, sizeof(proc->sid), 0); } @@ -113,7 +112,8 @@ int proc_table_add(main_server_st *s, struct proc_st *proc) return -1; } - if (htable_add(s->proc_table.db_sid, rehash_sid(proc, NULL), proc) == 0) { + if (htable_add(s->proc_table.db_sid, rehash_sid(proc, NULL), proc) == + 0) { htable_del(s->proc_table.db_ip, ip_hash, proc); htable_del(s->proc_table.db_dtls_id, dtls_id_hash, proc); return -1; @@ -124,19 +124,21 @@ int proc_table_add(main_server_st *s, struct proc_st *proc) return 0; } -int proc_table_update_ip(main_server_st *s, struct proc_st *proc, struct sockaddr_storage *addr, - unsigned addr_size) +int proc_table_update_ip(main_server_st *s, struct proc_st *proc, + struct sockaddr_storage *addr, unsigned int addr_size) { char buf[MAX_IP_STR]; - unsigned removed; + unsigned int removed; /* only update if we can remove the old IP */ if (addr_size != proc->remote_addr_len || memcmp(addr, &proc->remote_addr, addr_size) != 0) { mslog(s, proc, LOG_INFO, "updating remote IP to %s", - human_addr2((struct sockaddr*)addr, addr_size, buf, sizeof(buf), 0)); + human_addr2((struct sockaddr *)addr, addr_size, buf, + sizeof(buf), 0)); - removed = htable_del(s->proc_table.db_ip, rehash_ip(proc, NULL), proc); + removed = htable_del(s->proc_table.db_ip, rehash_ip(proc, NULL), + proc); memcpy(&proc->remote_addr, addr, addr_size); proc->remote_addr_len = addr_size; @@ -147,8 +149,8 @@ int proc_table_update_ip(main_server_st *s, struct proc_st *proc, struct sockadd memcmp(SA_IN_P_GENERIC(addr, addr_size), SA_IN_P_GENERIC(&proc->dtls_remote_addr, addr_size), SA_IN_SIZE(addr_size)) == 0) { - - if (htable_del(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), proc) != 0) + if (htable_del(s->proc_table.db_dtls_ip, + rehash_dtls_ip(proc, NULL), proc) != 0) proc->dtls_remote_addr_len = 0; } @@ -156,7 +158,8 @@ int proc_table_update_ip(main_server_st *s, struct proc_st *proc, struct sockadd * we may be called even before that entry is added, and we don't want * duplicates */ if (removed) { - if (htable_add(s->proc_table.db_ip, rehash_ip(proc, NULL), proc) == 0) + if (htable_add(s->proc_table.db_ip, + rehash_ip(proc, NULL), proc) == 0) return -1; } } @@ -167,7 +170,9 @@ int proc_table_update_ip(main_server_st *s, struct proc_st *proc, struct sockadd /* Adds the IP of the DTLS channel into the DTLS IP hash table. It * only adds the IP if it is different than the CSTP channel IP. */ -int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, struct sockaddr_storage *addr, unsigned addr_size) +int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, + struct sockaddr_storage *addr, + unsigned int addr_size) { if (proc->dtls_remote_addr_len) { if (proc->dtls_remote_addr_len == addr_size && @@ -176,7 +181,8 @@ int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, struct so SA_IN_SIZE(addr_size)) == 0) { return -1; /* DTLS address is already up to date */ } - htable_del(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), proc); + htable_del(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), + proc); } proc->dtls_remote_addr_len = 0; @@ -193,7 +199,8 @@ int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, struct so proc->dtls_remote_addr_len = addr_size; memcpy(&proc->dtls_remote_addr, addr, addr_size); - if (htable_add(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), proc) == 0) + if (htable_add(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), + proc) == 0) return -1; return 0; @@ -202,24 +209,26 @@ int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, struct so void proc_table_del(main_server_st *s, struct proc_st *proc) { if (proc->dtls_remote_addr_len > 0) - htable_del(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), proc); + htable_del(s->proc_table.db_dtls_ip, rehash_dtls_ip(proc, NULL), + proc); htable_del(s->proc_table.db_ip, rehash_ip(proc, NULL), proc); htable_del(s->proc_table.db_dtls_id, rehash_dtls_id(proc, NULL), proc); htable_del(s->proc_table.db_sid, rehash_sid(proc, NULL), proc); } -static bool local_ip_cmp(const void* _c1, void* _c2) +static bool local_ip_cmp(const void *_c1, void *_c2) { - const struct proc_st* c1 = _c1; - struct find_ip_st* c2 = _c2; + const struct proc_st *c1 = _c1; + struct find_ip_st *c2 = _c2; if (c2->sockaddr_size == 0) return 0; /* Test if peer IP matches DTLS IP */ if (c1->dtls_remote_addr_len == c2->sockaddr_size && - memcmp(SA_IN_P_GENERIC(&c1->dtls_remote_addr, c1->dtls_remote_addr_len), + memcmp(SA_IN_P_GENERIC(&c1->dtls_remote_addr, + c1->dtls_remote_addr_len), SA_IN_P_GENERIC(c2->sockaddr, c2->sockaddr_size), SA_IN_SIZE(c1->dtls_remote_addr_len)) == 0) { c2->found_ips++; @@ -242,7 +251,7 @@ static bool local_ip_cmp(const void* _c1, void* _c2) */ struct proc_st *proc_search_single_ip(struct main_server_st *s, struct sockaddr_storage *sockaddr, - unsigned sockaddr_size) + unsigned int sockaddr_size) { struct proc_st *proc; struct find_ip_st fip; @@ -252,7 +261,7 @@ struct proc_st *proc_search_single_ip(struct main_server_st *s, fip.sockaddr_size = sockaddr_size; h = hash_any(SA_IN_P_GENERIC(sockaddr, sockaddr_size), - SA_IN_SIZE(sockaddr_size), 0); + SA_IN_SIZE(sockaddr_size), 0); fip.found_ips = 0; proc = htable_get(s->proc_table.db_dtls_ip, h, local_ip_cmp, &fip); @@ -267,16 +276,15 @@ struct proc_st *proc_search_single_ip(struct main_server_st *s, return NULL; } -static bool dtls_id_cmp(const void* _c1, void* _c2) +static bool dtls_id_cmp(const void *_c1, void *_c2) { - const struct proc_st* c1 = _c1; - struct find_dtls_id_st* c2 = _c2; + const struct proc_st *c1 = _c1; + struct find_dtls_id_st *c2 = _c2; if (c1->dtls_session_id_size != c2->dtls_id_size) return 0; - if (memcmp(c1->dtls_session_id, - c2->dtls_id, + if (memcmp(c1->dtls_session_id, c2->dtls_id, c1->dtls_session_id_size) == 0) { return 1; } @@ -284,25 +292,24 @@ static bool dtls_id_cmp(const void* _c1, void* _c2) return 0; } -struct proc_st *proc_search_dtls_id(struct main_server_st *s, - const uint8_t *id, unsigned id_size) +struct proc_st *proc_search_dtls_id(struct main_server_st *s, const uint8_t *id, + unsigned int id_size) { struct find_dtls_id_st fdtls_id; fdtls_id.dtls_id = id; fdtls_id.dtls_id_size = id_size; - return htable_get(s->proc_table.db_dtls_id, hash_any(id, id_size, 0), dtls_id_cmp, &fdtls_id); + return htable_get(s->proc_table.db_dtls_id, hash_any(id, id_size, 0), + dtls_id_cmp, &fdtls_id); } -static bool sid_cmp(const void* _c1, void* _c2) +static bool sid_cmp(const void *_c1, void *_c2) { - const struct proc_st* c1 = _c1; - struct find_sid_st* c2 = _c2; + const struct proc_st *c1 = _c1; + struct find_sid_st *c2 = _c2; - if (memcmp(c1->sid, - c2->sid, - sizeof(c1->sid)) == 0) { + if (memcmp(c1->sid, c2->sid, sizeof(c1->sid)) == 0) { return 1; } @@ -310,10 +317,12 @@ static bool sid_cmp(const void* _c1, void* _c2) } struct proc_st *proc_search_sid(struct main_server_st *s, - const uint8_t sid[SID_SIZE]) + const uint8_t sid[SID_SIZE]) { struct find_sid_st fsid; + fsid.sid = sid; - return htable_get(s->proc_table.db_sid, hash_any(sid, SID_SIZE, 0), sid_cmp, &fsid); + return htable_get(s->proc_table.db_sid, hash_any(sid, SID_SIZE, 0), + sid_cmp, &fsid); } diff --git a/src/proc-search.h b/src/proc-search.h index b8a716f3..528c5563 100644 --- a/src/proc-search.h +++ b/src/proc-search.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_PROC_SEARCH_H -# define OC_PROC_SEARCH_H +#define OC_PROC_SEARCH_H #include #include @@ -28,17 +28,21 @@ #include struct proc_st *proc_search_single_ip(struct main_server_st *s, - struct sockaddr_storage *sockaddr, - unsigned sockaddr_size); -struct proc_st *proc_search_dtls_id(struct main_server_st *s, const uint8_t *id, unsigned id_size); + struct sockaddr_storage *sockaddr, + unsigned int sockaddr_size); +struct proc_st *proc_search_dtls_id(struct main_server_st *s, const uint8_t *id, + unsigned int id_size); struct proc_st *proc_search_sid(struct main_server_st *s, - const uint8_t id[SID_SIZE]); + const uint8_t id[SID_SIZE]); void proc_table_init(main_server_st *s); void proc_table_deinit(main_server_st *s); int proc_table_add(main_server_st *s, struct proc_st *proc); void proc_table_del(main_server_st *s, struct proc_st *proc); -int proc_table_update_ip(main_server_st *s, struct proc_st *proc, struct sockaddr_storage *addr, unsigned addr_size); -int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, struct sockaddr_storage *addr, unsigned addr_size); +int proc_table_update_ip(main_server_st *s, struct proc_st *proc, + struct sockaddr_storage *addr, unsigned int addr_size); +int proc_table_update_dtls_ip(main_server_st *s, struct proc_st *proc, + struct sockaddr_storage *addr, + unsigned int addr_size); #endif diff --git a/src/route-add.c b/src/route-add.c index 929558a1..05efabf3 100644 --- a/src/route-add.c +++ b/src/route-add.c @@ -34,11 +34,10 @@ #include #include -static -int call_script(main_server_st *s, proc_st *proc, const char *cmd) +static int call_script(main_server_st *s, proc_st *proc, const char *cmd) { -pid_t pid; -int ret, status = 0; + pid_t pid; + int ret, status = 0; if (cmd == NULL) return 0; @@ -50,7 +49,8 @@ int ret, status = 0; mslog(s, proc, LOG_DEBUG, "executing route script %s", cmd); ret = execl("/bin/sh", "sh", "-c", cmd, NULL); if (ret == -1) { - mslog(s, proc, LOG_ERR, "Could not execute route script %s", cmd); + mslog(s, proc, LOG_ERR, + "Could not execute route script %s", cmd); exit(EXIT_FAILURE); } @@ -72,17 +72,16 @@ int ret, status = 0; } if (WEXITSTATUS(status)) { - mslog(s, proc, LOG_INFO, "cmd: %s: exited with error %d", cmd, WEXITSTATUS(ret)); + mslog(s, proc, LOG_INFO, "cmd: %s: exited with error %d", cmd, + WEXITSTATUS(ret)); return ERR_EXEC; } return 0; } -static -int replace_cmd(struct main_server_st* s, proc_st *proc, - char **cmd, const char* pattern, - const char* route, const char* dev) +static int replace_cmd(struct main_server_st *s, proc_st *proc, char **cmd, + const char *pattern, const char *route, const char *dev) { str_st str; int ret; @@ -106,23 +105,23 @@ int replace_cmd(struct main_server_st* s, proc_st *proc, if (ret < 0) goto fail; - *cmd = (char*)str.data; + *cmd = (char *)str.data; return 0; - fail: +fail: str_clear(&str); return ERR_MEM; } -static -int route_adddel(struct main_server_st* s, proc_st *proc, - const char* pattern, const char* route, const char* dev) +static int route_adddel(struct main_server_st *s, proc_st *proc, + const char *pattern, const char *route, const char *dev) { -int ret; -char *cmd = NULL; + int ret; + char *cmd = NULL; if (pattern == 0) { - mslog(s, NULL, LOG_WARNING, "route-add-cmd or route-del-cmd are not set."); + mslog(s, NULL, LOG_WARNING, + "route-add-cmd or route-del-cmd are not set."); return 0; } @@ -133,25 +132,27 @@ char *cmd = NULL; ret = call_script(s, proc, cmd); if (ret < 0) { int e = errno; - mslog(s, NULL, LOG_INFO, "failed to spawn cmd: %s: %s", cmd, strerror(e)); + + mslog(s, NULL, LOG_INFO, "failed to spawn cmd: %s: %s", cmd, + strerror(e)); ret = ERR_EXEC; goto fail; } ret = 0; - fail: +fail: talloc_free(cmd); return ret; } -static -int route_add(struct main_server_st* s, proc_st *proc, const char* route, const char* dev) +static int route_add(struct main_server_st *s, proc_st *proc, const char *route, + const char *dev) { return route_adddel(s, proc, GETCONFIG(s)->route_add_cmd, route, dev); } -static -int route_del(struct main_server_st* s, proc_st *proc, const char* route, const char* dev) +static int route_del(struct main_server_st *s, proc_st *proc, const char *route, + const char *dev) { return route_adddel(s, proc, GETCONFIG(s)->route_del_cmd, route, dev); } @@ -159,25 +160,27 @@ int route_del(struct main_server_st* s, proc_st *proc, const char* route, const /* Executes the commands required to apply all the configured routes * for this client locally. */ -int apply_iroutes(struct main_server_st* s, struct proc_st *proc) +int apply_iroutes(struct main_server_st *s, struct proc_st *proc) { -unsigned i, j; -int ret; + unsigned int i, j; + int ret; if (proc->config->n_iroutes == 0) return 0; - for (i=0;iconfig->n_iroutes;i++) { - ret = route_add(s, proc, proc->config->iroutes[i], proc->tun_lease.name); + for (i = 0; i < proc->config->n_iroutes; i++) { + ret = route_add(s, proc, proc->config->iroutes[i], + proc->tun_lease.name); if (ret < 0) goto fail; } proc->applied_iroutes = 1; return 0; - fail: - for (j=0;jconfig->iroutes[j], proc->tun_lease.name); +fail: + for (j = 0; j < i; j++) + route_del(s, proc, proc->config->iroutes[j], + proc->tun_lease.name); return -1; } @@ -185,15 +188,17 @@ int ret; /* Executes the commands required to removed all the configured routes * for this client. */ -void remove_iroutes(struct main_server_st* s, struct proc_st *proc) +void remove_iroutes(struct main_server_st *s, struct proc_st *proc) { -unsigned i; + unsigned int i; - if (proc->config == NULL || proc->config->n_iroutes == 0 || proc->applied_iroutes == 0) + if (proc->config == NULL || proc->config->n_iroutes == 0 || + proc->applied_iroutes == 0) return; - for (i=0;iconfig->n_iroutes;i++) { - route_del(s, proc, proc->config->iroutes[i], proc->tun_lease.name); + for (i = 0; i < proc->config->n_iroutes; i++) { + route_del(s, proc, proc->config->iroutes[i], + proc->tun_lease.name); } proc->applied_iroutes = 0; } diff --git a/src/route-add.h b/src/route-add.h index 8258f5ef..32d65480 100644 --- a/src/route-add.h +++ b/src/route-add.h @@ -19,12 +19,12 @@ * along with this program. If not, see */ #ifndef OC_ROUTE_ADD_H -# define OC_ROUTE_ADD_H +#define OC_ROUTE_ADD_H #include #include -int apply_iroutes(struct main_server_st* s, struct proc_st *proc); -void remove_iroutes(struct main_server_st* s, struct proc_st *proc); +int apply_iroutes(struct main_server_st *s, struct proc_st *proc); +void remove_iroutes(struct main_server_st *s, struct proc_st *proc); #endif diff --git a/src/script-list.h b/src/script-list.h index b4f4f20c..52e3e212 100644 --- a/src/script-list.h +++ b/src/script-list.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_SCRIPT_LIST_H -# define OC_SCRIPT_LIST_H +#define OC_SCRIPT_LIST_H #include #include @@ -28,10 +28,10 @@ void script_child_watcher_cb(struct ev_loop *loop, ev_child *w, int revents); -inline static -void add_to_script_list(main_server_st* s, pid_t pid, struct proc_st* proc) +inline static void add_to_script_list(main_server_st *s, pid_t pid, + struct proc_st *proc) { -struct script_wait_st *stmp; + struct script_wait_st *stmp; stmp = talloc(s, struct script_wait_st); if (stmp == NULL) @@ -49,12 +49,14 @@ struct script_wait_st *stmp; /* Removes the tracked connect script, and kills it. It returns the pid * of the removed script or -1. */ -inline static pid_t remove_from_script_list(main_server_st* s, struct proc_st* proc) +inline static pid_t remove_from_script_list(main_server_st *s, + struct proc_st *proc) { struct script_wait_st *stmp = NULL, *spos; pid_t ret = -1; - list_for_each_safe(&s->script_list.head, stmp, spos, list) { + list_for_each_safe(&s->script_list.head, stmp, spos, list) + { if (stmp->proc == proc) { list_del(&stmp->list); ev_child_stop(main_loop, &stmp->ev_child); diff --git a/src/sec-mod-acct.h b/src/sec-mod-acct.h index d6d6a693..dde47c0c 100644 --- a/src/sec-mod-acct.h +++ b/src/sec-mod-acct.h @@ -19,21 +19,30 @@ * along with this program. If not, see */ #ifndef OC_SEC_MOD_ACCT_H -# define OC_SEC_MOD_ACCT_H +#define OC_SEC_MOD_ACCT_H #include #include typedef struct acct_mod_st { unsigned int type; /* ACCT_TYPE_ */ - unsigned int auth_types; /* or of the AUTH_TYPEs which are compatible with this */ - void (*vhost_init)(void **vctx, void *pool, void* additional); + unsigned int + auth_types; /* or of the AUTH_TYPEs which are compatible with this */ + void (*vhost_init)(void **vctx, void *pool, void *additional); void (*vhost_deinit)(void *vctx); /* The context provided below is of the authentication method */ - int (*open_session)(void *vctx, unsigned auth_method, const common_acct_info_st *ai, const void *sid, unsigned sid_size); /* optional, may be null */ - void (*session_stats)(void *vctx, unsigned auth_method, const common_acct_info_st *ai, struct stats_st *stats); /* optional, may be null */ - void (*close_session)(void *vctx, unsigned auth_method, const common_acct_info_st *ai, struct stats_st *stats, unsigned discon_reason/*REASON_*/); /* optional may be null */ + int (*open_session)(void *vctx, unsigned int auth_method, + const common_acct_info_st *ai, const void *sid, + unsigned int sid_size); /* optional, may be null */ + void (*session_stats)( + void *vctx, unsigned int auth_method, + const common_acct_info_st *ai, + struct stats_st *stats); /* optional, may be null */ + void (*close_session)( + void *vctx, unsigned int auth_method, + const common_acct_info_st *ai, struct stats_st *stats, + unsigned discon_reason /*REASON_*/); /* optional may be null */ } acct_mod_st; /* The accounting messages exchanged with the worker thread are shown in ipc.proto. diff --git a/src/sec-mod-auth.c b/src/sec-mod-auth.c index 5906de98..791cafff 100644 --- a/src/sec-mod-auth.c +++ b/src/sec-mod-auth.c @@ -54,33 +54,40 @@ #include #ifdef HAVE_GSSAPI -# include -# include +#include +#include #endif /* initializes vhost acct and auth modules if not already initialized */ void sec_auth_init(struct vhost_cfg_st *vhost) { - unsigned i; + unsigned int i; void *pool = vhost; - for (i=0;iperm_config.auth_methods;i++) { - if (vhost->perm_config.auth[i].enabled && vhost->perm_config.auth[i].amod && - vhost->perm_config.auth[i].amod->vhost_init && vhost->perm_config.auth[i].auth_ctx == NULL) { - vhost->perm_config.auth[i].amod->vhost_init(&vhost->perm_config.auth[i].auth_ctx, pool, vhost->perm_config.auth[i].additional); + for (i = 0; i < vhost->perm_config.auth_methods; i++) { + if (vhost->perm_config.auth[i].enabled && + vhost->perm_config.auth[i].amod && + vhost->perm_config.auth[i].amod->vhost_init && + vhost->perm_config.auth[i].auth_ctx == NULL) { + vhost->perm_config.auth[i].amod->vhost_init( + &vhost->perm_config.auth[i].auth_ctx, pool, + vhost->perm_config.auth[i].additional); } } - if (vhost->perm_config.acct.amod && vhost->perm_config.acct.amod->vhost_init && + if (vhost->perm_config.acct.amod && + vhost->perm_config.acct.amod->vhost_init && vhost->perm_config.acct.acct_ctx == NULL) - vhost->perm_config.acct.amod->vhost_init(&vhost->perm_config.acct.acct_ctx, pool, vhost->perm_config.acct.additional); + vhost->perm_config.acct.amod->vhost_init( + &vhost->perm_config.acct.acct_ctx, pool, + vhost->perm_config.acct.additional); } /* returns a negative number if we have reached the score for this client. */ -static -void sec_mod_add_score_to_ip(sec_mod_st *sec, client_entry_st *e, const char *ip, unsigned points) +static void sec_mod_add_score_to_ip(sec_mod_st *sec, client_entry_st *e, + const char *ip, unsigned int points) { void *lpool = talloc_new(e); int ret, err; @@ -90,7 +97,7 @@ void sec_mod_add_score_to_ip(sec_mod_st *sec, client_entry_st *e, const char *ip if (e->vhost->perm_config.config->max_ban_score == 0) return; - msg.ip = (char*)ip; + msg.ip = (char *)ip; msg.score = points; msg.sid.data = e->sid; msg.sid.len = sizeof(e->sid); @@ -101,19 +108,20 @@ void sec_mod_add_score_to_ip(sec_mod_st *sec, client_entry_st *e, const char *ip } ret = send_msg(lpool, sec->cmd_fd, CMD_SECM_BAN_IP, &msg, - (pack_size_func) ban_ip_msg__get_packed_size, - (pack_func) ban_ip_msg__pack); + (pack_size_func)ban_ip_msg__get_packed_size, + (pack_func)ban_ip_msg__pack); if (ret < 0) { err = errno; - seclog(sec, LOG_WARNING, "error in sending BAN IP message: %s", strerror(err)); + seclog(sec, LOG_WARNING, "error in sending BAN IP message: %s", + strerror(err)); goto fail; } - fail: +fail: talloc_free(lpool); } -static void update_auth_time_stats(sec_mod_st * sec, time_t secs) +static void update_auth_time_stats(sec_mod_st *sec, time_t secs) { if (secs < 0) return; @@ -127,11 +135,15 @@ static void update_auth_time_stats(sec_mod_st * sec, time_t secs) if (secs > sec->max_auth_time) sec->max_auth_time = secs; - sec->avg_auth_time = ((uint64_t)sec->avg_auth_time*((uint64_t)(sec->total_authentications-1))+secs) / (uint64_t)sec->total_authentications; + sec->avg_auth_time = + ((uint64_t)sec->avg_auth_time * + ((uint64_t)(sec->total_authentications - 1)) + + secs) / + (uint64_t)sec->total_authentications; } -static -int send_sec_auth_reply(int cfd, sec_mod_st * sec, client_entry_st * entry, AUTHREP r) +static int send_sec_auth_reply(int cfd, sec_mod_st *sec, client_entry_st *entry, + AUTHREP r) { SecAuthReplyMsg msg = SEC_AUTH_REPLY_MSG__INIT; int ret; @@ -157,25 +169,24 @@ int send_sec_auth_reply(int cfd, sec_mod_st * sec, client_entry_st * entry, AUTH msg.dtls_session_id.data = entry->dtls_session_id; msg.dtls_session_id.len = sizeof(entry->dtls_session_id); - ret = send_msg(entry, cfd, CMD_SEC_AUTH_REPLY, - &msg, - (pack_size_func) - sec_auth_reply_msg__get_packed_size, - (pack_func) sec_auth_reply_msg__pack); + ret = send_msg( + entry, cfd, CMD_SEC_AUTH_REPLY, &msg, + (pack_size_func)sec_auth_reply_msg__get_packed_size, + (pack_func)sec_auth_reply_msg__pack); } else { sec->auth_failures++; msg.reply = AUTH__REP__FAILED; - ret = send_msg(entry, cfd, CMD_SEC_AUTH_REPLY, - &msg, - (pack_size_func) - sec_auth_reply_msg__get_packed_size, - (pack_func) sec_auth_reply_msg__pack); + ret = send_msg( + entry, cfd, CMD_SEC_AUTH_REPLY, &msg, + (pack_size_func)sec_auth_reply_msg__get_packed_size, + (pack_func)sec_auth_reply_msg__pack); } if (ret < 0) { int e = errno; + seclog(sec, LOG_ERR, "send_msg: %s", strerror(e)); return ret; } @@ -186,8 +197,7 @@ int send_sec_auth_reply(int cfd, sec_mod_st * sec, client_entry_st * entry, AUTH return 0; } -static -int send_sec_auth_reply_msg(int cfd, sec_mod_st * sec, client_entry_st * e) +static int send_sec_auth_reply_msg(int cfd, sec_mod_st *sec, client_entry_st *e) { SecAuthReplyMsg msg = SEC_AUTH_REPLY_MSG__INIT; int ret; @@ -204,8 +214,8 @@ int send_sec_auth_reply_msg(int cfd, sec_mod_st * sec, client_entry_st * e) msg.sid.len = sizeof(e->sid); ret = send_msg(e, cfd, CMD_SEC_AUTH_REPLY, &msg, - (pack_size_func) sec_auth_reply_msg__get_packed_size, - (pack_func) sec_auth_reply_msg__pack); + (pack_size_func)sec_auth_reply_msg__get_packed_size, + (pack_func)sec_auth_reply_msg__pack); if (ret < 0) { seclog(sec, LOG_ERR, "send_auth_reply_msg error"); } @@ -216,47 +226,69 @@ int send_sec_auth_reply_msg(int cfd, sec_mod_st * sec, client_entry_st * e) return ret; } -static int check_cert_user_group_status(sec_mod_st * sec, client_entry_st * e) +static int check_cert_user_group_status(sec_mod_st *sec, client_entry_st *e) { - unsigned found, i; + unsigned int found, i; if (e->auth_type & AUTH_TYPE_CERTIFICATE) { if (e->tls_auth_ok == 0) { - seclog(sec, LOG_INFO, "user %s "SESSION_STR" presented no certificate; rejecting", + seclog(sec, LOG_INFO, + "user %s " SESSION_STR + " presented no certificate; rejecting", e->acct_info.username, e->acct_info.safe_id); return -1; } - if (e->acct_info.username[0] == 0 && e->vhost->perm_config.config->cert_user_oid != NULL) { + if (e->acct_info.username[0] == 0 && + e->vhost->perm_config.config->cert_user_oid != NULL) { if (e->cert_user_name[0] == 0) { - seclog(sec, LOG_INFO, "no username in the certificate; rejecting"); - return -1; - } - - strlcpy(e->acct_info.username, e->cert_user_name, sizeof(e->acct_info.username)); - if (e->cert_group_names_size > 0 && e->vhost->perm_config.config->cert_group_oid != NULL && e->acct_info.groupname[0] == 0) - strlcpy(e->acct_info.groupname, e->cert_group_names[0], sizeof(e->acct_info.groupname)); - } else { - if (e->vhost->perm_config.config->cert_user_oid != NULL && e->cert_user_name[0] && strcmp(e->acct_info.username, e->cert_user_name) != 0) { seclog(sec, LOG_INFO, - "user '%s' "SESSION_STR" presented a certificate which is for user '%s'; rejecting", - e->acct_info.username, e->acct_info.safe_id, e->cert_user_name); + "no username in the certificate; rejecting"); return -1; } - if (e->vhost->perm_config.config->cert_group_oid != NULL) { + strlcpy(e->acct_info.username, e->cert_user_name, + sizeof(e->acct_info.username)); + if (e->cert_group_names_size > 0 && + e->vhost->perm_config.config->cert_group_oid != + NULL && + e->acct_info.groupname[0] == 0) + strlcpy(e->acct_info.groupname, + e->cert_group_names[0], + sizeof(e->acct_info.groupname)); + } else { + if (e->vhost->perm_config.config->cert_user_oid != + NULL && + e->cert_user_name[0] && + strcmp(e->acct_info.username, e->cert_user_name) != + 0) { + seclog(sec, LOG_INFO, + "user '%s' " SESSION_STR + " presented a certificate which is for user '%s'; rejecting", + e->acct_info.username, + e->acct_info.safe_id, e->cert_user_name); + return -1; + } + + if (e->vhost->perm_config.config->cert_group_oid != + NULL) { found = 0; - for (i=0;icert_group_names_size;i++) { - if (strcmp(e->acct_info.groupname, e->cert_group_names[i]) == 0) { + for (i = 0; i < e->cert_group_names_size; i++) { + if (strcmp(e->acct_info.groupname, + e->cert_group_names[i]) == + 0) { found++; break; } } if (found == 0) { seclog(sec, LOG_INFO, - "user '%s' "SESSION_STR" presented a certificate from group '%s' but he isn't a member of it; rejecting", - e->acct_info.username, e->acct_info.safe_id, e->acct_info.groupname); - return -1; + "user '%s' " SESSION_STR + " presented a certificate from group '%s' but he isn't a member of it; rejecting", + e->acct_info.username, + e->acct_info.safe_id, + e->acct_info.groupname); + return -1; } } } @@ -265,8 +297,7 @@ static int check_cert_user_group_status(sec_mod_st * sec, client_entry_st * e) return 0; } -static -int check_group(sec_mod_st * sec, client_entry_st * e) +static int check_group(sec_mod_st *sec, client_entry_st *e) { int ret; const char *req_group = NULL; @@ -275,9 +306,9 @@ int check_group(sec_mod_st * sec, client_entry_st * e) req_group = e->req_group_name; if (e->module && e->module->auth_group) { - ret = - e->module->auth_group(e->auth_ctx, req_group, e->acct_info.groupname, - sizeof(e->acct_info.groupname)); + ret = e->module->auth_group(e->auth_ctx, req_group, + e->acct_info.groupname, + sizeof(e->acct_info.groupname)); if (ret != 0) { return -1; } @@ -286,27 +317,31 @@ int check_group(sec_mod_st * sec, client_entry_st * e) /* set group name using the certificate info */ if (e->auth_type & AUTH_TYPE_CERTIFICATE) { - if (e->acct_info.groupname[0] == 0 && req_group != NULL && e->vhost->perm_config.config->cert_group_oid != NULL) { - unsigned i, found = 0; + if (e->acct_info.groupname[0] == 0 && req_group != NULL && + e->vhost->perm_config.config->cert_group_oid != NULL) { + unsigned int i, found = 0; - for (i=0;icert_group_names_size;i++) { - if (strcmp(req_group, e->cert_group_names[i]) == 0) { - strlcpy(e->acct_info.groupname, e->cert_group_names[i], sizeof(e->acct_info.groupname)); + for (i = 0; i < e->cert_group_names_size; i++) { + if (strcmp(req_group, e->cert_group_names[i]) == + 0) { + strlcpy(e->acct_info.groupname, + e->cert_group_names[i], + sizeof(e->acct_info.groupname)); found = 1; break; } } if (found == 0) { - seclog(sec, LOG_NOTICE, "user '%s' requested group '%s' but is not included on his certificate groups", - e->acct_info.username, req_group); + seclog(sec, LOG_NOTICE, + "user '%s' requested group '%s' but is not included on his certificate groups", + e->acct_info.username, req_group); return -1; } } } - ret = - check_cert_user_group_status(sec, e); + ret = check_cert_user_group_status(sec, e); if (ret < 0) { return -1; } @@ -320,8 +355,8 @@ int check_group(sec_mod_st * sec, client_entry_st * e) * @cmd: the command received * @result: the auth result */ -static -int handle_sec_auth_res(int cfd, sec_mod_st * sec, client_entry_st * e, int result) +static int handle_sec_auth_res(int cfd, sec_mod_st *sec, client_entry_st *e, + int result) { int ret; passwd_msg_st pst; @@ -344,8 +379,12 @@ int handle_sec_auth_res(int cfd, sec_mod_st * sec, client_entry_st * e, int resu if (result == ERR_AUTH_CONTINUE) { /* if the module allows multiple retries for the password and the password refers to the same stage */ - if (e->status != PS_AUTH_INIT && e->module && e->module->allows_retries && passwd_retries == 1) { - sec_mod_add_score_to_ip(sec, e, e->acct_info.remote_ip, e->vhost->perm_config.config->ban_points_wrong_password); + if (e->status != PS_AUTH_INIT && e->module && + e->module->allows_retries && passwd_retries == 1) { + sec_mod_add_score_to_ip( + sec, e, e->acct_info.remote_ip, + e->vhost->perm_config.config + ->ban_points_wrong_password); } ret = send_sec_auth_reply_msg(cfd, sec, e); @@ -354,7 +393,7 @@ int handle_sec_auth_res(int cfd, sec_mod_st * sec, client_entry_st * e, int resu seclog(sec, LOG_ERR, "could not send reply auth cmd."); return ret; } - return 0; /* wait for another command */ + return 0; /* wait for another command */ } else if (result == 0 && e->status != PS_AUTH_FAILED) { /* we checked status for PS_AUTH_FAILED, because status may * change async if we receive a message from main that the @@ -374,9 +413,13 @@ int handle_sec_auth_res(int cfd, sec_mod_st * sec, client_entry_st * e, int resu sizeof(e->acct_info.username)); } - seclog(sec, LOG_DEBUG, "auth complete %sfor user '%s' "SESSION_STR" of group: '%s'", - (e->auth_type & AUTH_TYPE_CERTIFICATE)?"(with cert)":"", - e->acct_info.username, e->acct_info.safe_id, e->acct_info.groupname); + seclog(sec, LOG_DEBUG, + "auth complete %sfor user '%s' " SESSION_STR + " of group: '%s'", + (e->auth_type & AUTH_TYPE_CERTIFICATE) ? "(with cert)" : + "", + e->acct_info.username, e->acct_info.safe_id, + e->acct_info.groupname); ret = send_sec_auth_reply(cfd, sec, e, AUTH__REP__OK); if (ret < 0) { @@ -389,7 +432,9 @@ int handle_sec_auth_res(int cfd, sec_mod_st * sec, client_entry_st * e, int resu } else { e->status = PS_AUTH_FAILED; - sec_mod_add_score_to_ip(sec, e, e->acct_info.remote_ip, e->vhost->perm_config.config->ban_points_wrong_password); + sec_mod_add_score_to_ip( + sec, e, e->acct_info.remote_ip, + e->vhost->perm_config.config->ban_points_wrong_password); ret = send_sec_auth_reply(cfd, sec, e, AUTH__REP__FAILED); if (ret < 0) { @@ -400,7 +445,8 @@ int handle_sec_auth_res(int cfd, sec_mod_st * sec, client_entry_st * e, int resu if (result < 0) { ret = result; } else { - seclog(sec, LOG_ERR, "unexpected auth result: %d\n", result); + seclog(sec, LOG_ERR, "unexpected auth result: %d\n", + result); ret = ERR_BAD_COMMAND; } } @@ -415,8 +461,7 @@ static void stats_add_to(stats_st *dst, stats_st *src1, stats_st *src2) dst->uptime = src1->uptime + src2->uptime; } -static -int send_failed_session_open_reply(sec_mod_st *sec, int fd) +static int send_failed_session_open_reply(sec_mod_st *sec, int fd) { SecmSessionReplyMsg rep = SECM_SESSION_REPLY_MSG__INIT; void *lpool; @@ -430,8 +475,8 @@ int send_failed_session_open_reply(sec_mod_st *sec, int fd) } ret = send_msg(lpool, fd, CMD_SECM_SESSION_REPLY, &rep, - (pack_size_func) secm_session_reply_msg__get_packed_size, - (pack_func) secm_session_reply_msg__pack); + (pack_size_func)secm_session_reply_msg__get_packed_size, + (pack_func)secm_session_reply_msg__pack); if (ret < 0) { seclog(sec, LOG_WARNING, "error in sending session reply"); ret = ERR_BAD_COMMAND; /* we desynced */ @@ -441,7 +486,8 @@ int send_failed_session_open_reply(sec_mod_st *sec, int fd) return ret; } -int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, const SecmSessionOpenMsg *req) +int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, + const SecmSessionOpenMsg *req) { client_entry_st *e; void *lpool; @@ -452,38 +498,53 @@ int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, const SecmSessionOpenM rep.config = &_cfg; if (req->sid.len != SID_SIZE) { - seclog(sec, LOG_ERR, "auth session open but with illegal sid size (%d)!", + seclog(sec, LOG_ERR, + "auth session open but with illegal sid size (%d)!", (int)req->sid.len); return send_failed_session_open_reply(sec, fd); } e = find_client_entry(sec, req->sid.data); if (e == NULL) { - seclog(sec, LOG_INFO, "session open but with non-existing SID!"); + seclog(sec, LOG_INFO, + "session open but with non-existing SID!"); return send_failed_session_open_reply(sec, fd); } if (e->status != PS_AUTH_COMPLETED) { - seclog(sec, LOG_ERR, "session open received in unauthenticated client %s "SESSION_STR"!", e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_ERR, + "session open received in unauthenticated client %s " SESSION_STR + "!", + e->acct_info.username, e->acct_info.safe_id); return send_failed_session_open_reply(sec, fd); } - if IS_CLIENT_ENTRY_EXPIRED(sec, e, time(NULL)) { - seclog(sec, LOG_ERR, "session expired; denied session for user '%s' "SESSION_STR, e->acct_info.username, e->acct_info.safe_id); + if IS_CLIENT_ENTRY_EXPIRED (sec, e, time(NULL)) { + seclog(sec, LOG_ERR, + "session expired; denied session for user '%s' " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); e->status = PS_AUTH_FAILED; return send_failed_session_open_reply(sec, fd); } if (req->ipv4) - strlcpy(e->acct_info.ipv4, req->ipv4, sizeof(e->acct_info.ipv4)); + strlcpy(e->acct_info.ipv4, req->ipv4, + sizeof(e->acct_info.ipv4)); if (req->ipv6) - strlcpy(e->acct_info.ipv6, req->ipv6, sizeof(e->acct_info.ipv6)); + strlcpy(e->acct_info.ipv6, req->ipv6, + sizeof(e->acct_info.ipv6)); - if (e->vhost->perm_config.acct.amod != NULL && e->vhost->perm_config.acct.amod->open_session != NULL && e->session_is_open == 0) { - ret = e->vhost->perm_config.acct.amod->open_session(e->vhost_acct_ctx, e->auth_type, &e->acct_info, req->sid.data, req->sid.len); + if (e->vhost->perm_config.acct.amod != NULL && + e->vhost->perm_config.acct.amod->open_session != NULL && + e->session_is_open == 0) { + ret = e->vhost->perm_config.acct.amod->open_session( + e->vhost_acct_ctx, e->auth_type, &e->acct_info, + req->sid.data, req->sid.len); if (ret < 0) { e->status = PS_AUTH_FAILED; - seclog(sec, LOG_INFO, "denied session for user '%s' "SESSION_STR, e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_INFO, + "denied session for user '%s' " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); return send_failed_session_open_reply(sec, fd); } } @@ -500,9 +561,11 @@ int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, const SecmSessionOpenM /* Fixme: possibly we should allow for completely random seeds */ if (e->vhost->perm_config.config->predictable_ips != 0) { - rep.ipv4_seed = hash_any(e->acct_info.username, strlen(e->acct_info.username), 0); + rep.ipv4_seed = hash_any(e->acct_info.username, + strlen(e->acct_info.username), 0); } else { - ret = gnutls_rnd(GNUTLS_RND_NONCE, &rep.ipv4_seed, sizeof(rep.ipv4_seed)); + ret = gnutls_rnd(GNUTLS_RND_NONCE, &rep.ipv4_seed, + sizeof(rep.ipv4_seed)); if (ret < 0) return -1; } @@ -517,68 +580,80 @@ int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, const SecmSessionOpenM return ERR_BAD_COMMAND; /* we desync */ } - if (e->vhost->config_module && e->vhost->config_module->get_sup_config) { - ret = e->vhost->config_module->get_sup_config(e->vhost->perm_config.config, e, &rep, lpool); + if (e->vhost->config_module && + e->vhost->config_module->get_sup_config) { + ret = e->vhost->config_module->get_sup_config( + e->vhost->perm_config.config, e, &rep, lpool); if (ret < 0) { - seclog(sec, LOG_ERR, "error reading additional configuration for '%s' "SESSION_STR, e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_ERR, + "error reading additional configuration for '%s' " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); talloc_free(lpool); return send_failed_session_open_reply(sec, fd); } } ret = send_msg(lpool, fd, CMD_SECM_SESSION_REPLY, &rep, - (pack_size_func) secm_session_reply_msg__get_packed_size, - (pack_func) secm_session_reply_msg__pack); + (pack_size_func)secm_session_reply_msg__get_packed_size, + (pack_func)secm_session_reply_msg__pack); if (ret < 0) { seclog(sec, LOG_ERR, "error in sending session reply"); return ERR_BAD_COMMAND; /* we desync */ } talloc_free(lpool); - seclog(sec, LOG_INFO, "%sinitiating session for user '%s' "SESSION_STR, PREFIX_VHOST(e->vhost), e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_INFO, "%sinitiating session for user '%s' " SESSION_STR, + PREFIX_VHOST(e->vhost), e->acct_info.username, + e->acct_info.safe_id); /* refresh cookie validity */ - e->exptime = time(NULL) + e->vhost->perm_config.config->cookie_timeout + AUTH_SLACK_TIME; + e->exptime = time(NULL) + e->vhost->perm_config.config->cookie_timeout + + AUTH_SLACK_TIME; e->in_use++; return 0; } -int handle_secm_session_close_cmd(sec_mod_st *sec, int fd, const SecmSessionCloseMsg *req) +int handle_secm_session_close_cmd(sec_mod_st *sec, int fd, + const SecmSessionCloseMsg *req) { client_entry_st *e; int ret; CliStatsMsg rep = CLI_STATS_MSG__INIT; if (req->sid.len != SID_SIZE) { - seclog(sec, LOG_ERR, "auth session close but with illegal sid size (%d)!", + seclog(sec, LOG_ERR, + "auth session close but with illegal sid size (%d)!", (int)req->sid.len); return ERR_BAD_COMMAND; } e = find_client_entry(sec, req->sid.data); if (e == NULL) { - seclog(sec, LOG_INFO, "session close but with non-existing SID"); + seclog(sec, LOG_INFO, + "session close but with non-existing SID"); return send_msg(sec, fd, CMD_SECM_CLI_STATS, &rep, - (pack_size_func) cli_stats_msg__get_packed_size, - (pack_func) cli_stats_msg__pack); + (pack_size_func)cli_stats_msg__get_packed_size, + (pack_func)cli_stats_msg__pack); } if (e->status < PS_AUTH_COMPLETED) { - seclog(sec, LOG_DEBUG, "session close received in unauthenticated client %s "SESSION_STR"!", e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_DEBUG, + "session close received in unauthenticated client %s " SESSION_STR + "!", + e->acct_info.username, e->acct_info.safe_id); return send_msg(e, fd, CMD_SECM_CLI_STATS, &rep, - (pack_size_func) cli_stats_msg__get_packed_size, - (pack_func) cli_stats_msg__pack); + (pack_size_func)cli_stats_msg__get_packed_size, + (pack_func)cli_stats_msg__pack); } - if (req->has_uptime && req->uptime > e->stats.uptime) { - e->stats.uptime = req->uptime; + e->stats.uptime = req->uptime; } if (req->has_bytes_in && req->bytes_in > e->stats.bytes_in) { - e->stats.bytes_in = req->bytes_in; + e->stats.bytes_in = req->bytes_in; } if (req->has_bytes_out && req->bytes_out > e->stats.bytes_out) { - e->stats.bytes_out = req->bytes_out; + e->stats.bytes_out = req->bytes_out; } if (req->server_disconnected) { @@ -592,8 +667,8 @@ int handle_secm_session_close_cmd(sec_mod_st *sec, int fd, const SecmSessionClos rep.discon_reason = e->discon_reason; ret = send_msg(e, fd, CMD_SECM_CLI_STATS, &rep, - (pack_size_func) cli_stats_msg__get_packed_size, - (pack_func) cli_stats_msg__pack); + (pack_size_func)cli_stats_msg__get_packed_size, + (pack_func)cli_stats_msg__pack); if (ret < 0) { seclog(sec, LOG_ERR, "error in sending session stats"); return ERR_BAD_COMMAND; @@ -612,7 +687,8 @@ void handle_sec_auth_ban_ip_reply(sec_mod_st *sec, const BanIpReplyMsg *msg) client_entry_st *e; if (msg->sid.len != SID_SIZE) { - seclog(sec, LOG_ERR, "ban IP reply but with illegal sid size (%d)!", + seclog(sec, LOG_ERR, + "ban IP reply but with illegal sid size (%d)!", (int)msg->sid.len); return; } @@ -627,25 +703,31 @@ void handle_sec_auth_ban_ip_reply(sec_mod_st *sec, const BanIpReplyMsg *msg) } } -int handle_sec_auth_stats_cmd(sec_mod_st * sec, const CliStatsMsg * req, pid_t pid) +int handle_sec_auth_stats_cmd(sec_mod_st *sec, const CliStatsMsg *req, + pid_t pid) { client_entry_st *e; stats_st totals; if (req->sid.len != SID_SIZE) { - seclog(sec, LOG_ERR, "auth session stats but with illegal sid size (%d)!", + seclog(sec, LOG_ERR, + "auth session stats but with illegal sid size (%d)!", (int)req->sid.len); return -1; } e = find_client_entry(sec, req->sid.data); if (e == NULL) { - seclog(sec, LOG_INFO, "session stats but with non-existing SID"); + seclog(sec, LOG_INFO, + "session stats but with non-existing SID"); return -1; } if (e->status != PS_AUTH_COMPLETED) { - seclog(sec, LOG_ERR, "session stats received in unauthenticated client %s "SESSION_STR"!", e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_ERR, + "session stats received in unauthenticated client %s " SESSION_STR + "!", + e->acct_info.username, e->acct_info.safe_id); return -1; } @@ -664,29 +746,35 @@ int handle_sec_auth_stats_cmd(sec_mod_st * sec, const CliStatsMsg * req, pid_t p /* update PID */ e->acct_info.id = pid; - if (e->vhost->perm_config.acct.amod == NULL || e->vhost->perm_config.acct.amod->session_stats == NULL) + if (e->vhost->perm_config.acct.amod == NULL || + e->vhost->perm_config.acct.amod->session_stats == NULL) return 0; stats_add_to(&totals, &e->stats, &e->saved_stats); if (req->remote_ip) - strlcpy(e->acct_info.remote_ip, req->remote_ip, sizeof(e->acct_info.remote_ip)); + strlcpy(e->acct_info.remote_ip, req->remote_ip, + sizeof(e->acct_info.remote_ip)); if (req->ipv4) - strlcpy(e->acct_info.ipv4, req->ipv4, sizeof(e->acct_info.ipv4)); + strlcpy(e->acct_info.ipv4, req->ipv4, + sizeof(e->acct_info.ipv4)); if (req->ipv6) - strlcpy(e->acct_info.ipv6, req->ipv6, sizeof(e->acct_info.ipv6)); + strlcpy(e->acct_info.ipv6, req->ipv6, + sizeof(e->acct_info.ipv6)); - e->vhost->perm_config.acct.amod->session_stats(e->vhost_acct_ctx, e->auth_type, &e->acct_info, &totals); + e->vhost->perm_config.acct.amod->session_stats( + e->vhost_acct_ctx, e->auth_type, &e->acct_info, &totals); return 0; } -int handle_sec_auth_cont(int cfd, sec_mod_st * sec, const SecAuthContMsg * req) +int handle_sec_auth_cont(int cfd, sec_mod_st *sec, const SecAuthContMsg *req) { client_entry_st *e; int ret; if (req->sid.len != SID_SIZE) { - seclog(sec, LOG_ERR, "auth cont but with illegal sid size (%d)!", + seclog(sec, LOG_ERR, + "auth cont but with illegal sid size (%d)!", (int)req->sid.len); return -1; } @@ -698,17 +786,22 @@ int handle_sec_auth_cont(int cfd, sec_mod_st * sec, const SecAuthContMsg * req) } if (e->status != PS_AUTH_INIT && e->status != PS_AUTH_CONT) { - seclog(sec, LOG_ERR, "auth cont received for %s "SESSION_STR" but we are on state %s(%u)!", - e->acct_info.username, e->acct_info.safe_id, ps_status_to_str(e->status, 0), e->status); + seclog(sec, LOG_ERR, + "auth cont received for %s " SESSION_STR + " but we are on state %s(%u)!", + e->acct_info.username, e->acct_info.safe_id, + ps_status_to_str(e->status, 0), e->status); ret = -1; goto cleanup; } - seclog(sec, LOG_DEBUG, "auth cont for user '%s' "SESSION_STR, e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_DEBUG, "auth cont for user '%s' " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); if (req->password == NULL) { - seclog(sec, LOG_ERR, "no password given in auth cont for user '%s' "SESSION_STR, - e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_ERR, + "no password given in auth cont for user '%s' " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); ret = -1; goto cleanup; } @@ -721,40 +814,45 @@ int handle_sec_auth_cont(int cfd, sec_mod_st * sec, const SecAuthContMsg * req) e->status = PS_AUTH_CONT; - ret = - e->module->auth_pass(e->auth_ctx, req->password, - strlen(req->password)); + ret = e->module->auth_pass(e->auth_ctx, req->password, + strlen(req->password)); if (ret < 0) { if (ret != ERR_AUTH_CONTINUE) { seclog(sec, LOG_DEBUG, - "error in password given in auth cont for user '%s' "SESSION_STR, + "error in password given in auth cont for user '%s' " SESSION_STR, e->acct_info.username, e->acct_info.safe_id); } goto cleanup; } - cleanup: +cleanup: return handle_sec_auth_res(cfd, sec, e, ret); } -static -int set_module(sec_mod_st * sec, vhost_cfg_st *vhost, client_entry_st *e, unsigned auth_type) +static int set_module(sec_mod_st *sec, vhost_cfg_st *vhost, client_entry_st *e, + unsigned int auth_type) { - unsigned i; + unsigned int i; if (auth_type == 0) return -1; /* Find the first configured authentication method which contains * the method asked by the worker, and use that. */ - for (i=0;iperm_config.auth_methods;i++) { - if (vhost->perm_config.auth[i].enabled && (vhost->perm_config.auth[i].type & auth_type) == auth_type) { + for (i = 0; i < vhost->perm_config.auth_methods; i++) { + if (vhost->perm_config.auth[i].enabled && + (vhost->perm_config.auth[i].type & auth_type) == + auth_type) { e->module = vhost->perm_config.auth[i].amod; e->auth_type = vhost->perm_config.auth[i].type; e->vhost_auth_ctx = vhost->perm_config.auth[i].auth_ctx; e->vhost_acct_ctx = vhost->perm_config.acct.acct_ctx; - seclog(sec, LOG_INFO, "%susing '%s' authentication to authenticate user "SESSION_STR, PREFIX_VHOST(vhost), vhost->perm_config.auth[i].name, e->acct_info.safe_id); + seclog(sec, LOG_INFO, + "%susing '%s' authentication to authenticate user " SESSION_STR, + PREFIX_VHOST(vhost), + vhost->perm_config.auth[i].name, + e->acct_info.safe_id); return 0; } } @@ -762,12 +860,13 @@ int set_module(sec_mod_st * sec, vhost_cfg_st *vhost, client_entry_st *e, unsign return -1; } -int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pid_t pid) +int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, + pid_t pid) { int ret = -1; client_entry_st *e; - unsigned i; - unsigned need_continue = 0; + unsigned int i; + unsigned int need_continue = 0; vhost_cfg_st *vhost; hmac_component_st hmac_components[3]; uint8_t computed_hmac[HMAC_DIGEST_SIZE]; @@ -780,27 +879,33 @@ int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pi } /* Authenticate the client parameters */ - session_start_time = (time_t)req->session_start_time; // avoid time_t size problem + session_start_time = + (time_t)req->session_start_time; // avoid time_t size problem - hmac_components[0].data = req->orig_remote_ip; + hmac_components[0].data = req->orig_remote_ip; // req->ip is required and protobuf doesn't permit null for required parameters hmac_components[0].length = strlen(req->orig_remote_ip); hmac_components[1].data = req->our_ip; hmac_components[1].length = req->our_ip ? strlen(req->our_ip) : 0; - hmac_components[2].data = (void*)&session_start_time; + hmac_components[2].data = (void *)&session_start_time; hmac_components[2].length = sizeof(session_start_time); - generate_hmac(sizeof(sec->hmac_key), sec->hmac_key, ARRAY_SIZE(hmac_components), hmac_components, computed_hmac); + generate_hmac(sizeof(sec->hmac_key), sec->hmac_key, + ARRAY_SIZE(hmac_components), hmac_components, + computed_hmac); if (memcmp(computed_hmac, req->hmac.data, req->hmac.len) != 0) { - seclog(sec, LOG_NOTICE, "hmac presented by client doesn't match parameters provided - possible replay"); + seclog(sec, LOG_NOTICE, + "hmac presented by client doesn't match parameters provided - possible replay"); return -1; } vhost = find_vhost(sec->vconfig, req->vhost); - if ((now - session_start_time) > vhost->perm_config.config->auth_timeout) { - seclog(sec, LOG_NOTICE, "hmac presented by client expired - possible replay"); + if ((now - session_start_time) > + vhost->perm_config.config->auth_timeout) { + seclog(sec, LOG_NOTICE, + "hmac presented by client expired - possible replay"); return -1; } @@ -812,7 +917,8 @@ int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pi ret = set_module(sec, vhost, e, req->auth_type); if (ret < 0) { - seclog(sec, LOG_ERR, "no module found for auth type %u", (unsigned)req->auth_type); + seclog(sec, LOG_ERR, "no module found for auth type %u", + (unsigned int)req->auth_type); goto cleanup; } @@ -825,8 +931,8 @@ int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pi st.user_agent = req->user_agent; st.id = pid; - ret = - e->module->auth_init(&e->auth_ctx, e, e->vhost_auth_ctx, &st); + ret = e->module->auth_init(&e->auth_ctx, e, e->vhost_auth_ctx, + &st); if (ret == ERR_AUTH_CONTINUE) { need_continue = 1; } else if (ret < 0) { @@ -837,38 +943,46 @@ int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pi e->tls_auth_ok = req->tls_auth_ok; if (req->device_platform != NULL) { - strlcpy(e->acct_info.device_platform, req->device_platform, sizeof(e->acct_info.device_platform)); + strlcpy(e->acct_info.device_platform, req->device_platform, + sizeof(e->acct_info.device_platform)); } if (req->device_type != NULL) { - strlcpy(e->acct_info.device_type, req->device_type, sizeof(e->acct_info.device_type)); + strlcpy(e->acct_info.device_type, req->device_type, + sizeof(e->acct_info.device_type)); } if (req->user_agent != NULL) - strlcpy(e->acct_info.user_agent, req->user_agent, sizeof(e->acct_info.user_agent)); + strlcpy(e->acct_info.user_agent, req->user_agent, + sizeof(e->acct_info.user_agent)); // Real user name is retrieved after auth. if (!(req->auth_type & CONFIDENTIAL_USER_NAME_AUTH_TYPES)) { if (req->user_name != NULL) { - strlcpy(e->acct_info.username, req->user_name, sizeof(e->acct_info.username)); + strlcpy(e->acct_info.username, req->user_name, + sizeof(e->acct_info.username)); } } if (req->our_ip != NULL) { - strlcpy(e->acct_info.our_ip, req->our_ip, sizeof(e->acct_info.our_ip)); + strlcpy(e->acct_info.our_ip, req->our_ip, + sizeof(e->acct_info.our_ip)); } if (req->group_name != NULL) { - strlcpy(e->req_group_name, req->group_name, sizeof(e->req_group_name)); + strlcpy(e->req_group_name, req->group_name, + sizeof(e->req_group_name)); } if (req->cert_user_name != NULL) { - strlcpy(e->cert_user_name, req->cert_user_name, sizeof(e->cert_user_name)); + strlcpy(e->cert_user_name, req->cert_user_name, + sizeof(e->cert_user_name)); } - e->cert_group_names_size = MIN(MAX_GROUPS,req->n_cert_group_names); - for (i=0;icert_group_names_size;i++) { - e->cert_group_names[i] = talloc_strdup(e, req->cert_group_names[i]); + e->cert_group_names_size = MIN(MAX_GROUPS, req->n_cert_group_names); + for (i = 0; i < e->cert_group_names_size; i++) { + e->cert_group_names[i] = + talloc_strdup(e, req->cert_group_names[i]); if (e->cert_group_names[i] == NULL) { e->cert_group_names_size = 0; break; @@ -876,9 +990,11 @@ int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pi } e->status = PS_AUTH_INIT; - seclog(sec, LOG_DEBUG, "auth init %sfor user '%s' "SESSION_STR" of group: '%s' from '%s'", - req->tls_auth_ok?"(with cert) ":"", - e->acct_info.username, e->acct_info.safe_id, e->acct_info.groupname, req->remote_ip); + seclog(sec, LOG_DEBUG, + "auth init %sfor user '%s' " SESSION_STR + " of group: '%s' from '%s'", + req->tls_auth_ok ? "(with cert) " : "", e->acct_info.username, + e->acct_info.safe_id, e->acct_info.groupname, req->remote_ip); if (need_continue != 0) { ret = ERR_AUTH_CONTINUE; @@ -886,7 +1002,7 @@ int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, pi } ret = 0; - cleanup: +cleanup: return handle_sec_auth_res(cfd, sec, e, ret); } @@ -896,9 +1012,15 @@ void sec_auth_user_deinit(sec_mod_st *sec, client_entry_st *e) vhost = e->vhost; - seclog(sec, LOG_DEBUG, "permanently closing session of user '%s' "SESSION_STR, e->acct_info.username, e->acct_info.safe_id); - if (vhost->perm_config.acct.amod != NULL && vhost->perm_config.acct.amod->close_session != NULL && e->session_is_open != 0) { - vhost->perm_config.acct.amod->close_session(e->vhost_acct_ctx, e->auth_type, &e->acct_info, &e->saved_stats, e->discon_reason); + seclog(sec, LOG_DEBUG, + "permanently closing session of user '%s' " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); + if (vhost->perm_config.acct.amod != NULL && + vhost->perm_config.acct.amod->close_session != NULL && + e->session_is_open != 0) { + vhost->perm_config.acct.amod->close_session( + e->vhost_acct_ctx, e->auth_type, &e->acct_info, + &e->saved_stats, e->discon_reason); } if (e->auth_ctx != NULL) { diff --git a/src/sec-mod-auth.h b/src/sec-mod-auth.h index 616d8d52..69c13650 100644 --- a/src/sec-mod-auth.h +++ b/src/sec-mod-auth.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_SEC_MOD_AUTH_H -# define OC_SEC_MOD_AUTH_H +#define OC_SEC_MOD_AUTH_H #include #include @@ -28,26 +28,30 @@ typedef struct passwd_msg_st { char *msg_str; - unsigned counter; + unsigned int counter; } passwd_msg_st; typedef struct auth_mod_st { unsigned int type; - unsigned int allows_retries; /* whether the module allows retries of the same password */ - void (*vhost_init)(void **vctx, void *pool, void* additional); + unsigned int + allows_retries; /* whether the module allows retries of the same password */ + void (*vhost_init)(void **vctx, void *pool, void *additional); void (*vhost_deinit)(void *vctx); - int (*auth_init)(void **ctx, void *pool, void *vctx, const common_auth_init_st *); - int (*auth_msg)(void* ctx, void *pool, passwd_msg_st *); - int (*auth_pass)(void* ctx, const char* pass, unsigned pass_len); - int (*auth_group)(void* ctx, const char *suggested, char *groupname, int groupname_size); - int (*auth_user)(void* ctx, char *groupname, int groupname_size); + int (*auth_init)(void **ctx, void *pool, void *vctx, + const common_auth_init_st *); + int (*auth_msg)(void *ctx, void *pool, passwd_msg_st *); + int (*auth_pass)(void *ctx, const char *pass, unsigned int pass_len); + int (*auth_group)(void *ctx, const char *suggested, char *groupname, + int groupname_size); + int (*auth_user)(void *ctx, char *groupname, int groupname_size); - void (*auth_deinit)(void* ctx); - void (*group_list)(void *pool, void *additional, char ***groupname, unsigned *groupname_size); + void (*auth_deinit)(void *ctx); + void (*group_list)(void *pool, void *additional, char ***groupname, + unsigned int *groupname_size); } auth_mod_st; void main_auth_init(main_server_st *s); -void proc_auth_deinit(main_server_st* s, struct proc_st* proc); +void proc_auth_deinit(main_server_st *s, struct proc_st *proc); /* The authentication with the worker thread is shown in ipc.proto. */ diff --git a/src/sec-mod-cookies.c b/src/sec-mod-cookies.c index 46d0dd90..c46546e9 100644 --- a/src/sec-mod-cookies.c +++ b/src/sec-mod-cookies.c @@ -32,11 +32,13 @@ static void send_empty_reply(void *pool, int fd, sec_mod_st *sec) SecmListCookiesReplyMsg msg = SECM_LIST_COOKIES_REPLY_MSG__INIT; int ret; - ret = send_msg(pool, fd, CMD_SECM_LIST_COOKIES_REPLY, &msg, - (pack_size_func) secm_list_cookies_reply_msg__get_packed_size, - (pack_func) secm_list_cookies_reply_msg__pack); + ret = send_msg( + pool, fd, CMD_SECM_LIST_COOKIES_REPLY, &msg, + (pack_size_func)secm_list_cookies_reply_msg__get_packed_size, + (pack_func)secm_list_cookies_reply_msg__pack); if (ret < 0) { - seclog(sec, LOG_ERR, "Error sending empty show cookies reply to main"); + seclog(sec, LOG_ERR, + "Error sending empty show cookies reply to main"); } } @@ -57,13 +59,13 @@ void handle_secm_list_cookies_reply(void *pool, int fd, sec_mod_st *sec) seclog(sec, LOG_DEBUG, "sending list cookies reply to main"); - msg.cookies = talloc_size(pool, sizeof(CookieIntMsg*)*db->elems); + msg.cookies = talloc_size(pool, sizeof(CookieIntMsg *) * db->elems); if (msg.cookies == NULL) { send_empty_reply(pool, fd, sec); return; } - cookies = talloc_size(pool, sizeof(CookieIntMsg)*db->elems); + cookies = talloc_size(pool, sizeof(CookieIntMsg) * db->elems); if (cookies == NULL) { send_empty_reply(pool, fd, sec); return; @@ -71,15 +73,17 @@ void handle_secm_list_cookies_reply(void *pool, int fd, sec_mod_st *sec) t = htable_first(db, &iter); while (t != NULL) { - if IS_CLIENT_ENTRY_EXPIRED(sec, t, now) + if IS_CLIENT_ENTRY_EXPIRED (sec, t, now) goto cont; if (msg.n_cookies >= db->elems) break; cookie_int_msg__init(&cookies[msg.n_cookies]); - cookies[msg.n_cookies].safe_id.data = (void*)t->acct_info.safe_id; - cookies[msg.n_cookies].safe_id.len = sizeof(t->acct_info.safe_id); + cookies[msg.n_cookies].safe_id.data = + (void *)t->acct_info.safe_id; + cookies[msg.n_cookies].safe_id.len = + sizeof(t->acct_info.safe_id); cookies[msg.n_cookies].session_is_open = t->session_is_open; cookies[msg.n_cookies].tls_auth_ok = t->tls_auth_ok; @@ -105,15 +109,17 @@ void handle_secm_list_cookies_reply(void *pool, int fd, sec_mod_st *sec) msg.cookies[msg.n_cookies] = &cookies[msg.n_cookies]; msg.n_cookies++; - cont: +cont: t = htable_next(db, &iter); } - ret = send_msg(pool, fd, CMD_SECM_LIST_COOKIES_REPLY, &msg, - (pack_size_func) secm_list_cookies_reply_msg__get_packed_size, - (pack_func) secm_list_cookies_reply_msg__pack); + ret = send_msg( + pool, fd, CMD_SECM_LIST_COOKIES_REPLY, &msg, + (pack_size_func)secm_list_cookies_reply_msg__get_packed_size, + (pack_func)secm_list_cookies_reply_msg__pack); if (ret < 0) { - seclog(sec, LOG_ERR, "Error sending show cookies reply to main"); + seclog(sec, LOG_ERR, + "Error sending show cookies reply to main"); } talloc_free(msg.cookies); diff --git a/src/sec-mod-db.c b/src/sec-mod-db.c index 6832fa9d..67f838f2 100644 --- a/src/sec-mod-db.c +++ b/src/sec-mod-db.c @@ -57,6 +57,7 @@ static size_t rehash(const void *_e, void *unused) void *sec_mod_client_db_init(sec_mod_st *sec) { struct htable *db = talloc(sec, struct htable); + if (db == NULL) return NULL; @@ -68,16 +69,16 @@ void *sec_mod_client_db_init(sec_mod_st *sec) void sec_mod_client_db_deinit(sec_mod_st *sec) { -struct htable *db = sec->client_db; + struct htable *db = sec->client_db; htable_clear(db); talloc_free(db); } /* The number of elements */ -unsigned sec_mod_client_db_elems(sec_mod_st *sec) +unsigned int sec_mod_client_db_elems(sec_mod_st *sec) { -struct htable *db = sec->client_db; + struct htable *db = sec->client_db; if (db) return db->elems; @@ -85,7 +86,8 @@ struct htable *db = sec->client_db; return 0; } -client_entry_st *new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *vhost, const char *ip, unsigned pid) +client_entry_st *new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *vhost, + const char *ip, unsigned int pid) { struct htable *db = sec->client_db; client_entry_st *e, *te; @@ -99,7 +101,8 @@ client_entry_st *new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *vhost, c } if (ip) - strlcpy(e->acct_info.remote_ip, ip, sizeof(e->acct_info.remote_ip)); + strlcpy(e->acct_info.remote_ip, ip, + sizeof(e->acct_info.remote_ip)); e->acct_info.id = pid; e->vhost = vhost; @@ -111,21 +114,23 @@ client_entry_st *new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *vhost, c } e->sid[0] = sec->sec_mod_instance_id; - seclog(sec, LOG_INFO, "sec-mod instance %d issue cookie", sec->sec_mod_instance_id); + seclog(sec, LOG_INFO, "sec-mod instance %d issue cookie", + sec->sec_mod_instance_id); /* check if in use */ te = find_client_entry(sec, e->sid); } while (te != NULL && retries-- >= 0); if (te != NULL) { - seclog(sec, LOG_ERR, - "could not generate a unique SID!"); + seclog(sec, LOG_ERR, "could not generate a unique SID!"); goto fail; } - calc_safe_id(e->sid, SID_SIZE, (char *)e->acct_info.safe_id, sizeof(e->acct_info.safe_id)); + calc_safe_id(e->sid, SID_SIZE, (char *)e->acct_info.safe_id, + sizeof(e->acct_info.safe_id)); now = time(NULL); - e->exptime = now + vhost->perm_config.config->cookie_timeout + AUTH_SLACK_TIME; + e->exptime = now + vhost->perm_config.config->cookie_timeout + + AUTH_SLACK_TIME; e->created = now; if (htable_add(db, rehash(e, NULL), e) == 0) { @@ -136,7 +141,7 @@ client_entry_st *new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *vhost, c return e; - fail: +fail: talloc_free(e); return NULL; } @@ -161,7 +166,7 @@ client_entry_st *find_client_entry(sec_mod_st *sec, uint8_t sid[SID_SIZE]) return htable_get(db, rehash(&t, NULL), client_entry_cmp, &t); } -static void clean_entry(sec_mod_st *sec, client_entry_st * e) +static void clean_entry(sec_mod_st *sec, client_entry_st *e) { sec_auth_user_deinit(sec, e); talloc_free(e->msg_str); @@ -177,16 +182,15 @@ void cleanup_client_entries(sec_mod_st *sec) t = htable_first(db, &iter); while (t != NULL) { - if IS_CLIENT_ENTRY_EXPIRED_FULL(sec, t, now, 1) { + if IS_CLIENT_ENTRY_EXPIRED_FULL (sec, t, now, 1) { htable_delval(db, &iter); clean_entry(sec, t); } t = htable_next(db, &iter); - } } -void del_client_entry(sec_mod_st *sec, client_entry_st * e) +void del_client_entry(sec_mod_st *sec, client_entry_st *e) { struct htable *db = sec->client_db; @@ -194,16 +198,20 @@ void del_client_entry(sec_mod_st *sec, client_entry_st * e) clean_entry(sec, e); } -void expire_client_entry(sec_mod_st *sec, client_entry_st * e) +void expire_client_entry(sec_mod_st *sec, client_entry_st *e) { time_t now; if (e->in_use > 0) e->in_use--; if (e->in_use == 0) { - if (e->vhost->perm_config.config->persistent_cookies == 0 && (e->discon_reason == REASON_SERVER_DISCONNECT || - e->discon_reason == REASON_SESSION_TIMEOUT || (e->session_is_open && e->discon_reason == REASON_USER_DISCONNECT))) { - seclog(sec, LOG_INFO, "invalidating session of user '%s' "SESSION_STR, + if (e->vhost->perm_config.config->persistent_cookies == 0 && + (e->discon_reason == REASON_SERVER_DISCONNECT || + e->discon_reason == REASON_SESSION_TIMEOUT || + (e->session_is_open && + e->discon_reason == REASON_USER_DISCONNECT))) { + seclog(sec, LOG_INFO, + "invalidating session of user '%s' " SESSION_STR, e->acct_info.username, e->acct_info.safe_id); /* immediately disconnect the user */ del_client_entry(sec, e); @@ -214,12 +222,19 @@ void expire_client_entry(sec_mod_st *sec, client_entry_st * e) * explicitly disconnect with the intention to reconnect * seconds later. */ if (e->discon_reason == REASON_USER_DISCONNECT) { - if (!e->vhost->perm_config.config->persistent_cookies || (now+AUTH_SLACK_TIME >= e->exptime)) + if (!e->vhost->perm_config.config + ->persistent_cookies || + (now + AUTH_SLACK_TIME >= e->exptime)) e->exptime = now + AUTH_SLACK_TIME; } else { - e->exptime = now + e->vhost->perm_config.config->cookie_timeout + AUTH_SLACK_TIME; + e->exptime = now + + e->vhost->perm_config.config + ->cookie_timeout + + AUTH_SLACK_TIME; } - seclog(sec, LOG_INFO, "temporarily closing session for %s "SESSION_STR, e->acct_info.username, e->acct_info.safe_id); + seclog(sec, LOG_INFO, + "temporarily closing session for %s " SESSION_STR, + e->acct_info.username, e->acct_info.safe_id); } } } diff --git a/src/sec-mod-resume.c b/src/sec-mod-resume.c index f7a0fe45..8a3bc287 100644 --- a/src/sec-mod-resume.c +++ b/src/sec-mod-resume.c @@ -39,8 +39,7 @@ #include #include -int handle_resume_delete_req(sec_mod_st *sec, - const SessionResumeFetchMsg *req) +int handle_resume_delete_req(sec_mod_st *sec, const SessionResumeFetchMsg *req) { tls_cache_st *cache; struct htable_iter iter; @@ -53,7 +52,6 @@ int handle_resume_delete_req(sec_mod_st *sec, if (req->session_id.len == cache->session_id_size && memcmp(req->session_id.data, cache->session_id, req->session_id.len) == 0) { - cache->session_data_size = 0; cache->session_id_size = 0; @@ -69,8 +67,7 @@ int handle_resume_delete_req(sec_mod_st *sec, return 0; } -int handle_resume_fetch_req(sec_mod_st *sec, - const SessionResumeFetchMsg *req, +int handle_resume_fetch_req(sec_mod_st *sec, const SessionResumeFetchMsg *req, SessionResumeReplyMsg *rep) { tls_cache_st *cache; @@ -86,28 +83,29 @@ int handle_resume_fetch_req(sec_mod_st *sec, if (req->session_id.len == cache->session_id_size && memcmp(req->session_id.data, cache->session_id, req->session_id.len) == 0) { - - if (req->vhost && cache->vhostname && strcasecmp(req->vhost, cache->vhostname) != 0) + if (req->vhost && cache->vhostname && + strcasecmp(req->vhost, cache->vhostname) != 0) return 0; else if (req->vhost != cache->vhostname) return 0; if (req->cli_addr.len == cache->remote_addr_len && - ip_cmp((struct sockaddr_storage *)req->cli_addr.data, &cache->remote_addr) == 0) { - + ip_cmp((struct sockaddr_storage *)req->cli_addr.data, + &cache->remote_addr) == 0) { rep->reply = - SESSION_RESUME_REPLY_MSG__RESUME__REP__OK; + SESSION_RESUME_REPLY_MSG__RESUME__REP__OK; rep->has_session_data = 1; rep->session_data.data = - (void *)cache->session_data; + (void *)cache->session_data; rep->session_data.len = - cache->session_data_size; + cache->session_data_size; - seclog_hex(sec, LOG_DEBUG, "TLS session DB resuming", - req->session_id.data, - req->session_id.len, 0); + seclog_hex(sec, LOG_DEBUG, + "TLS session DB resuming", + req->session_id.data, + req->session_id.len, 0); return 0; } @@ -117,7 +115,6 @@ int handle_resume_fetch_req(sec_mod_st *sec, } return 0; - } int handle_resume_store_req(sec_mod_st *sec, @@ -132,17 +129,17 @@ int handle_resume_store_req(sec_mod_st *sec, if (req->session_data.len > MAX_SESSION_DATA_SIZE) return -1; - max = MAX(2 * GETCONFIG(sec)->max_clients, DEFAULT_MAX_CACHED_TLS_SESSIONS); + max = MAX(2 * GETCONFIG(sec)->max_clients, + DEFAULT_MAX_CACHED_TLS_SESSIONS); if (sec->tls_db.entries >= max) { seclog(sec, LOG_INFO, - "maximum number of stored TLS sessions reached (%u)", - max); + "maximum number of stored TLS sessions reached (%u)", + max); return -1; } if (req->cli_addr.len == 0) { - seclog(sec, LOG_INFO, - "invalid address length"); + seclog(sec, LOG_INFO, "invalid address length"); return -1; } @@ -167,14 +164,13 @@ int handle_resume_store_req(sec_mod_st *sec, if (htable_add(sec->tls_db.ht, key, cache) == 0) { seclog(sec, LOG_INFO, - "could not add TLS session to hash table"); + "could not add TLS session to hash table"); talloc_free(cache); } else { sec->tls_db.entries++; seclog_hex(sec, LOG_DEBUG, "TLS session DB storing", - req->session_id.data, - req->session_id.len, 0); + req->session_id.data, req->session_id.len, 0); } return 0; @@ -202,7 +198,8 @@ void expire_tls_sessions(sec_mod_st *sec) htable_delval(sec->tls_db.ht, &iter); - safe_memset(cache->session_data, 0, cache->session_data_size); + safe_memset(cache->session_data, 0, + cache->session_data_size); talloc_free(cache); sec->tls_db.entries--; } diff --git a/src/sec-mod-resume.h b/src/sec-mod-resume.h index bd9b7a7d..4b9f9dfe 100644 --- a/src/sec-mod-resume.h +++ b/src/sec-mod-resume.h @@ -19,19 +19,16 @@ * along with this program. If not, see */ #ifndef OC_SEC_MOD_RESUME_H -# define OC_SEC_MOD_RESUME_H +#define OC_SEC_MOD_RESUME_H #include -int handle_resume_delete_req(sec_mod_st* sec, - const SessionResumeFetchMsg * req); +int handle_resume_delete_req(sec_mod_st *sec, const SessionResumeFetchMsg *req); -int handle_resume_fetch_req(sec_mod_st* sec, - const SessionResumeFetchMsg * req, - SessionResumeReplyMsg* rep); +int handle_resume_fetch_req(sec_mod_st *sec, const SessionResumeFetchMsg *req, + SessionResumeReplyMsg *rep); -int handle_resume_store_req(sec_mod_st* sec, - const SessionResumeStoreReqMsg *); +int handle_resume_store_req(sec_mod_st *sec, const SessionResumeStoreReqMsg *); void expire_tls_sessions(sec_mod_st *sec); diff --git a/src/sec-mod-sup-config.c b/src/sec-mod-sup-config.c index dd7fc445..ba0b123b 100644 --- a/src/sec-mod-sup-config.c +++ b/src/sec-mod-sup-config.c @@ -34,13 +34,19 @@ void sup_config_init(sec_mod_st *sec) { vhost_cfg_st *vhost = NULL; - list_for_each(sec->vconfig, vhost, list) { + list_for_each(sec->vconfig, vhost, list) + { if (vhost->perm_config.sup_config_type == SUP_CONFIG_FILE) { - seclog(sec, LOG_INFO, "%sreading supplemental config from files", PREFIX_VHOST(vhost)); + seclog(sec, LOG_INFO, + "%sreading supplemental config from files", + PREFIX_VHOST(vhost)); vhost->config_module = &file_sup_config; #ifdef HAVE_RADIUS - } else if (vhost->perm_config.sup_config_type == SUP_CONFIG_RADIUS) { - seclog(sec, LOG_INFO, "%sreading supplemental config from radius", PREFIX_VHOST(vhost)); + } else if (vhost->perm_config.sup_config_type == + SUP_CONFIG_RADIUS) { + seclog(sec, LOG_INFO, + "%sreading supplemental config from radius", + PREFIX_VHOST(vhost)); vhost->config_module = &radius_sup_config; #endif } diff --git a/src/sec-mod-sup-config.h b/src/sec-mod-sup-config.h index 9e5444cb..6ea6e6b4 100644 --- a/src/sec-mod-sup-config.h +++ b/src/sec-mod-sup-config.h @@ -19,15 +19,14 @@ * along with this program. If not, see */ #ifndef OC_SEC_MOD_SUP_CONFIG_H -# define OC_SEC_MOD_SUP_CONFIG_H +#define OC_SEC_MOD_SUP_CONFIG_H #include #define SUP_CONFIG_FILE 1 #define SUP_CONFIG_RADIUS 2 -inline static -const char *sup_config_name(unsigned s) +inline static const char *sup_config_name(unsigned int s) { switch (s) { case SUP_CONFIG_FILE: @@ -43,8 +42,9 @@ const char *sup_config_name(unsigned s) * proc->username/proc->groupname and save it in proc->config. */ struct config_mod_st { - int (*get_sup_config)(struct cfg_st *perm_config, client_entry_st *entry, - SecmSessionReplyMsg *msg, void *pool); + int (*get_sup_config)(struct cfg_st *perm_config, + client_entry_st *entry, SecmSessionReplyMsg *msg, + void *pool); }; void sup_config_init(sec_mod_st *sec); diff --git a/src/sec-mod.c b/src/sec-mod.c index 5d1e8b0c..8211addc 100644 --- a/src/sec-mod.c +++ b/src/sec-mod.c @@ -51,41 +51,41 @@ #define MAINTAINANCE_TIME 310 -static int need_maintainance = 0; -static int need_reload = 0; -static int need_exit = 0; +static int need_maintainance; +static int need_reload; +static int need_exit; static void reload_server(sec_mod_st *sec); -static int load_keys(sec_mod_st *sec, unsigned force); +static int load_keys(sec_mod_st *sec, unsigned int force); -static -int pin_callback(void *user, int attempt, const char *token_url, - const char *token_label, unsigned int flags, char *pin, - size_t pin_max) +static int pin_callback(void *user, int attempt, const char *token_url, + const char *token_label, unsigned int flags, char *pin, + size_t pin_max) { struct pin_st *ps = user; int srk = 0; const char *p; - unsigned len; + unsigned int len; if (flags & GNUTLS_PIN_FINAL_TRY) { - oc_syslog(LOG_ERR, - "PIN callback: final try before locking; not attempting to unlock"); + oc_syslog( + LOG_ERR, + "PIN callback: final try before locking; not attempting to unlock"); return -1; } if (flags & GNUTLS_PIN_WRONG) { oc_syslog(LOG_ERR, - "PIN callback: wrong PIN was entered for '%s' (%s)", - token_label, token_url); + "PIN callback: wrong PIN was entered for '%s' (%s)", + token_label, token_url); return -1; } if (ps->pin[0] == 0) { oc_syslog(LOG_ERR, - "PIN required for '%s' but pin-file was not set", - token_label); + "PIN required for '%s' but pin-file was not set", + token_label); return -1; } @@ -98,8 +98,8 @@ int pin_callback(void *user, int attempt, const char *token_url, if (srk != 0 && ps->srk_pin[0] == 0) { oc_syslog(LOG_ERR, - "PIN required for '%s' but srk-pin-file was not set", - token_label); + "PIN required for '%s' but srk-pin-file was not set", + token_label); return -1; } @@ -115,8 +115,7 @@ int pin_callback(void *user, int attempt, const char *token_url, return 0; } -static -int load_pins(struct perm_cfg_st *config, struct pin_st *s) +static int load_pins(struct perm_cfg_st *config, struct pin_st *s) { int fd, ret; @@ -127,7 +126,7 @@ int load_pins(struct perm_cfg_st *config, struct pin_st *s) fd = open(config->srk_pin_file, O_RDONLY); if (fd < 0) { oc_syslog(LOG_ERR, "could not open SRK PIN file '%s'", - config->srk_pin_file); + config->srk_pin_file); return -1; } @@ -135,7 +134,7 @@ int load_pins(struct perm_cfg_st *config, struct pin_st *s) close(fd); if (ret <= 1) { oc_syslog(LOG_ERR, "could not read from PIN file '%s'", - config->srk_pin_file); + config->srk_pin_file); return -1; } @@ -148,7 +147,7 @@ int load_pins(struct perm_cfg_st *config, struct pin_st *s) fd = open(config->pin_file, O_RDONLY); if (fd < 0) { oc_syslog(LOG_ERR, "could not open PIN file '%s'", - config->pin_file); + config->pin_file); return -1; } @@ -156,7 +155,7 @@ int load_pins(struct perm_cfg_st *config, struct pin_st *s) close(fd); if (ret <= 1) { oc_syslog(LOG_ERR, "could not read from PIN file '%s'", - config->pin_file); + config->pin_file); return -1; } @@ -176,8 +175,8 @@ int load_pins(struct perm_cfg_st *config, struct pin_st *s) return 0; } -static int handle_op(void *pool, int cfd, sec_mod_st * sec, uint8_t type, uint8_t * rep, - size_t rep_size) +static int handle_op(void *pool, int cfd, sec_mod_st *sec, uint8_t type, + uint8_t *rep, size_t rep_size) { SecOpMsg msg = SEC_OP_MSG__INIT; int ret; @@ -186,8 +185,8 @@ static int handle_op(void *pool, int cfd, sec_mod_st * sec, uint8_t type, uint8_ msg.data.len = rep_size; ret = send_msg(pool, cfd, type, &msg, - (pack_size_func) sec_op_msg__get_packed_size, - (pack_func) sec_op_msg__pack); + (pack_size_func)sec_op_msg__get_packed_size, + (pack_func)sec_op_msg__pack); if (ret < 0) { seclog(sec, LOG_WARNING, "sec-mod error in sending reply"); } @@ -195,17 +194,17 @@ static int handle_op(void *pool, int cfd, sec_mod_st * sec, uint8_t type, uint8_ return 0; } -static -int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_request_t cmd, - uint8_t * buffer, size_t buffer_size) +static int process_worker_packet(void *pool, int cfd, pid_t pid, + sec_mod_st *sec, cmd_request_t cmd, + uint8_t *buffer, size_t buffer_size) { - unsigned i; + unsigned int i; gnutls_datum_t data, out; int ret; SecOpMsg *op; vhost_cfg_st *vhost; #if GNUTLS_VERSION_NUMBER >= 0x030600 - unsigned bits; + unsigned int bits; SecGetPkMsg *pkm; #endif PROTOBUF_ALLOCATOR(pa, pool); @@ -231,7 +230,8 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r i = pkm->key_idx; if (i >= vhost->key_size) { seclog(sec, LOG_INFO, - "%sreceived out-of-bounds key index (%d); have %d keys", PREFIX_VHOST(vhost), i, vhost->key_size); + "%sreceived out-of-bounds key index (%d); have %d keys", + PREFIX_VHOST(vhost), i, vhost->key_size); return -1; } @@ -239,8 +239,8 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r pkm->bits = bits; ret = send_msg(pool, cfd, CMD_SEC_GET_PK, pkm, - (pack_size_func) sec_get_pk_msg__get_packed_size, - (pack_func) sec_get_pk_msg__pack); + (pack_size_func)sec_get_pk_msg__get_packed_size, + (pack_func)sec_get_pk_msg__pack); sec_get_pk_msg__free_unpacked(pkm, &pa); @@ -266,7 +266,8 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r i = op->key_idx; if (op->has_key_idx == 0 || i >= vhost->key_size) { seclog(sec, LOG_INFO, - "%sreceived out-of-bounds key index (%d); have %d keys", PREFIX_VHOST(vhost), i, vhost->key_size); + "%sreceived out-of-bounds key index (%d); have %d keys", + PREFIX_VHOST(vhost), i, vhost->key_size); return -1; } @@ -274,9 +275,11 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r data.size = op->data.len; if (cmd == CMD_SEC_SIGN_DATA) { - ret = gnutls_privkey_sign_data2(vhost->key[i], op->sig, 0, &data, &out); + ret = gnutls_privkey_sign_data2(vhost->key[i], op->sig, + 0, &data, &out); } else { - ret = gnutls_privkey_sign_hash2(vhost->key[i], op->sig, 0, &data, &out); + ret = gnutls_privkey_sign_hash2(vhost->key[i], op->sig, + 0, &data, &out); } sec_op_msg__free_unpacked(op, &pa); @@ -305,7 +308,8 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r i = op->key_idx; if (op->has_key_idx == 0 || i >= vhost->key_size) { seclog(sec, LOG_INFO, - "%sreceived out-of-bounds key index (%d); have %d keys", PREFIX_VHOST(vhost), i, vhost->key_size); + "%sreceived out-of-bounds key index (%d); have %d keys", + PREFIX_VHOST(vhost), i, vhost->key_size); return -1; } @@ -313,14 +317,12 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r data.size = op->data.len; if (cmd == CMD_SEC_DECRYPT) { - ret = - gnutls_privkey_decrypt_data(vhost->key[i], 0, &data, - &out); + ret = gnutls_privkey_decrypt_data(vhost->key[i], 0, + &data, &out); } else { - ret = - gnutls_privkey_sign_hash(vhost->key[i], 0, - GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA, - &data, &out); + ret = gnutls_privkey_sign_hash( + vhost->key[i], 0, + GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA, &data, &out); } sec_op_msg__free_unpacked(op, &pa); @@ -335,144 +337,134 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r return ret; - case CMD_SEC_CLI_STATS:{ - CliStatsMsg *tmsg; + case CMD_SEC_CLI_STATS: { + CliStatsMsg *tmsg; - tmsg = cli_stats_msg__unpack(&pa, data.size, data.data); - if (tmsg == NULL) { - seclog(sec, LOG_ERR, "error unpacking data"); - return -1; - } - - ret = handle_sec_auth_stats_cmd(sec, tmsg, pid); - cli_stats_msg__free_unpacked(tmsg, &pa); - return ret; - } - break; - - case CMD_SEC_AUTH_INIT:{ - SecAuthInitMsg *auth_init; - - auth_init = - sec_auth_init_msg__unpack(&pa, data.size, - data.data); - if (auth_init == NULL) { - seclog(sec, LOG_INFO, "error unpacking auth init\n"); - return -1; - } - - ret = handle_sec_auth_init(cfd, sec, auth_init, pid); - sec_auth_init_msg__free_unpacked(auth_init, &pa); - return ret; - } - case CMD_SEC_AUTH_CONT:{ - SecAuthContMsg *auth_cont; - - auth_cont = - sec_auth_cont_msg__unpack(&pa, data.size, - data.data); - if (auth_cont == NULL) { - seclog(sec, LOG_INFO, "error unpacking auth cont\n"); - return -1; - } - - ret = handle_sec_auth_cont(cfd, sec, auth_cont); - sec_auth_cont_msg__free_unpacked(auth_cont, &pa); - return ret; - } - case RESUME_STORE_REQ:{ - SessionResumeStoreReqMsg *smsg; - - smsg = - session_resume_store_req_msg__unpack(&pa, buffer_size, - buffer); - if (smsg == NULL) { - seclog(sec, LOG_ERR, "error unpacking data"); - return ERR_BAD_COMMAND; - } - - ret = handle_resume_store_req(sec, smsg); - - /* zeroize the data */ - safe_memset(buffer, 0, buffer_size); - safe_memset(smsg->session_data.data, 0, smsg->session_data.len); - - session_resume_store_req_msg__free_unpacked(smsg, &pa); - - if (ret < 0) { - seclog(sec, LOG_DEBUG, - "could not store resumption data"); - } + tmsg = cli_stats_msg__unpack(&pa, data.size, data.data); + if (tmsg == NULL) { + seclog(sec, LOG_ERR, "error unpacking data"); + return -1; } - break; + ret = handle_sec_auth_stats_cmd(sec, tmsg, pid); + cli_stats_msg__free_unpacked(tmsg, &pa); + return ret; + } break; - case RESUME_DELETE_REQ:{ - SessionResumeFetchMsg *fmsg; + case CMD_SEC_AUTH_INIT: { + SecAuthInitMsg *auth_init; - fmsg = - session_resume_fetch_msg__unpack(&pa, buffer_size, - buffer); - if (fmsg == NULL) { - seclog(sec, LOG_ERR, "error unpacking data"); - return ERR_BAD_COMMAND; - } - - ret = handle_resume_delete_req(sec, fmsg); - - session_resume_fetch_msg__free_unpacked(fmsg, &pa); - - if (ret < 0) { - seclog(sec, LOG_DEBUG, - "could not delete resumption data."); - } + auth_init = + sec_auth_init_msg__unpack(&pa, data.size, data.data); + if (auth_init == NULL) { + seclog(sec, LOG_INFO, "error unpacking auth init\n"); + return -1; } - break; - case RESUME_FETCH_REQ:{ - SessionResumeReplyMsg msg = - SESSION_RESUME_REPLY_MSG__INIT; - SessionResumeFetchMsg *fmsg; - - fmsg = - session_resume_fetch_msg__unpack(&pa, buffer_size, - buffer); - if (fmsg == NULL) { - seclog(sec, LOG_ERR, "error unpacking data"); - return ERR_BAD_COMMAND; - } - - ret = handle_resume_fetch_req(sec, fmsg, &msg); - - session_resume_fetch_msg__free_unpacked(fmsg, &pa); - - if (ret < 0) { - msg.reply = - SESSION_RESUME_REPLY_MSG__RESUME__REP__FAILED; - seclog(sec, LOG_DEBUG, - "could not fetch resumption data."); - } else { - msg.reply = - SESSION_RESUME_REPLY_MSG__RESUME__REP__OK; - } - - ret = - send_msg(pool, cfd, RESUME_FETCH_REP, &msg, - (pack_size_func) - session_resume_reply_msg__get_packed_size, - (pack_func) - session_resume_reply_msg__pack); - - if (ret < 0) { - seclog(sec, LOG_ERR, - "could not send reply cmd %d.", - (unsigned)cmd); - return ERR_BAD_COMMAND; - } + ret = handle_sec_auth_init(cfd, sec, auth_init, pid); + sec_auth_init_msg__free_unpacked(auth_init, &pa); + return ret; + } + case CMD_SEC_AUTH_CONT: { + SecAuthContMsg *auth_cont; + auth_cont = + sec_auth_cont_msg__unpack(&pa, data.size, data.data); + if (auth_cont == NULL) { + seclog(sec, LOG_INFO, "error unpacking auth cont\n"); + return -1; } - break; + ret = handle_sec_auth_cont(cfd, sec, auth_cont); + sec_auth_cont_msg__free_unpacked(auth_cont, &pa); + return ret; + } + case RESUME_STORE_REQ: { + SessionResumeStoreReqMsg *smsg; + + smsg = session_resume_store_req_msg__unpack(&pa, buffer_size, + buffer); + if (smsg == NULL) { + seclog(sec, LOG_ERR, "error unpacking data"); + return ERR_BAD_COMMAND; + } + + ret = handle_resume_store_req(sec, smsg); + + /* zeroize the data */ + safe_memset(buffer, 0, buffer_size); + safe_memset(smsg->session_data.data, 0, smsg->session_data.len); + + session_resume_store_req_msg__free_unpacked(smsg, &pa); + + if (ret < 0) { + seclog(sec, LOG_DEBUG, + "could not store resumption data"); + } + } + + break; + + case RESUME_DELETE_REQ: { + SessionResumeFetchMsg *fmsg; + + fmsg = session_resume_fetch_msg__unpack(&pa, buffer_size, + buffer); + if (fmsg == NULL) { + seclog(sec, LOG_ERR, "error unpacking data"); + return ERR_BAD_COMMAND; + } + + ret = handle_resume_delete_req(sec, fmsg); + + session_resume_fetch_msg__free_unpacked(fmsg, &pa); + + if (ret < 0) { + seclog(sec, LOG_DEBUG, + "could not delete resumption data."); + } + } + + break; + case RESUME_FETCH_REQ: { + SessionResumeReplyMsg msg = SESSION_RESUME_REPLY_MSG__INIT; + SessionResumeFetchMsg *fmsg; + + fmsg = session_resume_fetch_msg__unpack(&pa, buffer_size, + buffer); + if (fmsg == NULL) { + seclog(sec, LOG_ERR, "error unpacking data"); + return ERR_BAD_COMMAND; + } + + ret = handle_resume_fetch_req(sec, fmsg, &msg); + + session_resume_fetch_msg__free_unpacked(fmsg, &pa); + + if (ret < 0) { + msg.reply = + SESSION_RESUME_REPLY_MSG__RESUME__REP__FAILED; + seclog(sec, LOG_DEBUG, + "could not fetch resumption data."); + } else { + msg.reply = SESSION_RESUME_REPLY_MSG__RESUME__REP__OK; + } + + ret = send_msg( + pool, cfd, RESUME_FETCH_REP, &msg, + (pack_size_func) + session_resume_reply_msg__get_packed_size, + (pack_func)session_resume_reply_msg__pack); + + if (ret < 0) { + seclog(sec, LOG_ERR, "could not send reply cmd %d.", + (unsigned int)cmd); + return ERR_BAD_COMMAND; + } + + } + + break; default: seclog(sec, LOG_WARNING, "unknown type 0x%.2x", cmd); @@ -482,12 +474,13 @@ int process_worker_packet(void *pool, int cfd, pid_t pid, sec_mod_st *sec, cmd_r return 0; } -static -int process_packet_from_main(void *pool, int fd, sec_mod_st * sec, cmd_request_t cmd, - uint8_t * buffer, size_t buffer_size) +static int process_packet_from_main(void *pool, int fd, sec_mod_st *sec, + cmd_request_t cmd, uint8_t *buffer, + size_t buffer_size) { gnutls_datum_t data; int ret; + PROTOBUF_ALLOCATOR(pa, pool); seclog(sec, LOG_DEBUG, "cmd [size=%d] %s\n", (int)buffer_size, @@ -499,10 +492,11 @@ int process_packet_from_main(void *pool, int fd, sec_mod_st * sec, cmd_request_t case CMD_SECM_RELOAD: reload_server(sec); - ret = send_msg(pool, fd, CMD_SECM_RELOAD_REPLY, NULL, - NULL, NULL); + ret = send_msg(pool, fd, CMD_SECM_RELOAD_REPLY, NULL, NULL, + NULL); if (ret < 0) { - seclog(sec, LOG_ERR, "could not send reload reply to main!\n"); + seclog(sec, LOG_ERR, + "could not send reload reply to main!\n"); return ERR_BAD_COMMAND; } break; @@ -510,14 +504,13 @@ int process_packet_from_main(void *pool, int fd, sec_mod_st * sec, cmd_request_t handle_secm_list_cookies_reply(pool, fd, sec); return 0; - case CMD_SECM_BAN_IP_REPLY:{ + case CMD_SECM_BAN_IP_REPLY: { BanIpReplyMsg *msg = NULL; - msg = - ban_ip_reply_msg__unpack(&pa, data.size, - data.data); + msg = ban_ip_reply_msg__unpack(&pa, data.size, data.data); if (msg == NULL) { - seclog(sec, LOG_INFO, "error unpacking auth ban ip reply\n"); + seclog(sec, LOG_INFO, + "error unpacking auth ban ip reply\n"); return ERR_BAD_COMMAND; } @@ -526,38 +519,35 @@ int process_packet_from_main(void *pool, int fd, sec_mod_st * sec, cmd_request_t return 0; } - case CMD_SECM_SESSION_OPEN:{ - SecmSessionOpenMsg *msg; + case CMD_SECM_SESSION_OPEN: { + SecmSessionOpenMsg *msg; - msg = - secm_session_open_msg__unpack(&pa, data.size, - data.data); - if (msg == NULL) { - seclog(sec, LOG_INFO, "error unpacking session open\n"); - return ERR_BAD_COMMAND; - } - - ret = handle_secm_session_open_cmd(sec, fd, msg); - secm_session_open_msg__free_unpacked(msg, &pa); - - return ret; + msg = secm_session_open_msg__unpack(&pa, data.size, data.data); + if (msg == NULL) { + seclog(sec, LOG_INFO, "error unpacking session open\n"); + return ERR_BAD_COMMAND; } - case CMD_SECM_SESSION_CLOSE:{ - SecmSessionCloseMsg *msg; - msg = - secm_session_close_msg__unpack(&pa, data.size, - data.data); - if (msg == NULL) { - seclog(sec, LOG_INFO, "error unpacking session close\n"); - return ERR_BAD_COMMAND; - } + ret = handle_secm_session_open_cmd(sec, fd, msg); + secm_session_open_msg__free_unpacked(msg, &pa); - ret = handle_secm_session_close_cmd(sec, fd, msg); - secm_session_close_msg__free_unpacked(msg, &pa); + return ret; + } + case CMD_SECM_SESSION_CLOSE: { + SecmSessionCloseMsg *msg; - return ret; + msg = secm_session_close_msg__unpack(&pa, data.size, data.data); + if (msg == NULL) { + seclog(sec, LOG_INFO, + "error unpacking session close\n"); + return ERR_BAD_COMMAND; } + + ret = handle_secm_session_close_cmd(sec, fd, msg); + secm_session_close_msg__free_unpacked(msg, &pa); + + return ret; + } default: seclog(sec, LOG_WARNING, "unknown type 0x%.2x", cmd); return ERR_BAD_COMMAND; @@ -603,8 +593,8 @@ static void send_stats_to_main(sec_mod_st *sec) msg.secmod_tlsdb_entries = sec->tls_db.entries; ret = send_msg(sec, sec->cmd_fd, CMD_SECM_STATS, &msg, - (pack_size_func) secm_stats_msg__get_packed_size, - (pack_func) secm_stats_msg__pack); + (pack_size_func)secm_stats_msg__get_packed_size, + (pack_func)secm_stats_msg__pack); if (ret < 0) { seclog(sec, LOG_ERR, "error in sending statistics to main"); return; @@ -619,7 +609,8 @@ static void reload_server(sec_mod_st *sec) reload_cfg_file(sec, sec->vconfig, 1); load_keys(sec, 0); - list_for_each(sec->vconfig, vhost, list) { + list_for_each(sec->vconfig, vhost, list) + { sec_auth_init(vhost); } sup_config_init(sec); @@ -632,9 +623,10 @@ static void check_other_work(sec_mod_st *sec) vhost_cfg_st *vhost = NULL; if (need_exit) { - unsigned i; + unsigned int i; - list_for_each(sec->vconfig, vhost, list) { + list_for_each(sec->vconfig, vhost, list) + { for (i = 0; i < vhost->key_size; i++) { gnutls_privkey_deinit(vhost->key[i]); vhost->key[i] = NULL; @@ -659,14 +651,14 @@ static void check_other_work(sec_mod_st *sec) expire_tls_sessions(sec); send_stats_to_main(sec); seclog(sec, LOG_DEBUG, "active sessions %d", - sec_mod_client_db_elems(sec)); + sec_mod_client_db_elems(sec)); alarm(MAINTAINANCE_TIME); need_maintainance = 0; } } -static -int serve_request_main(sec_mod_st *sec, int fd, uint8_t *buffer, unsigned buffer_size) +static int serve_request_main(sec_mod_st *sec, int fd, uint8_t *buffer, + unsigned int buffer_size) { int ret, e; uint8_t cmd; @@ -685,13 +677,15 @@ int serve_request_main(sec_mod_st *sec, int fd, uint8_t *buffer, unsigned buffer seclog(sec, LOG_DEBUG, "received request %s", cmd_request_to_str(cmd)); if (cmd <= MIN_SECM_CMD || cmd >= MAX_SECM_CMD) { - seclog(sec, LOG_ERR, "received invalid message from main of %u bytes (cmd: %u)\n", - (unsigned)length, (unsigned)cmd); + seclog(sec, LOG_ERR, + "received invalid message from main of %u bytes (cmd: %u)\n", + (unsigned int)length, (unsigned int)cmd); return ERR_BAD_COMMAND; } if (length > buffer_size) { - seclog(sec, LOG_ERR, "received too big message (%d)", (int)length); + seclog(sec, LOG_ERR, "received too big message (%d)", + (int)length); ret = ERR_BAD_COMMAND; goto leave; } @@ -700,23 +694,26 @@ int serve_request_main(sec_mod_st *sec, int fd, uint8_t *buffer, unsigned buffer ret = force_read_timeout(fd, buffer, length, MAIN_SEC_MOD_TIMEOUT); if (ret < 0) { e = errno; - seclog(sec, LOG_ERR, "error receiving msg body of cmd %u with length %u: %s", - cmd, (unsigned)length, strerror(e)); + seclog(sec, LOG_ERR, + "error receiving msg body of cmd %u with length %u: %s", + cmd, (unsigned int)length, strerror(e)); ret = ERR_BAD_COMMAND; goto leave; } ret = process_packet_from_main(pool, fd, sec, cmd, buffer, ret); if (ret < 0) { - seclog(sec, LOG_ERR, "error processing data for '%s' command (%d)", cmd_request_to_str(cmd), ret); + seclog(sec, LOG_ERR, + "error processing data for '%s' command (%d)", + cmd_request_to_str(cmd), ret); } - leave: +leave: return ret; } -static -int serve_request_worker(sec_mod_st *sec, int cfd, pid_t pid, uint8_t *buffer, unsigned buffer_size) +static int serve_request_worker(sec_mod_st *sec, int cfd, pid_t pid, + uint8_t *buffer, unsigned int buffer_size) { int ret, e; uint8_t cmd; @@ -750,24 +747,33 @@ int serve_request_worker(sec_mod_st *sec, int cfd, pid_t pid, uint8_t *buffer, u ret = process_worker_packet(pool, cfd, pid, sec, cmd, buffer, ret); if (ret < 0) { - seclog(sec, LOG_DEBUG, "error processing '%s' command (%d)", cmd_request_to_str(cmd), ret); + seclog(sec, LOG_DEBUG, "error processing '%s' command (%d)", + cmd_request_to_str(cmd), ret); } - leave: +leave: return ret; } -#define CHECK_LOOP_ERR(x) { \ - if (force != 0) { GNUTLS_FATAL_ERR(x); } \ - else { if (ret < 0) { \ - seclog(sec, LOG_ERR, "could not reload key %s", vhost->perm_config.key[i]); \ - continue; } \ - }} +#define CHECK_LOOP_ERR(x) \ + { \ + if (force != 0) { \ + GNUTLS_FATAL_ERR(x); \ + } else { \ + if (ret < 0) { \ + seclog(sec, LOG_ERR, \ + "could not reload key %s", \ + vhost->perm_config.key[i]); \ + continue; \ + } \ + } \ + } -static void read_private_key(sec_mod_st *sec, vhost_cfg_st *vhost, unsigned force) +static void read_private_key(sec_mod_st *sec, vhost_cfg_st *vhost, + unsigned int force) { int ret; - unsigned i; + unsigned int i; /* read private keys */ for (i = 0; i < vhost->key_size; i++) { @@ -778,33 +784,33 @@ static void read_private_key(sec_mod_st *sec, vhost_cfg_st *vhost, unsigned forc /* load the private key */ if (gnutls_url_is_supported(vhost->perm_config.key[i]) != 0) { - gnutls_privkey_set_pin_function(p, - pin_callback, &vhost->pins); - ret = - gnutls_privkey_import_url(p, - vhost->perm_config.key[i], 0); + gnutls_privkey_set_pin_function(p, pin_callback, + &vhost->pins); + ret = gnutls_privkey_import_url( + p, vhost->perm_config.key[i], 0); CHECK_LOOP_ERR(ret); } else { gnutls_datum_t data; - ret = gnutls_load_file(vhost->perm_config.key[i], &data); + + ret = gnutls_load_file(vhost->perm_config.key[i], + &data); if (ret < 0) { seclog(sec, LOG_ERR, "error loading file '%s'", vhost->perm_config.key[i]); CHECK_LOOP_ERR(ret); } - ret = - gnutls_privkey_import_x509_raw(p, &data, - GNUTLS_X509_FMT_PEM, - NULL, 0); + ret = gnutls_privkey_import_x509_raw( + p, &data, GNUTLS_X509_FMT_PEM, NULL, 0); /* GnuTLS 3.7.3 introduces a backwards incompatible change and * GNUTLS_E_PKCS11_PIN_ERROR is returned when an encrypted * file is loaded https://gitlab.com/gnutls/gnutls/-/issues/1321 */ - if ((ret == GNUTLS_E_DECRYPTION_FAILED || ret == GNUTLS_E_PKCS11_PIN_ERROR) && vhost->pins.pin[0]) { - ret = - gnutls_privkey_import_x509_raw(p, &data, - GNUTLS_X509_FMT_PEM, - vhost->pins.pin, 0); + if ((ret == GNUTLS_E_DECRYPTION_FAILED || + ret == GNUTLS_E_PKCS11_PIN_ERROR) && + vhost->pins.pin[0]) { + ret = gnutls_privkey_import_x509_raw( + p, &data, GNUTLS_X509_FMT_PEM, + vhost->pins.pin, 0); } CHECK_LOOP_ERR(ret); gnutls_free(data.data); @@ -815,21 +821,25 @@ static void read_private_key(sec_mod_st *sec, vhost_cfg_st *vhost, unsigned forc } vhost->key[i] = p; } - seclog(sec, LOG_DEBUG, "%sloaded %d keys\n", PREFIX_VHOST(vhost), vhost->key_size); + seclog(sec, LOG_DEBUG, "%sloaded %d keys\n", PREFIX_VHOST(vhost), + vhost->key_size); } -static int load_keys(sec_mod_st *sec, unsigned force) +static int load_keys(sec_mod_st *sec, unsigned int force) { - unsigned i, reload_file; + unsigned int i, reload_file; int ret; vhost_cfg_st *vhost = NULL; - list_for_each_rev(sec->vconfig, vhost, list) { + list_for_each_rev(sec->vconfig, vhost, list) + { if (force == 0) { reload_file = 0; for (i = 0; i < vhost->perm_config.key_size; i++) { - if (need_file_reload(vhost->perm_config.key[i], vhost->cert_last_access) != 0) { + if (need_file_reload(vhost->perm_config.key[i], + vhost->cert_last_access) != + 0) { reload_file = 1; break; } @@ -851,9 +861,12 @@ static int load_keys(sec_mod_st *sec, unsigned force) */ if (vhost->key == NULL) { vhost->key_size = vhost->perm_config.key_size; - vhost->key = talloc_zero_size(sec, sizeof(*vhost->key) * vhost->perm_config.key_size); + vhost->key = talloc_zero_size( + sec, sizeof(*vhost->key) * + vhost->perm_config.key_size); if (vhost->key == NULL) { - seclog(sec, LOG_ERR, "error in memory allocation"); + seclog(sec, LOG_ERR, + "error in memory allocation"); exit(EXIT_FAILURE); } } @@ -892,15 +905,15 @@ static int load_keys(sec_mod_st *sec, unsigned force) * clients fast without becoming a bottleneck due to private * key operations. */ -void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfig, - const char *socket_file, int cmd_fd, int cmd_fd_sync, - size_t hmac_key_length, const uint8_t * hmac_key, - const uint8_t instance_id) +void sec_mod_server(void *main_pool, void *config_pool, + struct list_head *vconfig, const char *socket_file, + int cmd_fd, int cmd_fd_sync, size_t hmac_key_length, + const uint8_t *hmac_key, const uint8_t instance_id) { struct sockaddr_un sa; socklen_t sa_len; int cfd, ret, e, n; - unsigned buffer_size; + unsigned int buffer_size; uid_t uid; uint8_t *buffer; int sd; @@ -941,7 +954,7 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi sec->vconfig = vconfig; sec->config_pool = config_pool; sec->sec_mod_pool = sec_mod_pool; - memcpy((uint8_t*)sec->hmac_key, hmac_key, hmac_key_length); + memcpy((uint8_t *)sec->hmac_key, hmac_key, hmac_key_length); sec->sec_mod_instance_id = instance_id; tls_cache_init(sec, &sec->tls_db); @@ -962,7 +975,8 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi ocsignal(SIGTERM, handle_sigterm); ocsignal(SIGALRM, handle_alarm); - list_for_each(sec->vconfig, vhost, list) { + list_for_each(sec->vconfig, vhost, list) + { sec_auth_init(vhost); } @@ -977,8 +991,8 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi sd = socket(AF_UNIX, SOCK_STREAM, 0); if (sd == -1) { e = errno; - seclog(sec, LOG_ERR, "could not create socket '%s': %s", SOCKET_FILE, - strerror(e)); + seclog(sec, LOG_ERR, "could not create socket '%s': %s", + SOCKET_FILE, strerror(e)); exit(EXIT_FAILURE); } set_cloexec_flag(sd, 1); @@ -987,16 +1001,16 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi ret = bind(sd, (struct sockaddr *)&sa, SUN_LEN(&sa)); if (ret == -1) { e = errno; - seclog(sec, LOG_ERR, "could not bind socket '%s': %s", SOCKET_FILE, - strerror(e)); + seclog(sec, LOG_ERR, "could not bind socket '%s': %s", + SOCKET_FILE, strerror(e)); exit(EXIT_FAILURE); } ret = chown(SOCKET_FILE, GETPCONFIG(sec)->uid, GETPCONFIG(sec)->gid); if (ret == -1) { e = errno; - seclog(sec, LOG_INFO, "could not chown socket '%s': %s", SOCKET_FILE, - strerror(e)); + seclog(sec, LOG_INFO, "could not chown socket '%s': %s", + SOCKET_FILE, strerror(e)); } ret = listen(sd, 1024); @@ -1017,7 +1031,6 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi alarm(MAINTAINANCE_TIME); seclog(sec, LOG_INFO, "sec-mod initialized (socket: %s)", SOCKET_FILE); - for (;;) { check_other_work(sec); @@ -1067,17 +1080,21 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi * ping-pong communication where each request is answered immediately. The * async is for messages sent back and forth in no particular order */ if (FD_ISSET(cmd_fd_sync, &rd_set)) { - ret = serve_request_main(sec, cmd_fd_sync, buffer, buffer_size); + ret = serve_request_main(sec, cmd_fd_sync, buffer, + buffer_size); if (ret < 0 && ret == ERR_BAD_COMMAND) { - seclog(sec, LOG_ERR, "error processing sync command from main"); + seclog(sec, LOG_ERR, + "error processing sync command from main"); exit(EXIT_FAILURE); } } if (FD_ISSET(cmd_fd, &rd_set)) { - ret = serve_request_main(sec, cmd_fd, buffer, buffer_size); + ret = serve_request_main(sec, cmd_fd, buffer, + buffer_size); if (ret < 0 && ret == ERR_BAD_COMMAND) { - seclog(sec, LOG_ERR, "error processing async command from main"); + seclog(sec, LOG_ERR, + "error processing async command from main"); exit(EXIT_FAILURE); } } @@ -1094,22 +1111,25 @@ void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfi goto cont; } } - set_cloexec_flag (cfd, 1); + set_cloexec_flag(cfd, 1); /* do not allow unauthorized processes to issue commands */ - ret = check_upeer_id("sec-mod", GETPCONFIG(sec)->log_level, cfd, - GETPCONFIG(sec)->uid, GETPCONFIG(sec)->gid, - &uid, &pid); + ret = check_upeer_id("sec-mod", + GETPCONFIG(sec)->log_level, cfd, + GETPCONFIG(sec)->uid, + GETPCONFIG(sec)->gid, &uid, &pid); if (ret < 0) { - seclog(sec, LOG_INFO, "rejected unauthorized connection"); + seclog(sec, LOG_INFO, + "rejected unauthorized connection"); } else { memset(buffer, 0, buffer_size); - serve_request_worker(sec, cfd, pid, buffer, buffer_size); + serve_request_worker(sec, cfd, pid, buffer, + buffer_size); } close(cfd); } - cont: +cont: talloc_free(buffer); #ifdef DEBUG_LEAKS talloc_report_full(sec, stderr); diff --git a/src/sec-mod.h b/src/sec-mod.h index bacdfa9f..2e55be7c 100644 --- a/src/sec-mod.h +++ b/src/sec-mod.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_SEC_MOD_H -# define OC_SEC_MOD_H +#define OC_SEC_MOD_H #include #include @@ -64,11 +64,11 @@ typedef struct common_auth_init_st { const char *ip; const char *our_ip; const char *user_agent; - unsigned id; + unsigned int id; } common_auth_init_st; typedef struct common_acct_info_st { - char username[MAX_USERNAME_SIZE*2]; + char username[MAX_USERNAME_SIZE * 2]; char groupname[MAX_GROUPNAME_SIZE]; /* the owner's group */ char safe_id[SAFE_ID_SIZE]; /* an ID to be sent to external apps - printable */ char remote_ip[MAX_IP_STR]; @@ -78,11 +78,13 @@ typedef struct common_acct_info_st { char our_ip[MAX_IP_STR]; char ipv4[MAX_IP_STR]; char ipv6[MAX_IP_STR]; - unsigned id; + unsigned int id; } common_acct_info_st; -#define IS_CLIENT_ENTRY_EXPIRED_FULL(sec, e, now, clean) (e->exptime != -1 && now >= e->exptime && e->in_use == 0) -#define IS_CLIENT_ENTRY_EXPIRED(sec, e, now) IS_CLIENT_ENTRY_EXPIRED_FULL(sec, e, now, 0) +#define IS_CLIENT_ENTRY_EXPIRED_FULL(sec, e, now, clean) \ + (e->exptime != -1 && now >= e->exptime && e->in_use == 0) +#define IS_CLIENT_ENTRY_EXPIRED(sec, e, now) \ + IS_CLIENT_ENTRY_EXPIRED_FULL(sec, e, now, 0) typedef struct client_entry_st { /* A unique session identifier used to distinguish sessions @@ -93,17 +95,18 @@ typedef struct client_entry_st { uint8_t sid[SID_SIZE]; void *auth_ctx; /* the context of authentication */ - unsigned session_is_open; /* whether open_session was done */ - unsigned in_use; /* counter of users of this structure */ - unsigned tls_auth_ok; + unsigned int session_is_open; /* whether open_session was done */ + unsigned int in_use; /* counter of users of this structure */ + unsigned int tls_auth_ok; char *msg_str; - unsigned passwd_counter; /* if msg_str is for a password this indicates the passwrd number (0,1,2) */ + unsigned int + passwd_counter; /* if msg_str is for a password this indicates the passwrd number (0,1,2) */ stats_st saved_stats; /* saved from previous cookie usage */ stats_st stats; /* current */ - unsigned status; /* PS_AUTH_ */ + unsigned int status; /* PS_AUTH_ */ uint8_t dtls_session_id[GNUTLS_MAX_SESSION_ID]; @@ -113,15 +116,16 @@ typedef struct client_entry_st { time_t exptime; /* the auth type associated with the user */ - unsigned auth_type; - unsigned discon_reason; /* reason for disconnection */ + unsigned int auth_type; + unsigned int discon_reason; /* reason for disconnection */ struct common_acct_info_st acct_info; /* saved during authentication; used after successful auth */ - char req_group_name[MAX_GROUPNAME_SIZE]; /* the requested by the user group */ + char req_group_name + [MAX_GROUPNAME_SIZE]; /* the requested by the user group */ char *cert_group_names[MAX_GROUPS]; - unsigned cert_group_names_size; + unsigned int cert_group_names_size; char cert_user_name[MAX_USERNAME_SIZE]; /* the module this entry is using */ @@ -135,28 +139,32 @@ typedef struct client_entry_st { void *sec_mod_client_db_init(sec_mod_st *sec); void sec_mod_client_db_deinit(sec_mod_st *sec); -unsigned sec_mod_client_db_elems(sec_mod_st *sec); -client_entry_st * new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *, const char *ip, unsigned pid); -client_entry_st * find_client_entry(sec_mod_st *sec, uint8_t sid[SID_SIZE]); -void del_client_entry(sec_mod_st *sec, client_entry_st * e); -void expire_client_entry(sec_mod_st *sec, client_entry_st * e); +unsigned int sec_mod_client_db_elems(sec_mod_st *sec); +client_entry_st *new_client_entry(sec_mod_st *sec, struct vhost_cfg_st *, + const char *ip, unsigned int pid); +client_entry_st *find_client_entry(sec_mod_st *sec, uint8_t sid[SID_SIZE]); +void del_client_entry(sec_mod_st *sec, client_entry_st *e); +void expire_client_entry(sec_mod_st *sec, client_entry_st *e); void cleanup_client_entries(sec_mod_st *sec); void sec_auth_init(struct vhost_cfg_st *vhost); void handle_secm_list_cookies_reply(void *pool, int fd, sec_mod_st *sec); void handle_sec_auth_ban_ip_reply(sec_mod_st *sec, const BanIpReplyMsg *msg); -int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg * req, pid_t pid); -int handle_sec_auth_cont(int cfd, sec_mod_st *sec, const SecAuthContMsg * req); -int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, const SecmSessionOpenMsg *req); -int handle_secm_session_close_cmd(sec_mod_st *sec, int fd, const SecmSessionCloseMsg *req); -int handle_sec_auth_stats_cmd(sec_mod_st * sec, const CliStatsMsg * req, pid_t pid); +int handle_sec_auth_init(int cfd, sec_mod_st *sec, const SecAuthInitMsg *req, + pid_t pid); +int handle_sec_auth_cont(int cfd, sec_mod_st *sec, const SecAuthContMsg *req); +int handle_secm_session_open_cmd(sec_mod_st *sec, int fd, + const SecmSessionOpenMsg *req); +int handle_secm_session_close_cmd(sec_mod_st *sec, int fd, + const SecmSessionCloseMsg *req); +int handle_sec_auth_stats_cmd(sec_mod_st *sec, const CliStatsMsg *req, + pid_t pid); void sec_auth_user_deinit(sec_mod_st *sec, client_entry_st *e); -void sec_mod_server(void *main_pool, void *config_pool, struct list_head *vconfig, - const char *socket_file, - int cmd_fd, int cmd_fd_sync, - size_t hmac_key_length, const uint8_t * hmac_key, - const uint8_t instance_id); +void sec_mod_server(void *main_pool, void *config_pool, + struct list_head *vconfig, const char *socket_file, + int cmd_fd, int cmd_fd_sync, size_t hmac_key_length, + const uint8_t *hmac_key, const uint8_t instance_id); #endif diff --git a/src/setproctitle.c b/src/setproctitle.c index 3f3591b0..2944d7e4 100644 --- a/src/setproctitle.c +++ b/src/setproctitle.c @@ -24,25 +24,25 @@ #if !defined(HAVE_SETPROCTITLE) -# if defined(__linux__) -# include +#if defined(__linux__) +#include /* This sets the process title as shown in top, but not in ps (*@#%@). * To change the ps name in Linux, one needs to do master black magic * trickery (see util-linux setproctitle). */ -void setproctitle (const char *fmt, ...) +void setproctitle(const char *fmt, ...) { char name[16]; va_list args; va_start(args, fmt); - vsnprintf(name, sizeof(name)-1, fmt, args); + vsnprintf(name, sizeof(name) - 1, fmt, args); va_end(args); -# ifdef PR_SET_NAME - prctl (PR_SET_NAME, name); -# endif +#ifdef PR_SET_NAME + prctl(PR_SET_NAME, name); +#endif /* Copied systemd's implementation under LGPL by Lennart Poettering */ if (saved_argc > 0) { int i; @@ -56,12 +56,12 @@ void setproctitle (const char *fmt, ...) } } } -# else /* not linux */ +#else /* not linux */ -void setproctitle (const char *fmt, ...) +void setproctitle(const char *fmt, ...) { } -# endif /* __linux__ */ +#endif /* __linux__ */ #endif /* HAVE_SETPROCTITLE */ diff --git a/src/setproctitle.h b/src/setproctitle.h index baf4ef8b..90686667 100644 --- a/src/setproctitle.h +++ b/src/setproctitle.h @@ -19,20 +19,19 @@ * along with this program. If not, see */ #ifndef OC_SETPROCTITLE_H -# define OC_SETPROCTITLE_H +#define OC_SETPROCTITLE_H -# include +#include -# ifndef HAVE_SETPROCTILE +#ifndef HAVE_SETPROCTILE -void __attribute__ ((format(printf, 1, 2))) -setproctitle(const char *fmt, ...); +void __attribute__((format(printf, 1, 2))) setproctitle(const char *fmt, ...); -# else +#else -# include -# include - -# endif +#include +#include + +#endif #endif diff --git a/src/str.c b/src/str.c index 3036ed0c..a5894c4d 100644 --- a/src/str.c +++ b/src/str.c @@ -31,11 +31,11 @@ void trim_trailing_whitespace(char *str) { - unsigned len = strlen(str); + unsigned int len = strlen(str); char *p; if (len > 0) { - p = str+len-1; + p = str + len - 1; while (p >= str && isspace(*p)) { *p = 0; p--; @@ -43,9 +43,9 @@ void trim_trailing_whitespace(char *str) } } -#define MEMSUB(x,y) ((ssize_t)((ptrdiff_t)x-(ptrdiff_t)y)) +#define MEMSUB(x, y) ((ssize_t)((ptrdiff_t)x - (ptrdiff_t)y)) -void str_clear(str_st * str) +void str_clear(str_st *str) { if (str == NULL || str->allocd == NULL) return; @@ -59,20 +59,19 @@ void str_clear(str_st * str) #define MIN_CHUNK 64 /* This function makes sure there is an additional byte in dest; */ -int str_append_size(str_st * dest, size_t data_size) +int str_append_size(str_st *dest, size_t data_size) { size_t tot_len = data_size + dest->length; if (data_size == 0) return 0; - if (dest->max_length >= tot_len+1) { + if (dest->max_length >= tot_len + 1) { size_t unused = MEMSUB(dest->data, dest->allocd); if (dest->max_length - unused <= tot_len) { if (dest->length && dest->data) - memmove(dest->allocd, dest->data, - dest->length); + memmove(dest->allocd, dest->data, dest->length); dest->data = dest->allocd; } @@ -80,11 +79,11 @@ int str_append_size(str_st * dest, size_t data_size) return tot_len; } else { size_t unused = MEMSUB(dest->data, dest->allocd); - size_t new_len = - MAX(data_size, MIN_CHUNK) + MAX(dest->max_length, - MIN_CHUNK); + size_t new_len = MAX(data_size, MIN_CHUNK) + + MAX(dest->max_length, MIN_CHUNK); - dest->allocd = talloc_realloc_size(dest->pool, dest->allocd, new_len+1); + dest->allocd = talloc_realloc_size(dest->pool, dest->allocd, + new_len + 1); if (dest->allocd == NULL) return ERR_MEM; dest->max_length = new_len; @@ -100,11 +99,11 @@ int str_append_size(str_st * dest, size_t data_size) /* This function always null terminates the string in dest. */ -int str_append_data(str_st * dest, const void *data, size_t data_size) +int str_append_data(str_st *dest, const void *data, size_t data_size) { - int ret; + int ret; - ret = str_append_size(dest, data_size+1); + ret = str_append_size(dest, data_size + 1); if (ret < 0) return ret; @@ -115,7 +114,7 @@ int str_append_data(str_st * dest, const void *data, size_t data_size) return 0; } -int str_append_data_prefix1(str_st * dest, const void *data, size_t data_size) +int str_append_data_prefix1(str_st *dest, const void *data, size_t data_size) { int ret; uint8_t prefix = data_size; @@ -131,7 +130,7 @@ int str_append_data_prefix1(str_st * dest, const void *data, size_t data_size) /* Appends the provided string. The null termination byte is appended * but not included in length. */ -int str_append_str(str_st * dest, const char *src) +int str_append_str(str_st *dest, const char *src) { int ret; @@ -145,8 +144,7 @@ int str_append_str(str_st * dest, const char *src) return ret; } -int -str_append_printf(str_st *dest, const char *fmt, ...) +int str_append_printf(str_st *dest, const char *fmt, ...) { va_list args; int len; @@ -170,9 +168,9 @@ int str_replace_str(str_st *str, const str_rep_tab *tab) { uint8_t *p; const str_rep_tab *ptab; - unsigned length; + unsigned int length; char *final; - unsigned final_len; + unsigned int final_len; int ret; size_t pos; @@ -183,25 +181,32 @@ int str_replace_str(str_st *str, const str_rep_tab *tab) if (p == NULL) break; - pos = (ptrdiff_t)(p-str->data); + pos = (ptrdiff_t)(p - str->data); length = str->length - pos; ptab = tab; do { if (length >= ptab->pattern_length && - memcmp(ptab->pattern, p, ptab->pattern_length) == 0) { + memcmp(ptab->pattern, p, ptab->pattern_length) == + 0) { /* replace */ final_len = length - ptab->pattern_length; - final = talloc_memdup(str->allocd, p+ptab->pattern_length, final_len); + final = talloc_memdup(str->allocd, + p + ptab->pattern_length, + final_len); if (final == NULL) return -1; str->length -= final_len + ptab->pattern_length; if (ptab->rep_val) - ret = str_append_str(str, ptab->rep_val); + ret = str_append_str(str, + ptab->rep_val); else { - char *t = ptab->rep_func(str->pool, ptab->rep_func_input); + char *t = ptab->rep_func( + str->pool, + ptab->rep_func_input); + ret = str_append_str(str, t); talloc_free(t); } diff --git a/src/str.h b/src/str.h index 7ef61a23..6b3289b4 100644 --- a/src/str.h +++ b/src/str.h @@ -27,17 +27,19 @@ #include #define STR_TAB_INIT(t, s_t) memset(t, 0, s_t) -#define STR_TAB_SET(i,pat,val) { \ - tab[i].pattern = pat; \ - tab[i].pattern_length = sizeof(pat)-1; \ - tab[i].rep_val = val; \ +#define STR_TAB_SET(i, pat, val) \ + { \ + tab[i].pattern = pat; \ + tab[i].pattern_length = sizeof(pat) - 1; \ + tab[i].rep_val = val; \ } -#define STR_TAB_SET_FUNC(i,pat,func,funcinput) { \ - tab[i].pattern = pat; \ - tab[i].pattern_length = sizeof(pat)-1; \ - tab[i].rep_val = NULL; \ - tab[i].rep_func = func; \ - tab[i].rep_func_input = funcinput; \ +#define STR_TAB_SET_FUNC(i, pat, func, funcinput) \ + { \ + tab[i].pattern = pat; \ + tab[i].pattern_length = sizeof(pat) - 1; \ + tab[i].rep_val = NULL; \ + tab[i].rep_func = func; \ + tab[i].rep_func_input = funcinput; \ } #define STR_TAB_TERM(i) tab[i].pattern = NULL @@ -45,22 +47,22 @@ typedef char *(*str_get_func)(void *pool, const char *input); typedef struct { const char *pattern; - unsigned pattern_length; + unsigned int pattern_length; const char *rep_val; str_get_func rep_func; const void *rep_func_input; } str_rep_tab; typedef struct { - uint8_t *allocd; /* pointer to allocated data */ - uint8_t *data; /* API: pointer to data to copy from */ + uint8_t *allocd; /* pointer to allocated data */ + uint8_t *data; /* API: pointer to data to copy from */ size_t max_length; - size_t length; /* API: current length */ + size_t length; /* API: current length */ void *pool; } str_st; /* Initialize a buffer */ -inline static void str_init(str_st * str, void *pool) +inline static void str_init(str_st *str, void *pool) { str->data = str->allocd = NULL; str->max_length = 0; @@ -72,7 +74,7 @@ inline static void str_init(str_st * str, void *pool) void str_clear(str_st *); /* Set the buffer data to be of zero length */ -inline static void str_reset(str_st * buf) +inline static void str_reset(str_st *buf) { buf->data = buf->allocd; buf->length = 0; @@ -87,6 +89,8 @@ int str_append_data(str_st *, const void *data, size_t data_size); int str_append_size(str_st *, size_t data_size); int str_append_data_prefix1(str_st *, const void *data, size_t data_size); -#define str_append_str_prefix1(s, str) (((str)==NULL)?str_append_data_prefix1(s, NULL, 0):str_append_data_prefix1(s, str, strlen(str))) +#define str_append_str_prefix1(s, str) \ + (((str) == NULL) ? str_append_data_prefix1(s, NULL, 0) : \ + str_append_data_prefix1(s, str, strlen(str))) #endif diff --git a/src/subconfig.c b/src/subconfig.c index 236d50c3..8432ee89 100644 --- a/src/subconfig.c +++ b/src/subconfig.c @@ -29,10 +29,12 @@ #include #include "common-config.h" -static void free_expanded_brackets_string(subcfg_val_st out[MAX_SUBOPTIONS], unsigned size) +static void free_expanded_brackets_string(subcfg_val_st out[MAX_SUBOPTIONS], + unsigned int size) { - unsigned i; - for (i=0;i 0) { - while (isspace(p[len-1])) + while (isspace(p[len - 1])) len--; } if (len2 > 0) { - while (isspace(p2[len2-1])) + while (isspace(p2[len2 - 1])) len2--; } out[pos].name = talloc_strndup(pool, p, len); out[pos].value = talloc_strndup(pool, p2, len2); pos++; - p = p2+len2; - while (isspace(*p)||*p==',') + p = p2 + len2; + while (isspace(*p) || *p == ',') p++; } while (finish == 0 && pos < MAX_SUBOPTIONS); @@ -102,10 +104,11 @@ unsigned expand_brackets_string(void *pool, const char *str, subcfg_val_st out[M } #ifdef HAVE_GSSAPI -void *gssapi_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str) +void *gssapi_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str) { subcfg_val_st vals[MAX_SUBOPTIONS]; - unsigned vals_size, i; + unsigned int vals_size, i; gssapi_cfg_st *additional; additional = talloc_zero(pool, gssapi_cfg_st); @@ -114,22 +117,27 @@ void *gssapi_get_brackets_string(void *pool, struct perm_cfg_st *config, const c } vals_size = expand_brackets_string(pool, str, vals); - for (i=0;ikeytab = vals[i].value; vals[i].value = NULL; - } else if (strcasecmp(vals[i].name, "require-local-user-map") == 0) { - additional->no_local_map = 1-CHECK_TRUE(vals[i].value); - } else if (strcasecmp(vals[i].name, "tgt-freshness-time") == 0) { + } else if (strcasecmp(vals[i].name, "require-local-user-map") == + 0) { + additional->no_local_map = + 1 - CHECK_TRUE(vals[i].value); + } else if (strcasecmp(vals[i].name, "tgt-freshness-time") == + 0) { additional->ticket_freshness_secs = atoi(vals[i].value); if (additional->ticket_freshness_secs == 0) { - fprintf(stderr, "Invalid value for '%s': %s\n", vals[i].name, vals[i].value); + fprintf(stderr, "Invalid value for '%s': %s\n", + vals[i].name, vals[i].value); exit(EXIT_FAILURE); } } else if (strcasecmp(vals[i].name, "gid-min") == 0) { additional->gid_min = atoi(vals[i].value); if (additional->gid_min < 0) { - fprintf(stderr, "error in gid-min value: %d\n", additional->gid_min); + fprintf(stderr, "error in gid-min value: %d\n", + additional->gid_min); exit(EXIT_FAILURE); } } else { @@ -145,7 +153,7 @@ void *gssapi_get_brackets_string(void *pool, struct perm_cfg_st *config, const c void *get_brackets_string1(void *pool, const char *str) { char *p, *p2; - unsigned len; + unsigned int len; p = strchr(str, '['); if (p == NULL) { @@ -173,7 +181,7 @@ void *get_brackets_string1(void *pool, const char *str) static void *get_brackets_string2(void *pool, const char *str) { char *p, *p2; - unsigned len; + unsigned int len; p = strchr(str, '['); if (p == NULL) { @@ -204,11 +212,12 @@ static void *get_brackets_string2(void *pool, const char *str) return talloc_strndup(pool, p, len); } -void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str) +void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str) { char *p; subcfg_val_st vals[MAX_SUBOPTIONS]; - unsigned vals_size, i; + unsigned int vals_size, i; radius_cfg_st *additional; additional = talloc_zero(pool, radius_cfg_st); @@ -216,13 +225,16 @@ void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, const c return NULL; } - if (str && str[0] == '[' && (str[1] == '/' || str[1] == '.')) { /* legacy format */ + if (str && str[0] == '[' && + (str[1] == '/' || str[1] == '.')) { /* legacy format */ additional->config = get_brackets_string1(pool, str); p = get_brackets_string2(config, str); if (p != NULL) { if (strcasecmp(p, "groupconfig") != 0) { - fprintf(stderr, "No known configuration option: %s\n", p); + fprintf(stderr, + "No known configuration option: %s\n", + p); exit(EXIT_FAILURE); } config->sup_config_type = SUP_CONFIG_RADIUS; @@ -230,18 +242,22 @@ void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, const c } else { /* new format */ vals_size = expand_brackets_string(pool, str, vals); - for (i=0;iconfig = vals[i].value; vals[i].value = NULL; - } else if (strcasecmp(vals[i].name, "nas-identifier") == 0) { + } else if (strcasecmp(vals[i].name, "nas-identifier") == + 0) { additional->nas_identifier = vals[i].value; vals[i].value = NULL; - } else if (strcasecmp(vals[i].name, "groupconfig") == 0) { + } else if (strcasecmp(vals[i].name, "groupconfig") == + 0) { if (CHECK_TRUE(vals[i].value)) - config->sup_config_type = SUP_CONFIG_RADIUS; + config->sup_config_type = + SUP_CONFIG_RADIUS; } else { - fprintf(stderr, "unknown option '%s'\n", vals[i].name); + fprintf(stderr, "unknown option '%s'\n", + vals[i].name); exit(EXIT_FAILURE); } } @@ -258,10 +274,11 @@ void *radius_get_brackets_string(void *pool, struct perm_cfg_st *config, const c #endif #ifdef HAVE_PAM -void *pam_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str) +void *pam_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str) { subcfg_val_st vals[MAX_SUBOPTIONS]; - unsigned vals_size, i; + unsigned int vals_size, i; pam_cfg_st *additional; additional = talloc_zero(pool, pam_cfg_st); @@ -271,11 +288,12 @@ void *pam_get_brackets_string(void *pool, struct perm_cfg_st *config, const char /* new format */ vals_size = expand_brackets_string(pool, str, vals); - for (i=0;igid_min = atoi(vals[i].value); if (additional->gid_min < 0) { - fprintf(stderr, "error in gid-min value: %d\n", additional->gid_min); + fprintf(stderr, "error in gid-min value: %d\n", + additional->gid_min); exit(EXIT_FAILURE); } } else { @@ -289,10 +307,11 @@ void *pam_get_brackets_string(void *pool, struct perm_cfg_st *config, const char } #endif -void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, const char *str) +void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str) { subcfg_val_st vals[MAX_SUBOPTIONS]; - unsigned vals_size, i; + unsigned int vals_size, i; plain_cfg_st *additional; additional = talloc_zero(pool, plain_cfg_st); @@ -300,11 +319,12 @@ void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, const ch return NULL; } - if (str && str[0] == '[' && (str[1] == '/' || str[1] == '.')) { /* legacy format */ + if (str && str[0] == '[' && + (str[1] == '/' || str[1] == '.')) { /* legacy format */ additional->passwd = get_brackets_string1(pool, str); } else { vals_size = expand_brackets_string(pool, str, vals); - for (i=0;ipasswd = vals[i].value; vals[i].value = NULL; @@ -314,7 +334,8 @@ void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, const ch vals[i].value = NULL; #endif } else { - fprintf(stderr, "unknown option '%s'\n", vals[i].name); + fprintf(stderr, "unknown option '%s'\n", + vals[i].name); exit(EXIT_FAILURE); } } @@ -329,17 +350,17 @@ void *plain_get_brackets_string(void *pool, struct perm_cfg_st *config, const ch return additional; } - -void *oidc_get_brackets_string(void * pool, struct perm_cfg_st *config, const char *str) +void *oidc_get_brackets_string(void *pool, struct perm_cfg_st *config, + const char *str) { subcfg_val_st vals[MAX_SUBOPTIONS]; - char * additional = NULL; + char *additional = NULL; - unsigned vals_size, i; + unsigned int vals_size, i; - vals_size = expand_brackets_string(pool, str, vals); + vals_size = expand_brackets_string(pool, str, vals); - for (i = 0; i < vals_size; i ++) { + for (i = 0; i < vals_size; i++) { if (strcasecmp(vals[i].name, "config") == 0) { additional = talloc_strdup(pool, vals[i].value); } diff --git a/src/sup-config/file.c b/src/sup-config/file.c index c9c20b0b..e0c99cff 100644 --- a/src/sup-config/file.c +++ b/src/sup-config/file.c @@ -42,38 +42,43 @@ #define READ_RAW_MULTI_LINE(varname, num) \ _add_multi_line_val(pool, &varname, &num, value) -#define READ_RAW_STRING(varname) { \ - if (varname != NULL) \ - talloc_free(varname); \ - varname = talloc_strdup(pool, value); \ +#define READ_RAW_STRING(varname) \ + { \ + if (varname != NULL) \ + talloc_free(varname); \ + varname = talloc_strdup(pool, value); \ } -#define READ_RAW_NUMERIC(varname, var_set) { \ - varname = strtol(value, NULL, 10); \ - var_set = 1; \ - } - -#define READ_RAW_PRIO_TOS(varname, var_set) { \ - if (strncmp(value, "0x", 2) == 0) { \ - varname = strtol(value, NULL, 16); \ - varname = TOS_PACK(varname); \ - var_set = 1; \ - } else { \ +#define READ_RAW_NUMERIC(varname, var_set) \ + { \ varname = strtol(value, NULL, 10); \ - varname++; \ - var_set = 1; \ - } \ + var_set = 1; \ } -#define READ_TF(varname, is_set) { \ - char* tmp_tf = NULL; \ - READ_RAW_STRING(tmp_tf); \ - if (strcasecmp(tmp_tf, "true") == 0 || strcasecmp(tmp_tf, "yes") == 0) \ - varname = 1; \ - else \ - varname = 0; \ - is_set = 1; \ - talloc_free(tmp_tf); \ +#define READ_RAW_PRIO_TOS(varname, var_set) \ + { \ + if (strncmp(value, "0x", 2) == 0) { \ + varname = strtol(value, NULL, 16); \ + varname = TOS_PACK(varname); \ + var_set = 1; \ + } else { \ + varname = strtol(value, NULL, 10); \ + varname++; \ + var_set = 1; \ + } \ + } + +#define READ_TF(varname, is_set) \ + { \ + char *tmp_tf = NULL; \ + READ_RAW_STRING(tmp_tf); \ + if (strcasecmp(tmp_tf, "true") == 0 || \ + strcasecmp(tmp_tf, "yes") == 0) \ + varname = 1; \ + else \ + varname = 0; \ + is_set = 1; \ + talloc_free(tmp_tf); \ } struct ini_ctx_st { @@ -82,18 +87,20 @@ struct ini_ctx_st { void *pool; }; -static int group_cfg_ini_handler(void *_ctx, const char *section, const char *name, const char* _value) +static int group_cfg_ini_handler(void *_ctx, const char *section, + const char *name, const char *_value) { struct ini_ctx_st *ctx = _ctx; SecmSessionReplyMsg *msg = ctx->msg; const char *file = ctx->file; void *pool = ctx->pool; - unsigned prefix = 0, prefix4 = 0; + unsigned int prefix = 0, prefix4 = 0; int ret; char *value; if (section != NULL && section[0] != 0) { - oc_syslog(LOG_INFO, "skipping unknown section '%s' in %s", section, file); + oc_syslog(LOG_INFO, "skipping unknown section '%s' in %s", + section, file); return 1; } @@ -103,20 +110,26 @@ static int group_cfg_ini_handler(void *_ctx, const char *section, const char *na if (strcmp(name, "no-udp") == 0) { READ_TF(msg->config->no_udp, msg->config->has_no_udp); - } else if (strcmp(name, "restrict-user-to-routes")==0) { - READ_TF(msg->config->restrict_user_to_routes, msg->config->has_restrict_user_to_routes); + } else if (strcmp(name, "restrict-user-to-routes") == 0) { + READ_TF(msg->config->restrict_user_to_routes, + msg->config->has_restrict_user_to_routes); } else if (strcmp(name, "tunnel_all_dns") == 0) { - READ_TF(msg->config->tunnel_all_dns, msg->config->has_tunnel_all_dns); + READ_TF(msg->config->tunnel_all_dns, + msg->config->has_tunnel_all_dns); } else if (strcmp(name, "deny-roaming") == 0) { - READ_TF(msg->config->deny_roaming, msg->config->has_deny_roaming); + READ_TF(msg->config->deny_roaming, + msg->config->has_deny_roaming); } else if (strcmp(name, "route") == 0) { READ_RAW_MULTI_LINE(msg->config->routes, msg->config->n_routes); } else if (strcmp(name, "split-dns") == 0) { - READ_RAW_MULTI_LINE(msg->config->split_dns, msg->config->n_split_dns); + READ_RAW_MULTI_LINE(msg->config->split_dns, + msg->config->n_split_dns); } else if (strcmp(name, "no-route") == 0) { - READ_RAW_MULTI_LINE(msg->config->no_routes, msg->config->n_no_routes); + READ_RAW_MULTI_LINE(msg->config->no_routes, + msg->config->n_no_routes); } else if (strcmp(name, "iroute") == 0) { - READ_RAW_MULTI_LINE(msg->config->iroutes, msg->config->n_iroutes); + READ_RAW_MULTI_LINE(msg->config->iroutes, + msg->config->n_iroutes); } else if (strcmp(name, "dns") == 0) { READ_RAW_MULTI_LINE(msg->config->dns, msg->config->n_dns); } else if (strcmp(name, "ipv6-dns") == 0) { @@ -135,7 +148,8 @@ static int group_cfg_ini_handler(void *_ctx, const char *section, const char *na READ_RAW_STRING(msg->config->ipv4_net); prefix4 = extract_prefix(msg->config->ipv4_net); if (prefix4 != 0) - msg->config->ipv4_netmask = ipv4_prefix_to_strmask(pool, prefix4); + msg->config->ipv4_netmask = + ipv4_prefix_to_strmask(pool, prefix4); } else if (strcmp(name, "ipv4-netmask") == 0) { READ_RAW_STRING(msg->config->ipv4_netmask); } else if (strcmp(name, "explicit-ipv4") == 0) { @@ -146,7 +160,9 @@ static int group_cfg_ini_handler(void *_ctx, const char *section, const char *na prefix = extract_prefix(msg->config->ipv6_net); if (prefix != 0) { if (valid_ipv6_prefix(prefix) == 0) { - oc_syslog(LOG_ERR, "unknown ipv6-prefix '%u' in %s", msg->config->ipv6_prefix, file); + oc_syslog(LOG_ERR, + "unknown ipv6-prefix '%u' in %s", + msg->config->ipv6_prefix, file); } msg->config->ipv6_prefix = prefix; msg->config->has_ipv6_prefix = 1; @@ -154,51 +170,65 @@ static int group_cfg_ini_handler(void *_ctx, const char *section, const char *na } else if (strcmp(name, "explicit-ipv6") == 0) { READ_RAW_STRING(msg->config->explicit_ipv6); } else if (strcmp(name, "ipv6-subnet-prefix") == 0) { - READ_RAW_NUMERIC(msg->config->ipv6_subnet_prefix, msg->config->has_ipv6_subnet_prefix); + READ_RAW_NUMERIC(msg->config->ipv6_subnet_prefix, + msg->config->has_ipv6_subnet_prefix); } else if (strcmp(name, "hostname") == 0) { READ_RAW_STRING(msg->config->hostname); } else if (strcmp(name, "rx-data-per-sec") == 0) { - READ_RAW_NUMERIC(msg->config->rx_per_sec, msg->config->has_rx_per_sec); + READ_RAW_NUMERIC(msg->config->rx_per_sec, + msg->config->has_rx_per_sec); msg->config->rx_per_sec /= 1000; /* in kb */ } else if (strcmp(name, "tx-data-per-sec") == 0) { - READ_RAW_NUMERIC(msg->config->tx_per_sec, msg->config->has_tx_per_sec); + READ_RAW_NUMERIC(msg->config->tx_per_sec, + msg->config->has_tx_per_sec); msg->config->tx_per_sec /= 1000; /* in kb */ } else if (strcmp(name, "stats-report-time") == 0) { - READ_RAW_NUMERIC(msg->config->interim_update_secs, msg->config->has_interim_update_secs); + READ_RAW_NUMERIC(msg->config->interim_update_secs, + msg->config->has_interim_update_secs); } else if (strcmp(name, "session-timeout") == 0) { - READ_RAW_NUMERIC(msg->config->session_timeout_secs, msg->config->has_session_timeout_secs); + READ_RAW_NUMERIC(msg->config->session_timeout_secs, + msg->config->has_session_timeout_secs); } else if (strcmp(name, "mtu") == 0) { READ_RAW_NUMERIC(msg->config->mtu, msg->config->has_mtu); } else if (strcmp(name, "dpd") == 0) { READ_RAW_NUMERIC(msg->config->dpd, msg->config->has_dpd); } else if (strcmp(name, "mobile-dpd") == 0) { - READ_RAW_NUMERIC(msg->config->mobile_dpd, msg->config->has_mobile_dpd); + READ_RAW_NUMERIC(msg->config->mobile_dpd, + msg->config->has_mobile_dpd); } else if (strcmp(name, "idle-timeout") == 0) { - READ_RAW_NUMERIC(msg->config->idle_timeout, msg->config->has_idle_timeout); + READ_RAW_NUMERIC(msg->config->idle_timeout, + msg->config->has_idle_timeout); } else if (strcmp(name, "mobile-idle-timeout") == 0) { - READ_RAW_NUMERIC(msg->config->mobile_idle_timeout, msg->config->has_mobile_idle_timeout); + READ_RAW_NUMERIC(msg->config->mobile_idle_timeout, + msg->config->has_mobile_idle_timeout); } else if (strcmp(name, "keepalive") == 0) { - READ_RAW_NUMERIC(msg->config->keepalive, msg->config->has_keepalive); + READ_RAW_NUMERIC(msg->config->keepalive, + msg->config->has_keepalive); } else if (strcmp(name, "max-same-clients") == 0) { - READ_RAW_NUMERIC(msg->config->max_same_clients, msg->config->has_max_same_clients); + READ_RAW_NUMERIC(msg->config->max_same_clients, + msg->config->has_max_same_clients); } else if (strcmp(name, "net-priority") == 0) { /* net-priority will contain the actual priority + 1, * to allow having zero as uninitialized. */ - READ_RAW_PRIO_TOS(msg->config->net_priority, msg->config->has_net_priority); + READ_RAW_PRIO_TOS(msg->config->net_priority, + msg->config->has_net_priority); #ifdef ANYCONNECT_CLIENT_COMPAT } else if (strcmp(name, "user-profile") == 0) { READ_RAW_STRING(msg->config->xml_config_file); #endif } else if (strcmp(name, "client-bypass-protocol") == 0) { - READ_TF(msg->config->client_bypass_protocol, msg->config->has_client_bypass_protocol); + READ_TF(msg->config->client_bypass_protocol, + msg->config->has_client_bypass_protocol); } else if (strcmp(name, "restrict-user-to-ports") == 0) { - ret = cfg_parse_ports(pool, &msg->config->fw_ports, &msg->config->n_fw_ports, value); + ret = cfg_parse_ports(pool, &msg->config->fw_ports, + &msg->config->n_fw_ports, value); if (ret < 0) { talloc_free(value); return 0; } } else { - oc_syslog(LOG_INFO, "skipping unknown option '%s' in %s", name, file); + oc_syslog(LOG_INFO, "skipping unknown option '%s' in %s", name, + file); } talloc_free(value); @@ -209,13 +239,12 @@ static int group_cfg_ini_handler(void *_ctx, const char *section, const char *na * config. The provided config must either be memset to zero, or be * already allocated using this function. */ -static -int parse_group_cfg_file(struct cfg_st *global_config, - SecmSessionReplyMsg *msg, void *pool, - const char* file) +static int parse_group_cfg_file(struct cfg_st *global_config, + SecmSessionReplyMsg *msg, void *pool, + const char *file) { int ret; - unsigned j; + unsigned int j; struct ini_ctx_st ctx; ctx.pool = pool; @@ -225,57 +254,65 @@ int parse_group_cfg_file(struct cfg_st *global_config, ret = ini_parse(file, group_cfg_ini_handler, &ctx); if (ret != 0) { if (ret > 0) - oc_syslog(LOG_ERR, "error in line %d of config file %s", ret, file); + oc_syslog(LOG_ERR, "error in line %d of config file %s", + ret, file); else oc_syslog(LOG_ERR, "cannot load config file %s", file); return 0; } - for (j=0;jconfig->n_routes;j++) { - if (ip_route_sanity_check(msg->config->routes, &msg->config->routes[j]) != 0) { + for (j = 0; j < msg->config->n_routes; j++) { + if (ip_route_sanity_check(msg->config->routes, + &msg->config->routes[j]) != 0) { ret = ERR_READ_CONFIG; goto fail; } } - for (j=0;jconfig->n_iroutes;j++) { - if (ip_route_sanity_check(msg->config->iroutes, &msg->config->iroutes[j]) != 0) { + for (j = 0; j < msg->config->n_iroutes; j++) { + if (ip_route_sanity_check(msg->config->iroutes, + &msg->config->iroutes[j]) != 0) { ret = ERR_READ_CONFIG; goto fail; } } - for (j=0;jconfig->n_no_routes;j++) { - if (ip_route_sanity_check(msg->config->no_routes, &msg->config->no_routes[j]) != 0) { + for (j = 0; j < msg->config->n_no_routes; j++) { + if (ip_route_sanity_check(msg->config->no_routes, + &msg->config->no_routes[j]) != 0) { ret = ERR_READ_CONFIG; goto fail; } } ret = 0; - fail: +fail: return ret; } static int read_sup_config_file(struct cfg_st *global_config, SecmSessionReplyMsg *msg, void *pool, - const char *file, const char *fallback, const char *type) + const char *file, const char *fallback, + const char *type) { int ret; if (access(file, R_OK) == 0) { oc_syslog(LOG_DEBUG, "Loading %s configuration '%s'", type, - file); + file); ret = parse_group_cfg_file(global_config, msg, pool, file); if (ret < 0) return ERR_READ_CONFIG; } else { if (fallback != NULL) { - oc_syslog(LOG_DEBUG, "Loading default %s configuration '%s'", type, fallback); + oc_syslog(LOG_DEBUG, + "Loading default %s configuration '%s'", type, + fallback); - ret = parse_group_cfg_file(global_config, msg, pool, fallback); + ret = parse_group_cfg_file(global_config, msg, pool, + fallback); if (ret < 0) return ERR_READ_CONFIG; } @@ -294,7 +331,8 @@ static int get_sup_config(struct cfg_st *cfg, client_entry_st *entry, snprintf(file, sizeof(file), "%s/%s", cfg->per_group_dir, entry->acct_info.groupname); - ret = read_sup_config_file(cfg, msg, pool, file, cfg->default_group_conf, "group"); + ret = read_sup_config_file(cfg, msg, pool, file, + cfg->default_group_conf, "group"); if (ret < 0) return ret; } @@ -302,7 +340,8 @@ static int get_sup_config(struct cfg_st *cfg, client_entry_st *entry, if (cfg->per_user_dir != NULL) { snprintf(file, sizeof(file), "%s/%s", cfg->per_user_dir, entry->acct_info.username); - ret = read_sup_config_file(cfg, msg, pool, file, cfg->default_user_conf, "user"); + ret = read_sup_config_file(cfg, msg, pool, file, + cfg->default_user_conf, "user"); if (ret < 0) return ret; } diff --git a/src/sup-config/radius.c b/src/sup-config/radius.c index 996206a8..b14a70bd 100644 --- a/src/sup-config/radius.c +++ b/src/sup-config/radius.c @@ -42,7 +42,7 @@ static int get_sup_config(struct cfg_st *cfg, client_entry_st *entry, SecmSessionReplyMsg *msg, void *pool) { struct radius_ctx_st *pctx = entry->auth_ctx; - unsigned dns = 0, i; + unsigned int dns = 0, i; if (pctx == NULL) return 0; @@ -60,20 +60,29 @@ static int get_sup_config(struct cfg_st *cfg, client_entry_st *entry, } if (pctx->ipv4_mask[0] != 0) { - msg->config->ipv4_netmask = talloc_strdup(pool, pctx->ipv4_mask); + msg->config->ipv4_netmask = + talloc_strdup(pool, pctx->ipv4_mask); } if (pctx->routes_size > 0) { - msg->config->routes = talloc_size(pool, pctx->routes_size*sizeof(char*)); + msg->config->routes = + talloc_size(pool, pctx->routes_size * sizeof(char *)); if (msg->config->routes != NULL) { - for (i=0;iroutes_size;i++) { - msg->config->routes[i] = talloc_strdup(pool, pctx->routes[i]); + for (i = 0; i < pctx->routes_size; i++) { + msg->config->routes[i] = + talloc_strdup(pool, pctx->routes[i]); if (msg->config->routes[i] == NULL) { - oc_syslog(LOG_ERR, "Error allocating memory for routes"); + oc_syslog( + LOG_ERR, + "Error allocating memory for routes"); return -1; } - if (ip_route_sanity_check(msg->config->routes, &msg->config->routes[i]) < 0) { - oc_syslog(LOG_ERR, "Route '%s' is malformed", msg->config->routes[i]); + if (ip_route_sanity_check( + msg->config->routes, + &msg->config->routes[i]) < 0) { + oc_syslog(LOG_ERR, + "Route '%s' is malformed", + msg->config->routes[i]); return -1; } } @@ -91,17 +100,22 @@ static int get_sup_config(struct cfg_st *cfg, client_entry_st *entry, dns++; if (dns > 0) { - msg->config->dns = talloc_size(pool, dns*sizeof(char*)); + msg->config->dns = talloc_size(pool, dns * sizeof(char *)); if (msg->config->dns != NULL) { - unsigned pos = 0; + unsigned int pos = 0; + if (pctx->ipv4_dns1[0] != 0) - msg->config->dns[pos++] = talloc_strdup(pool, pctx->ipv4_dns1); + msg->config->dns[pos++] = + talloc_strdup(pool, pctx->ipv4_dns1); if (pctx->ipv4_dns2[0] != 0) - msg->config->dns[pos++] = talloc_strdup(pool, pctx->ipv4_dns2); + msg->config->dns[pos++] = + talloc_strdup(pool, pctx->ipv4_dns2); if (pctx->ipv6_dns1[0] != 0) - msg->config->dns[pos++] = talloc_strdup(pool, pctx->ipv6_dns1); + msg->config->dns[pos++] = + talloc_strdup(pool, pctx->ipv6_dns1); if (pctx->ipv6_dns2[0] != 0) - msg->config->dns[pos++] = talloc_strdup(pool, pctx->ipv6_dns2); + msg->config->dns[pos++] = + talloc_strdup(pool, pctx->ipv6_dns2); msg->config->n_dns = dns; } diff --git a/src/tlslib.c b/src/tlslib.c index b90c536a..046bfadb 100644 --- a/src/tlslib.c +++ b/src/tlslib.c @@ -50,7 +50,7 @@ #include "log.h" #ifndef UNDER_TEST -static void tls_reload_ocsp(main_server_st* s, struct vhost_cfg_st *vhost); +static void tls_reload_ocsp(main_server_st *s, struct vhost_cfg_st *vhost); #endif /* UNDER_TEST */ void cstp_cork(worker_st *ws) @@ -60,12 +60,15 @@ void cstp_cork(worker_st *ws) } else { int state = 1, ret = 0; #if defined(__linux__) - ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_CORK, &state, sizeof(state)); + ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_CORK, &state, + sizeof(state)); #elif defined(TCP_NOPUSH) - ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_NOPUSH, &state, sizeof(state)); + ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_NOPUSH, &state, + sizeof(state)); #endif if (ret == -1) { - oclog(ws, LOG_ERR, "setsockopt(IPPROTO_TCP(TCP_CORK) failed"); + oclog(ws, LOG_ERR, + "setsockopt(IPPROTO_TCP(TCP_CORK) failed"); } } } @@ -77,30 +80,32 @@ int cstp_uncork(worker_st *ws) } else { int state = 0, ret = 0; #if defined(__linux__) - ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_CORK, &state, sizeof(state)); + ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_CORK, &state, + sizeof(state)); #elif defined(TCP_NOPUSH) - ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_NOPUSH, &state, sizeof(state)); + ret = setsockopt(ws->conn_fd, IPPROTO_TCP, TCP_NOPUSH, &state, + sizeof(state)); #endif if (ret == -1) { - oclog(ws, LOG_ERR, "setsockopt(IPPROTO_TCP(TCP_UNCORK) failed"); + oclog(ws, LOG_ERR, + "setsockopt(IPPROTO_TCP(TCP_UNCORK) failed"); } return 0; } } - -ssize_t cstp_send(worker_st *ws, const void *data, - size_t data_size) +ssize_t cstp_send(worker_st *ws, const void *data, size_t data_size) { int ret; int left = data_size; - const uint8_t* p = data; + const uint8_t *p = data; if (ws->session != NULL) { while (left > 0) { ret = gnutls_record_send(ws->session, p, data_size); if (ret < 0) { - if (ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED) { + if (ret != GNUTLS_E_AGAIN && + ret != GNUTLS_E_INTERRUPTED) { return ret; } else { /* do not cause mayhem */ @@ -131,9 +136,9 @@ ssize_t cstp_send_file(worker_st *ws, const char *file) if (fd == -1) return GNUTLS_E_FILE_ERROR; - while ( (len = read( fd, buf, sizeof(buf))) > 0 || - (len == -1 && counter > 0 && (errno == EINTR || errno == EAGAIN))) { - + while ((len = read(fd, buf, sizeof(buf))) > 0 || + (len == -1 && counter > 0 && + (errno == EINTR || errno == EAGAIN))) { if (len == -1) { counter--; ms_sleep(100); @@ -151,16 +156,16 @@ ssize_t cstp_send_file(worker_st *ws, const char *file) return total; } -static -int recv_remaining(int fd, uint8_t *p, int left) +static int recv_remaining(int fd, uint8_t *p, int left) { int counter = 100; /* allow 10 seconds for a full packet */ - unsigned total = 0; + unsigned int total = 0; int ret; while (left > 0) { ret = recv(fd, p, left, 0); - if (ret == -1 && counter > 0 && (errno == EINTR || errno == EAGAIN)) { + if (ret == -1 && counter > 0 && + (errno == EINTR || errno == EAGAIN)) { counter--; ms_sleep(100); continue; @@ -195,7 +200,7 @@ static ssize_t _cstp_recv_packet(worker_st *ws, void *data, size_t data_size) * incomplete CSTP packet. In that case we attempt to read * a full CSTP packet. */ - unsigned pktlen; + unsigned int pktlen; uint8_t *p = data; /* read the header */ @@ -205,18 +210,18 @@ static ssize_t _cstp_recv_packet(worker_st *ws, void *data, size_t data_size) /* get the actual length from headers */ pktlen = (p[4] << 8) + p[5]; - if (pktlen+8 > data_size) { + if (pktlen + 8 > data_size) { oclog(ws, LOG_ERR, "error in CSTP packet length"); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } if (pktlen > 0) { - ret = recv_remaining(ws->conn_fd, p+8, pktlen); + ret = recv_remaining(ws->conn_fd, p + 8, pktlen); if (ret <= 0) return ret; } - return 8+pktlen; + return 8 + pktlen; } } @@ -255,11 +260,14 @@ ssize_t cstp_recv(worker_st *ws, void *data, size_t data_size) if (ws->session != NULL) { do { ret = gnutls_record_recv(ws->session, data, data_size); - if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) { + if (ret == GNUTLS_E_AGAIN || + ret == GNUTLS_E_INTERRUPTED) { counter--; ms_sleep(20); } - } while ((ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) && counter > 0); + } while ((ret == GNUTLS_E_AGAIN || + ret == GNUTLS_E_INTERRUPTED) && + counter > 0); } else { do { ret = recv(ws->conn_fd, data, data_size, 0); @@ -267,20 +275,20 @@ ssize_t cstp_recv(worker_st *ws, void *data, size_t data_size) counter--; ms_sleep(20); } - } while (ret == -1 && (errno == EINTR || errno == EAGAIN) && counter > 0); + } while (ret == -1 && (errno == EINTR || errno == EAGAIN) && + counter > 0); } return ret; } - /* Typically used in a resumed session. It will return * true if a certificate has been used. */ -unsigned tls_has_session_cert(struct worker_st * ws) +unsigned int tls_has_session_cert(struct worker_st *ws) { unsigned int list_size = 0; - const gnutls_datum_t * certs; + const gnutls_datum_t *certs; if (ws->session == NULL) return 0; @@ -299,8 +307,8 @@ unsigned tls_has_session_cert(struct worker_st * ws) return 0; } -int __attribute__ ((format(printf, 2, 3))) - cstp_printf(worker_st *ws, const char *fmt, ...) +int __attribute__((format(printf, 2, 3))) cstp_printf(worker_st *ws, + const char *fmt, ...) { char *buf; va_list args; @@ -328,8 +336,7 @@ void cstp_close(worker_st *ws) } } -void cstp_fatal_close(worker_st *ws, - gnutls_alert_description_t a) +void cstp_fatal_close(worker_st *ws, gnutls_alert_description_t a) { if (ws->session) { gnutls_alert_send(ws->session, GNUTLS_AL_FATAL, a); @@ -353,8 +360,8 @@ ssize_t dtls_recv_packet(struct dtls_st *dtls, gnutls_datum_t *data, void **p) data->size = 0; } #else - ret = - gnutls_record_recv(dtls->dtls_session, ws->buffer, ws->buffer_size); + ret = gnutls_record_recv(dtls->dtls_session, ws->buffer, + ws->buffer_size); data->data = ws->buffer; data->size = ret; #endif @@ -362,17 +369,17 @@ ssize_t dtls_recv_packet(struct dtls_st *dtls, gnutls_datum_t *data, void **p) return ret; } -ssize_t dtls_send(struct dtls_st *dtls, const void *data, - size_t data_size) +ssize_t dtls_send(struct dtls_st *dtls, const void *data, size_t data_size) { int ret; int left = data_size; - const uint8_t* p = data; + const uint8_t *p = data; while (left > 0) { ret = gnutls_record_send(dtls->dtls_session, p, data_size); if (ret < 0) { - if (ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED) { + if (ret != GNUTLS_E_AGAIN && + ret != GNUTLS_E_INTERRUPTED) { return ret; } else { /* do not cause mayhem */ @@ -402,7 +409,7 @@ static size_t rehash(const void *_e, void *unused) return hash_any(e->session_id, e->session_id_size, 0); } -void tls_cache_init(void *pool, tls_sess_db_st* db) +void tls_cache_init(void *pool, tls_sess_db_st *db) { db->ht = talloc(pool, struct htable); if (db->ht == NULL) @@ -412,23 +419,24 @@ void tls_cache_init(void *pool, tls_sess_db_st* db) db->entries = 0; } -void tls_cache_deinit(tls_sess_db_st* db) +void tls_cache_deinit(tls_sess_db_st *db) { - tls_cache_st* cache; + tls_cache_st *cache; struct htable_iter iter; cache = htable_first(db->ht, &iter); while (cache != NULL) { if (cache->session_data_size > 0) { - safe_memset(cache->session_data, 0, cache->session_data_size); + safe_memset(cache->session_data, 0, + cache->session_data_size); cache->session_data_size = 0; cache->session_id_size = 0; } talloc_free(cache); cache = htable_next(db->ht, &iter); - } - htable_clear(db->ht); + } + htable_clear(db->ht); db->entries = 0; talloc_free(db->ht); } @@ -442,7 +450,7 @@ static void tls_log_func(int level, const char *str) static void tls_audit_log_func(gnutls_session_t session, const char *str) { - worker_st * ws; + worker_st *ws; (void)(ws); @@ -460,17 +468,19 @@ static int verify_certificate_cb(gnutls_session_t session) { unsigned int status; int ret; - worker_st * ws; + worker_st *ws; ws = gnutls_session_get_ptr(session); if (ws == NULL) { - oc_syslog(LOG_ERR, "%s:%d: could not obtain worker state", __func__, __LINE__); + oc_syslog(LOG_ERR, "%s:%d: could not obtain worker state", + __func__, __LINE__); return -1; } if ((session == DTLS_ACTIVE(ws)->dtls_session) || - (session == DTLS_INACTIVE(ws)->dtls_session)) { - oclog(ws, LOG_ERR, "unexpected issue; client shouldn't have offered a certificate in DTLS"); + (session == DTLS_INACTIVE(ws)->dtls_session)) { + oclog(ws, LOG_ERR, + "unexpected issue; client shouldn't have offered a certificate in DTLS"); return GNUTLS_E_CERTIFICATE_ERROR; } @@ -480,11 +490,13 @@ static int verify_certificate_cb(gnutls_session_t session) if (ws->cert_username[0] != 0) { char prev_username[MAX_USERNAME_SIZE]; const gnutls_datum_t *cert; - unsigned cert_size; + unsigned int cert_size; cert = gnutls_certificate_get_peers(session, &cert_size); - if (cert != NULL) { /* it's ok for the user not to send any certificate on renegotiation */ - memcpy(prev_username, ws->cert_username, MAX_USERNAME_SIZE); + if (cert != + NULL) { /* it's ok for the user not to send any certificate on renegotiation */ + memcpy(prev_username, ws->cert_username, + MAX_USERNAME_SIZE); ret = get_cert_names(ws, &cert[0]); if (ret < 0) { oclog(ws, LOG_ERR, "cannot parse certificate"); @@ -492,7 +504,8 @@ static int verify_certificate_cb(gnutls_session_t session) } if (strcmp(prev_username, ws->cert_username) != 0) { - oclog(ws, LOG_ERR, "user switched during renegotiation!"); + oclog(ws, LOG_ERR, + "user switched during renegotiation!"); return GNUTLS_E_CERTIFICATE_ERROR; } } @@ -507,7 +520,8 @@ static int verify_certificate_cb(gnutls_session_t session) goto no_cert; } if (ret < 0) { - oclog(ws, LOG_ERR, "error verifying client certificate: %s", gnutls_strerror(ret)); + oclog(ws, LOG_ERR, "error verifying client certificate: %s", + gnutls_strerror(ret)); goto fail; } @@ -515,26 +529,28 @@ static int verify_certificate_cb(gnutls_session_t session) gnutls_datum_t out; int type = gnutls_certificate_type_get(session); - ret = - gnutls_certificate_verification_status_print(status, type, - &out, 0); + ret = gnutls_certificate_verification_status_print(status, type, + &out, 0); if (ret < 0) goto fail; - oclog(ws, LOG_INFO, "client certificate verification failed: %s", out.data); + oclog(ws, LOG_INFO, + "client certificate verification failed: %s", out.data); gnutls_free(out.data); goto fail; } else { ws->cert_auth_ok = 1; - oclog(ws, LOG_INFO, "client certificate verification succeeded"); + oclog(ws, LOG_INFO, + "client certificate verification succeeded"); } /* notify gnutls to continue handshake normally */ return 0; no_cert: - if (WSCONFIG(ws)->cisco_client_compat != 0 || WSCONFIG(ws)->cert_req != GNUTLS_CERT_REQUIRE) + if (WSCONFIG(ws)->cisco_client_compat != 0 || + WSCONFIG(ws)->cert_req != GNUTLS_CERT_REQUIRE) return 0; fail: return GNUTLS_E_CERTIFICATE_ERROR; @@ -576,13 +592,14 @@ void tls_vhost_deinit(struct vhost_cfg_st *vhost) #ifndef UNDER_TEST /* Checks, if there is a single certificate specified, whether it * is compatible with all ciphersuites */ -static void certificate_check(main_server_st *s, const char *vhostname, gnutls_pcert_st *pcert) +static void certificate_check(main_server_st *s, const char *vhostname, + gnutls_pcert_st *pcert) { - gnutls_datum_t data = {NULL, 0}; + gnutls_datum_t data = { NULL, 0 }; gnutls_x509_crt_t crt = NULL; int ret; - unsigned usage; - gnutls_datum_t dn = {NULL, 0}; + unsigned int usage; + gnutls_datum_t dn = { NULL, 0 }; const char *cert_name = "unnamed"; time_t t; @@ -604,13 +621,15 @@ static void certificate_check(main_server_st *s, const char *vhostname, gnutls_p ret = gnutls_x509_crt_get_dn2(crt, &dn); #endif if (ret >= 0) { - cert_name = (char*)dn.data; + cert_name = (char *)dn.data; } ret = gnutls_x509_crt_get_key_usage(crt, &usage, NULL); if (ret >= 0) { if (!(usage & GNUTLS_KEY_KEY_ENCIPHERMENT)) { - oc_syslog(LOG_WARNING, "%s certificate key usage prevents key encipherment; unable to support the RSA ciphersuites; " + oc_syslog( + LOG_WARNING, + "%s certificate key usage prevents key encipherment; unable to support the RSA ciphersuites; " "if that is not intentional, regenerate the server certificate with the key usage flag 'key encipherment' set.", cert_name); } @@ -619,19 +638,24 @@ static void certificate_check(main_server_st *s, const char *vhostname, gnutls_p if (vhostname) { /* check whether the hostname matches our vhost */ if (!gnutls_x509_crt_check_hostname(crt, vhostname)) { - oc_syslog(LOG_WARNING, "The %s certificate's name doesn't match for vhost %s", - cert_name, vhostname); + oc_syslog( + LOG_WARNING, + "The %s certificate's name doesn't match for vhost %s", + cert_name, vhostname); } } t = gnutls_x509_crt_get_expiration_time(crt); if (t < time(NULL)) { - oc_syslog(LOG_WARNING, "The %s certificate set is expired!", cert_name); + oc_syslog(LOG_WARNING, "The %s certificate set is expired!", + cert_name); } t = gnutls_x509_crt_get_activation_time(crt); if (t > time(NULL)) { - oc_syslog(LOG_WARNING, "The %s certificate set is not yet active!", cert_name); + oc_syslog(LOG_WARNING, + "The %s certificate set is not yet active!", + cert_name); } cleanup: @@ -641,49 +665,55 @@ cleanup: gnutls_free(dn.data); } -static void set_dh_params(main_server_st* s, struct vhost_cfg_st *vhost) +static void set_dh_params(main_server_st *s, struct vhost_cfg_st *vhost) { gnutls_datum_t data; int ret; if (vhost->perm_config.dh_params_file != NULL) { - ret = gnutls_dh_params_init (&vhost->creds.dh_params); + ret = gnutls_dh_params_init(&vhost->creds.dh_params); GNUTLS_FATAL_ERR(ret); - ret = gnutls_load_file(vhost->perm_config.dh_params_file, &data); + ret = gnutls_load_file(vhost->perm_config.dh_params_file, + &data); GNUTLS_FATAL_ERR(ret); - ret = gnutls_dh_params_import_pkcs3(vhost->creds.dh_params, &data, GNUTLS_X509_FMT_PEM); + ret = gnutls_dh_params_import_pkcs3(vhost->creds.dh_params, + &data, GNUTLS_X509_FMT_PEM); GNUTLS_FATAL_ERR(ret); gnutls_free(data.data); - gnutls_certificate_set_dh_params(vhost->creds.xcred, vhost->creds.dh_params); + gnutls_certificate_set_dh_params(vhost->creds.xcred, + vhost->creds.dh_params); } else { #if GNUTLS_VERSION_NUMBER >= 0x030506 /* use pre-generated parameters */ - gnutls_certificate_set_known_dh_params(vhost->creds.xcred, GNUTLS_SEC_PARAM_MEDIUM); + gnutls_certificate_set_known_dh_params(vhost->creds.xcred, + GNUTLS_SEC_PARAM_MEDIUM); #endif } } struct key_cb_data { - unsigned pk; - unsigned bits; - unsigned idx; /* the index of the key */ + unsigned int pk; + unsigned int bits; + unsigned int idx; /* the index of the key */ struct sockaddr_un sa; - unsigned sa_len; + unsigned int sa_len; const char *vhost; }; -static -int key_cb_common_func (gnutls_privkey_t key, void* userdata, const gnutls_datum_t * raw_data, - gnutls_datum_t * output, unsigned sigalgo, unsigned type) +static int key_cb_common_func(gnutls_privkey_t key, void *userdata, + const gnutls_datum_t *raw_data, + gnutls_datum_t *output, unsigned int sigalgo, + unsigned int type) { - struct key_cb_data* cdata = userdata; + struct key_cb_data *cdata = userdata; int sd = -1, ret, e; SecOpMsg msg = SEC_OP_MSG__INIT; SecOpMsg *reply = NULL; + PROTOBUF_ALLOCATOR(pa, userdata); output->data = NULL; @@ -700,8 +730,9 @@ int key_cb_common_func (gnutls_privkey_t key, void* userdata, const gnutls_datum ret = connect(sd, (struct sockaddr *)&cdata->sa, cdata->sa_len); if (ret == -1) { e = errno; - oc_syslog(LOG_DEBUG, "error connecting to sec-mod socket '%s': %s", - cdata->sa.sun_path, strerror(e)); + oc_syslog(LOG_DEBUG, + "error connecting to sec-mod socket '%s': %s", + cdata->sa.sun_path, strerror(e)); goto error; } @@ -710,22 +741,21 @@ int key_cb_common_func (gnutls_privkey_t key, void* userdata, const gnutls_datum msg.sig = sigalgo; msg.data.data = raw_data->data; msg.data.len = raw_data->size; - msg.vhost = (char*)cdata->vhost; + msg.vhost = (char *)cdata->vhost; ret = send_msg(userdata, sd, type, &msg, - (pack_size_func)sec_op_msg__get_packed_size, - (pack_func)sec_op_msg__pack); + (pack_size_func)sec_op_msg__get_packed_size, + (pack_func)sec_op_msg__pack); if (ret < 0) { goto error; } - ret = recv_msg(userdata, sd, type, (void*)&reply, - (unpack_func)sec_op_msg__unpack, - DEFAULT_SOCKET_TIMEOUT); + ret = recv_msg(userdata, sd, type, (void *)&reply, + (unpack_func)sec_op_msg__unpack, DEFAULT_SOCKET_TIMEOUT); if (ret < 0) { e = errno; oc_syslog(LOG_ERR, "error receiving sec-mod reply: %s", - strerror(e)); + strerror(e)); goto error; } close(sd); @@ -753,7 +783,8 @@ error: } #if GNUTLS_VERSION_NUMBER >= 0x030600 -static int key_cb_info_func(gnutls_privkey_t key, unsigned int flags, void *userdata) +static int key_cb_info_func(gnutls_privkey_t key, unsigned int flags, + void *userdata) { struct key_cb_data *p = userdata; @@ -764,7 +795,7 @@ static int key_cb_info_func(gnutls_privkey_t key, unsigned int flags, void *user return p->bits; #endif } else if (flags & GNUTLS_PRIVKEY_INFO_HAVE_SIGN_ALGO) { - unsigned sig = GNUTLS_FLAGS_TO_SIGN_ALGO(flags); + unsigned int sig = GNUTLS_FLAGS_TO_SIGN_ALGO(flags); if (gnutls_sign_supports_pk_algorithm(sig, p->pk)) return 1; @@ -775,83 +806,98 @@ static int key_cb_info_func(gnutls_privkey_t key, unsigned int flags, void *user return -1; } -static -int key_cb_sign_data_func (gnutls_privkey_t key, gnutls_sign_algorithm_t sig, - void* userdata, unsigned int flags, const gnutls_datum_t *data, - gnutls_datum_t *signature) +static int key_cb_sign_data_func(gnutls_privkey_t key, + gnutls_sign_algorithm_t sig, void *userdata, + unsigned int flags, const gnutls_datum_t *data, + gnutls_datum_t *signature) { - return key_cb_common_func(key, userdata, data, signature, sig, CMD_SEC_SIGN_DATA); + return key_cb_common_func(key, userdata, data, signature, sig, + CMD_SEC_SIGN_DATA); } -static -int key_cb_sign_hash_func (gnutls_privkey_t key, gnutls_sign_algorithm_t sig, - void* userdata, unsigned int flags, const gnutls_datum_t *data, - gnutls_datum_t *signature) +static int key_cb_sign_hash_func(gnutls_privkey_t key, + gnutls_sign_algorithm_t sig, void *userdata, + unsigned int flags, const gnutls_datum_t *data, + gnutls_datum_t *signature) { if (sig == GNUTLS_SIGN_RSA_RAW) - return key_cb_common_func(key, userdata, data, signature, 0, CMD_SEC_SIGN); + return key_cb_common_func(key, userdata, data, signature, 0, + CMD_SEC_SIGN); - return key_cb_common_func(key, userdata, data, signature, sig, CMD_SEC_SIGN_HASH); + return key_cb_common_func(key, userdata, data, signature, sig, + CMD_SEC_SIGN_HASH); } #else -static -int key_cb_sign_func (gnutls_privkey_t key, void* userdata, const gnutls_datum_t * raw_data, - gnutls_datum_t * signature) +static int key_cb_sign_func(gnutls_privkey_t key, void *userdata, + const gnutls_datum_t *raw_data, + gnutls_datum_t *signature) { - return key_cb_common_func(key, userdata, raw_data, signature, 0, CMD_SEC_SIGN); + return key_cb_common_func(key, userdata, raw_data, signature, 0, + CMD_SEC_SIGN); } #endif -static int key_cb_decrypt_func(gnutls_privkey_t key, void* userdata, const gnutls_datum_t * ciphertext, - gnutls_datum_t * plaintext) +static int key_cb_decrypt_func(gnutls_privkey_t key, void *userdata, + const gnutls_datum_t *ciphertext, + gnutls_datum_t *plaintext) { - return key_cb_common_func(key, userdata, ciphertext, plaintext, 0, CMD_SEC_DECRYPT); + return key_cb_common_func(key, userdata, ciphertext, plaintext, 0, + CMD_SEC_DECRYPT); } -static void key_cb_deinit_func(gnutls_privkey_t key, void* userdata) +static void key_cb_deinit_func(gnutls_privkey_t key, void *userdata) { talloc_free(userdata); } -static -int load_cert_files(main_server_st *s, struct vhost_cfg_st *vhost) +static int load_cert_files(main_server_st *s, struct vhost_cfg_st *vhost) { int ret; gnutls_pcert_st *pcert_list; - unsigned pcert_list_size, i; + unsigned int pcert_list_size, i; gnutls_privkey_t key; gnutls_datum_t data; struct key_cb_data *cdata; - unsigned flags; + unsigned int flags; - for (i=0;iperm_config.key_size;i++) { + for (i = 0; i < vhost->perm_config.key_size; i++) { /* load the certificate */ if (gnutls_url_is_supported(vhost->perm_config.cert[i]) != 0) { - oc_syslog(LOG_ERR, "Loading a certificate from '%s' is unsupported", vhost->perm_config.cert[i]); + oc_syslog( + LOG_ERR, + "Loading a certificate from '%s' is unsupported", + vhost->perm_config.cert[i]); return -1; } else { - ret = gnutls_load_file(vhost->perm_config.cert[i], &data); + ret = gnutls_load_file(vhost->perm_config.cert[i], + &data); if (ret < 0) { - oc_syslog(LOG_ERR, "error loading file[%d] '%s'", i, vhost->perm_config.cert[i]); + oc_syslog(LOG_ERR, + "error loading file[%d] '%s'", i, + vhost->perm_config.cert[i]); return -1; } pcert_list_size = 8; - pcert_list = talloc_size(vhost->pool, sizeof(pcert_list[0])*pcert_list_size); + pcert_list = talloc_size(vhost->pool, + sizeof(pcert_list[0]) * + pcert_list_size); if (pcert_list == NULL) { oc_syslog(LOG_ERR, "error allocating memory"); return -1; } - flags = GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED|GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED; + flags = GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED | + GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED; #if GNUTLS_VERSION_NUMBER > 0x030409 flags |= GNUTLS_X509_CRT_LIST_SORT; #endif - ret = gnutls_pcert_list_import_x509_raw(pcert_list, &pcert_list_size, - &data, GNUTLS_X509_FMT_PEM, flags); + ret = gnutls_pcert_list_import_x509_raw( + pcert_list, &pcert_list_size, &data, + GNUTLS_X509_FMT_PEM, flags); GNUTLS_FATAL_ERR(ret); gnutls_free(data.data); @@ -877,34 +923,41 @@ int load_cert_files(main_server_st *s, struct vhost_cfg_st *vhost) /* when called here configuration may not be populated, so avoid using it */ cdata->sa.sun_family = AF_UNIX; - strlcpy(cdata->sa.sun_path, secmod_socket_file_name(&vhost->perm_config), sizeof(cdata->sa.sun_path)); + strlcpy(cdata->sa.sun_path, + secmod_socket_file_name(&vhost->perm_config), + sizeof(cdata->sa.sun_path)); cdata->sa_len = SUN_LEN(&cdata->sa); - /* load the private key */ #if GNUTLS_VERSION_NUMBER >= 0x030600 - cdata->pk = gnutls_pubkey_get_pk_algorithm(pcert_list[0].pubkey, &cdata->bits); - ret = gnutls_privkey_import_ext4(key, cdata, key_cb_sign_data_func, - key_cb_sign_hash_func,key_cb_decrypt_func, + cdata->pk = gnutls_pubkey_get_pk_algorithm(pcert_list[0].pubkey, + &cdata->bits); + ret = gnutls_privkey_import_ext4( + key, cdata, key_cb_sign_data_func, + key_cb_sign_hash_func, key_cb_decrypt_func, key_cb_deinit_func, key_cb_info_func, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE); #else - ret = gnutls_privkey_import_ext2(key, gnutls_pubkey_get_pk_algorithm(pcert_list[0].pubkey, NULL), + ret = gnutls_privkey_import_ext2( + key, + gnutls_pubkey_get_pk_algorithm(pcert_list[0].pubkey, + NULL), cdata, key_cb_sign_func, key_cb_decrypt_func, key_cb_deinit_func, GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE); #endif GNUTLS_FATAL_ERR(ret); - ret = gnutls_certificate_set_key(vhost->creds.xcred, NULL, 0, pcert_list, - pcert_list_size, key); + ret = gnutls_certificate_set_key(vhost->creds.xcred, NULL, 0, + pcert_list, pcert_list_size, + key); GNUTLS_FATAL_ERR(ret); } return 0; } -unsigned need_file_reload(const char *file, time_t last_access) +unsigned int need_file_reload(const char *file, time_t last_access) { struct stat st; int ret, e; @@ -918,8 +971,9 @@ unsigned need_file_reload(const char *file, time_t last_access) ret = stat(file, &st); if (ret == -1) { e = errno; - oc_syslog(LOG_INFO, "file %s (to be reloaded) was not found: %s", - file, strerror(e)); + oc_syslog(LOG_INFO, + "file %s (to be reloaded) was not found: %s", file, + strerror(e)); return 0; } @@ -932,23 +986,28 @@ unsigned need_file_reload(const char *file, time_t last_access) /* reload key files etc. * @s may be %NULL, and should be used for mslog() purposes only. */ -void tls_load_files(main_server_st *s, struct vhost_cfg_st *vhost, unsigned silent) +void tls_load_files(main_server_st *s, struct vhost_cfg_st *vhost, + unsigned int silent) { int ret; - unsigned i; - unsigned need_reload = 0; + unsigned int i; + unsigned int need_reload = 0; if (vhost->params_last_access != 0) { - for (i=0;iperm_config.key_size;i++) { - if (need_file_reload(vhost->perm_config.cert[i], vhost->params_last_access) != 0) { + for (i = 0; i < vhost->perm_config.key_size; i++) { + if (need_file_reload(vhost->perm_config.cert[i], + vhost->params_last_access) != 0) { need_reload = 1; break; } } - if (need_file_reload(vhost->perm_config.ca, vhost->params_last_access) || - need_file_reload(vhost->perm_config.config->ocsp_response, vhost->params_last_access) || - need_file_reload(vhost->perm_config.dh_params_file, vhost->params_last_access)) { + if (need_file_reload(vhost->perm_config.ca, + vhost->params_last_access) || + need_file_reload(vhost->perm_config.config->ocsp_response, + vhost->params_last_access) || + need_file_reload(vhost->perm_config.dh_params_file, + vhost->params_last_access)) { need_reload = 1; } @@ -976,15 +1035,19 @@ void tls_load_files(main_server_st *s, struct vhost_cfg_st *vhost, unsigned sile set_dh_params(s, vhost); - if (vhost->perm_config.key_size == 0 || vhost->perm_config.cert_size == 0) { - oc_syslog(LOG_ERR, "no certificate or key files were specified"); + if (vhost->perm_config.key_size == 0 || + vhost->perm_config.cert_size == 0) { + oc_syslog(LOG_ERR, + "no certificate or key files were specified"); exit(EXIT_FAILURE); } /* on reload reduce any checks done */ if (need_reload) { #if GNUTLS_VERSION_NUMBER >= 0x030407 - gnutls_certificate_set_flags(vhost->creds.xcred, GNUTLS_CERTIFICATE_SKIP_KEY_CERT_MATCH); + gnutls_certificate_set_flags( + vhost->creds.xcred, + GNUTLS_CERTIFICATE_SKIP_KEY_CERT_MATCH); #endif } @@ -996,18 +1059,20 @@ void tls_load_files(main_server_st *s, struct vhost_cfg_st *vhost, unsigned sile if (vhost->perm_config.config->cert_req != GNUTLS_CERT_IGNORE) { if (vhost->perm_config.ca != NULL) { - ret = - gnutls_certificate_set_x509_trust_file(vhost->creds.xcred, - vhost->perm_config.ca, - GNUTLS_X509_FMT_PEM); + ret = gnutls_certificate_set_x509_trust_file( + vhost->creds.xcred, vhost->perm_config.ca, + GNUTLS_X509_FMT_PEM); if (ret < 0) { - oc_syslog(LOG_ERR, "error setting the CA (%s) file", - vhost->perm_config.ca); + oc_syslog(LOG_ERR, + "error setting the CA (%s) file", + vhost->perm_config.ca); exit(EXIT_FAILURE); } if (!silent) - oc_syslog(LOG_INFO, "processed %d CA certificate(s)", ret); + oc_syslog(LOG_INFO, + "processed %d CA certificate(s)", + ret); } tls_reload_crl(s, vhost, 1); @@ -1019,7 +1084,8 @@ void tls_load_files(main_server_st *s, struct vhost_cfg_st *vhost, unsigned sile tls_reload_ocsp(s, vhost); } -static int ocsp_get_func(gnutls_session_t session, void *ptr, gnutls_datum_t *response) +static int ocsp_get_func(gnutls_session_t session, void *ptr, + gnutls_datum_t *response) { struct vhost_cfg_st *vhost = ptr; @@ -1030,13 +1096,14 @@ static int ocsp_get_func(gnutls_session_t session, void *ptr, gnutls_datum_t *re if (response->data == NULL) return GNUTLS_E_NO_CERTIFICATE_STATUS; - memcpy(response->data, vhost->creds.ocsp_response.data, vhost->creds.ocsp_response.size); + memcpy(response->data, vhost->creds.ocsp_response.data, + vhost->creds.ocsp_response.size); response->size = vhost->creds.ocsp_response.size; return 0; } -static void tls_reload_ocsp(main_server_st* s, struct vhost_cfg_st *vhost) +static void tls_reload_ocsp(main_server_st *s, struct vhost_cfg_st *vhost) { int ret; @@ -1044,14 +1111,16 @@ static void tls_reload_ocsp(main_server_st* s, struct vhost_cfg_st *vhost) vhost->creds.ocsp_response.data = NULL; if (vhost->perm_config.config->ocsp_response != NULL) { - ret = gnutls_load_file(vhost->perm_config.config->ocsp_response, &vhost->creds.ocsp_response); + ret = gnutls_load_file(vhost->perm_config.config->ocsp_response, + &vhost->creds.ocsp_response); if (ret < 0) return; - gnutls_certificate_set_ocsp_status_request_function(vhost->creds.xcred, - ocsp_get_func, vhost); + gnutls_certificate_set_ocsp_status_request_function( + vhost->creds.xcred, ocsp_get_func, vhost); } else { - gnutls_certificate_set_ocsp_status_request_function(vhost->creds.xcred, NULL, 0); + gnutls_certificate_set_ocsp_status_request_function( + vhost->creds.xcred, NULL, 0); } } @@ -1061,12 +1130,14 @@ static void tls_reload_ocsp(main_server_st* s, struct vhost_cfg_st *vhost) void tls_load_prio(main_server_st *s, struct vhost_cfg_st *vhost) { int ret; - const char* perr; + const char *perr; if (vhost->creds.cprio != NULL) gnutls_priority_deinit(vhost->creds.cprio); - ret = gnutls_priority_init(&vhost->creds.cprio, vhost->perm_config.config->priorities, &perr); + ret = gnutls_priority_init(&vhost->creds.cprio, + vhost->perm_config.config->priorities, + &perr); if (ret == GNUTLS_E_PARSING_ERROR) oc_syslog(LOG_ERR, "error in TLS priority string: %s", perr); GNUTLS_FATAL_ERR(ret); @@ -1075,43 +1146,49 @@ void tls_load_prio(main_server_st *s, struct vhost_cfg_st *vhost) /* * @s may be %NULL, and should be used for mslog() purposes only. */ -void tls_reload_crl(main_server_st* s, struct vhost_cfg_st *vhost, unsigned force) +void tls_reload_crl(main_server_st *s, struct vhost_cfg_st *vhost, + unsigned int force) { int ret, saved_ret; - static unsigned crl_type = GNUTLS_X509_FMT_PEM; + static unsigned int crl_type = GNUTLS_X509_FMT_PEM; if (force) vhost->crl_last_access = 0; - if (vhost->perm_config.config->cert_req != GNUTLS_CERT_IGNORE && vhost->perm_config.config->crl != NULL) { - if (need_file_reload(vhost->perm_config.config->crl, vhost->crl_last_access) == 0) { - oc_syslog(LOG_DEBUG, "skipping already loaded CRL: %s", vhost->perm_config.config->crl); + if (vhost->perm_config.config->cert_req != GNUTLS_CERT_IGNORE && + vhost->perm_config.config->crl != NULL) { + if (need_file_reload(vhost->perm_config.config->crl, + vhost->crl_last_access) == 0) { + oc_syslog(LOG_DEBUG, "skipping already loaded CRL: %s", + vhost->perm_config.config->crl); return; } vhost->crl_last_access = time(NULL); - ret = - gnutls_certificate_set_x509_crl_file(vhost->creds.xcred, - vhost->perm_config.config->crl, - crl_type); - if (ret == GNUTLS_E_BASE64_DECODING_ERROR && crl_type == GNUTLS_X509_FMT_PEM) { + ret = gnutls_certificate_set_x509_crl_file( + vhost->creds.xcred, vhost->perm_config.config->crl, + crl_type); + if (ret == GNUTLS_E_BASE64_DECODING_ERROR && + crl_type == GNUTLS_X509_FMT_PEM) { crl_type = GNUTLS_X509_FMT_DER; saved_ret = ret; - ret = - gnutls_certificate_set_x509_crl_file(vhost->creds.xcred, - vhost->perm_config.config->crl, - crl_type); + ret = gnutls_certificate_set_x509_crl_file( + vhost->creds.xcred, + vhost->perm_config.config->crl, crl_type); if (ret < 0) ret = saved_ret; } if (ret < 0) { /* ignore the CRL file when empty */ - oc_syslog(LOG_ERR, "error reading the CRL (%s) file: %s", - vhost->perm_config.config->crl, gnutls_strerror(ret)); + oc_syslog(LOG_ERR, + "error reading the CRL (%s) file: %s", + vhost->perm_config.config->crl, + gnutls_strerror(ret)); exit(EXIT_FAILURE); } - oc_syslog(LOG_INFO, "loaded CRL: %s", vhost->perm_config.config->crl); + oc_syslog(LOG_INFO, "loaded CRL: %s", + vhost->perm_config.config->crl); } } #endif /* UNDER_TEST */ @@ -1126,14 +1203,14 @@ int tls_uncork(gnutls_session_t session) return gnutls_record_uncork(session, GNUTLS_RECORD_WAIT); } -void *calc_sha1_hash(void *pool, char* file, unsigned cert) +void *calc_sha1_hash(void *pool, char *file, unsigned int cert) { int ret; gnutls_datum_t data; uint8_t digest[20]; - char * retval; + char *retval; gnutls_x509_crt_t crt; - unsigned i; + unsigned int i; ret = gnutls_load_file(file, &data); if (ret < 0) { @@ -1146,7 +1223,8 @@ void *calc_sha1_hash(void *pool, char* file, unsigned cert) ret = gnutls_x509_crt_import(crt, &data, GNUTLS_X509_FMT_PEM); if (ret == GNUTLS_E_BASE64_DECODING_ERROR) - ret = gnutls_x509_crt_import(crt, &data, GNUTLS_X509_FMT_DER); + ret = gnutls_x509_crt_import(crt, &data, + GNUTLS_X509_FMT_DER); GNUTLS_FATAL_ERR(ret); gnutls_free(data.data); @@ -1160,11 +1238,13 @@ void *calc_sha1_hash(void *pool, char* file, unsigned cert) gnutls_free(data.data); if (ret < 0) { - oc_syslog(LOG_ERR, "error calculating hash of '%s': %s", file, gnutls_strerror(ret)); + oc_syslog(LOG_ERR, "error calculating hash of '%s': %s", file, + gnutls_strerror(ret)); exit(EXIT_FAILURE); } - size_t ret_size = sizeof(digest)*2+1; + size_t ret_size = sizeof(digest) * 2 + 1; + retval = talloc_size(pool, ret_size); if (retval == NULL) { oc_syslog(LOG_ERR, "memory error"); @@ -1175,20 +1255,24 @@ void *calc_sha1_hash(void *pool, char* file, unsigned cert) data.size = sizeof(digest); ret = gnutls_hex_encode(&data, retval, &ret_size); if (ret < 0) { - oc_syslog(LOG_ERR, "error in hex encode: %s", gnutls_strerror(ret)); + oc_syslog(LOG_ERR, "error in hex encode: %s", + gnutls_strerror(ret)); exit(EXIT_FAILURE); } - if (retval[ret_size-1] == 0) ret_size--; /* remove the null terminator */ + if (retval[ret_size - 1] == 0) + ret_size--; /* remove the null terminator */ /* convert to all caps */ - for (i=0;i #include -# if GNUTLS_VERSION_NUMBER < 0x030200 -# define GNUTLS_DTLS1_2 202 -# endif +#if GNUTLS_VERSION_NUMBER < 0x030200 +#define GNUTLS_DTLS1_2 202 +#endif -# if GNUTLS_VERSION_NUMBER >= 0x030305 -# define ZERO_COPY -# endif +#if GNUTLS_VERSION_NUMBER >= 0x030305 +#define ZERO_COPY +#endif #define PSK_KEY_SIZE 32 #if TLS_MASTER_SIZE < PSK_KEY_SIZE -# error +#error #endif -typedef struct -{ +typedef struct { struct htable *ht; unsigned int entries; } tls_sess_db_st; @@ -57,89 +56,108 @@ typedef struct tls_st { struct vhost_cfg_st; -void tls_reload_crl(struct main_server_st* s, struct vhost_cfg_st *vhost, unsigned force); +void tls_reload_crl(struct main_server_st *s, struct vhost_cfg_st *vhost, + unsigned int force); void tls_global_init(void); void tls_vhost_init(struct vhost_cfg_st *vhost); void tls_vhost_deinit(struct vhost_cfg_st *vhost); -void tls_load_files(struct main_server_st* s, struct vhost_cfg_st *vhost, unsigned silent); +void tls_load_files(struct main_server_st *s, struct vhost_cfg_st *vhost, + unsigned int silent); void tls_load_prio(struct main_server_st *s, struct vhost_cfg_st *vhost); -size_t tls_get_overhead(gnutls_protocol_t, gnutls_cipher_algorithm_t, gnutls_mac_algorithm_t); +size_t tls_get_overhead(gnutls_protocol_t, gnutls_cipher_algorithm_t, + gnutls_mac_algorithm_t); #define GNUTLS_FATAL_ERR DTLS_FATAL_ERR -#define GNUTLS_ALERT_PRINT(ws, session, err) { \ - if (err == GNUTLS_E_FATAL_ALERT_RECEIVED || err == GNUTLS_E_WARNING_ALERT_RECEIVED) { \ - oclog(ws, LOG_NOTICE, "TLS alert (at %s:%d): %s", __FILE__, __LINE__, gnutls_alert_get_name(gnutls_alert_get(session))); \ - }} +#define GNUTLS_ALERT_PRINT(ws, session, err) \ + { \ + if (err == GNUTLS_E_FATAL_ALERT_RECEIVED || \ + err == GNUTLS_E_WARNING_ALERT_RECEIVED) { \ + oclog(ws, LOG_NOTICE, "TLS alert (at %s:%d): %s", \ + __FILE__, __LINE__, \ + gnutls_alert_get_name( \ + gnutls_alert_get(session))); \ + } \ + } -#define DTLS_FATAL_ERR_CMD(err, CMD) { \ - if (err < 0 && gnutls_error_is_fatal (err) != 0) { \ - if (syslog_open) \ - syslog(LOG_WARNING, "GnuTLS error (at %s:%d): %s", __FILE__, __LINE__, gnutls_strerror(err)); \ - else \ - fprintf(stderr, "GnuTLS error (at %s:%d): %s\n", __FILE__, __LINE__, gnutls_strerror(err)); \ - CMD; \ - }} +#define DTLS_FATAL_ERR_CMD(err, CMD) \ + { \ + if (err < 0 && gnutls_error_is_fatal(err) != 0) { \ + if (syslog_open) \ + syslog(LOG_WARNING, \ + "GnuTLS error (at %s:%d): %s", \ + __FILE__, __LINE__, \ + gnutls_strerror(err)); \ + else \ + fprintf(stderr, \ + "GnuTLS error (at %s:%d): %s\n", \ + __FILE__, __LINE__, \ + gnutls_strerror(err)); \ + CMD; \ + } \ + } #define DTLS_FATAL_ERR(err) DTLS_FATAL_ERR_CMD(err, exit(EXIT_FAILURE)) -#define CSTP_FATAL_ERR_CMD(ws, err, CMD) { \ - if (ws->session != NULL) { \ - if (err < 0 && gnutls_error_is_fatal (err) != 0) { \ - oclog(ws, LOG_WARNING, "GnuTLS error (at %s:%d): %s", __FILE__, __LINE__, gnutls_strerror(err)); \ - CMD; \ - } \ - } else { \ - if (err < 0 && errno != EINTR && errno != EAGAIN) { \ - oclog(ws, LOG_WARNING, "socket error (at %s:%d): %s", __FILE__, __LINE__, strerror(errno)); \ - CMD; \ - } \ - }} +#define CSTP_FATAL_ERR_CMD(ws, err, CMD) \ + { \ + if (ws->session != NULL) { \ + if (err < 0 && gnutls_error_is_fatal(err) != 0) { \ + oclog(ws, LOG_WARNING, \ + "GnuTLS error (at %s:%d): %s", __FILE__, \ + __LINE__, gnutls_strerror(err)); \ + CMD; \ + } \ + } else { \ + if (err < 0 && errno != EINTR && errno != EAGAIN) { \ + oclog(ws, LOG_WARNING, \ + "socket error (at %s:%d): %s", __FILE__, \ + __LINE__, strerror(errno)); \ + CMD; \ + } \ + } \ + } #define CSTP_FATAL_ERR(ws, err) CSTP_FATAL_ERR_CMD(ws, err, exit(EXIT_FAILURE)) void tls_close(gnutls_session_t session); -unsigned tls_has_session_cert(struct worker_st * ws); +unsigned int tls_has_session_cert(struct worker_st *ws); -void tls_fatal_close(gnutls_session_t session, - gnutls_alert_description_t a); +void tls_fatal_close(gnutls_session_t session, gnutls_alert_description_t a); -typedef struct -{ - /* does not allow resumption from different address +typedef struct { + /* does not allow resumption from different address * than the original */ - struct sockaddr_storage remote_addr; - socklen_t remote_addr_len; + struct sockaddr_storage remote_addr; + socklen_t remote_addr_len; - char session_id[GNUTLS_MAX_SESSION_ID]; - unsigned int session_id_size; + char session_id[GNUTLS_MAX_SESSION_ID]; + unsigned int session_id_size; - char session_data[MAX_SESSION_DATA_SIZE]; - unsigned int session_data_size; + char session_data[MAX_SESSION_DATA_SIZE]; + unsigned int session_data_size; - char *vhostname; + char *vhostname; } tls_cache_st; #define TLS_SESSION_EXPIRATION_TIME(config) ((config)->cookie_timeout) #define DEFAULT_MAX_CACHED_TLS_SESSIONS 64 -void tls_cache_init(void *pool, tls_sess_db_st* db); -void tls_cache_deinit(tls_sess_db_st* db); -void *calc_sha1_hash(void *pool, char* file, unsigned cert); +void tls_cache_init(void *pool, tls_sess_db_st *db); +void tls_cache_deinit(tls_sess_db_st *db); +void *calc_sha1_hash(void *pool, char *file, unsigned int cert); /* TLS API */ -int __attribute__ ((format(printf, 2, 3))) - cstp_printf(struct worker_st *ws, const char *fmt, ...); +int __attribute__((format(printf, 2, 3))) cstp_printf(struct worker_st *ws, + const char *fmt, ...); void cstp_close(struct worker_st *ws); -void cstp_fatal_close(struct worker_st *ws, - gnutls_alert_description_t a); +void cstp_fatal_close(struct worker_st *ws, gnutls_alert_description_t a); ssize_t cstp_recv(struct worker_st *ws, void *data, size_t data_size); ssize_t cstp_send_file(struct worker_st *ws, const char *file); -ssize_t cstp_send(struct worker_st *ws, const void *data, - size_t data_size); -#define cstp_puts(s, str) cstp_send(s, str, sizeof(str)-1) +ssize_t cstp_send(struct worker_st *ws, const void *data, size_t data_size); +#define cstp_puts(s, str) cstp_send(s, str, sizeof(str) - 1) void cstp_cork(struct worker_st *ws); int cstp_uncork(struct worker_st *ws); @@ -153,6 +171,7 @@ inline static void packet_deinit(void *p) { #ifdef ZERO_COPY gnutls_packet_t packet = p; + if (packet) gnutls_packet_deinit(packet); #endif @@ -162,7 +181,7 @@ ssize_t cstp_recv_packet(struct worker_st *ws, gnutls_datum_t *data, void **p); ssize_t dtls_recv_packet(struct dtls_st *dtls, gnutls_datum_t *data, void **p); /* Helper functions */ -unsigned need_file_reload(const char *file, time_t last_access); -void safe_hash(const uint8_t *data, unsigned data_size, uint8_t output[20]); +unsigned int need_file_reload(const char *file, time_t last_access); +void safe_hash(const uint8_t *data, unsigned int data_size, uint8_t output[20]); #endif diff --git a/src/tun.c b/src/tun.c index 53aa8139..e53ec7d2 100644 --- a/src/tun.c +++ b/src/tun.c @@ -37,9 +37,9 @@ #include #if defined(HAVE_LINUX_IF_TUN_H) -# include +#include #elif defined(HAVE_NET_IF_TUN_H) -# include +#include #endif #include @@ -51,14 +51,14 @@ #include "log.h" #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) -# include -# include +#include +#include #endif #if defined(__OpenBSD__) -# include +#include #endif #if defined(__DragonFly__) -# include +#include #endif #ifdef __linux__ @@ -72,14 +72,13 @@ struct in6_ifreq { unsigned int ifr6_ifindex; }; -static -int os_set_ipv6_addr(main_server_st * s, struct proc_st *proc) +static int os_set_ipv6_addr(main_server_st *s, struct proc_st *proc) { int fd, e, ret; struct in6_ifreq ifr6; struct in6_rtmsg rt6; struct ifreq ifr; - unsigned idx; + unsigned int idx; fd = socket(AF_INET6, SOCK_STREAM, 0); if (fd == -1) { @@ -147,14 +146,15 @@ int os_set_ipv6_addr(main_server_st * s, struct proc_st *proc) ret = ioctl(fd, SIOCADDRT, &rt6); if (ret != 0) { e = errno; - mslog(s, NULL, LOG_ERR, "%s: Error setting route to remote IPv6: %s\n", + mslog(s, NULL, LOG_ERR, + "%s: Error setting route to remote IPv6: %s\n", proc->tun_lease.name, strerror(e)); ret = -1; goto cleanup; } ret = 0; - cleanup: +cleanup: close(fd); return ret; @@ -166,7 +166,7 @@ static void os_reset_ipv6_addr(struct proc_st *proc) struct in6_ifreq ifr6; struct in6_rtmsg rt6; struct ifreq ifr; - unsigned idx; + unsigned int idx; if (proc->ipv6 == NULL || proc->ipv6->lip_len == 0) return; @@ -210,7 +210,7 @@ static void os_reset_ipv6_addr(struct proc_st *proc) goto cleanup; } - cleanup: +cleanup: close(fd); } @@ -218,8 +218,7 @@ static void os_reset_ipv6_addr(struct proc_st *proc) #include -static -int os_set_ipv6_addr(main_server_st * s, struct proc_st *proc) +static int os_set_ipv6_addr(main_server_st *s, struct proc_st *proc) { int fd, e, ret; struct in6_aliasreq ifr6; @@ -246,9 +245,11 @@ int os_set_ipv6_addr(main_server_st * s, struct proc_st *proc) ifr6.ifra_dstaddr.sin6_len = sizeof(struct sockaddr_in6); ifr6.ifra_dstaddr.sin6_family = AF_INET6; - ret = ipv6_prefix_to_mask(&ifr6.ifra_prefixmask.sin6_addr, proc->ipv6->prefix); + ret = ipv6_prefix_to_mask(&ifr6.ifra_prefixmask.sin6_addr, + proc->ipv6->prefix); if (ret == 0) { - memset(&ifr6.ifra_prefixmask.sin6_addr, 0xff, sizeof(struct in6_addr)); + memset(&ifr6.ifra_prefixmask.sin6_addr, 0xff, + sizeof(struct in6_addr)); } ifr6.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6); ifr6.ifra_prefixmask.sin6_family = AF_INET6; @@ -281,7 +282,7 @@ int os_set_ipv6_addr(main_server_st * s, struct proc_st *proc) } ret = 0; - cleanup: +cleanup: close(fd); return ret; @@ -302,7 +303,7 @@ static void os_reset_ipv6_addr(struct proc_st *proc) strlcpy(ifr6.ifr_name, proc->tun_lease.name, IFNAMSIZ); memcpy(&ifr6.ifr_addr.sin6_addr, SA_IN6_P(&proc->ipv6->lip), - SA_IN_SIZE(proc->ipv6->lip_len)); + SA_IN_SIZE(proc->ipv6->lip_len)); ifr6.ifr_addr.sin6_len = sizeof(struct sockaddr_in6); ifr6.ifr_addr.sin6_family = AF_INET6; @@ -313,7 +314,7 @@ static void os_reset_ipv6_addr(struct proc_st *proc) #else #warning "No IPv6 support on this platform" -static int os_set_ipv6_addr(main_server_st * s, struct proc_st *proc) +static int os_set_ipv6_addr(main_server_st *s, struct proc_st *proc) { return -1; } @@ -324,7 +325,7 @@ static void os_reset_ipv6_addr(struct proc_st *proc) #endif -static int set_network_info(main_server_st * s, struct proc_st *proc) +static int set_network_info(main_server_st *s, struct proc_st *proc) { int fd = -1, ret, e; #ifdef SIOCAIFADDR @@ -347,7 +348,8 @@ static int set_network_info(main_server_st * s, struct proc_st *proc) ifr.ifra_addr.sin_len = sizeof(struct sockaddr_in); ifr.ifra_addr.sin_family = AF_INET; - memcpy(&ifr.ifra_dstaddr, &proc->ipv4->rip, proc->ipv4->rip_len); + memcpy(&ifr.ifra_dstaddr, &proc->ipv4->rip, + proc->ipv4->rip_len); ifr.ifra_dstaddr.sin_len = sizeof(struct sockaddr_in); ifr.ifra_dstaddr.sin_family = AF_INET; @@ -429,7 +431,7 @@ static int set_network_info(main_server_st * s, struct proc_st *proc) ret = 0; - cleanup: +cleanup: if (fd != -1) close(fd); return ret; @@ -446,10 +448,10 @@ static int bsd_ifrename(main_server_st *s, struct proc_st *proc) int e, ret; struct ifreq ifr; uint8_t ctr; - unsigned i; + unsigned int i; char tun_name[IFNAMSIZ]; - static unsigned next_tun_nr = 0; - unsigned renamed = 0; + static unsigned int next_tun_nr; + unsigned int renamed = 0; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) @@ -459,17 +461,18 @@ static int bsd_ifrename(main_server_st *s, struct proc_st *proc) strlcpy(ifr.ifr_name, proc->tun_lease.name, IFNAMSIZ); ret = snprintf(tun_name, sizeof(tun_name), "%s%u", - GETCONFIG(s)->network.name, next_tun_nr+1024); + GETCONFIG(s)->network.name, next_tun_nr + 1024); if (ret >= sizeof(tun_name)) next_tun_nr = 0; ctr = next_tun_nr; - for (i=ctr;inetwork.name, i); if (ret != strlen(tun_name)) { - mslog(s, NULL, LOG_ERR, "Truncation error in tun name: %s; adjust 'device' option\n", + mslog(s, NULL, LOG_ERR, + "Truncation error in tun name: %s; adjust 'device' option\n", proc->tun_lease.name); return -1; } @@ -482,8 +485,9 @@ static int bsd_ifrename(main_server_st *s, struct proc_st *proc) if (e == EEXIST) continue; - mslog(s, NULL, LOG_ERR, "%s: Error renaming interface: %s\n", - proc->tun_lease.name, strerror(e)); + mslog(s, NULL, LOG_ERR, + "%s: Error renaming interface: %s\n", + proc->tun_lease.name, strerror(e)); goto fail; } @@ -491,21 +495,22 @@ static int bsd_ifrename(main_server_st *s, struct proc_st *proc) break; } - /* set new name */ - next_tun_nr = ctr+1; + next_tun_nr = ctr + 1; if (renamed) { - strlcpy(proc->tun_lease.name, tun_name, sizeof(proc->tun_lease.name)); + strlcpy(proc->tun_lease.name, tun_name, + sizeof(proc->tun_lease.name)); ret = 0; } else { e = errno; - mslog(s, NULL, LOG_WARNING, "Error renaming interface: %s to %s: %s\n", + mslog(s, NULL, LOG_WARNING, + "Error renaming interface: %s to %s: %s\n", proc->tun_lease.name, tun_name, strerror(e)); ret = -1; } - fail: +fail: close(fd); return ret; @@ -513,7 +518,7 @@ static int bsd_ifrename(main_server_st *s, struct proc_st *proc) } /* BSD version */ -static int os_open_tun(main_server_st * s, struct proc_st *proc) +static int os_open_tun(main_server_st *s, struct proc_st *proc) { int fd, e, ret; int sock; @@ -525,9 +530,16 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) if (fd == -1) { /* try iterating */ e = errno; - mslog(s, NULL, LOG_DEBUG, "cannot open /dev/tun; falling back to iteration: %s", strerror(e)); - for (unit_nr = 0; GETCONFIG(s)->max_clients > 0 ? GETCONFIG(s)->max_clients : 8192; unit_nr++) { - snprintf(proc->tun_lease.name, sizeof(proc->tun_lease.name), "/dev/tun%d", unit_nr); + mslog(s, NULL, LOG_DEBUG, + "cannot open /dev/tun; falling back to iteration: %s", + strerror(e)); + for (unit_nr = 0; + GETCONFIG(s)->max_clients > 0 ? GETCONFIG(s)->max_clients : + 8192; + unit_nr++) { + snprintf(proc->tun_lease.name, + sizeof(proc->tun_lease.name), "/dev/tun%d", + unit_nr); fd = open(proc->tun_lease.name, O_RDWR); #ifdef SIOCIFCREATE if (fd == -1) { @@ -535,12 +547,15 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { e = errno; - mslog(s, NULL, LOG_ERR, "cannot create tun socket: %s", strerror(e)); + mslog(s, NULL, LOG_ERR, + "cannot create tun socket: %s", + strerror(e)); return -1; } memset(&ifr, 0, sizeof(ifr)); - strncpy(ifr.ifr_name, proc->tun_lease.name + 5, sizeof(ifr.ifr_name) - 1); + strncpy(ifr.ifr_name, proc->tun_lease.name + 5, + sizeof(ifr.ifr_name) - 1); if (!ioctl(sock, SIOCIFCREATE, &ifr)) fd = open(proc->tun_lease.name, O_RDWR); close(sock); @@ -555,20 +570,23 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) return fd; #if defined(__OpenBSD__) - /* OpenBSD's devname does not return the correct name if unit_nr>=4. - * See https://gitlab.com/openconnect/ocserv/-/issues/399 - */ - snprintf(proc->tun_lease.name, sizeof(proc->tun_lease.name), "tun%d", unit_nr); + /* OpenBSD's devname does not return the correct name if unit_nr>=4. + * See https://gitlab.com/openconnect/ocserv/-/issues/399 + */ + snprintf(proc->tun_lease.name, sizeof(proc->tun_lease.name), "tun%d", + unit_nr); #else - /* get tun name */ - ret = fstat(fd, &st); - if (ret < 0) { - e = errno; - mslog(s, NULL, LOG_ERR, "tun fd %d: stat: %s\n", fd, strerror(e)); - close(fd); - return -1; - } - strlcpy(proc->tun_lease.name, devname(st.st_rdev, S_IFCHR), sizeof(proc->tun_lease.name)); + /* get tun name */ + ret = fstat(fd, &st); + if (ret < 0) { + e = errno; + mslog(s, NULL, LOG_ERR, "tun fd %d: stat: %s\n", fd, + strerror(e)); + close(fd); + return -1; + } + strlcpy(proc->tun_lease.name, devname(st.st_rdev, S_IFCHR), + sizeof(proc->tun_lease.name)); #endif if (fd >= 0) { @@ -576,11 +594,12 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) #if defined(__OpenBSD__) /* enable multicast for tun interface (OpenBSD) */ struct tuninfo inf; + ret = ioctl(fd, TUNGIFINFO, &inf); if (ret < 0) { e = errno; mslog(s, NULL, LOG_ERR, "%s: TUNGIFINFO: %s\n", - proc->tun_lease.name, strerror(e)); + proc->tun_lease.name, strerror(e)); } else { inf.flags |= IFF_MULTICAST; @@ -588,7 +607,7 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) if (ret < 0) { e = errno; mslog(s, NULL, LOG_ERR, "%s: TUNSIFINFO: %s\n", - proc->tun_lease.name, strerror(e)); + proc->tun_lease.name, strerror(e)); } } #else /* FreeBSD + NetBSD */ @@ -620,7 +639,6 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) proc->tun_lease.name, strerror(e)); } #endif /* TUNSIFHEAD */ - } /* rename the device if possible */ @@ -633,16 +651,17 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) } #elif defined(__linux__) /* Linux version */ -static int os_open_tun(main_server_st * s, struct proc_st *proc) +static int os_open_tun(main_server_st *s, struct proc_st *proc) { int tunfd, ret, e; struct ifreq ifr; unsigned int t; - ret = snprintf(proc->tun_lease.name, sizeof(proc->tun_lease.name), "%s%%d", - GETCONFIG(s)->network.name); + ret = snprintf(proc->tun_lease.name, sizeof(proc->tun_lease.name), + "%s%%d", GETCONFIG(s)->network.name); if (ret != strlen(proc->tun_lease.name)) { - mslog(s, NULL, LOG_ERR, "Truncation error in tun name: %s; adjust 'device' option\n", + mslog(s, NULL, LOG_ERR, + "Truncation error in tun name: %s; adjust 'device' option\n", proc->tun_lease.name); return -1; } @@ -651,6 +670,7 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) tunfd = open("/dev/net/tun", O_RDWR); if (tunfd < 0) { int e = errno; + mslog(s, NULL, LOG_ERR, "Can't open /dev/net/tun: %s\n", strerror(e)); return -1; @@ -707,13 +727,13 @@ static int os_open_tun(main_server_st * s, struct proc_st *proc) #endif return tunfd; - fail: +fail: close(tunfd); return -1; } #endif /* __linux__ */ -int open_tun(main_server_st * s, struct proc_st *proc) +int open_tun(main_server_st *s, struct proc_st *proc) { int tunfd, ret; @@ -726,6 +746,7 @@ int open_tun(main_server_st * s, struct proc_st *proc) tunfd = os_open_tun(s, proc); if (tunfd < 0) { int e = errno; + mslog(s, NULL, LOG_ERR, "Can't open tun device: %s\n", strerror(e)); return -1; @@ -747,14 +768,13 @@ int open_tun(main_server_st * s, struct proc_st *proc) proc->tun_lease.fd = tunfd; return 0; - fail: +fail: close(tunfd); return -1; } -void close_tun(main_server_st * s, struct proc_st *proc) +void close_tun(main_server_st *s, struct proc_st *proc) { - if (proc->tun_lease.fd >= 0) { close(proc->tun_lease.fd); proc->tun_lease.fd = -1; @@ -776,8 +796,9 @@ void close_tun(main_server_st * s, struct proc_st *proc) ret = ioctl(fd, SIOCIFDESTROY, &ifr); if (ret != 0) { e = errno; - mslog(s, NULL, LOG_ERR, "%s: Error destroying interface: %s\n", - proc->tun_lease.name, strerror(e)); + mslog(s, NULL, LOG_ERR, + "%s: Error destroying interface: %s\n", + proc->tun_lease.name, strerror(e)); } } @@ -825,11 +846,10 @@ static void reset_ipv4_addr(struct proc_st *proc) #endif } -void reset_tun(struct proc_st* proc) +void reset_tun(struct proc_st *proc) { if (proc->tun_lease.name[0] != 0) { reset_ipv4_addr(proc); os_reset_ipv6_addr(proc); } } - diff --git a/src/tun.h b/src/tun.h index 870983f4..d390f4da 100644 --- a/src/tun.h +++ b/src/tun.h @@ -19,17 +19,16 @@ * along with this program. If not, see */ #ifndef OC_TUN_H -# define OC_TUN_H +#define OC_TUN_H #include #include #include struct tun_lease_st { - char name[IFNAMSIZ]; - /* this is used temporarily. */ + /* this is used temporarily. */ int fd; }; diff --git a/src/valid-hostname.c b/src/valid-hostname.c index aa267526..3c9c8aa7 100644 --- a/src/valid-hostname.c +++ b/src/valid-hostname.c @@ -24,7 +24,7 @@ #include #include -unsigned valid_hostname(const char *host) +unsigned int valid_hostname(const char *host) { const char *p; diff --git a/src/vasprintf.c b/src/vasprintf.c index 51b55743..323c0d83 100644 --- a/src/vasprintf.c +++ b/src/vasprintf.c @@ -34,7 +34,7 @@ int _ocserv_vasprintf(char **strp, const char *fmt, va_list ap) if (!res) goto err; - /* Use a copy of 'ap', preserving it in case we need to retry into + /* Use a copy of 'ap', preserving it in case we need to retry into a larger buffer. 160 characters should be sufficient for most strings in openconnect. */ #ifdef HAVE_VA_COPY @@ -52,7 +52,7 @@ int _ocserv_vasprintf(char **strp, const char *fmt, va_list ap) va_end(ap2); if (len < 0) { - printf_err: +printf_err: errno_save = errno; free(res); res = NULL; @@ -62,21 +62,21 @@ int _ocserv_vasprintf(char **strp, const char *fmt, va_list ap) goto out; free(res); - res = malloc(len+1); + res = malloc(len + 1); if (!res) goto err; - len2 = vsnprintf(res, len+1, fmt, ap); + len2 = vsnprintf(res, len + 1, fmt, ap); if (len2 < 0 || len2 > len) goto printf_err; ret = 0; goto out; - err: +err: errno = errno_save; ret = -1; - out: +out: *strp = res; return ret; } diff --git a/src/vhost.h b/src/vhost.h index 4118e5e2..4881edab 100644 --- a/src/vhost.h +++ b/src/vhost.h @@ -38,7 +38,7 @@ typedef struct vhost_cfg_st { tls_st creds; /* set to non-zero if authentication/accounting is initialized */ - unsigned auth_init; + unsigned int auth_init; /* vhost is pool by itself on current implementation, * but made explicit to avoid future breakage due to changes */ @@ -52,7 +52,7 @@ typedef struct vhost_cfg_st { struct config_mod_st *config_module; gnutls_privkey_t *key; - unsigned key_size; + unsigned int key_size; /* temporary values used during config loading */ @@ -61,7 +61,7 @@ typedef struct vhost_cfg_st { size_t auth_size; char **eauth; size_t eauth_size; - unsigned expose_iroutes; + unsigned int expose_iroutes; #ifdef HAVE_GSSAPI char **urlfw; size_t urlfw_size; @@ -73,35 +73,39 @@ typedef struct vhost_cfg_st { /* macros to retrieve the default vhost configuration; they * are non-null as there is always a configured host. */ #ifdef __clang_analyzer__ -static volatile void *v = (void*)0xffffffff; +static volatile void *v = (void *)0xffffffff; -static inline vhost_cfg_st *default_vhost(void * s) __attribute__((returns_nonnull)); -static inline vhost_cfg_st *default_vhost(void * s) +static inline vhost_cfg_st *default_vhost(void *s) + __attribute__((returns_nonnull)); +static inline vhost_cfg_st *default_vhost(void *s) { - return v; + return v; } -static inline struct vhost_cfg_st *GETVHOST(void *s) __attribute__((returns_nonnull)); +static inline struct vhost_cfg_st *GETVHOST(void *s) + __attribute__((returns_nonnull)); static inline struct vhost_cfg_st *GETVHOST(void *s) { return v; } -static inline struct cfg_st *GETCONFIG(void *s) __attribute__((returns_nonnull)); +static inline struct cfg_st *GETCONFIG(void *s) + __attribute__((returns_nonnull)); static inline struct cfg_st *GETCONFIG(void *s) { return v; } -static inline struct perm_cfg_st* GETPCONFIG(void *s) __attribute__((returns_nonnull)); -static inline struct perm_cfg_st* GETPCONFIG(void *s) +static inline struct perm_cfg_st *GETPCONFIG(void *s) + __attribute__((returns_nonnull)); +static inline struct perm_cfg_st *GETPCONFIG(void *s) { return v; } #else -# define GETVHOST(s) default_vhost((s)->vconfig) -# define GETCONFIG(s) GETVHOST(s)->perm_config.config -# define GETPCONFIG(s) (&(GETVHOST(s)->perm_config)) +#define GETVHOST(s) default_vhost((s)->vconfig) +#define GETCONFIG(s) GETVHOST(s)->perm_config.config +#define GETPCONFIG(s) (&(GETVHOST(s)->perm_config)) inline static vhost_cfg_st *default_vhost(struct list_head *vconfig) { @@ -109,18 +113,28 @@ inline static vhost_cfg_st *default_vhost(struct list_head *vconfig) } #endif -#define VHOSTNAME(vhost) (vhost!=NULL)?(vhost->name?vhost->name:DEFAULT_VHOST_NAME):("unknown") -#define PREFIX_VHOST(vhost) (vhost!=NULL)?(vhost->name?_vhost_prefix(vhost->name):""):("") -#define HAVE_VHOSTS(s) (list_tail(s->vconfig, struct vhost_cfg_st, list) == list_top(s->vconfig, struct vhost_cfg_st, list))?0:1 +#define VHOSTNAME(vhost) \ + (vhost != NULL) ? (vhost->name ? vhost->name : DEFAULT_VHOST_NAME) : \ + ("unknown") +#define PREFIX_VHOST(vhost) \ + (vhost != NULL) ? (vhost->name ? _vhost_prefix(vhost->name) : "") : ("") +#define HAVE_VHOSTS(s) \ + (list_tail(s->vconfig, struct vhost_cfg_st, list) == \ + list_top(s->vconfig, struct vhost_cfg_st, list)) ? \ + 0 : \ + 1 /* always returns a vhost */ -inline static vhost_cfg_st *find_vhost(struct list_head *vconfig, const char *name) +inline static vhost_cfg_st *find_vhost(struct list_head *vconfig, + const char *name) { vhost_cfg_st *vhost = NULL; + if (name == NULL) return default_vhost(vconfig); - list_for_each(vconfig, vhost, list) { + list_for_each(vconfig, vhost, list) + { if (vhost->name != NULL && strcasecmp(vhost->name, name) == 0) return vhost; } diff --git a/src/vpn.h b/src/vpn.h index f45597be..a8a3d167 100644 --- a/src/vpn.h +++ b/src/vpn.h @@ -36,25 +36,21 @@ #include #ifdef __GNUC__ -# define _OCSERV_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -# if _OCSERV_GCC_VERSION >= 30000 -# define _ATTR_PACKED __attribute__ ((__packed__)) -# endif +#define _OCSERV_GCC_VERSION \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#if _OCSERV_GCC_VERSION >= 30000 +#define _ATTR_PACKED __attribute__((__packed__)) +#endif #endif /* __GNUC__ */ #ifndef _ATTR_PACKED -# define _ATTR_PACKED +#define _ATTR_PACKED #endif -#define MAX_MSG_SIZE 16*1024 +#define MAX_MSG_SIZE 16 * 1024 #define DTLS_PROTO_INDICATOR "PSK-NEGOTIATE" - -typedef enum { - SOCK_TYPE_TCP, - SOCK_TYPE_UDP, - SOCK_TYPE_UNIX -} sock_type_t; +typedef enum { SOCK_TYPE_TCP, SOCK_TYPE_UDP, SOCK_TYPE_UNIX } sock_type_t; typedef enum { OC_COMP_NULL = 0, @@ -74,17 +70,10 @@ typedef enum fw_proto_t { PROTO_MAX } fw_proto_t; - inline static const char *proto_to_str(fw_proto_t proto) { - const char *proto2str[] = { - "udp", - "tcp", - "sctp", - "esp", - "icmp", - "icmpv6" - }; + const char *proto2str[] = { "udp", "tcp", "sctp", + "esp", "icmp", "icmpv6" }; if ((int)proto < 0 || proto >= PROTO_MAX) return "unknown"; @@ -100,7 +89,7 @@ inline static const char *proto_to_str(fw_proto_t proto) #define DEFAULT_PASSWORD_POINTS 10 #define DEFAULT_CONNECT_POINTS 1 #define DEFAULT_KKDCP_POINTS 1 -#define DEFAULT_MAX_BAN_SCORE (MAX_PASSWORD_TRIES*DEFAULT_PASSWORD_POINTS) +#define DEFAULT_MAX_BAN_SCORE (MAX_PASSWORD_TRIES * DEFAULT_PASSWORD_POINTS) #define DEFAULT_BAN_RESET_TIME 300 #define MIN_NO_COMPRESS_LIMIT 64 @@ -115,13 +104,13 @@ inline static const char *proto_to_str(fw_proto_t proto) #define DEFAULT_DPD_TIME 600 -#define AC_PKT_DATA 0 /* Uncompressed data */ -#define AC_PKT_DPD_OUT 3 /* Dead Peer Detection */ -#define AC_PKT_DPD_RESP 4 /* DPD response */ -#define AC_PKT_DISCONN 5 /* Client disconnection notice */ -#define AC_PKT_KEEPALIVE 7 /* Keepalive */ -#define AC_PKT_COMPRESSED 8 /* Compressed data */ -#define AC_PKT_TERM_SERVER 9 /* Server kick */ +#define AC_PKT_DATA 0 /* Uncompressed data */ +#define AC_PKT_DPD_OUT 3 /* Dead Peer Detection */ +#define AC_PKT_DPD_RESP 4 /* DPD response */ +#define AC_PKT_DISCONN 5 /* Client disconnection notice */ +#define AC_PKT_KEEPALIVE 7 /* Keepalive */ +#define AC_PKT_COMPRESSED 8 /* Compressed data */ +#define AC_PKT_TERM_SERVER 9 /* Server kick */ #define REKEY_METHOD_SSL 1 #define REKEY_METHOD_NEW_TUNNEL 2 @@ -129,20 +118,23 @@ inline static const char *proto_to_str(fw_proto_t proto) extern int syslog_open; /* the first is generic, for the methods that require a username password */ -#define AUTH_TYPE_USERNAME_PASS (1<<0) -#define AUTH_TYPE_PAM (1<<1 | AUTH_TYPE_USERNAME_PASS) -#define AUTH_TYPE_PLAIN (1<<2 | AUTH_TYPE_USERNAME_PASS) -#define AUTH_TYPE_CERTIFICATE (1<<3) -#define AUTH_TYPE_RADIUS (1<<5 | AUTH_TYPE_USERNAME_PASS) -#define AUTH_TYPE_GSSAPI (1<<6) -#define AUTH_TYPE_OIDC (1<<7) +#define AUTH_TYPE_USERNAME_PASS (1 << 0) +#define AUTH_TYPE_PAM (1 << 1 | AUTH_TYPE_USERNAME_PASS) +#define AUTH_TYPE_PLAIN (1 << 2 | AUTH_TYPE_USERNAME_PASS) +#define AUTH_TYPE_CERTIFICATE (1 << 3) +#define AUTH_TYPE_RADIUS (1 << 5 | AUTH_TYPE_USERNAME_PASS) +#define AUTH_TYPE_GSSAPI (1 << 6) +#define AUTH_TYPE_OIDC (1 << 7) -#define ALL_AUTH_TYPES ((AUTH_TYPE_PAM|AUTH_TYPE_PLAIN|AUTH_TYPE_CERTIFICATE|AUTH_TYPE_RADIUS|AUTH_TYPE_GSSAPI|AUTH_TYPE_OIDC) & (~AUTH_TYPE_USERNAME_PASS)) +#define ALL_AUTH_TYPES \ + ((AUTH_TYPE_PAM | AUTH_TYPE_PLAIN | AUTH_TYPE_CERTIFICATE | \ + AUTH_TYPE_RADIUS | AUTH_TYPE_GSSAPI | AUTH_TYPE_OIDC) & \ + (~AUTH_TYPE_USERNAME_PASS)) #define VIRTUAL_AUTH_TYPES (AUTH_TYPE_USERNAME_PASS) #define CONFIDENTIAL_USER_NAME_AUTH_TYPES (AUTH_TYPE_GSSAPI | AUTH_TYPE_OIDC) -#define ACCT_TYPE_PAM (1<<1) -#define ACCT_TYPE_RADIUS (1<<2) +#define ACCT_TYPE_PAM (1 << 1) +#define ACCT_TYPE_RADIUS (1 << 2) #include "defs.h" @@ -153,11 +145,9 @@ extern int syslog_open; */ #define AUTH_SLACK_TIME 15 - #define MAX_CIPHERSUITE_NAME 64 #define SID_SIZE 32 - struct vpn_st { char name[IFNAMSIZ]; char *ipv4_netmask; @@ -165,7 +155,7 @@ struct vpn_st { char *ipv4; char *ipv4_local; /* local IPv4 address */ char *ipv6_network; - unsigned ipv6_prefix; + unsigned int ipv6_prefix; char *ipv6; char *ipv6_local; /* local IPv6 address */ @@ -192,7 +182,7 @@ struct vpn_st { typedef struct auth_struct_st { char *name; char *additional; - unsigned type; + unsigned int type; const struct auth_mod_st *amod; void *auth_ctx; void *dl_ctx; @@ -220,7 +210,7 @@ typedef struct kkdcp_st { char *url; /* the supported realms by this URL */ kkdcp_realm_st realms[MAX_KRB_REALMS]; - unsigned realms_size; + unsigned int realms_size; } kkdcp_st; struct cfg_st { @@ -231,15 +221,15 @@ struct cfg_st { kkdcp_st *kkdcp; unsigned int kkdcp_size; - char *cert_user_oid; /* The OID that will be used to extract the username */ - char *cert_group_oid; /* The OID that will be used to extract the groupname */ - + char *cert_user_oid; /* The OID that will be used to extract the username */ + char *cert_group_oid; /* The OID that will be used to extract the groupname */ gnutls_certificate_request_t cert_req; char *priorities; #ifdef ENABLE_COMPRESSION - unsigned enable_compression; - unsigned no_compress_limit; /* under this size (in bytes) of data there will be no compression */ + unsigned int enable_compression; + unsigned int + no_compress_limit; /* under this size (in bytes) of data there will be no compression */ #endif char *banner; char *pre_login_banner; @@ -251,77 +241,88 @@ struct cfg_st { char **friendly_group_list; /* the same size as group_list_size */ - unsigned select_group_by_url; - unsigned auto_select_group; + unsigned int select_group_by_url; + unsigned int auto_select_group; char *default_select_group; char **custom_header; - size_t custom_header_size;; + size_t custom_header_size; char **split_dns; - size_t split_dns_size;; + size_t split_dns_size; /* http headers to include */ char **included_http_headers; size_t included_http_headers_size; - unsigned int append_routes; /* whether to append global routes to per-user config */ - unsigned restrict_user_to_routes; /* whether the firewall script will be run for the user */ - unsigned deny_roaming; /* whether a cookie is restricted to a single IP */ - time_t cookie_timeout; /* in seconds */ - time_t session_timeout; /* in seconds */ - unsigned persistent_cookies; /* whether cookies stay valid after disconnect */ + unsigned int + append_routes; /* whether to append global routes to per-user config */ + unsigned int + restrict_user_to_routes; /* whether the firewall script will be run for the user */ + unsigned int + deny_roaming; /* whether a cookie is restricted to a single IP */ + time_t cookie_timeout; /* in seconds */ + time_t session_timeout; /* in seconds */ + unsigned int + persistent_cookies; /* whether cookies stay valid after disconnect */ - time_t rekey_time; /* in seconds */ - unsigned rekey_method; /* REKEY_METHOD_ */ + time_t rekey_time; /* in seconds */ + unsigned int rekey_method; /* REKEY_METHOD_ */ - time_t min_reauth_time; /* after a failed auth, how soon one can reauthenticate -> in seconds */ - unsigned max_ban_score; /* the score allowed before a user is banned (see vpn.h) */ + time_t min_reauth_time; /* after a failed auth, how soon one can reauthenticate -> in seconds */ + unsigned int + max_ban_score; /* the score allowed before a user is banned (see vpn.h) */ int ban_reset_time; - unsigned ban_points_wrong_password; - unsigned ban_points_connect; - unsigned ban_points_kkdcp; + unsigned int ban_points_wrong_password; + unsigned int ban_points_connect; + unsigned int ban_points_kkdcp; /* when using the new PSK DTLS negotiation make sure that * the negotiated DTLS cipher/mac matches the TLS cipher/mac. */ - unsigned match_dtls_and_tls; - unsigned dtls_psk; /* whether to enable DTLS-PSK */ - unsigned dtls_legacy; /* whether to enable DTLS-LEGACY */ + unsigned int match_dtls_and_tls; + unsigned int dtls_psk; /* whether to enable DTLS-PSK */ + unsigned int dtls_legacy; /* whether to enable DTLS-LEGACY */ - unsigned isolate; /* whether seccomp should be enabled or not */ + unsigned int isolate; /* whether seccomp should be enabled or not */ - unsigned auth_timeout; /* timeout of HTTP auth */ - unsigned idle_timeout; /* timeout when idle */ - unsigned mobile_idle_timeout; /* timeout when a mobile is idle */ - unsigned switch_to_tcp_timeout; /* length of no traffic period to automatically switch to TCP */ - unsigned keepalive; - unsigned dpd; - unsigned mobile_dpd; - unsigned max_clients; - unsigned max_same_clients; - unsigned use_utmp; - unsigned tunnel_all_dns; - unsigned use_occtl; /* whether support for the occtl tool will be enabled */ + unsigned int auth_timeout; /* timeout of HTTP auth */ + unsigned int idle_timeout; /* timeout when idle */ + unsigned int mobile_idle_timeout; /* timeout when a mobile is idle */ + unsigned int + switch_to_tcp_timeout; /* length of no traffic period to automatically switch to TCP */ + unsigned int keepalive; + unsigned int dpd; + unsigned int mobile_dpd; + unsigned int max_clients; + unsigned int max_same_clients; + unsigned int use_utmp; + unsigned int tunnel_all_dns; + unsigned int + use_occtl; /* whether support for the occtl tool will be enabled */ - unsigned try_mtu; /* MTU discovery enabled */ - unsigned cisco_client_compat; /* do not require client certificate, - * and allow auth to complete in different - * TCP sessions. */ - unsigned cisco_svc_client_compat; /* force allowed ciphers and disable dtls-legacy */ - unsigned rate_limit_ms; /* if non zero force a connection every rate_limit milliseconds if ocserv-sm is heavily loaded */ - unsigned ping_leases; /* non zero if we need to ping prior to leasing */ - unsigned server_drain_ms; /* how long to wait after we stop accepting new connections before closing old connections */ + unsigned int try_mtu; /* MTU discovery enabled */ + unsigned int cisco_client_compat; /* do not require client certificate, + * and allow auth to complete in different + * TCP sessions. */ + unsigned int + cisco_svc_client_compat; /* force allowed ciphers and disable dtls-legacy */ + unsigned int + rate_limit_ms; /* if non zero force a connection every rate_limit milliseconds if ocserv-sm is heavily loaded */ + unsigned int + ping_leases; /* non zero if we need to ping prior to leasing */ + unsigned int + server_drain_ms; /* how long to wait after we stop accepting new connections before closing old connections */ size_t rx_per_sec; size_t tx_per_sec; - unsigned net_priority; + unsigned int net_priority; char *crl; - unsigned output_buffer; - unsigned default_mtu; - unsigned predictable_ips; /* boolean */ + unsigned int output_buffer; + unsigned int default_mtu; + unsigned int predictable_ips; /* boolean */ char *route_add_cmd; char *route_del_cmd; @@ -338,7 +339,7 @@ struct cfg_st { char *xml_config_hash; #endif - unsigned client_bypass_protocol; + unsigned int client_bypass_protocol; /* additional configuration files */ char *per_group_dir; @@ -373,13 +374,13 @@ struct perm_cfg_st { /* stuff here don't change on reload */ auth_struct_st auth[MAX_AUTH_METHODS]; - unsigned auth_methods; + unsigned int auth_methods; acct_struct_st acct; unsigned int sup_config_type; /* one of SUP_CONFIG_ */ - char *chroot_dir; /* where the xml files are served from */ - char* occtl_socket_file; - char* socket_file_prefix; + char *chroot_dir; /* where the xml files are served from */ + char *occtl_socket_file; + char *socket_file_prefix; uid_t uid; gid_t gid; @@ -397,13 +398,13 @@ struct perm_cfg_st { char *cert_hash; #endif unsigned int stats_reset_time; - unsigned foreground; - unsigned no_chdir; - unsigned log_level; - unsigned log_stderr; - unsigned syslog; + unsigned int foreground; + unsigned int no_chdir; + unsigned int log_level; + unsigned int log_stderr; + unsigned int syslog; - unsigned pr_dumpable; + unsigned int pr_dumpable; char *ca; char *dh_params_file; @@ -417,7 +418,7 @@ struct perm_cfg_st { unsigned int sec_mod_scale; /* for testing ocserv only */ - unsigned debug_no_secmod_stats; + unsigned int debug_no_secmod_stats; /* attic, where old config allocated values are stored */ struct list_head attic; @@ -428,7 +429,6 @@ typedef struct attic_entry_st { int *usage_count; } attic_entry_st; - /* generic thing to stop complaints */ struct worker_st; struct main_server_st; @@ -443,7 +443,7 @@ struct dtls_st; #define TLS_MASTER_SIZE 48 #define MAX_HOSTNAME_SIZE MAX_USERNAME_SIZE #define MAX_GROUPNAME_SIZE MAX_USERNAME_SIZE -#define MAX_SESSION_DATA_SIZE (4*1024) +#define MAX_SESSION_DATA_SIZE (4 * 1024) #if defined(CAPTURE_LATENCY_SUPPORT) #define LATENCY_SAMPLE_SIZE 1024 @@ -454,24 +454,30 @@ struct dtls_st; #include -unsigned extract_prefix(char *network); +unsigned int extract_prefix(char *network); /* macros */ -#define TOS_PACK(x) (x<<4) -#define TOS_UNPACK(x) (x>>4) -#define IS_TOS(x) ((x&0x0f)==0) +#define TOS_PACK(x) (x << 4) +#define TOS_UNPACK(x) (x >> 4) +#define IS_TOS(x) ((x & 0x0f) == 0) /* Helper structures */ -enum option_types { OPTION_NUMERIC, OPTION_STRING, OPTION_BOOLEAN, OPTION_MULTI_LINE }; +enum option_types { + OPTION_NUMERIC, + OPTION_STRING, + OPTION_BOOLEAN, + OPTION_MULTI_LINE +}; #include -void reload_cfg_file(void *pool, struct list_head *configs, unsigned sec_mod); +void reload_cfg_file(void *pool, struct list_head *configs, + unsigned int sec_mod); void clear_old_configs(struct list_head *configs); void write_pid_file(void); void remove_pid_file(void); -unsigned switch_comp_priority(void *pool, const char *modstring); +unsigned int switch_comp_priority(void *pool, const char *modstring); extern sigset_t sig_default_set; diff --git a/src/worker-auth.c b/src/worker-auth.c index 43aa472c..0db66b34 100644 --- a/src/worker-auth.c +++ b/src/worker-auth.c @@ -46,58 +46,58 @@ #define VERSION_MSG "0.1(1)\n" -static const char oc_success_msg_head[] = "\n" - "\n" - VERSION_MSG - "\n" - "SSL VPN Service"; +static const char oc_success_msg_head[] = + "\n" + "\n" VERSION_MSG + "\n" + "SSL VPN Service"; #define OC_SUCCESS_MSG_FOOT "\n" -#define OC_SUCCESS_MSG_FOOT_PROFILE \ - "\n" \ - "" \ - "" \ - "" \ - "" \ - "/profiles/%s" \ - "%s" \ - "" \ - "" \ - "\n" \ - "" \ - "" +#define OC_SUCCESS_MSG_FOOT_PROFILE \ + "\n" \ + "" \ + "" \ + "" \ + "" \ + "/profiles/%s" \ + "%s" \ + "" \ + "" \ + "\n" \ + "" \ + "" -static const char ocv3_success_msg_head[] = "\n" - "\n" - "SSL VPN Service"; +static const char ocv3_success_msg_head[] = + "\n" + "\n" + "SSL VPN Service"; static const char ocv3_success_msg_foot[] = "\n"; -#define OC_LOGIN_START \ - "\n" \ - "\n" \ - VERSION_MSG \ - "\n" +#define OC_LOGIN_START \ + "\n" \ + "\n" VERSION_MSG \ + "\n" -#define OC_LOGIN_FORM_START \ - "%s\n" \ - "
\n" +#define OC_LOGIN_FORM_START \ + "%s\n" \ + "\n" -#define OC_LOGIN_END \ - "
\n" "
" +#define OC_LOGIN_END "
\n
" #define OC_LOGIN_FORM_INPUT_USER \ - "\n" + "\n" #define DEFAULT_PASSWD_LABEL "Password:" -#define OC_LOGIN_FORM_INPUT_PASSWORD \ - "\n" +#define OC_LOGIN_FORM_INPUT_PASSWORD \ + "\n" #define OC_LOGIN_FORM_INPUT_PASSWORD_CTR \ - "\n" + "\n" -#define _OCV3_LOGIN_MSG_START(x) \ - "\n" \ - "\n" +#define _OCV3_LOGIN_MSG_START(x) \ + "\n" \ + "\n" #define OCV3_LOGIN_START _OCV3_LOGIN_MSG_START("main") #define OCV3_PASSWD_START _OCV3_LOGIN_MSG_START("passwd") @@ -108,23 +108,24 @@ static const char ocv3_success_msg_foot[] = "\n"; #define HTTP_AUTH_OIDC_PREFIX "Bearer" #endif - -static int basic_auth_handler(worker_st * ws, unsigned http_ver, const char *msg); +static int basic_auth_handler(worker_st *ws, unsigned int http_ver, + const char *msg); #ifdef SUPPORT_OIDC_AUTH -static int oidc_auth_handler(worker_st * ws, unsigned http_ver); +static int oidc_auth_handler(worker_st *ws, unsigned int http_ver); #endif -int ws_switch_auth_to(struct worker_st *ws, unsigned auth) +int ws_switch_auth_to(struct worker_st *ws, unsigned int auth) { - unsigned i; + unsigned int i; if (ws->selected_auth && ws->selected_auth->enabled != 0 && ws->selected_auth->type & auth) return 1; - for (i=0;iauth_methods;i++) { - if (WSPCONFIG(ws)->auth[i].enabled && (WSPCONFIG(ws)->auth[i].type & auth) != 0) { + for (i = 0; i < WSPCONFIG(ws)->auth_methods; i++) { + if (WSPCONFIG(ws)->auth[i].enabled && + (WSPCONFIG(ws)->auth[i].type & auth) != 0) { ws->selected_auth = &WSPCONFIG(ws)->auth[i]; return 1; } @@ -137,7 +138,7 @@ int ws_switch_auth_to(struct worker_st *ws, unsigned auth) * non-zero on success */ int ws_switch_auth_to_next(struct worker_st *ws) { - unsigned i; + unsigned int i; if (!ws->selected_auth) { return 0; @@ -145,10 +146,9 @@ int ws_switch_auth_to_next(struct worker_st *ws) ws->selected_auth->enabled = 0; - for (i=0;iauth_methods;i++) { + for (i = 0; i < WSPCONFIG(ws)->auth_methods; i++) { if (&WSPCONFIG(ws)->auth[i] != ws->selected_auth && WSPCONFIG(ws)->auth[i].enabled != 0) { - ws->selected_auth = &WSPCONFIG(ws)->auth[i]; return 1; } @@ -156,52 +156,58 @@ int ws_switch_auth_to_next(struct worker_st *ws) return 0; } -static int append_group_idx(worker_st * ws, str_st *str, unsigned i) +static int append_group_idx(worker_st *ws, str_st *str, unsigned int i) { char temp[128]; const char *name; const char *value; value = WSCONFIG(ws)->group_list[i]; - if (WSCONFIG(ws)->friendly_group_list != NULL && WSCONFIG(ws)->friendly_group_list[i] != NULL) + if (WSCONFIG(ws)->friendly_group_list != NULL && + WSCONFIG(ws)->friendly_group_list[i] != NULL) name = WSCONFIG(ws)->friendly_group_list[i]; else name = WSCONFIG(ws)->group_list[i]; - snprintf(temp, sizeof(temp), "\n", value, name); + snprintf(temp, sizeof(temp), "\n", + value, name); if (str_append_str(str, temp) < 0) return -1; return 0; } -static int append_group_str(worker_st * ws, str_st *str, const char *group) +static int append_group_str(worker_st *ws, str_st *str, const char *group) { char temp[256]; const char *name; const char *value; - unsigned i; + unsigned int i; value = name = group; if (WSCONFIG(ws)->friendly_group_list) { - for (i=0;igroup_list_size;i++) { + for (i = 0; i < WSCONFIG(ws)->group_list_size; i++) { if (strcmp(WSCONFIG(ws)->group_list[i], group) == 0) { - if (WSCONFIG(ws)->friendly_group_list[i] != NULL) - name = WSCONFIG(ws)->friendly_group_list[i]; + if (WSCONFIG(ws)->friendly_group_list[i] != + NULL) + name = WSCONFIG(ws) + ->friendly_group_list[i]; break; } } } - snprintf(temp, sizeof(temp), "\n", value, name); + snprintf(temp, sizeof(temp), "\n", + value, name); if (str_append_str(str, temp) < 0) return -1; return 0; } -int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsigned pcounter) +int get_auth_handler2(worker_st *ws, unsigned int http_ver, const char *pmsg, + unsigned int pcounter) { int ret; char context[BASE64_ENCODE_RAW_LENGTH(SID_SIZE) + 1]; @@ -223,8 +229,10 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig login_end = OC_LOGIN_END; } - if ((ws->selected_auth->type & AUTH_TYPE_GSSAPI) && ws->auth_state < S_AUTH_COOKIE) { - if (ws->req.authorization == NULL || ws->req.authorization_size == 0) + if ((ws->selected_auth->type & AUTH_TYPE_GSSAPI) && + ws->auth_state < S_AUTH_COOKIE) { + if (ws->req.authorization == NULL || + ws->req.authorization_size == 0) return basic_auth_handler(ws, http_ver, NULL); else return post_auth_handler(ws, http_ver); @@ -238,25 +246,26 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig if (ret < 0) return -1; - if (ws->sid_set != 0) { char safe_id[SAFE_ID_SIZE]; - oc_base64_encode((char *)ws->sid, sizeof(ws->sid), (char *)context, - sizeof(context)); + oc_base64_encode((char *)ws->sid, sizeof(ws->sid), + (char *)context, sizeof(context)); - ret = - cstp_printf(ws, - "Set-Cookie: webvpncontext=%s; Max-Age=%u; Secure; HttpOnly\r\n", - context, (unsigned)WSCONFIG(ws)->cookie_timeout); + ret = cstp_printf( + ws, + "Set-Cookie: webvpncontext=%s; Max-Age=%u; Secure; HttpOnly\r\n", + context, (unsigned int)WSCONFIG(ws)->cookie_timeout); if (ret < 0) return -1; - oclog(ws, LOG_SENSITIVE, "sent session id: %s", calc_safe_id(ws->sid, sizeof(ws->sid), safe_id, sizeof(safe_id))); + oclog(ws, LOG_SENSITIVE, "sent session id: %s", + calc_safe_id(ws->sid, sizeof(ws->sid), safe_id, + sizeof(safe_id))); } else { - ret = - cstp_puts(ws, - "Set-Cookie: webvpncontext=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; Secure; HttpOnly\r\n"); + ret = cstp_puts( + ws, + "Set-Cookie: webvpncontext=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; Secure; HttpOnly\r\n"); if (ret < 0) return -1; } @@ -269,7 +278,9 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig if (ws->auth_state == S_AUTH_REQ) { /* Password Form */ - if (pmsg == NULL || strncasecmp(pmsg, DEFAULT_PASSWD_LABEL, sizeof(DEFAULT_PASSWD_LABEL)-1) == 0) + if (pmsg == NULL || + strncasecmp(pmsg, DEFAULT_PASSWD_LABEL, + sizeof(DEFAULT_PASSWD_LABEL) - 1) == 0) pmsg = "Please enter your password."; ret = str_append_str(&str, login_start); @@ -285,9 +296,12 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig } if (pcounter > 0) - ret = str_append_printf(&str, OC_LOGIN_FORM_INPUT_PASSWORD_CTR, pcounter); + ret = str_append_printf( + &str, OC_LOGIN_FORM_INPUT_PASSWORD_CTR, + pcounter); else - ret = str_append_str(&str, OC_LOGIN_FORM_INPUT_PASSWORD); + ret = str_append_str(&str, + OC_LOGIN_FORM_INPUT_PASSWORD); if (ret < 0) { ret = -1; goto cleanup; @@ -311,7 +325,8 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig } if (WSCONFIG(ws)->pre_login_banner) { - ret = str_append_printf(&str, "%s", WSCONFIG(ws)->pre_login_banner); + ret = str_append_printf(&str, "%s", + WSCONFIG(ws)->pre_login_banner); if (ret < 0) { ret = -1; goto cleanup; @@ -332,18 +347,23 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig } } - if ((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && ws->cert_auth_ok != 0) { + if ((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && + ws->cert_auth_ok != 0) { ret = get_cert_info(ws); if (ret < 0) { ret = -1; - oclog(ws, LOG_WARNING, "cannot obtain certificate information"); + oclog(ws, LOG_WARNING, + "cannot obtain certificate information"); goto cleanup; } } /* send groups */ - if (WSCONFIG(ws)->group_list_size > 0 || ws->cert_groups_size > 0) { - ret = str_append_str(&str, "\n"); if (ret < 0) { ret = -1; goto cleanup; @@ -363,8 +383,11 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig } /* we send a list of possible groups only if user is not forcing group e.g. by url to disable dialog on client side */ - if (ws->groupname[0] == 0 && WSCONFIG(ws)->default_select_group) { - ret = str_append_printf(&str, "\n", WSCONFIG(ws)->default_select_group); + if (ws->groupname[0] == 0 && + WSCONFIG(ws)->default_select_group) { + ret = str_append_printf( + &str, "\n", + WSCONFIG(ws)->default_select_group); if (ret < 0) { ret = -1; goto cleanup; @@ -372,25 +395,34 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig } /* append any groups available in the certificate */ - if ((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && ws->cert_auth_ok != 0) { - unsigned dup; + if ((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && + ws->cert_auth_ok != 0) { + unsigned int dup; - for (i=0;icert_groups_size;i++) { + for (i = 0; i < ws->cert_groups_size; i++) { dup = 0; - for (j=0;jgroup_list_size;j++) { - if (strcmp(ws->cert_groups[i], WSCONFIG(ws)->group_list[j]) == 0) { + for (j = 0; + j < WSCONFIG(ws)->group_list_size; + j++) { + if (strcmp(ws->cert_groups[i], + WSCONFIG(ws)->group_list + [j]) == 0) { dup = 1; break; } } - if (dup == 0 && ws->groupname[0] != 0 && strcmp(ws->groupname, ws->cert_groups[i]) == 0) + if (dup == 0 && ws->groupname[0] != 0 && + strcmp(ws->groupname, + ws->cert_groups[i]) == 0) dup = 1; if (dup != 0) continue; - ret = str_append_printf(&str, "\n", ws->cert_groups[i]); + ret = str_append_printf( + &str, "\n", + ws->cert_groups[i]); if (ret < 0) { ret = -1; goto cleanup; @@ -400,8 +432,12 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig /* we send a list of possible groups only if user is not forcing group e.g. by url to disable dialog on client side */ if (ws->groupname[0] == 0) { - for (i=0;igroup_list_size;i++) { - if (ws->groupname[0] != 0 && strcmp(ws->groupname, WSCONFIG(ws)->group_list[i]) == 0) + for (i = 0; i < WSCONFIG(ws)->group_list_size; + i++) { + if (ws->groupname[0] != 0 && + strcmp(ws->groupname, + WSCONFIG(ws)->group_list[i]) == + 0) continue; ret = append_group_idx(ws, &str, i); @@ -423,12 +459,10 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig ret = -1; goto cleanup; } - } - ret = - cstp_printf(ws, "Content-Length: %u\r\n", - (unsigned int)str.length); + ret = cstp_printf(ws, "Content-Length: %u\r\n", + (unsigned int)str.length); if (ret < 0) { ret = -1; goto cleanup; @@ -458,7 +492,6 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig goto cleanup; } - ret = cstp_uncork(ws); if (ret < 0) { ret = -1; @@ -467,21 +500,21 @@ int get_auth_handler2(worker_st * ws, unsigned http_ver, const char *pmsg, unsig ret = 0; - cleanup: +cleanup: str_clear(&str); return ret; } -int get_auth_handler(worker_st * ws, unsigned http_ver) +int get_auth_handler(worker_st *ws, unsigned int http_ver) { return get_auth_handler2(ws, http_ver, NULL, 0); } -int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) +int get_cert_names(worker_st *ws, const gnutls_datum_t *raw) { gnutls_x509_crt_t crt; int ret; - unsigned i; + unsigned int i; size_t size; char cert_username[MAX_USERNAME_SIZE]; @@ -502,54 +535,60 @@ int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) goto fail; } - if (strcmp(WSCONFIG(ws)->cert_user_oid, "SAN(rfc822name)") == 0) { /* check for RFC822Name */ + if (strcmp(WSCONFIG(ws)->cert_user_oid, "SAN(rfc822name)") == + 0) { /* check for RFC822Name */ for (i = 0;; i++) { size = sizeof(ws->cert_username); - ret = - gnutls_x509_crt_get_subject_alt_name(crt, i, - cert_username, - &size, NULL); + ret = gnutls_x509_crt_get_subject_alt_name( + crt, i, cert_username, &size, NULL); if (ret < 0) { - if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) + if (ret == + GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) ret = 1; break; } if (ret == GNUTLS_SAN_RFC822NAME) { - strlcpy(ws->cert_username, cert_username, sizeof(ws->cert_username)); - oclog(ws, LOG_INFO, - "RFC822NAME (%s) retrieved", + strlcpy(ws->cert_username, cert_username, + sizeof(ws->cert_username)); + oclog(ws, LOG_INFO, "RFC822NAME (%s) retrieved", cert_username); break; } } - } else if (WSCONFIG(ws)->cert_user_oid) { /* otherwise we check at the DN */ + } else if (WSCONFIG(ws) + ->cert_user_oid) { /* otherwise we check at the DN */ size = sizeof(ws->cert_username); - ret = - gnutls_x509_crt_get_dn_by_oid(crt, - WSCONFIG(ws)->cert_user_oid, 0, - 0, cert_username, &size); + ret = gnutls_x509_crt_get_dn_by_oid(crt, + WSCONFIG(ws)->cert_user_oid, + 0, 0, cert_username, &size); if (ret >= 0) - strlcpy(ws->cert_username, cert_username, sizeof(ws->cert_username)); + strlcpy(ws->cert_username, cert_username, + sizeof(ws->cert_username)); } else { size = sizeof(ws->cert_username); ret = gnutls_x509_crt_get_dn(crt, cert_username, &size); if (ret >= 0) - strlcpy(ws->cert_username, cert_username, sizeof(ws->cert_username)); + strlcpy(ws->cert_username, cert_username, + sizeof(ws->cert_username)); } if (ret < 0) { if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) - oclog(ws, LOG_ERR, "certificate's username exceed the maximum buffer size (%u)", - (unsigned)sizeof(ws->cert_username)); + oclog(ws, LOG_ERR, + "certificate's username exceed the maximum buffer size (%u)", + (unsigned int)sizeof(ws->cert_username)); else if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { - oclog(ws, LOG_ERR, "the certificate's DN does not contain OID %s; cannot determine username", + oclog(ws, LOG_ERR, + "the certificate's DN does not contain OID %s; cannot determine username", WSCONFIG(ws)->cert_user_oid); } else { - oclog(ws, LOG_ERR, "cannot obtain user name from certificate DN(%s): %s", - WSCONFIG(ws)->cert_user_oid, gnutls_strerror(ret)); + oclog(ws, LOG_ERR, + "cannot obtain user name from certificate DN(%s): %s", + WSCONFIG(ws)->cert_user_oid, + gnutls_strerror(ret)); } goto fail; } @@ -557,18 +596,19 @@ int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) if (WSCONFIG(ws)->cert_group_oid) { i = 0; do { - ws->cert_groups = talloc_realloc(ws, ws->cert_groups, char*, i+1); + ws->cert_groups = talloc_realloc(ws, ws->cert_groups, + char *, i + 1); if (ws->cert_groups == NULL) { - oclog(ws, LOG_ERR, "cannot allocate memory for cert groups"); + oclog(ws, LOG_ERR, + "cannot allocate memory for cert groups"); ret = -1; goto fail; } size = 0; - ret = - gnutls_x509_crt_get_dn_by_oid(crt, - WSCONFIG(ws)->cert_group_oid, i, - 0, NULL, &size); + ret = gnutls_x509_crt_get_dn_by_oid( + crt, WSCONFIG(ws)->cert_group_oid, i, 0, NULL, + &size); if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) break; @@ -577,21 +617,22 @@ int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) ret = GNUTLS_E_INTERNAL_ERROR; oclog(ws, LOG_ERR, "cannot obtain group from certificate DN(%s): %s", - WSCONFIG(ws)->cert_group_oid, gnutls_strerror(ret)); + WSCONFIG(ws)->cert_group_oid, + gnutls_strerror(ret)); goto fail; } ws->cert_groups[i] = talloc_size(ws->cert_groups, size); if (ws->cert_groups[i] == NULL) { - oclog(ws, LOG_ERR, "cannot allocate memory for cert group"); + oclog(ws, LOG_ERR, + "cannot allocate memory for cert group"); ret = -1; goto fail; } - ret = - gnutls_x509_crt_get_dn_by_oid(crt, - WSCONFIG(ws)->cert_group_oid, i, - 0, ws->cert_groups[i], &size); + ret = gnutls_x509_crt_get_dn_by_oid( + crt, WSCONFIG(ws)->cert_group_oid, i, 0, + ws->cert_groups[i], &size); if (ret < 0) { oclog(ws, LOG_ERR, "cannot obtain group from certificate DN: %s", @@ -606,18 +647,17 @@ int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) ret = 0; - fail: +fail: gnutls_x509_crt_deinit(crt); return ret; - } -static -unsigned check_if_default_route(char **routes, unsigned routes_size) +static unsigned int check_if_default_route(char **routes, + unsigned int routes_size) { - unsigned i; + unsigned int i; - for (i=0;icmd_fd, AUTH_COOKIE_REP, &socketfd, (void *)&msg, - (unpack_func) auth_cookie_reply_msg__unpack, + (unpack_func)auth_cookie_reply_msg__unpack, WSCONFIG(ws)->auth_timeout); if (ret < 0) { oclog(ws, LOG_ERR, "error receiving auth reply message"); @@ -644,7 +685,7 @@ static int recv_cookie_auth_reply(worker_st * ws) } oclog(ws, LOG_DEBUG, "received auth reply message (value: %u)", - (unsigned)msg->reply); + (unsigned int)msg->reply); switch (msg->reply) { case AUTH__REP__OK: @@ -654,7 +695,9 @@ static int recv_cookie_auth_reply(worker_st * ws) ret = ERR_AUTH_FAIL; goto cleanup; } - if (msg->vname == NULL || msg->config == NULL || msg->user_name == NULL || msg->sid.len != sizeof(ws->sid)) { + if (msg->vname == NULL || msg->config == NULL || + msg->user_name == NULL || + msg->sid.len != sizeof(ws->sid)) { ret = ERR_AUTH_FAIL; goto cleanup; } @@ -663,11 +706,14 @@ static int recv_cookie_auth_reply(worker_st * ws) memcpy(ws->sid, msg->sid.data, sizeof(ws->sid)); ws->sid_set = 1; - strlcpy(ws->vinfo.name, msg->vname, sizeof(ws->vinfo.name)); - strlcpy(ws->username, msg->user_name, sizeof(ws->username)); + strlcpy(ws->vinfo.name, msg->vname, + sizeof(ws->vinfo.name)); + strlcpy(ws->username, msg->user_name, + sizeof(ws->username)); if (msg->group_name != NULL) { - strlcpy(ws->groupname, msg->group_name, sizeof(ws->groupname)); + strlcpy(ws->groupname, msg->group_name, + sizeof(ws->groupname)); } else { ws->groupname[0] = 0; } @@ -683,7 +729,7 @@ static int recv_cookie_auth_reply(worker_st * ws) ws->vinfo.ipv4 = NULL; else ws->vinfo.ipv4 = - talloc_strdup(ws, msg->ipv4); + talloc_strdup(ws, msg->ipv4); } if (msg->ipv6 != NULL) { @@ -692,7 +738,7 @@ static int recv_cookie_auth_reply(worker_st * ws) ws->vinfo.ipv6 = NULL; else ws->vinfo.ipv6 = - talloc_strdup(ws, msg->ipv6); + talloc_strdup(ws, msg->ipv6); } if (msg->ipv4_local != NULL) { @@ -700,8 +746,8 @@ static int recv_cookie_auth_reply(worker_st * ws) if (strcmp(msg->ipv4_local, "0.0.0.0") == 0) ws->vinfo.ipv4_local = NULL; else - ws->vinfo.ipv4_local = - talloc_strdup(ws, msg->ipv4_local); + ws->vinfo.ipv4_local = talloc_strdup( + ws, msg->ipv4_local); } if (msg->ipv6_local != NULL) { @@ -709,15 +755,16 @@ static int recv_cookie_auth_reply(worker_st * ws) if (strcmp(msg->ipv6_local, "::") == 0) ws->vinfo.ipv6_local = NULL; else - ws->vinfo.ipv6_local = - talloc_strdup(ws, msg->ipv6_local); + ws->vinfo.ipv6_local = talloc_strdup( + ws, msg->ipv6_local); } if (msg->config->no_udp != 0) WSPCONFIG(ws)->udp_port = 0; /* routes */ - if (check_if_default_route(msg->config->routes, msg->config->n_routes)) + if (check_if_default_route(msg->config->routes, + msg->config->n_routes)) ws->default_route = 1; } else { oclog(ws, LOG_ERR, "error in received message"); @@ -729,13 +776,13 @@ static int recv_cookie_auth_reply(worker_st * ws) default: if (msg->reply != AUTH__REP__FAILED) oclog(ws, LOG_ERR, "unexpected auth reply %u", - (unsigned)msg->reply); + (unsigned int)msg->reply); ret = ERR_AUTH_FAIL; goto cleanup; } ret = 0; - cleanup: +cleanup: if (ret < 0) { /* we only release on error, as the user configuration * remains. */ @@ -746,7 +793,7 @@ static int recv_cookie_auth_reply(worker_st * ws) } /* returns the fd */ -int connect_to_secmod(worker_st * ws) +int connect_to_secmod(worker_st *ws) { int sd, ret, e; @@ -758,9 +805,8 @@ int connect_to_secmod(worker_st * ws) return -1; } - ret = - connect(sd, (struct sockaddr *)&ws->secmod_addr, - ws->secmod_addr_len); + ret = connect(sd, (struct sockaddr *)&ws->secmod_addr, + ws->secmod_addr_len); if (ret < 0) { e = errno; close(sd); @@ -772,17 +818,18 @@ int connect_to_secmod(worker_st * ws) return sd; } -int recv_auth_reply(worker_st * ws, int sd, char **txt, unsigned *pcounter) +int recv_auth_reply(worker_st *ws, int sd, char **txt, unsigned int *pcounter) { int ret; SecAuthReplyMsg *msg = NULL; + PROTOBUF_ALLOCATOR(pa, ws); /* We don't use the default socket timeout here, but rather the * longer WSCONFIG(ws)->auth_timeout to allow for authentication * methods which require the user input prior to returning a reply */ - ret = recv_msg(ws, sd, CMD_SEC_AUTH_REPLY, - (void *)&msg, (unpack_func) sec_auth_reply_msg__unpack, + ret = recv_msg(ws, sd, CMD_SEC_AUTH_REPLY, (void *)&msg, + (unpack_func)sec_auth_reply_msg__unpack, WSCONFIG(ws)->auth_timeout); if (ret < 0) { oclog(ws, LOG_ERR, "error receiving auth reply message"); @@ -790,9 +837,10 @@ int recv_auth_reply(worker_st * ws, int sd, char **txt, unsigned *pcounter) } oclog(ws, LOG_DEBUG, "received auth reply message (value: %u)", - (unsigned)msg->reply); + (unsigned int)msg->reply); - if (txt) *txt = NULL; + if (txt) + *txt = NULL; switch (msg->reply) { case AUTH__REP__MSG: @@ -827,10 +875,8 @@ int recv_auth_reply(worker_st * ws, int sd, char **txt, unsigned *pcounter) ws->sid_set = 1; } - if (msg->has_sid == 0 || - msg->sid.len != sizeof(ws->cookie) || + if (msg->has_sid == 0 || msg->sid.len != sizeof(ws->cookie) || msg->dtls_session_id.len != sizeof(ws->session_id)) { - ret = ERR_AUTH_FAIL; goto cleanup; } @@ -849,19 +895,19 @@ int recv_auth_reply(worker_st * ws, int sd, char **txt, unsigned *pcounter) default: if (msg->reply != AUTH__REP__FAILED) oclog(ws, LOG_ERR, "unexpected auth reply %u", - (unsigned)msg->reply); + (unsigned int)msg->reply); ret = ERR_AUTH_FAIL; goto cleanup; } ret = 0; - cleanup: +cleanup: sec_auth_reply_msg__free_unpacked(msg, &pa); return ret; } /* grabs the username from the session certificate */ -int get_cert_info(worker_st * ws) +int get_cert_info(worker_st *ws) { const gnutls_datum_t *cert; unsigned int ncerts; @@ -886,9 +932,11 @@ int get_cert_info(worker_st * ws) ret = get_cert_names(ws, cert); if (ret < 0) { if (WSCONFIG(ws)->cert_user_oid == NULL) { - oclog(ws, LOG_ERR, "cannot read username from certificate; cert-user-oid is not set"); + oclog(ws, LOG_ERR, + "cannot read username from certificate; cert-user-oid is not set"); } else { - oclog(ws, LOG_ERR, "cannot read username from certificate"); + oclog(ws, LOG_ERR, + "cannot read username from certificate"); } return -1; } @@ -909,8 +957,7 @@ void cookie_authenticate_or_exit(worker_st *ws) /* we must be in S_AUTH_COOKIE state */ if (ws->auth_state != S_AUTH_COOKIE || ws->cookie_set == 0) { oclog(ws, LOG_WARNING, "no cookie found"); - cstp_puts(ws, - "HTTP/1.1 503 Service Unavailable\r\n\r\n"); + cstp_puts(ws, "HTTP/1.1 503 Service Unavailable\r\n\r\n"); cstp_fatal_close(ws, GNUTLS_A_ACCESS_DENIED); exit_worker(ws); } @@ -920,18 +967,17 @@ void cookie_authenticate_or_exit(worker_st *ws) ret = auth_cookie(ws, ws->cookie, sizeof(ws->cookie)); if (ret < 0) { oclog(ws, LOG_WARNING, "failed cookie authentication attempt"); - if (WSCONFIG(ws)->camouflage && ws->camouflage_check_passed == 0) - { + if (WSCONFIG(ws)->camouflage && + ws->camouflage_check_passed == 0) { cstp_puts(ws, - "HTTP/1.1 405 Method Not Allowed\r\n\r\n"); - } - else - if (ret == ERR_AUTH_FAIL) { - cstp_puts(ws, - "HTTP/1.1 401 Cookie is not acceptable\r\n\r\n"); + "HTTP/1.1 405 Method Not Allowed\r\n\r\n"); + } else if (ret == ERR_AUTH_FAIL) { + cstp_puts( + ws, + "HTTP/1.1 401 Cookie is not acceptable\r\n\r\n"); } else { cstp_puts(ws, - "HTTP/1.1 503 Service Unavailable\r\n\r\n"); + "HTTP/1.1 503 Service Unavailable\r\n\r\n"); } cstp_fatal_close(ws, GNUTLS_A_ACCESS_DENIED); exit_worker(ws); @@ -943,13 +989,13 @@ void cookie_authenticate_or_exit(worker_st *ws) * a reply. * Returns 0 on success. */ -int auth_cookie(worker_st * ws, void *cookie, size_t cookie_size) +int auth_cookie(worker_st *ws, void *cookie, size_t cookie_size) { int ret; AuthCookieRequestMsg msg = AUTH_COOKIE_REQUEST_MSG__INIT; - if ((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) - && WSCONFIG(ws)->cisco_client_compat == 0) { + if ((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && + WSCONFIG(ws)->cisco_client_compat == 0) { if (ws->cert_auth_ok == 0) { oclog(ws, LOG_INFO, "no certificate provided for cookie authentication"); @@ -957,7 +1003,8 @@ int auth_cookie(worker_st * ws, void *cookie, size_t cookie_size) } else { ret = get_cert_info(ws); if (ret < 0) { - oclog(ws, LOG_INFO, "cannot obtain certificate info"); + oclog(ws, LOG_INFO, + "cannot obtain certificate info"); return -1; } } @@ -968,9 +1015,10 @@ int auth_cookie(worker_st * ws, void *cookie, size_t cookie_size) if (ws->req.hostname[0] != 0) msg.hostname = ws->req.hostname; - ret = send_msg_to_main(ws, AUTH_COOKIE_REQ, &msg, (pack_size_func) - auth_cookie_request_msg__get_packed_size, - (pack_func) auth_cookie_request_msg__pack); + ret = send_msg_to_main( + ws, AUTH_COOKIE_REQ, &msg, + (pack_size_func)auth_cookie_request_msg__get_packed_size, + (pack_func)auth_cookie_request_msg__pack); if (ret < 0) { oclog(ws, LOG_INFO, "error sending cookie authentication request"); @@ -987,45 +1035,48 @@ int auth_cookie(worker_st * ws, void *cookie, size_t cookie_size) return 0; } -int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) +int post_common_handler(worker_st *ws, unsigned int http_ver, const char *imsg) { int ret, size; - char str_cookie[BASE64_ENCODE_RAW_LENGTH(sizeof(ws->cookie))+1]; + char str_cookie[BASE64_ENCODE_RAW_LENGTH(sizeof(ws->cookie)) + 1]; size_t str_cookie_size = sizeof(str_cookie); char msg[MAX_BANNER_SIZE + 32]; const char *success_msg_head; char *success_msg_foot; - unsigned success_msg_head_size; - unsigned success_msg_foot_size; + unsigned int success_msg_head_size; + unsigned int success_msg_foot_size; if (ws->req.user_agent_type == AGENT_OPENCONNECT_V3) { success_msg_head = ocv3_success_msg_head; success_msg_foot = talloc_strdup(ws, ocv3_success_msg_foot); - success_msg_head_size = sizeof(ocv3_success_msg_head)-1; + success_msg_head_size = sizeof(ocv3_success_msg_head) - 1; success_msg_foot_size = strlen(success_msg_foot); } else { success_msg_head = oc_success_msg_head; success_msg_foot = NULL; #ifdef ANYCONNECT_CLIENT_COMPAT if (WSCONFIG(ws)->xml_config_file) { - success_msg_foot = talloc_asprintf(ws, OC_SUCCESS_MSG_FOOT_PROFILE, - WSCONFIG(ws)->xml_config_file, WSCONFIG(ws)->xml_config_hash); + success_msg_foot = + talloc_asprintf(ws, OC_SUCCESS_MSG_FOOT_PROFILE, + WSCONFIG(ws)->xml_config_file, + WSCONFIG(ws)->xml_config_hash); } #endif if (success_msg_foot == NULL) { - success_msg_foot = talloc_strdup(ws, OC_SUCCESS_MSG_FOOT); + success_msg_foot = + talloc_strdup(ws, OC_SUCCESS_MSG_FOOT); } if (success_msg_foot == NULL) return -1; - success_msg_head_size = sizeof(oc_success_msg_head)-1; + success_msg_head_size = sizeof(oc_success_msg_head) - 1; success_msg_foot_size = strlen(success_msg_foot); } oc_base64_encode((char *)ws->cookie, sizeof(ws->cookie), - (char *)str_cookie, str_cookie_size); + (char *)str_cookie, str_cookie_size); /* reply */ oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: 200 OK"); @@ -1039,8 +1090,10 @@ int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) if (ret < 0) goto fail; - if ((ws->selected_auth->type & AUTH_TYPE_GSSAPI) && imsg != NULL && imsg[0] != 0) { - ret = cstp_printf(ws, "WWW-Authenticate: Negotiate %s\r\n", imsg); + if ((ws->selected_auth->type & AUTH_TYPE_GSSAPI) && imsg != NULL && + imsg[0] != 0) { + ret = cstp_printf(ws, "WWW-Authenticate: Negotiate %s\r\n", + imsg); if (ret < 0) goto fail; } @@ -1050,9 +1103,8 @@ int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) goto fail; if (WSCONFIG(ws)->banner) { - size = - snprintf(msg, sizeof(msg), "%s", - WSCONFIG(ws)->banner); + size = snprintf(msg, sizeof(msg), "%s", + WSCONFIG(ws)->banner); if (size <= 0) goto fail; /* snprintf() returns not a very useful value, so we need to recalculate */ @@ -1064,7 +1116,7 @@ int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) size += success_msg_head_size + success_msg_foot_size; - ret = cstp_printf(ws, "Content-Length: %u\r\n", (unsigned)size); + ret = cstp_printf(ws, "Content-Length: %u\r\n", (unsigned int)size); if (ret < 0) goto fail; @@ -1076,60 +1128,56 @@ int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) char context[BASE64_ENCODE_RAW_LENGTH(SID_SIZE) + 1]; char safe_id[SAFE_ID_SIZE]; - oc_base64_encode((char *)ws->sid, sizeof(ws->sid), (char *)context, - sizeof(context)); + oc_base64_encode((char *)ws->sid, sizeof(ws->sid), + (char *)context, sizeof(context)); - ret = - cstp_printf(ws, - "Set-Cookie: webvpncontext=%s; Secure; HttpOnly\r\n", - context); + ret = cstp_printf( + ws, + "Set-Cookie: webvpncontext=%s; Secure; HttpOnly\r\n", + context); if (ret < 0) goto fail; - oclog(ws, LOG_SENSITIVE, "sent session id: %s", calc_safe_id(ws->sid, sizeof(ws->sid), safe_id, sizeof(safe_id))); + oclog(ws, LOG_SENSITIVE, "sent session id: %s", + calc_safe_id(ws->sid, sizeof(ws->sid), safe_id, + sizeof(safe_id))); } - ret = - cstp_printf(ws, - "Set-Cookie: webvpn=%s; Secure; HttpOnly\r\n", - str_cookie); + ret = cstp_printf(ws, "Set-Cookie: webvpn=%s; Secure; HttpOnly\r\n", + str_cookie); if (ret < 0) goto fail; - ret = - cstp_puts(ws, - "Set-Cookie: webvpnc=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; Secure; HttpOnly\r\n"); + ret = cstp_puts( + ws, + "Set-Cookie: webvpnc=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; Secure; HttpOnly\r\n"); if (ret < 0) goto fail; - ret = - add_owasp_headers(ws); + ret = add_owasp_headers(ws); if (ret < 0) goto fail; - #ifdef ANYCONNECT_CLIENT_COMPAT if (WSCONFIG(ws)->xml_config_file) { - ret = - cstp_printf(ws, - "Set-Cookie: webvpnc=bu:/&p:t&iu:1/&sh:%s&lu:/+CSCOT+/translation-table?textdomain%%3DAnyConnect%%26type%%3Dmanifest&fu:profiles%%2F%s&fh:%s; path=/; Secure; HttpOnly\r\n", - WSPCONFIG(ws)->cert_hash, - WSCONFIG(ws)->xml_config_file, - WSCONFIG(ws)->xml_config_hash); + ret = cstp_printf( + ws, + "Set-Cookie: webvpnc=bu:/&p:t&iu:1/&sh:%s&lu:/+CSCOT+/translation-table?textdomain%%3DAnyConnect%%26type%%3Dmanifest&fu:profiles%%2F%s&fh:%s; path=/; Secure; HttpOnly\r\n", + WSPCONFIG(ws)->cert_hash, WSCONFIG(ws)->xml_config_file, + WSCONFIG(ws)->xml_config_hash); } else { - ret = - cstp_printf(ws, - "Set-Cookie: webvpnc=bu:/&p:t&iu:1/&sh:%s; path=/; Secure; HttpOnly\r\n", - WSPCONFIG(ws)->cert_hash); + ret = cstp_printf( + ws, + "Set-Cookie: webvpnc=bu:/&p:t&iu:1/&sh:%s; path=/; Secure; HttpOnly\r\n", + WSPCONFIG(ws)->cert_hash); } #endif if (ret < 0) goto fail; - ret = - cstp_printf(ws, - "\r\n%s%s%s", success_msg_head, msg, success_msg_foot); + ret = cstp_printf(ws, "\r\n%s%s%s", success_msg_head, msg, + success_msg_foot); if (ret < 0) goto fail; @@ -1139,7 +1187,7 @@ int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) return 0; - fail: +fail: talloc_free(success_msg_foot); return -1; } @@ -1150,12 +1198,11 @@ int post_common_handler(worker_st * ws, unsigned http_ver, const char *imsg) * @body: is the string to search the xml field at, should be null-terminated. * @value: the value that was found */ -static -int match_password_in_reply(worker_st * ws, char *body, unsigned body_length, - char **value) +static int match_password_in_reply(worker_st *ws, char *body, + unsigned int body_length, char **value) { char *p; - unsigned len, xml = 0; + unsigned int len, xml = 0; if (body == NULL || body_length == 0) return -1; @@ -1164,11 +1211,9 @@ int match_password_in_reply(worker_st * ws, char *body, unsigned body_length, xml = 1; /* body should contain test or test */ - *value = - strcasestr(body, ""); + *value = strcasestr(body, "_password>"); if (*value == NULL) { oclog(ws, LOG_HTTP_DEBUG, @@ -1187,16 +1232,15 @@ int match_password_in_reply(worker_st * ws, char *body, unsigned body_length, *value = p; len = 0; while (*p != 0) { - if (*p == '<' && *(p+1) == '/') { + if (*p == '<' && *(p + 1) == '/') { break; } p++; len++; } - } else { /* non-xml version */ + } else { /* non-xml version */ /* body should be "username=test&password?=test" */ - *value = - strcasestr(body, "password"); + *value = strcasestr(body, "password"); if (*value == NULL) { oclog(ws, LOG_HTTP_DEBUG, "cannot find password in client message"); @@ -1249,16 +1293,16 @@ int match_password_in_reply(worker_st * ws, char *body, unsigned body_length, * @xml_field: the XML field to check for (e.g., MYFIELD) * @value: the value that was found */ -int parse_reply(worker_st * ws, char *body, unsigned body_length, - const char *field, unsigned field_size, - const char *xml_field, unsigned xml_field_size, +int parse_reply(worker_st *ws, char *body, unsigned int body_length, + const char *field, unsigned int field_size, + const char *xml_field, unsigned int xml_field_size, char **value) { char *p; char temp1[64]; char temp2[64]; - unsigned temp2_len, temp1_len; - unsigned len, xml = 0; + unsigned int temp2_len, temp1_len; + unsigned int len, xml = 0; if (body == NULL || body_length == 0) return -1; @@ -1277,8 +1321,7 @@ int parse_reply(worker_st * ws, char *body, unsigned body_length, temp2_len = strlen(temp2); /* body should contain test */ - *value = - strcasestr(body, temp1); + *value = strcasestr(body, temp1); if (*value == NULL) { oclog(ws, LOG_HTTP_DEBUG, "cannot find '%s' in client XML message", field); @@ -1289,20 +1332,19 @@ int parse_reply(worker_st * ws, char *body, unsigned body_length, p = *value; len = 0; while (*p != 0) { - if (*p == '<' - && (strncasecmp(p, temp2, temp2_len) == 0)) { + if (*p == '<' && + (strncasecmp(p, temp2, temp2_len) == 0)) { break; } p++; len++; } - } else { /* non-xml version */ + } else { /* non-xml version */ snprintf(temp1, sizeof(temp1), "%s=", field); temp1_len = strlen(temp1); /* body should be "username=test&password=test" */ - *value = - strcasestr(body, temp1); + *value = strcasestr(body, temp1); if (*value == NULL) { oclog(ws, LOG_HTTP_DEBUG, "cannot find '%s' in client message", field); @@ -1335,7 +1377,8 @@ int parse_reply(worker_st * ws, char *body, unsigned body_length, if (*value == NULL) { oclog(ws, LOG_ERR, - "%s requested but no such field in client message", field); + "%s requested but no such field in client message", + field); return -1; } @@ -1343,8 +1386,8 @@ int parse_reply(worker_st * ws, char *body, unsigned body_length, } #define SPNEGO_MSG "Please authenticate using GSSAPI" -static -int basic_auth_handler(worker_st * ws, unsigned http_ver, const char *msg) +static int basic_auth_handler(worker_st *ws, unsigned int http_ver, + const char *msg) { int ret; @@ -1361,11 +1404,14 @@ int basic_auth_handler(worker_st * ws, unsigned http_ver, const char *msg) } if (msg == NULL) { - oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: WWW-Authenticate: Negotiate"); + oclog(ws, LOG_HTTP_DEBUG, + "HTTP sending: WWW-Authenticate: Negotiate"); ret = cstp_puts(ws, "WWW-Authenticate: Negotiate\r\n"); } else { - oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: WWW-Authenticate: Negotiate %s", msg); - ret = cstp_printf(ws, "WWW-Authenticate: Negotiate %s\r\n", msg); + oclog(ws, LOG_HTTP_DEBUG, + "HTTP sending: WWW-Authenticate: Negotiate %s", msg); + ret = cstp_printf(ws, "WWW-Authenticate: Negotiate %s\r\n", + msg); } if (ret < 0) return -1; @@ -1390,13 +1436,12 @@ int basic_auth_handler(worker_st * ws, unsigned http_ver, const char *msg) ret = 0; - cleanup: +cleanup: return ret; } #ifdef SUPPORT_OIDC_AUTH -static -int oidc_auth_handler(worker_st * ws, unsigned http_ver) +static int oidc_auth_handler(worker_st *ws, unsigned int http_ver) { int ret; @@ -1406,8 +1451,10 @@ int oidc_auth_handler(worker_st * ws, unsigned http_ver) if (ret < 0) return -1; - oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: WWW-Authenticate: %s", HTTP_AUTH_OIDC_PREFIX); - ret = cstp_printf(ws, "WWW-Authenticate: %s\r\n", HTTP_AUTH_OIDC_PREFIX); + oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: WWW-Authenticate: %s", + HTTP_AUTH_OIDC_PREFIX); + ret = cstp_printf(ws, "WWW-Authenticate: %s\r\n", + HTTP_AUTH_OIDC_PREFIX); if (ret < 0) return -1; @@ -1432,7 +1479,7 @@ int oidc_auth_handler(worker_st * ws, unsigned http_ver) ret = 0; - cleanup: +cleanup: return ret; } #endif @@ -1447,7 +1494,7 @@ int oidc_auth_handler(worker_st * ws, unsigned http_ver) #define MSG_NO_CERT_ERROR "No certificate" #define MSG_NO_PASSWORD_ERROR "No password" -int post_auth_handler(worker_st * ws, unsigned http_ver) +int post_auth_handler(worker_st *ws, unsigned int http_ver) { int ret = -1, sd = -1; struct http_req_st *req = &ws->req; @@ -1456,12 +1503,12 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) char *password = NULL; char *groupname = NULL; char *msg = NULL; - unsigned def_group = 0; - unsigned pcounter = 0; + unsigned int def_group = 0; + unsigned int pcounter = 0; if (req->body_length > 0) { - oclog(ws, LOG_HTTP_DEBUG, "POST body: '%.*s'", (int)req->body_length, - req->body); + oclog(ws, LOG_HTTP_DEBUG, "POST body: '%.*s'", + (int)req->body_length, req->body); } if (ws->sid_set && ws->auth_state == S_AUTH_INACTIVE) @@ -1472,23 +1519,28 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) /* If the URL is not a known one and more than a character, we parse it as a group indicator */ if (WSCONFIG(ws)->select_group_by_url != 0 && - http_post_known_service_check(ws, req->url) == NULL && strlen(req->url) > 1) { - groupname = talloc_strdup(ws->req.body, req->url+1); + http_post_known_service_check(ws, req->url) == NULL && + strlen(req->url) > 1) { + groupname = talloc_strdup(ws->req.body, req->url + 1); ret = 0; - } if (ret < 0) { ret = parse_reply(ws, req->body, req->body_length, - GROUPNAME_FIELD, sizeof(GROUPNAME_FIELD)-1, - GROUPNAME_FIELD_XML, sizeof(GROUPNAME_FIELD_XML)-1, - &groupname); + GROUPNAME_FIELD, + sizeof(GROUPNAME_FIELD) - 1, + GROUPNAME_FIELD_XML, + sizeof(GROUPNAME_FIELD_XML) - 1, + &groupname); if (ret < 0) { - ret = parse_reply(ws, req->body, req->body_length, - GROUPNAME_FIELD2, sizeof(GROUPNAME_FIELD2)-1, - GROUPNAME_FIELD_XML, sizeof(GROUPNAME_FIELD_XML)-1, - &groupname); + ret = parse_reply( + ws, req->body, req->body_length, + GROUPNAME_FIELD2, + sizeof(GROUPNAME_FIELD2) - 1, + GROUPNAME_FIELD_XML, + sizeof(GROUPNAME_FIELD_XML) - 1, + &groupname); } } @@ -1496,33 +1548,55 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) oclog(ws, LOG_HTTP_DEBUG, "failed reading groupname"); } else { if (WSCONFIG(ws)->default_select_group != NULL && - strcmp(groupname, WSCONFIG(ws)->default_select_group) == 0) { + strcmp(groupname, + WSCONFIG(ws)->default_select_group) == 0) { def_group = 1; } else { /* Some anyconnect clients send the group friendly name instead of * the actual value; see #267 */ ws->groupname[0] = 0; if (WSCONFIG(ws)->friendly_group_list != NULL) { - unsigned found = 0, i; + unsigned int found = 0, i; - for (i=0;igroup_list_size;i++) { - if (strcmp(WSCONFIG(ws)->group_list[i], groupname) == 0) { + for (i = 0; + i < WSCONFIG(ws)->group_list_size; + i++) { + if (strcmp(WSCONFIG(ws) + ->group_list + [i], + groupname) == 0) { found = 1; break; } } if (!found) - for (i=0;igroup_list_size;i++) { - if (WSCONFIG(ws)->friendly_group_list[i] != NULL && strcmp(WSCONFIG(ws)->friendly_group_list[i], groupname) == 0) { - strlcpy(ws->groupname, WSCONFIG(ws)->group_list[i], sizeof(ws->groupname)); + for (i = 0; + i < + WSCONFIG(ws) + ->group_list_size; + i++) { + if (WSCONFIG(ws)->friendly_group_list + [i] != + NULL && + strcmp(WSCONFIG(ws)->friendly_group_list + [i], + groupname) == + 0) { + strlcpy(ws->groupname, + WSCONFIG( + ws) + ->group_list + [i], + sizeof(ws->groupname)); break; } } } if (ws->groupname[0] == 0) - strlcpy(ws->groupname, groupname, sizeof(ws->groupname)); + strlcpy(ws->groupname, groupname, + sizeof(ws->groupname)); ireq.group_name = ws->groupname; } } @@ -1530,40 +1604,53 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) #ifdef SUPPORT_OIDC_AUTH if (ws->selected_auth->type & AUTH_TYPE_OIDC) { - if (req->authorization == NULL || req->authorization_size == 0) + if (req->authorization == NULL || + req->authorization_size == 0) return oidc_auth_handler(ws, http_ver); - if ((req->authorization_size > (sizeof(HTTP_AUTH_OIDC_PREFIX) - 1)) && strncasecmp(req->authorization, HTTP_AUTH_OIDC_PREFIX, sizeof(HTTP_AUTH_OIDC_PREFIX) - 1) == 0) { + if ((req->authorization_size > + (sizeof(HTTP_AUTH_OIDC_PREFIX) - 1)) && + strncasecmp( + req->authorization, HTTP_AUTH_OIDC_PREFIX, + sizeof(HTTP_AUTH_OIDC_PREFIX) - 1) == 0) { ireq.auth_type |= AUTH_TYPE_OIDC; - ireq.user_name = req->authorization + sizeof(HTTP_AUTH_OIDC_PREFIX); + ireq.user_name = req->authorization + + sizeof(HTTP_AUTH_OIDC_PREFIX); } else { - oclog(ws, LOG_HTTP_DEBUG, "Invalid authorization data: %.*s", req->authorization_size, req->authorization); + oclog(ws, LOG_HTTP_DEBUG, + "Invalid authorization data: %.*s", + req->authorization_size, + req->authorization); goto auth_fail; } } #endif if (ws->selected_auth->type & AUTH_TYPE_GSSAPI) { - if (req->authorization == NULL || req->authorization_size == 0) + if (req->authorization == NULL || + req->authorization_size == 0) return basic_auth_handler(ws, http_ver, NULL); if (req->authorization_size > 10) { ireq.user_name = req->authorization + 10; ireq.auth_type |= AUTH_TYPE_GSSAPI; } else { - oclog(ws, LOG_HTTP_DEBUG, "Invalid authorization data: %.*s", req->authorization_size, req->authorization); + oclog(ws, LOG_HTTP_DEBUG, + "Invalid authorization data: %.*s", + req->authorization_size, + req->authorization); goto auth_fail; } } if (ws->selected_auth->type & AUTH_TYPE_USERNAME_PASS) { - ret = parse_reply(ws, req->body, req->body_length, - USERNAME_FIELD, sizeof(USERNAME_FIELD)-1, - NULL, 0, - &username); + USERNAME_FIELD, + sizeof(USERNAME_FIELD) - 1, NULL, 0, + &username); if (ret < 0) { - oclog(ws, LOG_HTTP_DEBUG, "failed reading username"); + oclog(ws, LOG_HTTP_DEBUG, + "failed reading username"); goto ask_auth; } @@ -1595,9 +1682,13 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) } } - if (def_group == 0 && ws->cert_groups_size > 0 && ws->groupname[0] == 0) { - oclog(ws, LOG_HTTP_DEBUG, "user has not selected a group"); - return get_auth_handler2(ws, http_ver, "Please select your group.", 0); + if (def_group == 0 && ws->cert_groups_size > 0 && + ws->groupname[0] == 0) { + oclog(ws, LOG_HTTP_DEBUG, + "user has not selected a group"); + return get_auth_handler2( + ws, http_ver, + "Please select your group.", 0); } ireq.tls_auth_ok = ws->cert_auth_ok; @@ -1615,7 +1706,7 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) ireq.orig_remote_ip = ws->orig_remote_ip_str; ireq.our_ip = ws->our_ip_str; ireq.session_start_time = ws->session_start_time; - ireq.hmac.data = (uint8_t*)ws->sec_auth_init_hmac; + ireq.hmac.data = (uint8_t *)ws->sec_auth_init_hmac; ireq.hmac.len = sizeof(ws->sec_auth_init_hmac); if (req->user_agent[0] != 0) ireq.user_agent = req->user_agent; @@ -1633,10 +1724,10 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) goto auth_fail; } - ret = send_msg_to_secmod(ws, sd, CMD_SEC_AUTH_INIT, - &ireq, (pack_size_func) - sec_auth_init_msg__get_packed_size, - (pack_func) sec_auth_init_msg__pack); + ret = send_msg_to_secmod( + ws, sd, CMD_SEC_AUTH_INIT, &ireq, + (pack_size_func)sec_auth_init_msg__get_packed_size, + (pack_func)sec_auth_init_msg__pack); if (ret < 0) { reason = MSG_INTERNAL_ERROR; oclog(ws, LOG_ERR, @@ -1645,25 +1736,31 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) } ws->auth_state = S_AUTH_INIT; - } else if (ws->auth_state == S_AUTH_INIT - || ws->auth_state == S_AUTH_REQ) { + } else if (ws->auth_state == S_AUTH_INIT || + ws->auth_state == S_AUTH_REQ) { SecAuthContMsg areq = SEC_AUTH_CONT_MSG__INIT; areq.ip = ws->remote_ip_str; if (ws->selected_auth->type & AUTH_TYPE_GSSAPI) { - if (req->authorization == NULL || req->authorization_size <= 10) { + if (req->authorization == NULL || + req->authorization_size <= 10) { if (req->authorization != NULL) - oclog(ws, LOG_HTTP_DEBUG, "Invalid authorization data: %.*s", req->authorization_size, req->authorization); + oclog(ws, LOG_HTTP_DEBUG, + "Invalid authorization data: %.*s", + req->authorization_size, + req->authorization); else - oclog(ws, LOG_HTTP_DEBUG, "No authorization data"); + oclog(ws, LOG_HTTP_DEBUG, + "No authorization data"); goto auth_fail; } areq.password = req->authorization + 10; } - if (areq.password == NULL && (ws->selected_auth->type & AUTH_TYPE_USERNAME_PASS)) { - ret = match_password_in_reply(ws, req->body, req->body_length, - &password); + if (areq.password == NULL && + (ws->selected_auth->type & AUTH_TYPE_USERNAME_PASS)) { + ret = match_password_in_reply( + ws, req->body, req->body_length, &password); if (ret < 0) { reason = MSG_NO_PASSWORD_ERROR; oclog(ws, LOG_ERR, "failed reading password"); @@ -1687,12 +1784,11 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) goto auth_fail; } - ret = - send_msg_to_secmod(ws, sd, CMD_SEC_AUTH_CONT, &areq, - (pack_size_func) - sec_auth_cont_msg__get_packed_size, - (pack_func) - sec_auth_cont_msg__pack); + ret = send_msg_to_secmod( + ws, sd, CMD_SEC_AUTH_CONT, &areq, + (pack_size_func) + sec_auth_cont_msg__get_packed_size, + (pack_func)sec_auth_cont_msg__pack); talloc_free(password); if (ret < 0) { @@ -1709,7 +1805,7 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) } } else { oclog(ws, LOG_ERR, "unexpected POST request in auth state %u", - (unsigned)ws->auth_state); + (unsigned int)ws->auth_state); goto auth_fail; } @@ -1720,7 +1816,6 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) } if (ret == ERR_AUTH_CONTINUE) { - oclog(ws, LOG_DEBUG, "continuing authentication for '%s'", ws->username); ws->auth_state = S_AUTH_REQ; @@ -1754,23 +1849,22 @@ int post_auth_handler(worker_st * ws, unsigned http_ver) ret = post_common_handler(ws, http_ver, msg); goto cleanup; - ask_auth: +ask_auth: return get_auth_handler(ws, http_ver); - auth_fail: +auth_fail: if (sd != -1) close(sd); oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: 401 Unauthorized"); - ret = cstp_printf(ws, - "HTTP/1.%d 401 %s\r\nContent-Length: 0\r\n\r\n", - http_ver, reason); + ret = cstp_printf(ws, "HTTP/1.%d 401 %s\r\nContent-Length: 0\r\n\r\n", + http_ver, reason); if (ret >= 0) cstp_fatal_close(ws, GNUTLS_A_ACCESS_DENIED); talloc_free(msg); exit_worker(ws); - cleanup: +cleanup: talloc_free(msg); return ret; } diff --git a/src/worker-bandwidth.c b/src/worker-bandwidth.c index 2fcefee4..7de46b5f 100644 --- a/src/worker-bandwidth.c +++ b/src/worker-bandwidth.c @@ -26,18 +26,17 @@ #include - -int _bandwidth_update(bandwidth_st* b, size_t bytes, struct timespec *now) +int _bandwidth_update(bandwidth_st *b, size_t bytes, struct timespec *now) { -size_t sum; -ssize_t t, remain; -unsigned int diff; -size_t transferred_kb; + size_t sum; + ssize_t t, remain; + unsigned int diff; + size_t transferred_kb; diff = timespec_sub_ms(now, &b->count_start); if (diff >= COUNT_UPDATE_MS) { transferred_kb = b->transferred_bytes / 1000; - transferred_kb = (transferred_kb*COUNT_UPDATE_MS)/diff; + transferred_kb = (transferred_kb * COUNT_UPDATE_MS) / diff; memcpy(&b->count_start, now, sizeof(*now)); @@ -51,7 +50,7 @@ size_t transferred_kb; } sum = b->transferred_bytes + bytes; - if (sum > b->allowed_kb*1000) + if (sum > b->allowed_kb * 1000) return 0; /* NO */ b->transferred_bytes = sum; diff --git a/src/worker-bandwidth.h b/src/worker-bandwidth.h index 104d5659..7ac1784f 100644 --- a/src/worker-bandwidth.h +++ b/src/worker-bandwidth.h @@ -19,7 +19,7 @@ * along with this program. If not, see */ #ifndef OC_WORKER_BANDWIDTH_H -# define OC_WORKER_BANDWIDTH_H +#define OC_WORKER_BANDWIDTH_H #include #include @@ -37,19 +37,19 @@ typedef struct bandwidth_st { size_t kb_per_sec; } bandwidth_st; -inline static void bandwidth_init(bandwidth_st* b, size_t kb_per_sec) +inline static void bandwidth_init(bandwidth_st *b, size_t kb_per_sec) { memset(b, 0, sizeof(*b)); b->kb_per_sec = kb_per_sec; - b->allowed_kb_per_count = (b->kb_per_sec*COUNT_UPDATE_MS)/1000; + b->allowed_kb_per_count = (b->kb_per_sec * COUNT_UPDATE_MS) / 1000; } -int _bandwidth_update(bandwidth_st* b, size_t bytes, struct timespec* now); +int _bandwidth_update(bandwidth_st *b, size_t bytes, struct timespec *now); /* returns true or false, depending on whether to send * the bytes */ -inline static -int bandwidth_update(bandwidth_st* b, size_t bytes, struct timespec* now) +inline static int bandwidth_update(bandwidth_st *b, size_t bytes, + struct timespec *now) { /* if bandwidth control is disabled */ if (b->kb_per_sec == 0) diff --git a/src/worker-http-handlers.c b/src/worker-http-handlers.c index bb8948a1..f7c45b65 100644 --- a/src/worker-http-handlers.c +++ b/src/worker-http-handlers.c @@ -41,58 +41,60 @@ #define HTML_404 "

404 Not Found

\r\n" #define HTML_401 "

401 Unauthorized

\r\n" -int response_404(worker_st *ws, unsigned http_ver) +int response_404(worker_st *ws, unsigned int http_ver) { if (cstp_printf(ws, "HTTP/1.%u 404 Not found\r\n", http_ver) < 0 || - cstp_printf(ws, "Content-Length: %u\r\n", (unsigned)(sizeof(HTML_404) - 1)) < 0 || - cstp_puts (ws, "Connection: close\r\n\r\n") < 0 || - cstp_puts (ws, HTML_404) < 0) + cstp_printf(ws, "Content-Length: %u\r\n", + (unsigned int)(sizeof(HTML_404) - 1)) < 0 || + cstp_puts(ws, "Connection: close\r\n\r\n") < 0 || + cstp_puts(ws, HTML_404) < 0) return -1; return 0; } -int response_401(worker_st *ws, unsigned http_ver, char* realm) +int response_401(worker_st *ws, unsigned int http_ver, char *realm) { if (cstp_printf(ws, "HTTP/1.%u 401 Unauthorized\r\n", http_ver) < 0 || - cstp_printf(ws, "WWW-Authenticate: Basic realm=\"%s\"\r\n", realm) < 0 || - cstp_printf(ws, "Content-Length: %u\r\n", (unsigned)(sizeof(HTML_401) - 1)) < 0 || - cstp_puts (ws, "Connection: close\r\n\r\n") < 0 || - cstp_puts (ws, HTML_401) < 0) - return -1; - return 0; -} - -static int send_headers(worker_st *ws, unsigned http_ver, const char *content_type, - unsigned content_length) -{ - if (cstp_printf(ws, "HTTP/1.%u 200 OK\r\n", http_ver) < 0 || - cstp_puts (ws, "Connection: Keep-Alive\r\n") < 0 || - cstp_printf(ws, "Content-Type: %s\r\n", content_type) < 0 || - cstp_puts (ws, "X-Transcend-Version: 1\r\n") < 0 || - cstp_printf(ws, "Content-Length: %u\r\n", content_length) < 0 || - add_owasp_headers(ws) < 0 || - cstp_puts (ws, "\r\n") < 0) + cstp_printf(ws, "WWW-Authenticate: Basic realm=\"%s\"\r\n", realm) < + 0 || + cstp_printf(ws, "Content-Length: %u\r\n", + (unsigned int)(sizeof(HTML_401) - 1)) < 0 || + cstp_puts(ws, "Connection: close\r\n\r\n") < 0 || + cstp_puts(ws, HTML_401) < 0) return -1; return 0; } -static int send_data(worker_st *ws, unsigned http_ver, const char *content_type, - const char *data, int content_length) +static int send_headers(worker_st *ws, unsigned int http_ver, + const char *content_type, unsigned int content_length) +{ + if (cstp_printf(ws, "HTTP/1.%u 200 OK\r\n", http_ver) < 0 || + cstp_puts(ws, "Connection: Keep-Alive\r\n") < 0 || + cstp_printf(ws, "Content-Type: %s\r\n", content_type) < 0 || + cstp_puts(ws, "X-Transcend-Version: 1\r\n") < 0 || + cstp_printf(ws, "Content-Length: %u\r\n", content_length) < 0 || + add_owasp_headers(ws) < 0 || cstp_puts(ws, "\r\n") < 0) + return -1; + return 0; +} + +static int send_data(worker_st *ws, unsigned int http_ver, + const char *content_type, const char *data, + int content_length) { /* don't bother uncorking on error - the connection will be closed anyway */ cstp_cork(ws); if (send_headers(ws, http_ver, content_type, content_length) < 0 || - cstp_send(ws, data, content_length) < 0 || - cstp_uncork(ws) < 0) + cstp_send(ws, data, content_length) < 0 || cstp_uncork(ws) < 0) return -1; return 0; } -int get_cert_handler(worker_st * ws, unsigned http_ver) +int get_cert_handler(worker_st *ws, unsigned int http_ver) { if (ws->conn_type != SOCK_TYPE_UNIX) { /* we have TLS */ const gnutls_datum_t *certs; - gnutls_datum_t out = {NULL, 0}; + gnutls_datum_t out = { NULL, 0 }; int ret; oclog(ws, LOG_DEBUG, "requested server certificate"); @@ -102,11 +104,13 @@ int get_cert_handler(worker_st * ws, unsigned http_ver) return -1; } - ret = gnutls_pem_base64_encode_alloc("CERTIFICATE", &certs[0], &out); + ret = gnutls_pem_base64_encode_alloc("CERTIFICATE", &certs[0], + &out); if (ret < 0) return -1; - ret = send_data(ws, http_ver, "application/x-pem-file", (char*)out.data, out.size); + ret = send_data(ws, http_ver, "application/x-pem-file", + (char *)out.data, out.size); gnutls_free(out.data); return ret; @@ -114,7 +118,7 @@ int get_cert_handler(worker_st * ws, unsigned http_ver) return -1; } } -int get_cert_der_handler(worker_st * ws, unsigned http_ver) +int get_cert_der_handler(worker_st *ws, unsigned int http_ver) { if (ws->conn_type != SOCK_TYPE_UNIX) { /* we have TLS */ const gnutls_datum_t *certs; @@ -126,20 +130,19 @@ int get_cert_der_handler(worker_st * ws, unsigned http_ver) return -1; } - return send_data(ws, http_ver, "application/pkix-cert", (char*)certs[0].data, certs[0].size); + return send_data(ws, http_ver, "application/pkix-cert", + (char *)certs[0].data, certs[0].size); } else { return -1; } } - -static -int ca_handler(worker_st * ws, unsigned http_ver, unsigned der) +static int ca_handler(worker_st *ws, unsigned int http_ver, unsigned int der) { if (ws->conn_type != SOCK_TYPE_UNIX) { /* we have TLS */ const gnutls_datum_t *certs; - gnutls_datum_t out = {NULL, 0}, tmpca; - unsigned i; + gnutls_datum_t out = { NULL, 0 }, tmpca; + unsigned int i; int ret; gnutls_x509_crt_t issuer = NULL, crt = NULL; @@ -164,32 +167,41 @@ int ca_handler(worker_st * ws, unsigned http_ver, unsigned der) goto cleanup; } - ret = gnutls_x509_crt_import(crt, &certs[0], GNUTLS_X509_FMT_DER); + ret = gnutls_x509_crt_import(crt, &certs[0], + GNUTLS_X509_FMT_DER); if (ret < 0) { ret = -1; oclog(ws, LOG_DEBUG, "could not import our cert"); goto cleanup; } - for (i=0;i<8;i++) { - ret = gnutls_certificate_get_crt_raw(WSCREDS(ws)->xcred, i, 1, &tmpca); + for (i = 0; i < 8; i++) { + ret = gnutls_certificate_get_crt_raw(WSCREDS(ws)->xcred, + i, 1, &tmpca); if (ret < 0) { goto cleanup; } - ret = gnutls_x509_crt_import(issuer, &tmpca, GNUTLS_X509_FMT_DER); + ret = gnutls_x509_crt_import(issuer, &tmpca, + GNUTLS_X509_FMT_DER); if (ret < 0) { ret = -1; - oclog(ws, LOG_DEBUG, "could not import issuer cert"); + oclog(ws, LOG_DEBUG, + "could not import issuer cert"); goto cleanup; } ret = gnutls_x509_crt_check_issuer(crt, issuer); if (ret != 0) { - ret = gnutls_x509_crt_export2(issuer, der?GNUTLS_X509_FMT_DER:GNUTLS_X509_FMT_PEM, &out); + ret = gnutls_x509_crt_export2( + issuer, + der ? GNUTLS_X509_FMT_DER : + GNUTLS_X509_FMT_PEM, + &out); if (ret < 0) { ret = -1; - oclog(ws, LOG_DEBUG, "could not export issuer of cert"); + oclog(ws, LOG_DEBUG, + "could not export issuer of cert"); goto cleanup; } break; @@ -199,11 +211,13 @@ int ca_handler(worker_st * ws, unsigned http_ver, unsigned der) issuer = NULL; } - ret = send_data(ws, http_ver, "application/pkix-cert", (char*)out.data, out.size); + ret = send_data(ws, http_ver, "application/pkix-cert", + (char *)out.data, out.size); - cleanup: +cleanup: if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { - oclog(ws, LOG_DEBUG, "could not get CA; does the server cert list contain the CA certificate?"); + oclog(ws, LOG_DEBUG, + "could not get CA; does the server cert list contain the CA certificate?"); ret = -1; } @@ -219,18 +233,18 @@ int ca_handler(worker_st * ws, unsigned http_ver, unsigned der) } } -int get_ca_handler(worker_st * ws, unsigned http_ver) +int get_ca_handler(worker_st *ws, unsigned int http_ver) { return ca_handler(ws, http_ver, 0); } -int get_ca_der_handler(worker_st * ws, unsigned http_ver) +int get_ca_der_handler(worker_st *ws, unsigned int http_ver) { return ca_handler(ws, http_ver, 1); } #ifdef ANYCONNECT_CLIENT_COMPAT -int get_config_handler(worker_st *ws, unsigned http_ver) +int get_config_handler(worker_st *ws, unsigned int http_ver) { int ret; struct stat st; @@ -240,26 +254,30 @@ int get_config_handler(worker_st *ws, unsigned http_ver) cookie_authenticate_or_exit(ws); if (ws->user_config->xml_config_file == NULL) { - oclog(ws, LOG_INFO, "requested config but no config file is set"); + oclog(ws, LOG_INFO, + "requested config but no config file is set"); response_404(ws, http_ver); return -1; } ret = stat(ws->user_config->xml_config_file, &st); if (ret == -1) { - oclog(ws, LOG_INFO, "cannot load config file '%s'", ws->user_config->xml_config_file); + oclog(ws, LOG_INFO, "cannot load config file '%s'", + ws->user_config->xml_config_file); response_404(ws, http_ver); return -1; } cstp_cork(ws); - if (send_headers(ws, http_ver, "text/xml", (unsigned)st.st_size) < 0 || + if (send_headers(ws, http_ver, "text/xml", (unsigned int)st.st_size) < + 0 || cstp_uncork(ws) < 0) return -1; ret = cstp_send_file(ws, ws->user_config->xml_config_file); if (ret < 0) { - oclog(ws, LOG_ERR, "error sending file '%s': %s", ws->user_config->xml_config_file, gnutls_strerror(ret)); + oclog(ws, LOG_ERR, "error sending file '%s': %s", + ws->user_config->xml_config_file, gnutls_strerror(ret)); return -1; } @@ -267,36 +285,38 @@ int get_config_handler(worker_st *ws, unsigned http_ver) } #define VPN_VERSION "0,0,0000\n" -#define XML_START "\n\n\n" +#define XML_START \ + "\n\n\n" -int get_string_handler(worker_st *ws, unsigned http_ver) +int get_string_handler(worker_st *ws, unsigned int http_ver) { oclog(ws, LOG_HTTP_DEBUG, "requested fixed string: %s", ws->req.url); if (!strcmp(ws->req.url, "/1/binaries/update.txt")) { return send_data(ws, http_ver, "text/xml", VPN_VERSION, - sizeof(VPN_VERSION) - 1); + sizeof(VPN_VERSION) - 1); } else { return send_data(ws, http_ver, "text/xml", XML_START, - sizeof(XML_START) - 1); + sizeof(XML_START) - 1); } } -#define SH_SCRIPT "#!/bin/sh\n\n" \ +#define SH_SCRIPT \ + "#!/bin/sh\n\n" \ "exit 0" -int get_dl_handler(worker_st *ws, unsigned http_ver) +int get_dl_handler(worker_st *ws, unsigned int http_ver) { oclog(ws, LOG_HTTP_DEBUG, "requested downloader: %s", ws->req.url); return send_data(ws, http_ver, "application/x-shellscript", SH_SCRIPT, - sizeof(SH_SCRIPT) - 1); + sizeof(SH_SCRIPT) - 1); } #define EMPTY_MSG "\n" -int get_empty_handler(worker_st *ws, unsigned http_ver) +int get_empty_handler(worker_st *ws, unsigned int http_ver) { return send_data(ws, http_ver, "text/html", EMPTY_MSG, - sizeof(EMPTY_MSG) - 1); + sizeof(EMPTY_MSG) - 1); } #endif diff --git a/src/worker-http.c b/src/worker-http.c index 260203b0..5ab499bc 100644 --- a/src/worker-http.c +++ b/src/worker-http.c @@ -25,10 +25,10 @@ #include #ifdef ENABLE_COMPRESSION -# ifdef HAVE_LZ4 -# include -# endif -# include "lzs.h" +#ifdef HAVE_LZ4 +#include +#endif +#include "lzs.h" #endif #include @@ -43,14 +43,14 @@ struct known_urls_st { const char *url; - unsigned url_size; - unsigned partial_match; + unsigned int url_size; + unsigned int partial_match; url_handler_fn get_handler; url_handler_fn post_handler; }; -#define LL(x,y,z) {x, sizeof(x)-1, 0, y, z} -#define LL_DIR(x,y,z) {x, sizeof(x)-1, 1, y, z} +#define LL(x, y, z) { x, sizeof(x) - 1, 0, y, z } +#define LL_DIR(x, y, z) { x, sizeof(x) - 1, 1, y, z } static const struct known_urls_st known_urls[] = { LL("/", get_auth_handler, post_auth_handler), LL("/auth", get_auth_handler, post_auth_handler), @@ -76,7 +76,7 @@ static const struct known_urls_st known_urls[] = { LL("/logout", get_empty_handler, NULL), #endif LL("/svc", get_svc_handler, post_svc_handler), - {NULL, 0, 0, NULL, NULL} + { NULL, 0, 0, NULL, NULL } }; /* In the following we use %NO_SESSION_HASH:%DISABLE_SAFE_RENEGOTIATION because certain @@ -87,9 +87,9 @@ static const struct known_urls_st known_urls[] = { * be sending the renegotiation extension which openssl doesn't like (see #193) */ #if GNUTLS_VERSION_NUMBER >= 0x030400 -# define WORKAROUND_STR "%NO_SESSION_HASH:%DISABLE_SAFE_RENEGOTIATION" +#define WORKAROUND_STR "%NO_SESSION_HASH:%DISABLE_SAFE_RENEGOTIATION" #else -# define WORKAROUND_STR "%DISABLE_SAFE_RENEGOTIATION" +#define WORKAROUND_STR "%DISABLE_SAFE_RENEGOTIATION" #endif /* Consider switching to gperf when this table grows significantly. @@ -98,123 +98,115 @@ static const struct known_urls_st known_urls[] = { */ static const dtls_ciphersuite_st ciphersuites[] = { { - .oc_name = CS_AES128_GCM, - .gnutls_name = - "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-128-GCM:+AEAD:+RSA:+SIGN-ALL:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS1_2, - .gnutls_mac = GNUTLS_MAC_AEAD, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_128_GCM, - .server_prio = 80, + .oc_name = CS_AES128_GCM, + .gnutls_name = + "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-128-GCM:+AEAD:+RSA:+SIGN-ALL:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS1_2, + .gnutls_mac = GNUTLS_MAC_AEAD, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_128_GCM, + .server_prio = 80, }, { - .oc_name = CS_AES256_GCM, - .gnutls_name = - "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-256-GCM:+AEAD:+RSA:+SIGN-ALL:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS1_2, - .gnutls_mac = GNUTLS_MAC_AEAD, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_256_GCM, - .server_prio = 90, + .oc_name = CS_AES256_GCM, + .gnutls_name = + "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-256-GCM:+AEAD:+RSA:+SIGN-ALL:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS1_2, + .gnutls_mac = GNUTLS_MAC_AEAD, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_256_GCM, + .server_prio = 90, }, { - .oc_name = "AES256-SHA", - .gnutls_name = - "NONE:+VERS-DTLS0.9:+COMP-NULL:+AES-256-CBC:+SHA1:+RSA:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS0_9, - .gnutls_mac = GNUTLS_MAC_SHA1, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_256_CBC, - .server_prio = 60, + .oc_name = "AES256-SHA", + .gnutls_name = + "NONE:+VERS-DTLS0.9:+COMP-NULL:+AES-256-CBC:+SHA1:+RSA:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS0_9, + .gnutls_mac = GNUTLS_MAC_SHA1, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_256_CBC, + .server_prio = 60, }, { - .oc_name = "AES128-SHA", - .gnutls_name = - "NONE:+VERS-DTLS0.9:+COMP-NULL:+AES-128-CBC:+SHA1:+RSA:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS0_9, - .gnutls_mac = GNUTLS_MAC_SHA1, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_128_CBC, - .server_prio = 50, + .oc_name = "AES128-SHA", + .gnutls_name = + "NONE:+VERS-DTLS0.9:+COMP-NULL:+AES-128-CBC:+SHA1:+RSA:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS0_9, + .gnutls_mac = GNUTLS_MAC_SHA1, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_128_CBC, + .server_prio = 50, }, { - .oc_name = "DES-CBC3-SHA", - .gnutls_name = - "NONE:+VERS-DTLS0.9:+COMP-NULL:+3DES-CBC:+SHA1:+RSA:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS0_9, - .gnutls_mac = GNUTLS_MAC_SHA1, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_3DES_CBC, - .server_prio = 1, + .oc_name = "DES-CBC3-SHA", + .gnutls_name = + "NONE:+VERS-DTLS0.9:+COMP-NULL:+3DES-CBC:+SHA1:+RSA:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS0_9, + .gnutls_mac = GNUTLS_MAC_SHA1, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_3DES_CBC, + .server_prio = 1, }, }; static const dtls_ciphersuite_st ciphersuites12[] = { - { - .oc_name = "AES128-GCM-SHA256", - .gnutls_name = - "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-128-GCM:+AEAD:+RSA:+SIGN-ALL:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS1_2, - .gnutls_mac = GNUTLS_MAC_AEAD, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_128_GCM, - .dtls12_mode = 1, - .server_prio = 50 - }, - { - .oc_name = "AES256-GCM-SHA384", - .gnutls_name = - "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-256-GCM:+AEAD:+RSA:+SIGN-ALL:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS1_2, - .gnutls_mac = GNUTLS_MAC_AEAD, - .gnutls_kx = GNUTLS_KX_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_256_GCM, - .dtls12_mode = 1, - .server_prio = 90 - }, + { .oc_name = "AES128-GCM-SHA256", + .gnutls_name = + "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-128-GCM:+AEAD:+RSA:+SIGN-ALL:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS1_2, + .gnutls_mac = GNUTLS_MAC_AEAD, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_128_GCM, + .dtls12_mode = 1, + .server_prio = 50 }, + { .oc_name = "AES256-GCM-SHA384", + .gnutls_name = + "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-256-GCM:+AEAD:+RSA:+SIGN-ALL:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS1_2, + .gnutls_mac = GNUTLS_MAC_AEAD, + .gnutls_kx = GNUTLS_KX_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_256_GCM, + .dtls12_mode = 1, + .server_prio = 90 }, /* these next two are currently only used by cisco-svc-client-compat devices */ { - .oc_name = "ECDHE-RSA-AES128-GCM-SHA256", - .gnutls_name = - "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-128-GCM:+AEAD:+SHA256:+ECDHE-RSA:+SIGN-ALL:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS1_2, - .gnutls_mac = GNUTLS_MAC_AEAD, - .gnutls_kx = GNUTLS_KX_ECDHE_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_128_GCM, - .dtls12_mode = 1, - .server_prio = 70, + .oc_name = "ECDHE-RSA-AES128-GCM-SHA256", + .gnutls_name = + "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-128-GCM:+AEAD:+SHA256:+ECDHE-RSA:+SIGN-ALL:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS1_2, + .gnutls_mac = GNUTLS_MAC_AEAD, + .gnutls_kx = GNUTLS_KX_ECDHE_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_128_GCM, + .dtls12_mode = 1, + .server_prio = 70, }, { - .oc_name = "ECDHE-RSA-AES256-GCM-SHA384", - .gnutls_name = - "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-256-GCM:+AEAD:+SHA384:+ECDHE-RSA:+SIGN-ALL:"WORKAROUND_STR, - .gnutls_version = GNUTLS_DTLS1_2, - .gnutls_mac = GNUTLS_MAC_AEAD, - .gnutls_kx = GNUTLS_KX_ECDHE_RSA, - .gnutls_cipher = GNUTLS_CIPHER_AES_256_GCM, - .dtls12_mode = 1, - .server_prio = 80, + .oc_name = "ECDHE-RSA-AES256-GCM-SHA384", + .gnutls_name = + "NONE:+VERS-DTLS1.2:+COMP-NULL:+AES-256-GCM:+AEAD:+SHA384:+ECDHE-RSA:+SIGN-ALL:" WORKAROUND_STR, + .gnutls_version = GNUTLS_DTLS1_2, + .gnutls_mac = GNUTLS_MAC_AEAD, + .gnutls_kx = GNUTLS_KX_ECDHE_RSA, + .gnutls_cipher = GNUTLS_CIPHER_AES_256_GCM, + .dtls12_mode = 1, + .server_prio = 80, } }; -#define STR_ST(x) {.data = (uint8_t*)x, .length = sizeof(x)-1} -static const str_st sensitve_http_headers[] = { - STR_ST("Cookie"), - STR_ST("X-DTLS-Master-Secret"), - STR_ST("Authorization"), - {NULL, 0} -}; +#define STR_ST(x) { .data = (uint8_t *)x, .length = sizeof(x) - 1 } +static const str_st sensitve_http_headers[] = { STR_ST("Cookie"), + STR_ST("X-DTLS-Master-Secret"), + STR_ST("Authorization"), + { NULL, 0 } }; #ifdef HAVE_LZ4 /* Wrappers over LZ4 functions */ -static -int lz4_decompress(void *dst, int dstlen, const void *src, int srclen) +static int lz4_decompress(void *dst, int dstlen, const void *src, int srclen) { return LZ4_decompress_safe(src, dst, srclen, dstlen); } -static -int lz4_compress(void *dst, int dstlen, const void *src, int srclen) +static int lz4_compress(void *dst, int dstlen, const void *src, int srclen) { /* we intentionally restrict output to srclen so that * compression fails early for packets that expand. */ @@ -242,9 +234,9 @@ struct compression_method_st comp_methods[] = { } }; -unsigned switch_comp_priority(void *pool, const char *modstring) +unsigned int switch_comp_priority(void *pool, const char *modstring) { - unsigned i, ret; + unsigned int i, ret; char *token, *str; const char *algo = NULL; long priority = -1; @@ -276,27 +268,29 @@ unsigned switch_comp_priority(void *pool, const char *modstring) ret = 0; - finish: +finish: talloc_free(str); return ret; } #endif -static bool header_is_sensitive(str_st * header) +static bool header_is_sensitive(str_st *header) { size_t i; + for (i = 0; sensitve_http_headers[i].length != 0; i++) { if ((header->length == sensitve_http_headers[i].length) && - (strncasecmp((char*)header->data, (char*)sensitve_http_headers[i].data, header->length) == 0)) + (strncasecmp((char *)header->data, + (char *)sensitve_http_headers[i].data, + header->length) == 0)) return true; } return false; } -static -void header_value_check(struct worker_st *ws, struct http_req_st *req) +static void header_value_check(struct worker_st *ws, struct http_req_st *req) { - unsigned tmplen, i; + unsigned int tmplen, i; int ret; size_t nlen, value_length; char *token, *value; @@ -311,12 +305,14 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) if (req->value.length <= 0) return; - if (WSPCONFIG(ws)->log_level < OCLOG_SENSITIVE && header_is_sensitive(&req->header)) - oclog(ws, LOG_HTTP_DEBUG, "HTTP processing: %.*s: (censored)", (int)req->header.length, - req->header.data); + if (WSPCONFIG(ws)->log_level < OCLOG_SENSITIVE && + header_is_sensitive(&req->header)) + oclog(ws, LOG_HTTP_DEBUG, "HTTP processing: %.*s: (censored)", + (int)req->header.length, req->header.data); else - oclog(ws, LOG_HTTP_DEBUG, "HTTP processing: %.*s: %.*s", (int)req->header.length, - req->header.data, (int)req->value.length, req->value.data); + oclog(ws, LOG_HTTP_DEBUG, "HTTP processing: %.*s: %.*s", + (int)req->header.length, req->header.data, + (int)req->value.length, req->value.data); value = talloc_size(ws, req->value.length + 1); if (value == NULL) @@ -340,8 +336,8 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) tmplen = TLS_MASTER_SIZE * 2; nlen = sizeof(req->master_secret); - gnutls_hex2bin((void *)value, tmplen, - req->master_secret, &nlen); + gnutls_hex2bin((void *)value, tmplen, req->master_secret, + &nlen); req->master_secret_set = 1; break; @@ -355,7 +351,8 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) /* check validity */ if (!valid_hostname(req->hostname)) { - oclog(ws, LOG_HTTP_DEBUG, "Skipping invalid hostname '%s'", req->hostname); + oclog(ws, LOG_HTTP_DEBUG, + "Skipping invalid hostname '%s'", req->hostname); req->hostname[0] = 0; } @@ -368,8 +365,7 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) memcpy(req->devtype, value, value_length); req->devtype[value_length] = 0; - oclog(ws, LOG_DEBUG, - "Device-type: '%s'", value); + oclog(ws, LOG_DEBUG, "Device-type: '%s'", value); break; case HEADER_PLATFORM: if (value_length + 1 > sizeof(req->devplatform)) { @@ -381,22 +377,20 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) if (strncasecmp(value, "apple-ios", 9) == 0 || strncasecmp(value, "android", 7) == 0) { - if (strncasecmp(value, "apple-ios", 9) == 0) req->is_ios = 1; - oclog(ws, LOG_DEBUG, - "Platform: '%s' (mobile)", value); + oclog(ws, LOG_DEBUG, "Platform: '%s' (mobile)", value); req->is_mobile = 1; } else { - oclog(ws, LOG_DEBUG, - "Platform: '%s'", value); + oclog(ws, LOG_DEBUG, "Platform: '%s'", value); } break; case HEADER_SUPPORT_SPNEGO: /* Switch to GSSAPI if the client supports it, but only * if we haven't already authenticated with a certificate */ - if (!((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && ws->cert_auth_ok != 0)) { + if (!((ws->selected_auth->type & AUTH_TYPE_CERTIFICATE) && + ws->cert_auth_ok != 0)) { ws_switch_auth_to(ws, AUTH_TYPE_GSSAPI); req->spnego_set = 1; } @@ -410,52 +404,70 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) break; case HEADER_USER_AGENT: if (value_length + 1 > MAX_AGENT_NAME) { - memcpy(req->user_agent, value, MAX_AGENT_NAME-1); - req->user_agent[MAX_AGENT_NAME-1] = 0; + memcpy(req->user_agent, value, MAX_AGENT_NAME - 1); + req->user_agent[MAX_AGENT_NAME - 1] = 0; } else { memcpy(req->user_agent, value, value_length); req->user_agent[value_length] = 0; } - oclog(ws, LOG_DEBUG, - "User-agent: '%s'", req->user_agent); + oclog(ws, LOG_DEBUG, "User-agent: '%s'", req->user_agent); + + if (strncasecmp(req->user_agent, "Open AnyConnect VPN Agent v", + 27) == 0) { + unsigned int version = atoi(&req->user_agent[27]); - if (strncasecmp(req->user_agent, "Open AnyConnect VPN Agent v", 27) == 0) { - unsigned version = atoi(&req->user_agent[27]); if (version <= 3) { - oclog(ws, LOG_DEBUG, "Detected OpenConnect v3 or older"); + oclog(ws, LOG_DEBUG, + "Detected OpenConnect v3 or older"); req->user_agent_type = AGENT_OPENCONNECT_V3; } else { - oclog(ws, LOG_DEBUG, "Detected OpenConnect v4 or newer"); + oclog(ws, LOG_DEBUG, + "Detected OpenConnect v4 or newer"); req->user_agent_type = AGENT_OPENCONNECT; } - } else if (strncasecmp(req->user_agent, "Cisco AnyConnect VPN Agent for Apple", 36) == 0) { - oclog(ws, LOG_DEBUG, "Detected Cisco AnyConnect on iOS"); + } else if (strncasecmp(req->user_agent, + "Cisco AnyConnect VPN Agent for Apple", + 36) == 0) { + oclog(ws, LOG_DEBUG, + "Detected Cisco AnyConnect on iOS"); req->user_agent_type = AGENT_ANYCONNECT; req->is_ios = 1; - } else if (strncasecmp(req->user_agent, "OpenConnect VPN Agent", 21) == 0) { - oclog(ws, LOG_DEBUG, "Detected OpenConnect v4 or newer"); + } else if (strncasecmp(req->user_agent, "OpenConnect VPN Agent", + 21) == 0) { + oclog(ws, LOG_DEBUG, + "Detected OpenConnect v4 or newer"); req->user_agent_type = AGENT_OPENCONNECT; - } else if (strncasecmp(req->user_agent, "Cisco AnyConnect", 16) == 0) { + } else if (strncasecmp(req->user_agent, "Cisco AnyConnect", + 16) == 0) { oclog(ws, LOG_DEBUG, "Detected Cisco AnyConnect"); req->user_agent_type = AGENT_ANYCONNECT; - } else if (strncasecmp(req->user_agent, "AnyConnect-compatible OpenConnect", 33) == 0) { - oclog(ws, LOG_DEBUG, "Detected OpenConnect v9 or newer"); + } else if (strncasecmp(req->user_agent, + "AnyConnect-compatible OpenConnect", + 33) == 0) { + oclog(ws, LOG_DEBUG, + "Detected OpenConnect v9 or newer"); req->user_agent_type = AGENT_OPENCONNECT; - } else if (strncasecmp(req->user_agent, "AnyConnect", 10) == 0) { + } else if (strncasecmp(req->user_agent, "AnyConnect", 10) == + 0) { oclog(ws, LOG_DEBUG, "Detected Cisco AnyConnect"); req->user_agent_type = AGENT_ANYCONNECT; - } else if (strncasecmp(req->user_agent, "Clavister OneConnect VPN", 24) == 0) { + } else if (strncasecmp(req->user_agent, + "Clavister OneConnect VPN", 24) == 0) { oclog(ws, LOG_DEBUG, "Detected Clavister OneConnect"); req->user_agent_type = AGENT_OPENCONNECT_CLAVISTER; - } else if (strncasecmp(req->user_agent, "AnyLink Secure Client", 21) == 0) { + } else if (strncasecmp(req->user_agent, "AnyLink Secure Client", + 21) == 0) { oclog(ws, LOG_DEBUG, "Detected AnyLink"); req->user_agent_type = AGENT_ANYLINK; - } else if (strncasecmp(req->user_agent, "Cisco SVC IPPhone Client", 24) == 0) { - oclog(ws, LOG_DEBUG, "Detected Cisco SVC IPPhone Client"); + } else if (strncasecmp(req->user_agent, + "Cisco SVC IPPhone Client", 24) == 0) { + oclog(ws, LOG_DEBUG, + "Detected Cisco SVC IPPhone Client"); req->user_agent_type = AGENT_SVC_IPPHONE; } else { - oclog(ws, LOG_DEBUG, "Unknown client (%s)", req->user_agent); + oclog(ws, LOG_DEBUG, "Unknown client (%s)", + req->user_agent); } break; @@ -463,11 +475,13 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) str = (char *)value; p = strstr(str, DTLS_PROTO_INDICATOR); - if (p != NULL && (p[sizeof(DTLS_PROTO_INDICATOR)-1] == 0 || p[sizeof(DTLS_PROTO_INDICATOR)-1] == ':')) { + if (p != NULL && (p[sizeof(DTLS_PROTO_INDICATOR) - 1] == 0 || + p[sizeof(DTLS_PROTO_INDICATOR) - 1] == ':')) { /* OpenConnect DTLS setup was detected. */ if (WSCONFIG(ws)->dtls_psk) { req->use_psk = 1; - req->master_secret_set = 1; /* we don't need it */ + req->master_secret_set = + 1; /* we don't need it */ req->selected_ciphersuite = NULL; break; } @@ -489,19 +503,26 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) while ((token = strtok(str, ":")) != NULL) { for (i = 0; i < ARRAY_SIZE(ciphersuites); i++) { - if (strcmp(token, ciphersuites[i].oc_name) == 0) { + if (strcmp(token, ciphersuites[i].oc_name) == + 0) { if (cand == NULL || - cand->server_prio < ciphersuites[i].server_prio || - (want_cipher != -1 && want_cipher == ciphersuites[i].gnutls_cipher && - want_mac == ciphersuites[i].gnutls_mac)) { - cand = - &ciphersuites[i]; + cand->server_prio < + ciphersuites[i].server_prio || + (want_cipher != -1 && + want_cipher == + ciphersuites[i] + .gnutls_cipher && + want_mac == ciphersuites[i] + .gnutls_mac)) { + cand = &ciphersuites[i]; /* if our candidate matches the TLS session * ciphersuite, we are finished */ if (want_cipher != -1) { - if (want_cipher == cand->gnutls_cipher && - want_mac == cand->gnutls_mac) + if (want_cipher == + cand->gnutls_cipher && + want_mac == + cand->gnutls_mac) goto ciphersuite_finish; } } @@ -509,21 +530,22 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) } str = NULL; } - ciphersuite_finish: - req->selected_ciphersuite = cand; +ciphersuite_finish: + req->selected_ciphersuite = cand; break; case HEADER_DTLS12_CIPHERSUITE: if (req->use_psk || !WSCONFIG(ws)->dtls_legacy) break; - /* in gnutls 3.6.0+ there is a regression which makes + /* in gnutls 3.6.0+ there is a regression which makes * anyconnect's openssl fail: https://gitlab.com/gnutls/gnutls/merge_requests/868 */ #ifdef gnutls_check_version_numeric if (req->user_agent_type == AGENT_ANYCONNECT && - (!gnutls_check_version_numeric(3,6,6) && - (!gnutls_check_version_numeric(3,3,0) || gnutls_check_version_numeric(3,6,0)))) { + (!gnutls_check_version_numeric(3, 6, 6) && + (!gnutls_check_version_numeric(3, 3, 0) || + gnutls_check_version_numeric(3, 6, 0)))) { break; } #endif @@ -531,11 +553,13 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) str = (char *)value; p = strstr(str, DTLS_PROTO_INDICATOR); - if (p != NULL && (p[sizeof(DTLS_PROTO_INDICATOR)-1] == 0 || p[sizeof(DTLS_PROTO_INDICATOR)-1] == ':')) { + if (p != NULL && (p[sizeof(DTLS_PROTO_INDICATOR) - 1] == 0 || + p[sizeof(DTLS_PROTO_INDICATOR) - 1] == ':')) { /* OpenConnect DTLS setup was detected. */ if (WSCONFIG(ws)->dtls_psk) { req->use_psk = 1; - req->master_secret_set = 1; /* we don't need it */ + req->master_secret_set = + 1; /* we don't need it */ req->selected_ciphersuite = NULL; break; } @@ -554,19 +578,27 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) while ((token = strtok(str, ":")) != NULL) { for (i = 0; i < ARRAY_SIZE(ciphersuites12); i++) { - if (strcmp(token, ciphersuites12[i].oc_name) == 0) { + if (strcmp(token, ciphersuites12[i].oc_name) == + 0) { if (cand == NULL || - cand->server_prio < ciphersuites12[i].server_prio || - (want_cipher != -1 && want_cipher == ciphersuites12[i].gnutls_cipher && - want_mac == ciphersuites12[i].gnutls_mac)) { - cand = - &ciphersuites12[i]; + cand->server_prio < + ciphersuites12[i] + .server_prio || + (want_cipher != -1 && + want_cipher == + ciphersuites12[i] + .gnutls_cipher && + want_mac == ciphersuites12[i] + .gnutls_mac)) { + cand = &ciphersuites12[i]; /* if our candidate matches the TLS session * ciphersuite, we are finished */ if (want_cipher != -1) { - if (want_cipher == cand->gnutls_cipher && - want_mac == cand->gnutls_mac) + if (want_cipher == + cand->gnutls_cipher && + want_mac == + cand->gnutls_mac) goto ciphersuite12_finish; } } @@ -574,10 +606,10 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) } str = NULL; } - ciphersuite12_finish: - req->selected_ciphersuite = cand; +ciphersuite12_finish: + req->selected_ciphersuite = cand; - if (req->selected_ciphersuite == NULL && saved_ciphersuite) + if (req->selected_ciphersuite == NULL && saved_ciphersuite) req->selected_ciphersuite = saved_ciphersuite; break; @@ -596,18 +628,18 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) str = (char *)value; while ((token = strtok(str, ",")) != NULL) { for (i = 0; i < ARRAY_SIZE(comp_methods); i++) { - if (strcasecmp(token, comp_methods[i].name) == 0) { + if (strcasecmp(token, comp_methods[i].name) == + 0) { if (comp_cand == NULL || comp_cand->server_prio < - comp_methods[i].server_prio) { - comp_cand = - &comp_methods[i]; + comp_methods[i].server_prio) { + comp_cand = &comp_methods[i]; } } } str = NULL; } - *selected_comp = comp_cand; + *selected_comp = comp_cand; break; #endif @@ -651,23 +683,24 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) /* we allow for BASE64_DECODE_LENGTH reporting few bytes more * than the expected */ nlen = BASE64_DECODE_LENGTH(tmplen); - if (nlen < sizeof(ws->cookie) || nlen > sizeof(ws->cookie)+8) + if (nlen < sizeof(ws->cookie) || + nlen > sizeof(ws->cookie) + 8) return; /* we assume that - should be build time optimized */ - if (sizeof(ws->buffer) < sizeof(ws->cookie)+8) + if (sizeof(ws->buffer) < sizeof(ws->cookie) + 8) abort(); - ret = - oc_base64_decode((uint8_t*)p, tmplen, - ws->buffer, &nlen); + ret = oc_base64_decode((uint8_t *)p, tmplen, + ws->buffer, &nlen); if (ret == 0 || nlen != sizeof(ws->cookie)) { oclog(ws, LOG_INFO, "could not decode cookie: %.*s", tmplen, p); ws->cookie_set = 0; } else { - memcpy(ws->cookie, ws->buffer, sizeof(ws->cookie)); + memcpy(ws->cookie, ws->buffer, + sizeof(ws->cookie)); ws->auth_state = S_AUTH_COOKIE; ws->cookie_set = 1; } @@ -680,9 +713,8 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) } nlen = BASE64_DECODE_LENGTH(tmplen); - ret = - oc_base64_decode((uint8_t*)p, tmplen, - ws->sid, &nlen); + ret = oc_base64_decode((uint8_t *)p, tmplen, + ws->sid, &nlen); if (ret == 0 || nlen != sizeof(ws->sid)) { oclog(ws, LOG_SENSITIVE, "could not decode sid: %.*s", @@ -700,24 +732,24 @@ void header_value_check(struct worker_st *ws, struct http_req_st *req) break; } - cleanup: +cleanup: talloc_free(value); } url_handler_fn http_get_url_handler(const char *url) { const struct known_urls_st *p; - unsigned len = strlen(url); + unsigned int len = strlen(url); p = known_urls; do { if (p->url != NULL) { if ((len == p->url_size && strcmp(p->url, url) == 0) || - (len >= p->url_size - && strncmp(p->url, url, p->url_size) == 0 - && (p->partial_match != 0 - || url[p->url_size] == '/' - || url[p->url_size] == '?'))) + (len >= p->url_size && + strncmp(p->url, url, p->url_size) == 0 && + (p->partial_match != 0 || + url[p->url_size] == '/' || + url[p->url_size] == '?'))) return p->get_handler; } p++; @@ -726,25 +758,28 @@ url_handler_fn http_get_url_handler(const char *url) return NULL; } -url_handler_fn http_post_known_service_check(struct worker_st *ws, const char *url) +url_handler_fn http_post_known_service_check(struct worker_st *ws, + const char *url) { const struct known_urls_st *p; - unsigned len = strlen(url); - unsigned i; + unsigned int len = strlen(url); + unsigned int i; p = known_urls; do { if (p->url != NULL) { if ((len == p->url_size && strcmp(p->url, url) == 0) || - (len > p->url_size && strncmp(p->url, url, p->url_size) == 0 - && p->partial_match == 0 && url[p->url_size] == '?')) + (len > p->url_size && + strncmp(p->url, url, p->url_size) == 0 && + p->partial_match == 0 && url[p->url_size] == '?')) return p->post_handler; } p++; } while (p->url != NULL); - for (i=0;ikkdcp_size;i++) { - if (WSCONFIG(ws)->kkdcp[i].url && strcmp(WSCONFIG(ws)->kkdcp[i].url, url) == 0) + for (i = 0; i < WSCONFIG(ws)->kkdcp_size; i++) { + if (WSCONFIG(ws)->kkdcp[i].url && + strcmp(WSCONFIG(ws)->kkdcp[i].url, url) == 0) return post_kkdcp_handler; } @@ -757,13 +792,13 @@ url_handler_fn http_post_url_handler(struct worker_st *ws, const char *url) h = http_post_known_service_check(ws, url); if (h == NULL && ws->auth_state == S_AUTH_INACTIVE) { - return post_auth_handler; + return post_auth_handler; } return h; } -int http_url_cb(llhttp_t * parser, const char *at, size_t length) +int http_url_cb(llhttp_t *parser, const char *at, size_t length) { struct worker_st *ws = parser->data; struct http_req_st *req = &ws->req; @@ -779,7 +814,7 @@ int http_url_cb(llhttp_t * parser, const char *at, size_t length) return 0; } -int http_header_field_cb(llhttp_t * parser, const char *at, size_t length) +int http_header_field_cb(llhttp_t *parser, const char *at, size_t length) { struct worker_st *ws = parser->data; struct http_req_st *req = &ws->req; @@ -815,7 +850,7 @@ static void header_check(struct http_req_st *req) req->next_header = 0; } -int http_header_value_cb(llhttp_t * parser, const char *at, size_t length) +int http_header_value_cb(llhttp_t *parser, const char *at, size_t length) { struct worker_st *ws = parser->data; struct http_req_st *req = &ws->req; @@ -835,7 +870,7 @@ int http_header_value_cb(llhttp_t * parser, const char *at, size_t length) return 0; } -int http_header_complete_cb(llhttp_t * parser) +int http_header_complete_cb(llhttp_t *parser) { struct worker_st *ws = parser->data; struct http_req_st *req = &ws->req; @@ -843,19 +878,20 @@ int http_header_complete_cb(llhttp_t * parser) /* handle header value */ header_value_check(ws, req); - if ((ws->selected_auth->type & AUTH_TYPE_GSSAPI) && ws->auth_state == S_AUTH_INACTIVE && - req->spnego_set == 0) { + if ((ws->selected_auth->type & AUTH_TYPE_GSSAPI) && + ws->auth_state == S_AUTH_INACTIVE && req->spnego_set == 0) { /* client retried getting the form without the SPNEGO header, probably * wants a fallback authentication method */ if (ws_switch_auth_to_next(ws) == 0) - oclog(ws, LOG_INFO, "no fallback from gssapi authentication"); + oclog(ws, LOG_INFO, + "no fallback from gssapi authentication"); } req->headers_complete = 1; return 0; } -int http_message_complete_cb(llhttp_t * parser) +int http_message_complete_cb(llhttp_t *parser) { struct worker_st *ws = parser->data; struct http_req_st *req = &ws->req; @@ -864,7 +900,7 @@ int http_message_complete_cb(llhttp_t * parser) return 0; } -int http_body_cb(llhttp_t * parser, const char *at, size_t length) +int http_body_cb(llhttp_t *parser, const char *at, size_t length) { struct worker_st *ws = parser->data; struct http_req_st *req = &ws->req; @@ -882,13 +918,13 @@ int http_body_cb(llhttp_t * parser, const char *at, size_t length) return 0; } -void http_req_init(worker_st * ws) +void http_req_init(worker_st *ws) { str_init(&ws->req.header, ws); str_init(&ws->req.value, ws); } -void http_req_reset(worker_st * ws) +void http_req_reset(worker_st *ws) { ws->req.headers_complete = 0; ws->req.message_complete = 0; @@ -901,7 +937,7 @@ void http_req_reset(worker_st * ws) str_reset(&ws->req.value); } -void http_req_deinit(worker_st * ws) +void http_req_deinit(worker_st *ws) { http_req_reset(ws); str_clear(&ws->req.header); @@ -917,15 +953,14 @@ void http_req_deinit(worker_st * ws) * There are security tools that flag the server as a security risk. * These are added to help users comply with security best practices. */ -int add_owasp_headers(worker_st * ws) +int add_owasp_headers(worker_st *ws) { - unsigned i; + unsigned int i; - for (i=0; i < GETCONFIG(ws)->included_http_headers_size; i++) - { - if (cstp_printf(ws, "%s", GETCONFIG(ws)->included_http_headers[i]) < 0 || - cstp_puts(ws, "\r\n") < 0) - { + for (i = 0; i < GETCONFIG(ws)->included_http_headers_size; i++) { + if (cstp_printf(ws, "%s", + GETCONFIG(ws)->included_http_headers[i]) < 0 || + cstp_puts(ws, "\r\n") < 0) { return -1; } } diff --git a/src/worker-kkdcp.c b/src/worker-kkdcp.c index d8dbcbfb..3e73b34f 100644 --- a/src/worker-kkdcp.c +++ b/src/worker-kkdcp.c @@ -30,13 +30,15 @@ #ifdef HAVE_GSSAPI -int der_decode(const uint8_t *der, unsigned der_size, uint8_t *out, unsigned *out_size, - char *realm, unsigned realm_size, int *error) +int der_decode(const uint8_t *der, unsigned int der_size, uint8_t *out, + unsigned int *out_size, char *realm, unsigned int realm_size, + int *error) { int ret, len; asn1_node c2 = NULL; - ret = asn1_create_element(_kkdcp_pkix1_asn, "KKDCP.KDC-PROXY-MESSAGE", &c2); + ret = asn1_create_element(_kkdcp_pkix1_asn, "KKDCP.KDC-PROXY-MESSAGE", + &c2); if (ret != ASN1_SUCCESS) { *error = ret; return -1; @@ -66,18 +68,19 @@ int der_decode(const uint8_t *der, unsigned der_size, uint8_t *out, unsigned *ou } ret = 0; - cleanup: +cleanup: asn1_delete_structure(&c2); return ret; - } -int der_encode_inplace(uint8_t *raw, unsigned *raw_size, unsigned max_size, int *error) +int der_encode_inplace(uint8_t *raw, unsigned int *raw_size, + unsigned int max_size, int *error) { int ret, len; asn1_node c2 = NULL; - ret = asn1_create_element(_kkdcp_pkix1_asn, "KKDCP.KDC-PROXY-MESSAGE", &c2); + ret = asn1_create_element(_kkdcp_pkix1_asn, "KKDCP.KDC-PROXY-MESSAGE", + &c2); if (ret != ASN1_SUCCESS) { *error = ret; return -1; @@ -104,20 +107,19 @@ int der_encode_inplace(uint8_t *raw, unsigned *raw_size, unsigned max_size, int *raw_size = len; ret = 0; - cleanup: +cleanup: asn1_delete_structure(&c2); return ret; - } /* max UDP size */ #define KKDCP_READ_TIMEOUT 20 -#define BUF_SIZE 64*1024 -int post_kkdcp_handler(worker_st *ws, unsigned http_ver) +#define BUF_SIZE 64 * 1024 +int post_kkdcp_handler(worker_st *ws, unsigned int http_ver) { int ret, e, fd = -1; struct http_req_st *req = &ws->req; - unsigned i, length; + unsigned int i, length; kkdcp_st *kkdcp = NULL; uint8_t *buf; uint32_t mlength; @@ -127,25 +129,30 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) oclog(ws, LOG_INFO, "Processing KKDCP request"); - for (i=0;ikkdcp_size;i++) { - if (WSCONFIG(ws)->kkdcp[i].url && strcmp(WSCONFIG(ws)->kkdcp[i].url, req->url) == 0) { + for (i = 0; i < WSCONFIG(ws)->kkdcp_size; i++) { + if (WSCONFIG(ws)->kkdcp[i].url && + strcmp(WSCONFIG(ws)->kkdcp[i].url, req->url) == 0) { kkdcp = &WSCONFIG(ws)->kkdcp[i]; break; } } if (kkdcp == NULL) { - oclog(ws, LOG_HTTP_DEBUG, "could not figure kkdcp handler for %s", req->url); + oclog(ws, LOG_HTTP_DEBUG, + "could not figure kkdcp handler for %s", req->url); return -1; } if (req->body_length == 0) { - oclog(ws, LOG_HTTP_DEBUG, "empty body length for kkdcp handler %s", req->url); + oclog(ws, LOG_HTTP_DEBUG, + "empty body length for kkdcp handler %s", req->url); return -1; } ws_add_score_to_ip(ws, WSCONFIG(ws)->ban_points_kkdcp, 0, 0); - oclog(ws, LOG_HTTP_DEBUG, "HTTP processing kkdcp framed request: %u bytes", (unsigned)req->body_length); + oclog(ws, LOG_HTTP_DEBUG, + "HTTP processing kkdcp framed request: %u bytes", + (unsigned int)req->body_length); length = BUF_SIZE; buf = talloc_size(ws, length); @@ -154,9 +161,11 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) return -1; } - ret = der_decode((uint8_t*)req->body, req->body_length, buf, &length, realm, sizeof(realm), &e); + ret = der_decode((uint8_t *)req->body, req->body_length, buf, &length, + realm, sizeof(realm), &e); if (ret < 0) { - oclog(ws, LOG_ERR, "kkdcp: DER decoding error: %s", asn1_strerror(e)); + oclog(ws, LOG_ERR, "kkdcp: DER decoding error: %s", + asn1_strerror(e)); reason = "kkdcp: DER decoding error"; goto fail; } @@ -165,7 +174,7 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) if (realm[0] != 0 && kkdcp->realms_size > 1) { oclog(ws, LOG_DEBUG, "kkdcp: client asked for '%s'", realm); - for (i=0;irealms_size;i++) { + for (i = 0; i < kkdcp->realms_size; i++) { if (strcmp(kkdcp->realms[i].realm, realm) == 0) { kr = &kkdcp->realms[i]; break; @@ -181,7 +190,7 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) goto fail; } - ret = connect(fd, (struct sockaddr*)&kr->addr, kr->addr_len); + ret = connect(fd, (struct sockaddr *)&kr->addr, kr->addr_len); if (ret == -1) { e = errno; oclog(ws, LOG_ERR, "kkdcp: connect error: %s", strerror(e)); @@ -189,14 +198,17 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) goto fail; } - oclog(ws, LOG_HTTP_DEBUG, "HTTP sending kkdcp request: %u bytes", (unsigned)length); + oclog(ws, LOG_HTTP_DEBUG, "HTTP sending kkdcp request: %u bytes", + (unsigned int)length); ret = send(fd, buf, length, 0); if (ret != length) { if (ret == -1) { e = errno; - oclog(ws, LOG_ERR, "kkdcp: send error: %s", strerror(e)); + oclog(ws, LOG_ERR, "kkdcp: send error: %s", + strerror(e)); } else { - oclog(ws, LOG_ERR, "kkdcp: send error: only %d were sent", ret); + oclog(ws, LOG_ERR, + "kkdcp: send error: only %d were sent", ret); } reason = "kkdcp: error sending to server"; goto fail; @@ -206,7 +218,8 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) ret = recv(fd, buf, BUF_SIZE, 0); if (ret == -1) { e = errno; - oclog(ws, LOG_ERR, "kkdcp: recv error: %s", strerror(e)); + oclog(ws, LOG_ERR, "kkdcp: recv error: %s", + strerror(e)); reason = "kkdcp: error receiving from server"; goto fail; } @@ -216,30 +229,35 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) ret = recv(fd, buf, 4, 0); if (ret < 4) { e = errno; - oclog(ws, LOG_ERR, "kkdcp: recv error: %s", strerror(e)); + oclog(ws, LOG_ERR, "kkdcp: recv error: %s", + strerror(e)); reason = "kkdcp: error receiving from server"; goto fail; } memcpy(&mlength, buf, 4); mlength = ntohl(mlength); - if (mlength >= BUF_SIZE-4) { - oclog(ws, LOG_ERR, "kkdcp: too long message (%d bytes)", (int)mlength); + if (mlength >= BUF_SIZE - 4) { + oclog(ws, LOG_ERR, "kkdcp: too long message (%d bytes)", + (int)mlength); reason = "kkdcp: error receiving from server"; goto fail; } - ret = force_read_timeout(fd, buf+4, mlength, KKDCP_READ_TIMEOUT); + ret = force_read_timeout(fd, buf + 4, mlength, + KKDCP_READ_TIMEOUT); if (ret == -1) { e = errno; - oclog(ws, LOG_ERR, "kkdcp: recv error: %s", strerror(e)); + oclog(ws, LOG_ERR, "kkdcp: recv error: %s", + strerror(e)); reason = "kkdcp: error receiving from server"; goto fail; } length = ret + 4; } - oclog(ws, LOG_HTTP_DEBUG, "HTTP processing kkdcp reply: %u bytes", (unsigned)length); + oclog(ws, LOG_HTTP_DEBUG, "HTTP processing kkdcp reply: %u bytes", + (unsigned int)length); cstp_cork(ws); ret = cstp_printf(ws, "HTTP/1.%u 200 OK\r\n", http_ver); @@ -247,23 +265,22 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) goto fail; } - ret = - cstp_puts(ws, "Content-Type: application/kerberos\r\n"); + ret = cstp_puts(ws, "Content-Type: application/kerberos\r\n"); if (ret < 0) { goto fail; } ret = der_encode_inplace(buf, &length, BUF_SIZE, &e); if (ret < 0) { - oclog(ws, LOG_ERR, "kkdcp: DER encoding error: %s", asn1_strerror(e)); + oclog(ws, LOG_ERR, "kkdcp: DER encoding error: %s", + asn1_strerror(e)); reason = "kkdcp: DER encoding error"; goto fail; } - oclog(ws, LOG_HTTP_DEBUG, "HTTP sending kkdcp framed reply: %u bytes", (unsigned)length); - ret = - cstp_printf(ws, "Content-Length: %u\r\n", - (unsigned int)length); + oclog(ws, LOG_HTTP_DEBUG, "HTTP sending kkdcp framed reply: %u bytes", + (unsigned int)length); + ret = cstp_printf(ws, "Content-Length: %u\r\n", (unsigned int)length); if (ret < 0) { goto fail; } @@ -295,13 +312,11 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) ret = 0; goto cleanup; - fail: - (void)cstp_printf(ws, - "HTTP/1.%u 502 %s\r\n\r\n", - http_ver, reason); +fail: + (void)cstp_printf(ws, "HTTP/1.%u 502 %s\r\n\r\n", http_ver, reason); ret = -1; - cleanup: +cleanup: talloc_free(buf); if (fd != -1) close(fd); @@ -310,7 +325,7 @@ int post_kkdcp_handler(worker_st *ws, unsigned http_ver) #else -int post_kkdcp_handler(worker_st *ws, unsigned http_ver) +int post_kkdcp_handler(worker_st *ws, unsigned int http_ver) { return -1; } diff --git a/src/worker-latency.c b/src/worker-latency.c index 8b781217..de30372d 100644 --- a/src/worker-latency.c +++ b/src/worker-latency.c @@ -28,16 +28,17 @@ #include #include - ssize_t dtls_pull_latency(gnutls_transport_ptr_t ptr, void *data, size_t size) { int err; dtls_transport_ptr *p = ptr; + p->rx_time.tv_sec = 0; p->rx_time.tv_nsec = 0; if (p->msg) { ssize_t need = p->msg->data.len; + if (need > size) { need = size; } @@ -49,34 +50,34 @@ ssize_t dtls_pull_latency(gnutls_transport_ptr_t ptr, void *data, size_t size) } char controlbuf[1024]; - struct cmsghdr * cmsg; + struct cmsghdr *cmsg; struct iovec io = { .iov_base = data, .iov_len = size, }; - struct msghdr hdr = { - .msg_iov = &io, - .msg_iovlen = 1, - .msg_control = controlbuf, - .msg_controllen = sizeof(controlbuf) - }; + struct msghdr hdr = { .msg_iov = &io, + .msg_iovlen = 1, + .msg_control = controlbuf, + .msg_controllen = sizeof(controlbuf) }; err = recvmsg(p->fd, &hdr, 0); if (err >= 0) { - for (cmsg = CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&hdr, cmsg)) { + for (cmsg = CMSG_FIRSTHDR(&hdr); cmsg != NULL; + cmsg = CMSG_NXTHDR(&hdr, cmsg)) { struct scm_timestamping *tss = NULL; - if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_TIMESTAMPING) { + + if (cmsg->cmsg_level != SOL_SOCKET || + cmsg->cmsg_type != SCM_TIMESTAMPING) { continue; } - tss = (struct scm_timestamping *) CMSG_DATA(cmsg); + tss = (struct scm_timestamping *)CMSG_DATA(cmsg); p->rx_time = tss->ts[0]; } } return err; } - -void send_latency_stats_delta_to_main(worker_st * ws, time_t now) +void send_latency_stats_delta_to_main(worker_st *ws, time_t now) { LatencyStatsDelta msg = LATENCY_STATS_DELTA__INIT; @@ -93,42 +94,49 @@ void send_latency_stats_delta_to_main(worker_st * ws, time_t now) ws->latency.sample_set_count = 0; send_msg_to_main(ws, CMD_LATENCY_STATS_DELTA, &msg, - (pack_size_func) latency_stats_delta__get_packed_size, - (pack_func) latency_stats_delta__pack); + (pack_size_func)latency_stats_delta__get_packed_size, + (pack_func)latency_stats_delta__pack); ws->latency.last_stats_msg = now; } -static int greater_than(const void * a, const void * b) +static int greater_than(const void *a, const void *b) { - const unsigned long lhs = *(const unsigned long*)a; - const unsigned long rhs = *(const unsigned long*)b; - return rhs - lhs; + const unsigned long lhs = *(const unsigned long *)a; + const unsigned long rhs = *(const unsigned long *)b; + + return rhs - lhs; } -void capture_latency_sample(struct worker_st* ws, struct timespec *processing_start_time) +void capture_latency_sample(struct worker_st *ws, + struct timespec *processing_start_time) { struct timespec now; + gettime_realtime(&now); - unsigned long sample = (unsigned long)timespec_sub_us(&now, processing_start_time); + unsigned long sample = + (unsigned long)timespec_sub_us(&now, processing_start_time); + if (ws->latency.next_sample == LATENCY_SAMPLE_SIZE) { unsigned long median; uint64_t total = 0; + long double sum_of_squares = 0; uint64_t mean = 0; uint64_t rms = 0; int i; ws->latency.next_sample = 0; - qsort(ws->latency.samples, LATENCY_SAMPLE_SIZE, sizeof(ws->latency.samples[0]), greater_than); + qsort(ws->latency.samples, LATENCY_SAMPLE_SIZE, + sizeof(ws->latency.samples[0]), greater_than); median = ws->latency.samples[LATENCY_SAMPLE_SIZE - 1]; - for (i = 0; i < LATENCY_SAMPLE_SIZE; i ++) { + for (i = 0; i < LATENCY_SAMPLE_SIZE; i++) { total += ws->latency.samples[i]; } mean = total / LATENCY_SAMPLE_SIZE; - for (i = 0; i < LATENCY_SAMPLE_SIZE; i ++) { + for (i = 0; i < LATENCY_SAMPLE_SIZE; i++) { long double delta = (long double)ws->latency.samples[i]; delta -= mean; sum_of_squares += delta * delta; @@ -138,8 +146,7 @@ void capture_latency_sample(struct worker_st* ws, struct timespec *processing_st (ws->latency.median_total) += median; (ws->latency.rms_total) += rms; - (ws->latency.sample_set_count) ++; - } - ws->latency.samples[(ws->latency.next_sample)++] = sample; - + (ws->latency.sample_set_count)++; + } + ws->latency.samples[(ws->latency.next_sample)++] = sample; } diff --git a/src/worker-latency.h b/src/worker-latency.h index a41c94a5..14f6242b 100644 --- a/src/worker-latency.h +++ b/src/worker-latency.h @@ -18,10 +18,11 @@ * along with this program. If not, see . */ #ifndef OC_WORKER_LATENCY_H -# define OC_WORKER_LATENCY_H +#define OC_WORKER_LATENCY_H ssize_t dtls_pull_latency(gnutls_transport_ptr_t ptr, void *data, size_t size); -void send_latency_stats_delta_to_main(worker_st * ws, time_t now); -void capture_latency_sample(struct worker_st* ws, struct timespec *processing_start_time); +void send_latency_stats_delta_to_main(worker_st *ws, time_t now); +void capture_latency_sample(struct worker_st *ws, + struct timespec *processing_start_time); #endif diff --git a/src/worker-log.c b/src/worker-log.c index 978af143..47cc6c07 100644 --- a/src/worker-log.c +++ b/src/worker-log.c @@ -31,15 +31,15 @@ #include "sec-mod.h" #include "log.h" -void __attribute__ ((format(printf, 3, 4))) - _oclog(const worker_st * ws, int priority, const char *fmt, ...) +void __attribute__((format(printf, 3, 4))) +_oclog(const worker_st *ws, int priority, const char *fmt, ...) { char buf[512]; - char name[MAX_USERNAME_SIZE+MAX_HOSTNAME_SIZE+3]; - const char* ip; + char name[MAX_USERNAME_SIZE + MAX_HOSTNAME_SIZE + 3]; + const char *ip; va_list args; int log_prio; - unsigned have_vhosts; + unsigned int have_vhosts; int syslog_prio; if (ws->vhost) @@ -59,24 +59,28 @@ void __attribute__ ((format(printf, 3, 4))) have_vhosts = HAVE_VHOSTS(ws); if (have_vhosts && ws->username[0] != 0) { - snprintf(name, sizeof(name), "[%s%s]", PREFIX_VHOST(ws->vhost), ws->username); - } else if (have_vhosts && ws->username[0] == 0 && ws->vhost && ws->vhost->name) { - snprintf(name, sizeof(name), "[vhost:%s]", VHOSTNAME(ws->vhost)); + snprintf(name, sizeof(name), "[%s%s]", PREFIX_VHOST(ws->vhost), + ws->username); + } else if (have_vhosts && ws->username[0] == 0 && ws->vhost && + ws->vhost->name) { + snprintf(name, sizeof(name), "[vhost:%s]", + VHOSTNAME(ws->vhost)); } else if (ws->username[0] != 0) { snprintf(name, sizeof(name), "[%s]", ws->username); } else name[0] = 0; - _oc_syslog(syslog_prio, "worker%s: %s %s", name, ip?ip:"[unknown]", buf); + _oc_syslog(syslog_prio, "worker%s: %s %s", name, ip ? ip : "[unknown]", + buf); } -void oclog_hex(const worker_st* ws, int priority, - const char *prefix, uint8_t* bin, unsigned bin_size, unsigned b64) +void oclog_hex(const worker_st *ws, int priority, const char *prefix, + uint8_t *bin, unsigned int bin_size, unsigned int b64) { char buf[512]; int ret; size_t buf_size; - gnutls_datum_t data = {bin, bin_size}; + gnutls_datum_t data = { bin, bin_size }; int log_prio; if (ws->vhost) @@ -88,7 +92,8 @@ void oclog_hex(const worker_st* ws, int priority, return; if (b64) { - oc_base64_encode((char*)bin, bin_size, (char*)buf, sizeof(buf)); + oc_base64_encode((char *)bin, bin_size, (char *)buf, + sizeof(buf)); } else { buf_size = sizeof(buf); ret = gnutls_hex_encode(&data, buf, &buf_size); @@ -98,4 +103,3 @@ void oclog_hex(const worker_st* ws, int priority, _oclog(ws, priority, "%s %s", prefix, buf); } - diff --git a/src/worker-misc.c b/src/worker-misc.c index f3e92906..57b5e328 100644 --- a/src/worker-misc.c +++ b/src/worker-misc.c @@ -44,12 +44,13 @@ #include #ifdef HAVE_SIGALTSTACK -# include -# include +#include +#include #endif /* recv from the new file descriptor and make sure we have a valid packet */ -static unsigned recv_from_new_fd(struct worker_st * ws, struct dtls_st *dtls, int fd, UdpFdMsg **tmsg) +static unsigned int recv_from_new_fd(struct worker_st *ws, struct dtls_st *dtls, + int fd, UdpFdMsg **tmsg) { int saved_fd, ret; UdpFdMsg *saved_tmsg; @@ -64,7 +65,8 @@ static unsigned recv_from_new_fd(struct worker_st * ws, struct dtls_st *dtls, in dtls->dtls_tptr.msg = *tmsg; dtls->dtls_tptr.fd = fd; - ret = gnutls_record_recv(dtls->dtls_session, ws->buffer, ws->buffer_size); + ret = gnutls_record_recv(dtls->dtls_session, ws->buffer, + ws->buffer_size); /* we receive GNUTLS_E_AGAIN in case the packet was discarded */ if (ret > 0) { ret = 1; @@ -72,7 +74,7 @@ static unsigned recv_from_new_fd(struct worker_st * ws, struct dtls_st *dtls, in } ret = 0; - revert: +revert: *tmsg = dtls->dtls_tptr.msg; dtls->dtls_tptr.fd = saved_fd; dtls->dtls_tptr.msg = saved_tmsg; @@ -86,12 +88,13 @@ int handle_commands_from_main(struct worker_st *ws) UdpFdMsg *tmsg = NULL; int ret; int fd = -1; - struct dtls_st * dtls = NULL; + struct dtls_st *dtls = NULL; /*int cmd_data_len;*/ memset(&ws->buffer, 0, sizeof(ws->buffer)); - ret = recv_msg_data(ws->cmd_fd, &cmd, ws->buffer, sizeof(ws->buffer), &fd); + ret = recv_msg_data(ws->cmd_fd, &cmd, ws->buffer, sizeof(ws->buffer), + &fd); if (ret < 0) { oclog(ws, LOG_DEBUG, "cannot obtain data from command socket"); exit_worker_reason(ws, REASON_SERVER_DISCONNECT); @@ -104,7 +107,8 @@ int handle_commands_from_main(struct worker_st *ws) length = ret; - oclog(ws, LOG_DEBUG, "worker received message %s of %u bytes\n", cmd_request_to_str(cmd), (unsigned)length); + oclog(ws, LOG_DEBUG, "worker received message %s of %u bytes\n", + cmd_request_to_str(cmd), (unsigned int)length); /*cmd_data_len = ret - 1;*/ @@ -112,7 +116,7 @@ int handle_commands_from_main(struct worker_st *ws) case CMD_TERMINATE: exit_worker_reason(ws, REASON_SERVER_DISCONNECT); case CMD_UDP_FD: { - unsigned has_hello = 1; + unsigned int has_hello = 1; if (DTLS_ACTIVE(ws)->udp_state != UP_WAIT_FD) { oclog(ws, LOG_DEBUG, "received another a UDP fd!"); @@ -124,7 +128,8 @@ int handle_commands_from_main(struct worker_st *ws) } if (fd == -1) { - oclog(ws, LOG_ERR, "received UDP fd message of wrong type"); + oclog(ws, LOG_ERR, + "received UDP fd message of wrong type"); if (tmsg) udp_fd_msg__free_unpacked(tmsg, NULL); @@ -139,7 +144,8 @@ int handle_commands_from_main(struct worker_st *ws) /* check if the first packet received is a valid one - * if not discard the new fd */ if (!recv_from_new_fd(ws, DTLS_ACTIVE(ws), fd, &tmsg)) { - oclog(ws, LOG_INFO, "received UDP fd message but its session has invalid data!"); + oclog(ws, LOG_INFO, + "received UDP fd message but its session has invalid data!"); if (tmsg) udp_fd_msg__free_unpacked(tmsg, NULL); close(fd); @@ -149,7 +155,8 @@ int handle_commands_from_main(struct worker_st *ws) } else { /* received client hello */ dtls = DTLS_INACTIVE(ws); dtls->udp_state = UP_SETUP; - oclog(ws, LOG_DEBUG, "Starting DTLS session %d", ws->dtls_active_session ^ 1); + oclog(ws, LOG_DEBUG, "Starting DTLS session %d", + ws->dtls_active_session ^ 1); } if (dtls->dtls_tptr.fd != -1) @@ -163,27 +170,26 @@ int handle_commands_from_main(struct worker_st *ws) if (WSCONFIG(ws)->try_mtu == 0) set_mtu_disc(fd, ws->proto, 0); - oclog(ws, LOG_DEBUG, "received new UDP fd and connected to peer"); + oclog(ws, LOG_DEBUG, + "received new UDP fd and connected to peer"); ws->udp_recv_time = time(NULL); return 0; - } - break; + } break; default: - oclog(ws, LOG_ERR, "unknown CMD 0x%x", (unsigned)cmd); + oclog(ws, LOG_ERR, "unknown CMD 0x%x", (unsigned int)cmd); exit_worker_reason(ws, REASON_ERROR); } return 0; - } /* Completes the VPN device information. * * Returns 0 on success. */ -int complete_vpn_info(worker_st * ws, struct vpn_st *vinfo) +int complete_vpn_info(worker_st *ws, struct vpn_st *vinfo) { int ret, fd; struct ifreq ifr; @@ -202,7 +208,7 @@ int complete_vpn_info(worker_st * ws, struct vpn_st *vinfo) memset(&ifr, 0, sizeof(ifr)); ifr.ifr_addr.sa_family = AF_INET; snprintf(ifr.ifr_name, IFNAMSIZ, "%s", vinfo->name); - ret = ioctl(fd, SIOCGIFMTU, (caddr_t) & ifr); + ret = ioctl(fd, SIOCGIFMTU, (caddr_t)&ifr); if (ret < 0) { oclog(ws, LOG_INFO, "cannot obtain MTU for %s. Assuming 1500", @@ -224,12 +230,12 @@ void ocsigaltstack(struct worker_st *ws) int e; /* setup the stack for signal handlers */ - if (posix_memalign((void**)&ss.ss_sp, getpagesize(), SIGSTKSZ) != 0) { + if (posix_memalign((void **)&ss.ss_sp, getpagesize(), SIGSTKSZ) != 0) { oclog(ws, LOG_ERR, "could not allocate memory for signal stack"); exit(EXIT_FAILURE); } - if (mprotect(ss.ss_sp, SIGSTKSZ, PROT_READ|PROT_WRITE) == -1) { + if (mprotect(ss.ss_sp, SIGSTKSZ, PROT_READ | PROT_WRITE) == -1) { e = errno; oclog(ws, LOG_ERR, "mprotect: %s\n", strerror(e)); exit(EXIT_FAILURE); diff --git a/src/worker-privs.c b/src/worker-privs.c index 6e076278..66058811 100644 --- a/src/worker-privs.c +++ b/src/worker-privs.c @@ -31,21 +31,23 @@ /* libseccomp 2.4.2 broke accidentally the API. Work around it. */ #ifndef __SNR_ppoll -# ifdef __NR_ppoll -# define __SNR_ppoll __NR_ppoll -# else -# define __SNR_ppoll __PNR_ppoll -# endif +#ifdef __NR_ppoll +#define __SNR_ppoll __NR_ppoll +#else +#define __SNR_ppoll __PNR_ppoll +#endif #endif #ifdef USE_SECCOMP_TRAP -# define _SECCOMP_ERR SCMP_ACT_TRAP +#define _SECCOMP_ERR SCMP_ACT_TRAP #include #include -void sigsys_action(int sig, siginfo_t * info, void* ucontext) +void sigsys_action(int sig, siginfo_t *info, void *ucontext) { - char * call_addr = *backtrace_symbols(&info->si_call_addr, 1); - oc_syslog(LOG_ERR, "Function %s called disabled syscall %d\n", call_addr, info->si_syscall); + char *call_addr = *backtrace_symbols(&info->si_call_addr, 1); + + oc_syslog(LOG_ERR, "Function %s called disabled syscall %d\n", + call_addr, info->si_syscall); exit(EXIT_FAILURE); } @@ -59,21 +61,19 @@ int set_sigsys_handler(struct worker_st *ws) return sigaction(SIGSYS, &sa, NULL); } #else -# define _SECCOMP_ERR SCMP_ACT_ERRNO(ENOSYS) +#define _SECCOMP_ERR SCMP_ACT_ERRNO(ENOSYS) int set_sigsys_handler(struct worker_st *ws) { return 0; } #endif - int disable_system_calls(struct worker_st *ws) { int ret; scmp_filter_ctx ctx; - if (set_sigsys_handler(ws)) - { + if (set_sigsys_handler(ws)) { oclog(ws, LOG_ERR, "set_sigsys_handler"); return -1; } @@ -84,15 +84,18 @@ int disable_system_calls(struct worker_st *ws) return -1; } -#define ADD_SYSCALL(name, ...) \ - do { \ - ret = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(name), __VA_ARGS__); \ +#define ADD_SYSCALL(name, ...) \ + do { \ + ret = seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(name), \ + __VA_ARGS__); \ /* libseccomp returns EDOM for pseudo-syscalls due to a bug */ \ - if (ret < 0 && ret != -EDOM) { \ - oclog(ws, LOG_DEBUG, "could not add " #name " to seccomp filter: %s", strerror(-ret)); \ - ret = -1; \ - goto fail; \ - } \ + if (ret < 0 && ret != -EDOM) { \ + oclog(ws, LOG_DEBUG, \ + "could not add " #name " to seccomp filter: %s", \ + strerror(-ret)); \ + ret = -1; \ + goto fail; \ + } \ } while (0) /* These seem to be called by libc or some other dependent library; diff --git a/src/worker-proxyproto.c b/src/worker-proxyproto.c index 45d01201..28f20311 100644 --- a/src/worker-proxyproto.c +++ b/src/worker-proxyproto.c @@ -35,14 +35,15 @@ */ #define PROXY_HEADER_V2 "\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A" -#define PROXY_HEADER_V2_SIZE (sizeof(PROXY_HEADER_V2)-1) +#define PROXY_HEADER_V2_SIZE (sizeof(PROXY_HEADER_V2) - 1) -#define AVAIL_HEADER_SIZE(hsize, want) { \ - if (hsize < want) { \ - oclog(ws, LOG_ERR, "proxy-hdr: invalid TLV header"); \ - return; \ - } \ - hsize -= want; \ +#define AVAIL_HEADER_SIZE(hsize, want) \ + { \ + if (hsize < want) { \ + oclog(ws, LOG_ERR, "proxy-hdr: invalid TLV header"); \ + return; \ + } \ + hsize -= want; \ } typedef struct proxy_hdr_v2 { @@ -53,12 +54,12 @@ typedef struct proxy_hdr_v2 { uint8_t data[520]; } _ATTR_PACKED proxy_hdr_v2; -#define PP2_TYPE_SSL 0x20 -#define PP2_TYPE_SSL_CN 0x22 +#define PP2_TYPE_SSL 0x20 +#define PP2_TYPE_SSL_CN 0x22 -#define PP2_CLIENT_SSL 0x01 -#define PP2_CLIENT_CERT_CONN 0x02 -#define PP2_CLIENT_CERT_SESS 0x04 +#define PP2_CLIENT_SSL 0x01 +#define PP2_CLIENT_CERT_CONN 0x02 +#define PP2_CLIENT_CERT_SESS 0x04 typedef struct pp2_tlv { uint8_t type; @@ -66,11 +67,12 @@ typedef struct pp2_tlv { } _ATTR_PACKED pp2_tlv; typedef struct pp2_tlv_ssl { - uint8_t client; + uint8_t client; uint32_t verify; } _ATTR_PACKED pp2_tlv_ssl; -static void parse_ssl_tlvs(struct worker_st *ws, uint8_t *data, size_t data_size) +static void parse_ssl_tlvs(struct worker_st *ws, uint8_t *data, + size_t data_size) { pp2_tlv tlv; @@ -83,11 +85,14 @@ static void parse_ssl_tlvs(struct worker_st *ws, uint8_t *data, size_t data_size data += sizeof(pp2_tlv); - oclog(ws, LOG_INFO, "proxy-hdr: TLV type %x", (unsigned)tlv.type); + oclog(ws, LOG_INFO, "proxy-hdr: TLV type %x", + (unsigned int)tlv.type); if (tlv.type == PP2_TYPE_SSL) { pp2_tlv_ssl tssl; + if (tlv.length < sizeof(pp2_tlv_ssl)) { - oclog(ws, LOG_ERR, "proxy-hdr: TLV SSL header size is invalid"); + oclog(ws, LOG_ERR, + "proxy-hdr: TLV SSL header size is invalid"); continue; } tlv.length = sizeof(pp2_tlv_ssl); @@ -98,13 +103,14 @@ static void parse_ssl_tlvs(struct worker_st *ws, uint8_t *data, size_t data_size if ((tssl.client & PP2_CLIENT_SSL) && (tssl.client & PP2_CLIENT_CERT_SESS) && (tssl.verify == 0)) { - oclog(ws, LOG_INFO, "proxy-hdr: user has presented valid certificate"); + oclog(ws, LOG_INFO, + "proxy-hdr: user has presented valid certificate"); ws->cert_auth_ok = 1; - } } else if (tlv.type == PP2_TYPE_SSL_CN && ws->cert_auth_ok) { - if (tlv.length > sizeof(ws->cert_username)-1) { - oclog(ws, LOG_ERR, "proxy-hdr: TLV SSL CN header size is too long"); + if (tlv.length > sizeof(ws->cert_username) - 1) { + oclog(ws, LOG_ERR, + "proxy-hdr: TLV SSL CN header size is too long"); continue; } @@ -113,14 +119,14 @@ static void parse_ssl_tlvs(struct worker_st *ws, uint8_t *data, size_t data_size memcpy(ws->cert_username, data, tlv.length); ws->cert_username[tlv.length] = 0; - oclog(ws, LOG_INFO, "proxy-hdr: user's name is '%s'", ws->cert_username); + oclog(ws, LOG_INFO, "proxy-hdr: user's name is '%s'", + ws->cert_username); } else { AVAIL_HEADER_SIZE(data_size, tlv.length); } data += tlv.length; } - } /* A null-terminated string of the form: @@ -136,7 +142,7 @@ static int parse_proxy_proto_header_v1(struct worker_st *ws, char *line) memset(&ws->our_addr, 0, sizeof(ws->our_addr)); if (strncmp(line, "TCP4 ", 5) == 0) { - struct sockaddr_in *sa = (void*)&ws->remote_addr; + struct sockaddr_in *sa = (void *)&ws->remote_addr; ws->our_addr_len = sizeof(struct sockaddr_in); ws->remote_addr_len = sizeof(struct sockaddr_in); @@ -146,25 +152,27 @@ static int parse_proxy_proto_header_v1(struct worker_st *ws, char *line) next = strchr(line, ' '); if (next == NULL) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } *next = 0; ret = inet_pton(AF_INET, line, &sa->sin_addr); if (ret != 1) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header: %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header: %s", line); return -1; } - - sa = (void*)&ws->our_addr; + sa = (void *)&ws->our_addr; sa->sin_family = AF_INET; - line = next+1; + line = next + 1; next = strchr(line, ' '); if (next == NULL) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } @@ -172,27 +180,29 @@ static int parse_proxy_proto_header_v1(struct worker_st *ws, char *line) ret = inet_pton(AF_INET, line, &sa->sin_addr); if (ret != 1) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } - line = next+1; + line = next + 1; - sa = (void*)&ws->remote_addr; + sa = (void *)&ws->remote_addr; sa->sin_port = htons(atoi(line)); next = strchr(line, ' '); if (next == NULL) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } - line = next+1; + line = next + 1; - sa = (void*)&ws->our_addr; + sa = (void *)&ws->our_addr; sa->sin_port = htons(atoi(line)); } else if (strncmp(line, "TCP6 ", 5) == 0) { - struct sockaddr_in6 *sa = (void*)&ws->remote_addr; + struct sockaddr_in6 *sa = (void *)&ws->remote_addr; ws->our_addr_len = sizeof(struct sockaddr_in6); ws->remote_addr_len = sizeof(struct sockaddr_in6); @@ -202,7 +212,8 @@ static int parse_proxy_proto_header_v1(struct worker_st *ws, char *line) next = strchr(line, ' '); if (next == NULL) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } @@ -210,42 +221,46 @@ static int parse_proxy_proto_header_v1(struct worker_st *ws, char *line) ret = inet_pton(AF_INET6, line, &sa->sin6_addr); if (ret != 1) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } - line = next+1; + line = next + 1; next = strchr(line, ' '); if (next == NULL) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } *next = 0; - sa = (void*)&ws->our_addr; + sa = (void *)&ws->our_addr; sa->sin6_family = AF_INET6; ret = inet_pton(AF_INET6, line, &sa->sin6_addr); if (ret != 1) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } - line = next+1; + line = next + 1; - sa = (void*)&ws->remote_addr; + sa = (void *)&ws->remote_addr; sa->sin6_port = htons(atoi(line)); next = strchr(line, ' '); if (next == NULL) { - oclog(ws, LOG_ERR, "proxy-hdr: error parsing v1 header %s", line); + oclog(ws, LOG_ERR, + "proxy-hdr: error parsing v1 header %s", line); return -1; } - line = next+1; + line = next + 1; - sa = (void*)&ws->our_addr; + sa = (void *)&ws->our_addr; sa->sin6_port = htons(atoi(line)); } else { oclog(ws, LOG_ERR, "proxy-hdr: unknown protocol: %s", line); @@ -256,7 +271,7 @@ static int parse_proxy_proto_header_v1(struct worker_st *ws, char *line) } #define PROXY_HEADER_V1 "PROXY " -#define PROXY_HEADER_V1_SIZE (sizeof(PROXY_HEADER_V1)-1) +#define PROXY_HEADER_V1_SIZE (sizeof(PROXY_HEADER_V1) - 1) #define MAX_PROXY_PROTO_V1_SIZE 108 /* This parses a version 2 Proxy protocol header (from haproxy). @@ -280,8 +295,7 @@ int parse_proxy_proto_header(struct worker_st *ws, int fd) ret = force_read_timeout(fd, &hdr, 16, DEFAULT_SOCKET_TIMEOUT); if (ret < 0) { - oclog(ws, LOG_ERR, - "proxy-hdr: recv timed out"); + oclog(ws, LOG_ERR, "proxy-hdr: recv timed out"); return -1; } @@ -291,24 +305,29 @@ int parse_proxy_proto_header(struct worker_st *ws, int fd) } if (memcmp(hdr.sig, PROXY_HEADER_V1, PROXY_HEADER_V1_SIZE) == 0) { - unsigned i; + unsigned int i; /* recv all */ oclog(ws, LOG_DEBUG, "proxy-hdr: detected v1 header"); memcpy(hdr.data, &hdr, 16); - for (i=0;i> 4; if (ver != 0x02) { - oclog(ws, LOG_ERR, "proxy-hdr: unsupported version (%x), skipping message", (unsigned)ver); + oclog(ws, LOG_ERR, + "proxy-hdr: unsupported version (%x), skipping message", + (unsigned int)ver); return 0; } if (cmd != 0x01) { if (cmd == 0) { - oclog(ws, LOG_DEBUG, "proxy-hdr: received health check command"); + oclog(ws, LOG_DEBUG, + "proxy-hdr: received health check command"); } else { - oclog(ws, LOG_ERR, "proxy-hdr: received unsupported command %x", (unsigned)cmd); + oclog(ws, LOG_ERR, + "proxy-hdr: received unsupported command %x", + (unsigned int)cmd); return -1; } } @@ -356,45 +380,51 @@ int parse_proxy_proto_header(struct worker_st *ws, int fd) proto = hdr.family & 0x0f; if (family != 0x1 && family != 0x2) { - oclog(ws, LOG_ERR, "proxy-hdr: received unsupported family %x; skipping header", (unsigned)family); + oclog(ws, LOG_ERR, + "proxy-hdr: received unsupported family %x; skipping header", + (unsigned int)family); return 0; } if ((proto != 0x1 && proto != 0x0)) { - oclog(ws, LOG_ERR, "proxy-hdr: received unsupported protocol %x; skipping header", (unsigned)proto); + oclog(ws, LOG_ERR, + "proxy-hdr: received unsupported protocol %x; skipping header", + (unsigned int)proto); return 0; } p = hdr.data; if (family == 0x01) { /* AF_INET */ - struct sockaddr_in *sa = (void*)&ws->remote_addr; + struct sockaddr_in *sa = (void *)&ws->remote_addr; if (data_size < 12) { - oclog(ws, LOG_INFO, "proxy-hdr: received not enough IPv4 data"); + oclog(ws, LOG_INFO, + "proxy-hdr: received not enough IPv4 data"); return 0; } memset(&ws->remote_addr, 0, sizeof(ws->remote_addr)); sa->sin_family = AF_INET; - memcpy(&sa->sin_port, p+8, 2); + memcpy(&sa->sin_port, p + 8, 2); memcpy(&sa->sin_addr, p, 4); ws->remote_addr_len = sizeof(struct sockaddr_in); memset(&ws->our_addr, 0, sizeof(ws->our_addr)); - sa = (void*)&ws->our_addr; + sa = (void *)&ws->our_addr; sa->sin_family = AF_INET; - memcpy(&sa->sin_addr, p+4, 4); - memcpy(&sa->sin_port, p+10, 2); + memcpy(&sa->sin_addr, p + 4, 4); + memcpy(&sa->sin_port, p + 10, 2); ws->our_addr_len = sizeof(struct sockaddr_in); p += 12; data_size -= 12; } else if (family == 0x02) { /* AF_INET6 */ - struct sockaddr_in6 *sa = (void*)&ws->remote_addr; + struct sockaddr_in6 *sa = (void *)&ws->remote_addr; if (data_size < 36) { - oclog(ws, LOG_INFO, "proxy-hdr: did not receive enough IPv6 data"); + oclog(ws, LOG_INFO, + "proxy-hdr: did not receive enough IPv6 data"); return 0; } @@ -402,14 +432,14 @@ int parse_proxy_proto_header(struct worker_st *ws, int fd) sa->sin6_family = AF_INET6; sa->sin6_port = 0; memcpy(&sa->sin6_addr, p, 16); - memcpy(&sa->sin6_port, p+32, 2); + memcpy(&sa->sin6_port, p + 32, 2); ws->remote_addr_len = sizeof(struct sockaddr_in6); memset(&ws->our_addr, 0, sizeof(ws->our_addr)); sa->sin6_family = AF_INET6; - sa = (void*)&ws->our_addr; - memcpy(&sa->sin6_addr, p+16, 16); - memcpy(&sa->sin6_port, p+34, 2); + sa = (void *)&ws->our_addr; + memcpy(&sa->sin6_addr, p + 16, 16); + memcpy(&sa->sin6_port, p + 34, 2); ws->our_addr_len = sizeof(struct sockaddr_in); p += 36; diff --git a/src/worker-resume.c b/src/worker-resume.c index ad7521f0..e0ad83b3 100644 --- a/src/worker-resume.c +++ b/src/worker-resume.c @@ -39,15 +39,16 @@ #include "ipc.pb-c.h" #include - static int recv_resume_fetch_reply(worker_st *ws, int sd, gnutls_datum_t *sdata) { int ret; SessionResumeReplyMsg *resp; + PROTOBUF_ALLOCATOR(pa, ws); - ret = recv_msg(ws, sd, RESUME_FETCH_REP, (void*)&resp, - (unpack_func)session_resume_reply_msg__unpack, DEFAULT_SOCKET_TIMEOUT); + ret = recv_msg(ws, sd, RESUME_FETCH_REP, (void *)&resp, + (unpack_func)session_resume_reply_msg__unpack, + DEFAULT_SOCKET_TIMEOUT); if (ret < 0) { oclog(ws, LOG_ERR, "error receiving resumption reply (fetch)"); return ret; @@ -86,7 +87,8 @@ static gnutls_datum_t resume_db_fetch(void *dbf, gnutls_datum_t key) SessionResumeFetchMsg msg = SESSION_RESUME_FETCH_MSG__INIT; if (key.size > GNUTLS_MAX_SESSION_ID) { - oclog(ws, LOG_DEBUG, "session ID size exceeds the maximum %u", key.size); + oclog(ws, LOG_DEBUG, "session ID size exceeds the maximum %u", + key.size); return r; } @@ -99,10 +101,11 @@ static gnutls_datum_t resume_db_fetch(void *dbf, gnutls_datum_t key) msg.session_id.len = key.size; msg.session_id.data = key.data; msg.cli_addr.len = ws->remote_addr_len; - msg.cli_addr.data = (void*)&ws->remote_addr; + msg.cli_addr.data = (void *)&ws->remote_addr; msg.vhost = ws->vhost->name; - ret = send_msg_to_secmod(ws, sd, RESUME_FETCH_REQ, &msg, + ret = send_msg_to_secmod( + ws, sd, RESUME_FETCH_REQ, &msg, (pack_size_func)session_resume_fetch_msg__get_packed_size, (pack_func)session_resume_fetch_msg__pack); if (ret < 0) { @@ -111,26 +114,26 @@ static gnutls_datum_t resume_db_fetch(void *dbf, gnutls_datum_t key) recv_resume_fetch_reply(ws, sd, &r); - cleanup: +cleanup: close(sd); return r; } - -static int -resume_db_store (void *dbf, gnutls_datum_t key, gnutls_datum_t data) +static int resume_db_store(void *dbf, gnutls_datum_t key, gnutls_datum_t data) { worker_st *ws = dbf; SessionResumeStoreReqMsg msg = SESSION_RESUME_STORE_REQ_MSG__INIT; int ret, sd; if (data.size > MAX_SESSION_DATA_SIZE) { - oclog(ws, LOG_DEBUG, "session data size exceeds the maximum %u", data.size); + oclog(ws, LOG_DEBUG, "session data size exceeds the maximum %u", + data.size); return GNUTLS_E_DB_ERROR; } if (key.size > GNUTLS_MAX_SESSION_ID) { - oclog(ws, LOG_DEBUG, "session ID size exceeds the maximum %u", key.size); + oclog(ws, LOG_DEBUG, "session ID size exceeds the maximum %u", + key.size); return GNUTLS_E_DB_ERROR; } @@ -141,7 +144,7 @@ resume_db_store (void *dbf, gnutls_datum_t key, gnutls_datum_t data) msg.session_data.data = data.data; msg.cli_addr.len = ws->remote_addr_len; - msg.cli_addr.data = (void*)&ws->remote_addr; + msg.cli_addr.data = (void *)&ws->remote_addr; msg.vhost = ws->vhost->name; @@ -151,7 +154,8 @@ resume_db_store (void *dbf, gnutls_datum_t key, gnutls_datum_t data) return GNUTLS_E_DB_ERROR; } - ret = send_msg_to_secmod(ws, sd, RESUME_STORE_REQ, &msg, + ret = send_msg_to_secmod( + ws, sd, RESUME_STORE_REQ, &msg, (pack_size_func)session_resume_store_req_msg__get_packed_size, (pack_func)session_resume_store_req_msg__pack); @@ -175,7 +179,8 @@ static int resume_db_delete(void *dbf, gnutls_datum_t key) SessionResumeFetchMsg msg = SESSION_RESUME_FETCH_MSG__INIT; if (key.size > GNUTLS_MAX_SESSION_ID) { - oclog(ws, LOG_DEBUG, "Session ID size exceeds the maximum %u", key.size); + oclog(ws, LOG_DEBUG, "Session ID size exceeds the maximum %u", + key.size); return GNUTLS_E_DB_ERROR; } @@ -188,7 +193,8 @@ static int resume_db_delete(void *dbf, gnutls_datum_t key) return GNUTLS_E_DB_ERROR; } - ret = send_msg_to_secmod(ws, sd, RESUME_DELETE_REQ, &msg, + ret = send_msg_to_secmod( + ws, sd, RESUME_DELETE_REQ, &msg, (pack_size_func)session_resume_fetch_msg__get_packed_size, (pack_func)session_resume_fetch_msg__pack); @@ -201,7 +207,7 @@ static int resume_db_delete(void *dbf, gnutls_datum_t key) void set_resume_db_funcs(gnutls_session_t session) { - gnutls_db_set_retrieve_function (session, resume_db_fetch); - gnutls_db_set_remove_function (session, resume_db_delete); - gnutls_db_set_store_function (session, resume_db_store); + gnutls_db_set_retrieve_function(session, resume_db_fetch); + gnutls_db_set_remove_function(session, resume_db_delete); + gnutls_db_set_store_function(session, resume_db_store); } diff --git a/src/worker-svc.c b/src/worker-svc.c index 38e3aeda..42d2e5d2 100644 --- a/src/worker-svc.c +++ b/src/worker-svc.c @@ -33,15 +33,17 @@ #include #include -int get_svc_handler(worker_st *ws, unsigned http_ver) +int get_svc_handler(worker_st *ws, unsigned int http_ver) { int ret; if (!WSCONFIG(ws)->cisco_svc_client_compat) - oclog(ws, LOG_WARNING, "request to /svc but cisco-svc-client-compat = false"); + oclog(ws, LOG_WARNING, + "request to /svc but cisco-svc-client-compat = false"); if (ws->req.user_agent_type != AGENT_SVC_IPPHONE) - oclog(ws, LOG_WARNING, "unexpected /svc user-agent of '%s'", ws->req.user_agent); + oclog(ws, LOG_WARNING, "unexpected /svc user-agent of '%s'", + ws->req.user_agent); oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: 200 OK"); cstp_cork(ws); @@ -54,7 +56,9 @@ int get_svc_handler(worker_st *ws, unsigned http_ver) if (ret < 0) goto fail; - ret = cstp_puts(ws, "Set-Cookie: webvpn=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; secure\r\n"); + ret = cstp_puts( + ws, + "Set-Cookie: webvpn=; expires=Thu, 01 Jan 1970 22:00:00 GMT; path=/; secure\r\n"); if (ret < 0) goto fail; @@ -89,7 +93,7 @@ static int client_auth(worker_st *ws, char *password) { int ret = -1, sd = -1; char *msg; - unsigned pcounter = 0; + unsigned int pcounter = 0; SecAuthInitMsg init = SEC_AUTH_INIT_MSG__INIT; SecAuthContMsg cont = SEC_AUTH_CONT_MSG__INIT; @@ -116,7 +120,7 @@ static int client_auth(worker_st *ws, char *password) init.orig_remote_ip = ws->orig_remote_ip_str; init.our_ip = ws->our_ip_str; init.session_start_time = ws->session_start_time; - init.hmac.data = (uint8_t*)ws->sec_auth_init_hmac; + init.hmac.data = (uint8_t *)ws->sec_auth_init_hmac; init.hmac.len = sizeof(ws->sec_auth_init_hmac); if (ws->req.user_agent[0] != 0) @@ -134,11 +138,13 @@ static int client_auth(worker_st *ws, char *password) goto fail; } - ret = send_msg_to_secmod(ws, sd, CMD_SEC_AUTH_INIT, &init, - (pack_size_func)sec_auth_init_msg__get_packed_size, - (pack_func)sec_auth_init_msg__pack); + ret = send_msg_to_secmod( + ws, sd, CMD_SEC_AUTH_INIT, &init, + (pack_size_func)sec_auth_init_msg__get_packed_size, + (pack_func)sec_auth_init_msg__pack); if (ret < 0) { - oclog(ws, LOG_ERR, "failed sending auth init message to sec mod"); + oclog(ws, LOG_ERR, + "failed sending auth init message to sec mod"); goto fail; } @@ -168,11 +174,13 @@ static int client_auth(worker_st *ws, char *password) goto fail; } - ret = send_msg_to_secmod(ws, sd, CMD_SEC_AUTH_CONT, &cont, - (pack_size_func)sec_auth_cont_msg__get_packed_size, - (pack_func)sec_auth_cont_msg__pack); + ret = send_msg_to_secmod( + ws, sd, CMD_SEC_AUTH_CONT, &cont, + (pack_size_func)sec_auth_cont_msg__get_packed_size, + (pack_func)sec_auth_cont_msg__pack); if (ret < 0) { - oclog(ws, LOG_ERR, "failed sending auth cont message to sec mod"); + oclog(ws, LOG_ERR, + "failed sending auth cont message to sec mod"); goto fail; } @@ -194,7 +202,7 @@ fail: return ret; } -int post_svc_handler(worker_st *ws, unsigned http_ver) +int post_svc_handler(worker_st *ws, unsigned int http_ver) { char *username = NULL; char *password = NULL; @@ -202,10 +210,12 @@ int post_svc_handler(worker_st *ws, unsigned http_ver) char cookie[BASE64_ENCODE_RAW_LENGTH(sizeof(ws->cookie)) + 1]; if (!WSCONFIG(ws)->cisco_svc_client_compat) - oclog(ws, LOG_WARNING, "request to /svc but cisco-svc-client-compat = false"); + oclog(ws, LOG_WARNING, + "request to /svc but cisco-svc-client-compat = false"); if (ws->req.user_agent_type != AGENT_SVC_IPPHONE) - oclog(ws, LOG_WARNING, "unexpected /svc user-agent of '%s'", ws->req.user_agent); + oclog(ws, LOG_WARNING, "unexpected /svc user-agent of '%s'", + ws->req.user_agent); if (ws->selected_auth->type & AUTH_TYPE_USERNAME_PASS) { /* fail if username or password is missing */ @@ -235,9 +245,11 @@ int post_svc_handler(worker_st *ws, unsigned http_ver) if (ret < 0) { oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: 401 Unauthorized"); - ret = cstp_printf(ws, "HTTP/1.%d 401 Authentication failed\r\n" + ret = cstp_printf(ws, + "HTTP/1.%d 401 Authentication failed\r\n" "Content-Length: 0\r\n" - "\r\n", http_ver); + "\r\n", + http_ver); if (ret >= 0) cstp_fatal_close(ws, GNUTLS_A_ACCESS_DENIED); @@ -248,8 +260,8 @@ int post_svc_handler(worker_st *ws, unsigned http_ver) oclog(ws, LOG_HTTP_DEBUG, "user '%s' obtained cookie", ws->username); ws->auth_state = S_AUTH_COOKIE; - oc_base64_encode((char *)ws->cookie, sizeof(ws->cookie), - cookie, sizeof(cookie)); + oc_base64_encode((char *)ws->cookie, sizeof(ws->cookie), cookie, + sizeof(cookie)); /* reply */ oclog(ws, LOG_HTTP_DEBUG, "HTTP sending: 200 OK"); diff --git a/src/worker-tun.c b/src/worker-tun.c index 1daf6284..3ad4b2a4 100644 --- a/src/worker-tun.c +++ b/src/worker-tun.c @@ -37,9 +37,9 @@ #include #if defined(HAVE_LINUX_IF_TUN_H) -# include +#include #elif defined(HAVE_NET_IF_TUN_H) -# include +#include #endif #include @@ -51,18 +51,18 @@ #include "log.h" #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) -# include -# include +#include +#include #endif #if defined(__OpenBSD__) -# include +#include #endif #if defined(__DragonFly__) -# include +#include #endif #if defined(__OpenBSD__) || defined(TUNSIFHEAD) -# define TUN_AF_PREFIX 1 +#define TUN_AF_PREFIX 1 #endif #ifdef TUN_AF_PREFIX @@ -71,7 +71,7 @@ ssize_t tun_write(int sockfd, const void *buf, size_t len) struct ip *iph = (void *)buf; uint32_t head; const uint8_t *data = buf; - static int complained = 0; + static int complained; struct iovec iov[2]; int ret; @@ -82,7 +82,9 @@ ssize_t tun_write(int sockfd, const void *buf, size_t len) else { if (!complained) { complained = 1; - oc_syslog(LOG_ERR, "tun_write: Unknown packet (len %d) received %02x %02x %02x %02x...\n", + oc_syslog( + LOG_ERR, + "tun_write: Unknown packet (len %d) received %02x %02x %02x %02x...\n", (int)len, data[0], data[1], data[2], data[3]); } return -1; @@ -90,7 +92,7 @@ ssize_t tun_write(int sockfd, const void *buf, size_t len) iov[0].iov_base = &head; iov[0].iov_len = sizeof(head); - iov[1].iov_base = (void*)buf; + iov[1].iov_base = (void *)buf; iov[1].iov_len = len; ret = writev(sockfd, iov, 2); @@ -143,4 +145,4 @@ int tun_claim(int sockfd) { return ioctl(sockfd, TUNSIFPID, 0); } -#endif /* !__FreeBSD__ */ +#endif /* !__FreeBSD__ */ diff --git a/src/worker-vpn.c b/src/worker-vpn.c index 2f3370c9..c4468bfd 100644 --- a/src/worker-vpn.c +++ b/src/worker-vpn.c @@ -50,7 +50,7 @@ #include #if defined(__linux__) && !defined(IPV6_PATHMTU) -# define IPV6_PATHMTU 61 +#define IPV6_PATHMTU 61 #endif #include @@ -65,7 +65,7 @@ #include #endif -#define MIN_MTU(ws) (((ws)->vinfo.ipv6!=NULL)?1280:800) +#define MIN_MTU(ws) (((ws)->vinfo.ipv6 != NULL) ? 1280 : 800) #define PERIODIC_CHECK_TIME 30 #define MIN_STATS_INTERVAL 10 @@ -85,16 +85,18 @@ #define TCP_HEADER_SIZE 20 #define UDP_HEADER_SIZE 8 -#define MSS_ADJUST(x) x += TCP_HEADER_SIZE + ((ws->proto == AF_INET)?(IP_HEADER_SIZE):(IPV6_HEADER_SIZE)) +#define MSS_ADJUST(x) \ + x += TCP_HEADER_SIZE + \ + ((ws->proto == AF_INET) ? (IP_HEADER_SIZE) : (IPV6_HEADER_SIZE)) #define WORKER_MAINTENANCE_TIME (10.) -struct worker_st *global_ws = NULL; +struct worker_st *global_ws; -static int terminate = 0; +static int terminate; static int terminate_reason = REASON_SERVER_DISCONNECT; -static struct ev_loop *worker_loop = NULL; +static struct ev_loop *worker_loop; ev_io command_watcher; ev_io tls_watcher; ev_io tun_watcher; @@ -103,24 +105,25 @@ ev_signal term_sig_watcher; ev_signal int_sig_watcher; ev_signal alarm_sig_watcher; -static void term_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revents); +static void term_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, + int revents); -static int worker_event_loop(struct worker_st * ws); +static int worker_event_loop(struct worker_st *ws); -static int parse_cstp_data(struct worker_st *ws, uint8_t * buf, size_t buf_size, +static int parse_cstp_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, time_t); -static int parse_dtls_data(struct worker_st *ws, uint8_t * buf, size_t buf_size, +static int parse_dtls_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, time_t); -static int connect_handler(worker_st * ws); -static void session_info_send(worker_st * ws); -static void set_net_priority(worker_st * ws, int fd, int priority); -static void set_socket_timeout(worker_st * ws, int fd); +static int connect_handler(worker_st *ws); +static void session_info_send(worker_st *ws); +static void set_net_priority(worker_st *ws, int fd, int priority); +static void set_socket_timeout(worker_st *ws, int fd); -static void link_mtu_set(worker_st * ws, struct dtls_st * dtls, unsigned mtu); +static void link_mtu_set(worker_st *ws, struct dtls_st *dtls, unsigned int mtu); static int test_for_tcp_health_probe(struct worker_st *ws); -static void dtls_watcher_cb (EV_P_ ev_io * w, int revents); +static void dtls_watcher_cb(EV_P_ ev_io *w, int revents); static void handle_alarm(int signo) { @@ -132,15 +135,14 @@ static void handle_alarm(int signo) static void handle_term(int signo) { - terminate = 1; - terminate_reason = REASON_SERVER_DISCONNECT; - alarm(2); /* force exit by SIGALRM */ + terminate = 1; + terminate_reason = REASON_SERVER_DISCONNECT; + alarm(2); /* force exit by SIGALRM */ } /* we override that function to force gnutls use poll() */ -static -int tls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms) +static int tls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms) { int ret; int fd = (long)ptr; @@ -160,19 +162,20 @@ int tls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms) inline static ssize_t dtls_pull_buffer_non_empty(gnutls_transport_ptr_t ptr) { dtls_transport_ptr *p = ptr; + if (p->msg) return 1; return 0; } #if !defined(CAPTURE_LATENCY_SUPPORT) -static -ssize_t dtls_pull(gnutls_transport_ptr_t ptr, void *data, size_t size) +static ssize_t dtls_pull(gnutls_transport_ptr_t ptr, void *data, size_t size) { dtls_transport_ptr *p = ptr; if (p->msg) { ssize_t need = p->msg->data.len; + if (need > size) { need = size; } @@ -186,8 +189,7 @@ ssize_t dtls_pull(gnutls_transport_ptr_t ptr, void *data, size_t size) } #endif -static -int dtls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms) +static int dtls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms) { int ret; dtls_transport_ptr *p = ptr; @@ -209,16 +211,16 @@ int dtls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms) return ret; } -static -ssize_t dtls_push(gnutls_transport_ptr_t ptr, const void *data, size_t size) +static ssize_t dtls_push(gnutls_transport_ptr_t ptr, const void *data, + size_t size) { dtls_transport_ptr *p = ptr; return send(p->fd, data, size, 0); } -int get_psk_key(gnutls_session_t session, - const char *username, gnutls_datum_t *key) +int get_psk_key(gnutls_session_t session, const char *username, + gnutls_datum_t *key) { struct worker_st *ws = gnutls_session_get_ptr(session); @@ -233,13 +235,13 @@ int get_psk_key(gnutls_session_t session, } #if GNUTLS_VERSION_NUMBER < 0x030318 -# define VERS_STRING "-VERS-TLS-ALL" +#define VERS_STRING "-VERS-TLS-ALL" #else -# define VERS_STRING "-VERS-ALL" +#define VERS_STRING "-VERS-ALL" #endif #define PSK_LABEL "EXPORTER-openconnect-psk" -#define PSK_LABEL_SIZE sizeof(PSK_LABEL)-1 +#define PSK_LABEL_SIZE sizeof(PSK_LABEL) - 1 /* We initial a PSK connection with ciphers and MAC matching the TLS negotiated * ciphers and MAC. The key is 32-bytes generated from gnutls_prf_rfc5705() * with label being the PSK_LABEL. @@ -251,10 +253,12 @@ static int setup_dtls_psk_keys(gnutls_session_t session, struct worker_st *ws) gnutls_mac_algorithm_t mac; gnutls_cipher_algorithm_t cipher; - gnutls_psk_set_server_credentials_function(WSCREDS(ws)->pskcred, get_psk_key); + gnutls_psk_set_server_credentials_function(WSCREDS(ws)->pskcred, + get_psk_key); if (!ws->session) { - oclog(ws, LOG_ERR, "cannot setup PSK keys without an encrypted CSTP channel"); + oclog(ws, LOG_ERR, + "cannot setup PSK keys without an encrypted CSTP channel"); return -1; } @@ -262,17 +266,21 @@ static int setup_dtls_psk_keys(gnutls_session_t session, struct worker_st *ws) cipher = gnutls_cipher_get(ws->session); mac = gnutls_mac_get(ws->session); - snprintf(prio_string, sizeof(prio_string), "%s:"VERS_STRING":-CIPHER-ALL:-MAC-ALL:-KX-ALL:+PSK:+VERS-DTLS-ALL:+%s:+%s", - WSCONFIG(ws)->priorities, gnutls_mac_get_name(mac), gnutls_cipher_get_name(cipher)); + snprintf( + prio_string, sizeof(prio_string), + "%s:" VERS_STRING + ":-CIPHER-ALL:-MAC-ALL:-KX-ALL:+PSK:+VERS-DTLS-ALL:+%s:+%s", + WSCONFIG(ws)->priorities, gnutls_mac_get_name(mac), + gnutls_cipher_get_name(cipher)); } else { /* if we haven't an associated session, enable all ciphers we would have enabled * otherwise for TLS. */ - snprintf(prio_string, sizeof(prio_string), "%s:"VERS_STRING":-KX-ALL:+PSK:+VERS-DTLS-ALL", + snprintf(prio_string, sizeof(prio_string), + "%s:" VERS_STRING ":-KX-ALL:+PSK:+VERS-DTLS-ALL", WSCONFIG(ws)->priorities); } - ret = - gnutls_priority_set_direct(session, prio_string, NULL); + ret = gnutls_priority_set_direct(session, prio_string, NULL); if (ret < 0) { oclog(ws, LOG_ERR, "could not set TLS priority: '%s': %s", prio_string, gnutls_strerror(ret)); @@ -282,16 +290,16 @@ static int setup_dtls_psk_keys(gnutls_session_t session, struct worker_st *ws) /* we should have used gnutls_prf_rfc5705() but since we don't use * the RFC5705 context, the output is identical with gnutls_prf(). The * latter is available in much earlier versions of gnutls. */ - ret = gnutls_prf(ws->session, PSK_LABEL_SIZE, PSK_LABEL, 0, 0, 0, PSK_KEY_SIZE, (char*)ws->master_secret); + ret = gnutls_prf(ws->session, PSK_LABEL_SIZE, PSK_LABEL, 0, 0, 0, + PSK_KEY_SIZE, (char *)ws->master_secret); if (ret < 0) { oclog(ws, LOG_ERR, "error in PSK key generation: %s", gnutls_strerror(ret)); return ret; } - ret = - gnutls_credentials_set(session, GNUTLS_CRD_PSK, - WSCREDS(ws)->pskcred); + ret = gnutls_credentials_set(session, GNUTLS_CRD_PSK, + WSCREDS(ws)->pskcred); if (ret < 0) { oclog(ws, LOG_ERR, "could not set TLS PSK credentials: %s", gnutls_strerror(ret)); @@ -301,11 +309,12 @@ static int setup_dtls_psk_keys(gnutls_session_t session, struct worker_st *ws) return 0; } -static int setup_legacy_dtls_keys(gnutls_session_t session, struct worker_st *ws) +static int setup_legacy_dtls_keys(gnutls_session_t session, + struct worker_st *ws) { int ret; - gnutls_datum_t master = - { ws->master_secret, sizeof(ws->master_secret) }; + gnutls_datum_t master = { ws->master_secret, + sizeof(ws->master_secret) }; gnutls_datum_t sid = { ws->session_id, sizeof(ws->session_id) }; if (ws->req.selected_ciphersuite == NULL) { @@ -313,26 +322,21 @@ static int setup_legacy_dtls_keys(gnutls_session_t session, struct worker_st *ws return -1; } - ret = - gnutls_priority_set_direct(session, - ws->req. - selected_ciphersuite->gnutls_name, NULL); + ret = gnutls_priority_set_direct( + session, ws->req.selected_ciphersuite->gnutls_name, NULL); if (ret < 0) { oclog(ws, LOG_ERR, "could not set TLS priority: %s", gnutls_strerror(ret)); return ret; } - ret = gnutls_session_set_premaster(session, GNUTLS_SERVER, - ws->req. - selected_ciphersuite->gnutls_version, - ws->req. - selected_ciphersuite->gnutls_kx, - ws->req. - selected_ciphersuite->gnutls_cipher, - ws->req. - selected_ciphersuite->gnutls_mac, - GNUTLS_COMP_NULL, &master, &sid); + ret = gnutls_session_set_premaster( + session, GNUTLS_SERVER, + ws->req.selected_ciphersuite->gnutls_version, + ws->req.selected_ciphersuite->gnutls_kx, + ws->req.selected_ciphersuite->gnutls_cipher, + ws->req.selected_ciphersuite->gnutls_mac, GNUTLS_COMP_NULL, + &master, &sid); if (ret < 0) { oclog(ws, LOG_ERR, "could not set TLS premaster: %s", gnutls_strerror(ret)); @@ -341,9 +345,8 @@ static int setup_legacy_dtls_keys(gnutls_session_t session, struct worker_st *ws gnutls_certificate_server_set_request(session, GNUTLS_CERT_IGNORE); - ret = - gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, - WSCREDS(ws)->xcred); + ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, + WSCREDS(ws)->xcred); if (ret < 0) { oclog(ws, LOG_ERR, "could not set TLS credentials: %s", gnutls_strerror(ret)); @@ -353,18 +356,20 @@ static int setup_legacy_dtls_keys(gnutls_session_t session, struct worker_st *ws return 0; } -static int setup_dtls_connection(struct worker_st *ws, struct dtls_st * dtls) +static int setup_dtls_connection(struct worker_st *ws, struct dtls_st *dtls) { int ret; gnutls_session_t session; #if defined(CAPTURE_LATENCY_SUPPORT) - int ts_socket_opt = SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE; + int ts_socket_opt = SOF_TIMESTAMPING_RX_SOFTWARE | + SOF_TIMESTAMPING_SOFTWARE; #endif /* DTLS cookie verified. * Initialize session. */ - ret = gnutls_init(&session, GNUTLS_SERVER|GNUTLS_DATAGRAM|GNUTLS_NONBLOCK); + ret = gnutls_init(&session, + GNUTLS_SERVER | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK); if (ret < 0) { oclog(ws, LOG_ERR, "could not initialize TLS session: %s", gnutls_strerror(ret)); @@ -378,10 +383,12 @@ static int setup_dtls_connection(struct worker_st *ws, struct dtls_st * dtls) ret = setup_dtls_psk_keys(session, ws); } else { if (!WSCONFIG(ws)->dtls_legacy) { - oclog(ws, LOG_INFO, "CISCO client compatibility (dtls-legacy) is disabled; will not setup a DTLS session"); + oclog(ws, LOG_INFO, + "CISCO client compatibility (dtls-legacy) is disabled; will not setup a DTLS session"); goto fail; } - oclog(ws, LOG_INFO, "setting up legacy DTLS (resumption) connection"); + oclog(ws, LOG_INFO, + "setting up legacy DTLS (resumption) connection"); ret = setup_legacy_dtls_keys(session, ws); } @@ -401,25 +408,27 @@ static int setup_dtls_connection(struct worker_st *ws, struct dtls_st * dtls) /* we decrease the default retransmission timeout to bring * our DTLS support in par with the DTLS1.3 recommendations. */ - gnutls_dtls_set_timeouts(session, 400, 60*1000); + gnutls_dtls_set_timeouts(session, 400, 60 * 1000); dtls->udp_state = UP_HANDSHAKE; #if defined(CAPTURE_LATENCY_SUPPORT) - ret = setsockopt(dtls->dtls_tptr.fd, SOL_SOCKET, SO_TIMESTAMPING, &ts_socket_opt, sizeof(ts_socket_opt)); + ret = setsockopt(dtls->dtls_tptr.fd, SOL_SOCKET, SO_TIMESTAMPING, + &ts_socket_opt, sizeof(ts_socket_opt)); if (ret == -1) - oclog(ws, LOG_DEBUG, "setsockopt(UDP, SO_TIMESTAMPING), failed."); + oclog(ws, LOG_DEBUG, + "setsockopt(UDP, SO_TIMESTAMPING), failed."); #endif /* Setup the fd settings */ if (WSCONFIG(ws)->output_buffer > 0) { int t = MIN(2048, ws->link_mtu * WSCONFIG(ws)->output_buffer); + ret = setsockopt(dtls->dtls_tptr.fd, SOL_SOCKET, SO_SNDBUF, &t, - sizeof(t)); + sizeof(t)); if (ret == -1) oclog(ws, LOG_DEBUG, - "setsockopt(UDP, SO_SNDBUF) to %u, failed.", - t); + "setsockopt(UDP, SO_SNDBUF) to %u, failed.", t); } set_net_priority(ws, dtls->dtls_tptr.fd, ws->user_config->net_priority); set_socket_timeout(ws, dtls->dtls_tptr.fd); @@ -438,16 +447,18 @@ static int setup_dtls_connection(struct worker_st *ws, struct dtls_st * dtls) ev_invoke(worker_loop, &dtls->io, EV_READ); return 0; - fail: +fail: gnutls_deinit(session); return -1; } -void ws_add_score_to_ip(worker_st *ws, unsigned points, unsigned final, unsigned discon_reason) +void ws_add_score_to_ip(worker_st *ws, unsigned int points, unsigned int final, + unsigned int discon_reason) { int ret, e; BanIpMsg msg = BAN_IP_MSG__INIT; BanIpReplyMsg *reply = NULL; + PROTOBUF_ALLOCATOR(pa, ws); /* no reporting if banning is disabled */ @@ -470,22 +481,24 @@ void ws_add_score_to_ip(worker_st *ws, unsigned points, unsigned final, unsigned } ret = send_msg(ws, ws->cmd_fd, CMD_BAN_IP, &msg, - (pack_size_func) ban_ip_msg__get_packed_size, - (pack_func) ban_ip_msg__pack); + (pack_size_func)ban_ip_msg__get_packed_size, + (pack_func)ban_ip_msg__pack); if (ret < 0) { e = errno; - oclog(ws, LOG_WARNING, "error in sending BAN IP message: %s", strerror(e)); + oclog(ws, LOG_WARNING, "error in sending BAN IP message: %s", + strerror(e)); return; } - ret = recv_msg(ws, ws->cmd_fd, CMD_BAN_IP_REPLY, - (void *)&reply, (unpack_func) ban_ip_reply_msg__unpack, DEFAULT_SOCKET_TIMEOUT); + ret = recv_msg(ws, ws->cmd_fd, CMD_BAN_IP_REPLY, (void *)&reply, + (unpack_func)ban_ip_reply_msg__unpack, + DEFAULT_SOCKET_TIMEOUT); if (ret < 0) { oclog(ws, LOG_ERR, "error receiving BAN IP reply message"); return; } - if (final ==0 && reply->reply != AUTH__REP__OK) { + if (final == 0 && reply->reply != AUTH__REP__OK) { /* we have exceeded the maximum score */ exit(EXIT_FAILURE); } @@ -493,8 +506,8 @@ void ws_add_score_to_ip(worker_st *ws, unsigned points, unsigned final, unsigned ban_ip_reply_msg__free_unpacked(reply, &pa); } -static -void send_stats_to_secmod(worker_st * ws, time_t now, unsigned discon_reason) +static void send_stats_to_secmod(worker_st *ws, time_t now, + unsigned int discon_reason) { CliStatsMsg msg = CLI_STATS_MSG__INIT; int sd, ret, e; @@ -508,6 +521,7 @@ void send_stats_to_secmod(worker_st * ws, time_t now, unsigned discon_reason) sd = connect_to_secmod(ws); if (sd >= 0) { char buf[64]; + msg.bytes_in = ws->tun_bytes_in; msg.bytes_out = ws->tun_bytes_out; msg.uptime = now - ws->session_start_time; @@ -520,20 +534,24 @@ void send_stats_to_secmod(worker_st * ws, time_t now, unsigned discon_reason) msg.discon_reason = discon_reason; } - msg.remote_ip = human_addr2((void *)&ws->remote_addr, ws->remote_addr_len, - buf, sizeof(buf), 0); + msg.remote_ip = human_addr2((void *)&ws->remote_addr, + ws->remote_addr_len, buf, + sizeof(buf), 0); msg.ipv4 = ws->vinfo.ipv4; msg.ipv6 = ws->vinfo.ipv6; - ret = send_msg_to_secmod(ws, sd, CMD_SEC_CLI_STATS, &msg, - (pack_size_func)cli_stats_msg__get_packed_size, - (pack_func) cli_stats_msg__pack); + ret = send_msg_to_secmod( + ws, sd, CMD_SEC_CLI_STATS, &msg, + (pack_size_func)cli_stats_msg__get_packed_size, + (pack_func)cli_stats_msg__pack); if (discon_reason) { /* wait for sec-mod to close connection to verify data have been accounted */ e = read(sd, buf, sizeof(buf)); if (e == -1) { e = errno; - oclog(ws, LOG_DEBUG, "could not wait for sec-mod: %s\n", strerror(e)); + oclog(ws, LOG_DEBUG, + "could not wait for sec-mod: %s\n", + strerror(e)); } } close(sd); @@ -545,7 +563,9 @@ void send_stats_to_secmod(worker_st * ws, time_t now, unsigned discon_reason) (unsigned long)msg.bytes_out); } else { e = errno; - oclog(ws, LOG_WARNING, "could not send periodic stats to sec-mod: %s\n", strerror(e)); + oclog(ws, LOG_WARNING, + "could not send periodic stats to sec-mod: %s\n", + strerror(e)); } } } @@ -553,12 +573,12 @@ void send_stats_to_secmod(worker_st * ws, time_t now, unsigned discon_reason) /* Terminates the worker process, but communicates any required * data to main process before (stats/ban points). */ -void exit_worker(worker_st * ws) +void exit_worker(worker_st *ws) { exit_worker_reason(ws, REASON_ANY); } -void exit_worker_reason(worker_st * ws, unsigned reason) +void exit_worker_reason(worker_st *ws, unsigned int reason) { /* send statistics to parent */ if (ws->auth_state == S_AUTH_COMPLETE) { @@ -574,47 +594,58 @@ void exit_worker_reason(worker_st * ws, unsigned reason) } #define HANDSHAKE_SESSION_ID_POS (34) -#define SKIP_V16(pos, total) \ - { \ - uint16_t _s; \ - if (pos+2 > total) goto finish; \ - _s = (msg->data[pos] << 8) | msg->data[pos+1]; \ - if (pos+2+_s > total) goto finish; \ - pos += 2+_s; \ +#define SKIP_V16(pos, total) \ + { \ + uint16_t _s; \ + if (pos + 2 > total) \ + goto finish; \ + _s = (msg->data[pos] << 8) | msg->data[pos + 1]; \ + if (pos + 2 + _s > total) \ + goto finish; \ + pos += 2 + _s; \ } -#define SKIP16(pos, total) { \ - if (pos+2 > total) goto finish; \ - pos += 2; } - -#define SKIP8(pos, total) { \ - if (pos+1 > total) goto finish; \ - pos++; } - -#define SKIP_V8(pos, total) \ - { \ - uint8_t _s; \ - if (pos+1 > total) goto finish; \ - _s = msg->data[pos]; \ - if (pos+1+_s > total) goto finish; \ - pos += 1+_s; \ +#define SKIP16(pos, total) \ + { \ + if (pos + 2 > total) \ + goto finish; \ + pos += 2; \ } -#define SET_VHOST_CREDS \ - do { \ - ret = \ - gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, \ - WSCREDS(ws)->xcred); \ - GNUTLS_FATAL_ERR(ret); \ - gnutls_certificate_server_set_request(session, WSCONFIG(ws)->cert_req); \ - ret = gnutls_priority_set(session, WSCREDS(ws)->cprio); \ - GNUTLS_FATAL_ERR(ret); \ - gnutls_db_set_cache_expiration(session, TLS_SESSION_EXPIRATION_TIME(WSCONFIG(ws))); \ +#define SKIP8(pos, total) \ + { \ + if (pos + 1 > total) \ + goto finish; \ + pos++; \ + } + +#define SKIP_V8(pos, total) \ + { \ + uint8_t _s; \ + if (pos + 1 > total) \ + goto finish; \ + _s = msg->data[pos]; \ + if (pos + 1 + _s > total) \ + goto finish; \ + pos += 1 + _s; \ + } + +#define SET_VHOST_CREDS \ + do { \ + ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, \ + WSCREDS(ws)->xcred); \ + GNUTLS_FATAL_ERR(ret); \ + gnutls_certificate_server_set_request(session, \ + WSCONFIG(ws)->cert_req); \ + ret = gnutls_priority_set(session, WSCREDS(ws)->cprio); \ + GNUTLS_FATAL_ERR(ret); \ + gnutls_db_set_cache_expiration( \ + session, TLS_SESSION_EXPIRATION_TIME(WSCONFIG(ws))); \ } while (0) /* Parse the TLS client hello to figure vhost */ static int hello_hook_func(gnutls_session_t session, unsigned int htype, - unsigned when, unsigned int incoming, + unsigned int when, unsigned int incoming, const gnutls_datum_t *msg) { @@ -654,23 +685,25 @@ static int hello_hook_func(gnutls_session_t session, unsigned int htype, /* read ExtensionType */ SKIP16(pos, msg->size); - type = (msg->data[pos-2] << 8) | msg->data[pos-1]; + type = (msg->data[pos - 2] << 8) | msg->data[pos - 1]; if (type == 0) { /* server name ext */ SKIP16(pos, msg->size); - SKIP16(pos, msg->size); /* we don't support anything but a single name */ + SKIP16(pos, + msg->size); /* we don't support anything but a single name */ SKIP8(pos, msg->size); - if (msg->data[pos-1] != 0) { /* HostName */ + if (msg->data[pos - 1] != 0) { /* HostName */ oclog(ws, LOG_DEBUG, "received server name extension with invalid name type field"); goto finish; } SKIP16(pos, msg->size); - hsize = (msg->data[pos-2] << 8) | msg->data[pos-1]; + hsize = (msg->data[pos - 2] << 8) | msg->data[pos - 1]; - if (hsize == 0 || hsize + pos > msg->size || hsize > sizeof(ws->buffer)-1) { + if (hsize == 0 || hsize + pos > msg->size || + hsize > sizeof(ws->buffer) - 1) { oclog(ws, LOG_DEBUG, "received server name extension with too large name"); goto finish; @@ -679,13 +712,16 @@ static int hello_hook_func(gnutls_session_t session, unsigned int htype, memcpy(ws->buffer, &msg->data[pos], hsize); ws->buffer[hsize] = 0; - oclog(ws, LOG_DEBUG, - "client requested hostname: %s", (char*)ws->buffer); + oclog(ws, LOG_DEBUG, "client requested hostname: %s", + (char *)ws->buffer); - ws->vhost = find_vhost(ws->vconfig, (char*)ws->buffer); - if (ws->vhost->name && strcasecmp(ws->vhost->name, (char*)ws->buffer) != 0) { + ws->vhost = find_vhost(ws->vconfig, (char *)ws->buffer); + if (ws->vhost->name && + strcasecmp(ws->vhost->name, (char *)ws->buffer) != + 0) { oclog(ws, LOG_INFO, - "client requested hostname %s does not match known vhost", (char*)ws->buffer); + "client requested hostname %s does not match known vhost", + (char *)ws->buffer); } goto finish; @@ -694,7 +730,7 @@ static int hello_hook_func(gnutls_session_t session, unsigned int htype, } } - finish: +finish: /* We set credentials irrespective of whether a virtual host was found, * as they have not been previously set. */ SET_VHOST_CREDS; @@ -703,7 +739,7 @@ static int hello_hook_func(gnutls_session_t session, unsigned int htype, } #if GNUTLS_VERSION_NUMBER < 0x030400 -# define SIMULATE_CLIENT_HELLO_HOOK +#define SIMULATE_CLIENT_HELLO_HOOK #endif #ifdef SIMULATE_CLIENT_HELLO_HOOK @@ -713,9 +749,10 @@ static int hello_hook_func(gnutls_session_t session, unsigned int htype, /* In gnutls 3.3 we don't get the size in the handshake callback * so we try to simulate. */ -static void peek_client_hello(struct worker_st *ws, gnutls_session_t session, int fd) +static void peek_client_hello(struct worker_st *ws, gnutls_session_t session, + int fd) { - unsigned read_tries = 0; + unsigned int read_tries = 0; int ret; size_t size, hsize; gnutls_datum_t msg; @@ -737,19 +774,20 @@ static void peek_client_hello(struct worker_st *ws, gnutls_session_t session, in goto fallback; hsize = (ws->buffer[3] << 8) | ws->buffer[4]; - } while (hsize+TLS_RECORD_HEADER > size); + } while (hsize + TLS_RECORD_HEADER > size); - if (size < TLS_RECORD_HEADER+TLS_HANDSHAKE_HEADER+HANDSHAKE_SESSION_ID_POS) + if (size < + TLS_RECORD_HEADER + TLS_HANDSHAKE_HEADER + HANDSHAKE_SESSION_ID_POS) goto fallback; - msg.data = ws->buffer + TLS_RECORD_HEADER+TLS_HANDSHAKE_HEADER; - msg.size = size - (TLS_RECORD_HEADER+TLS_HANDSHAKE_HEADER); - hello_hook_func(session, GNUTLS_HANDSHAKE_CLIENT_HELLO, - GNUTLS_HOOK_PRE, 1, &msg); + msg.data = ws->buffer + TLS_RECORD_HEADER + TLS_HANDSHAKE_HEADER; + msg.size = size - (TLS_RECORD_HEADER + TLS_HANDSHAKE_HEADER); + hello_hook_func(session, GNUTLS_HANDSHAKE_CLIENT_HELLO, GNUTLS_HOOK_PRE, + 1, &msg); return; - fallback: +fallback: SET_VHOST_CREDS; } #endif @@ -764,10 +802,10 @@ static void check_camouflage_url(struct worker_st *ws) return; } - char* url_camouflage_part = strchr(ws->req.url, '?'); - if (url_camouflage_part - && !strcmp(url_camouflage_part + 1, WSCONFIG(ws)->camouflage_secret)) - { + char *url_camouflage_part = strchr(ws->req.url, '?'); + + if (url_camouflage_part && + !strcmp(url_camouflage_part + 1, WSCONFIG(ws)->camouflage_secret)) { *url_camouflage_part = '\0'; ws->camouflage_check_passed = 1; } @@ -838,7 +876,9 @@ void vpn_server(struct worker_st *ws) } /* update ws->remote_ip_str */ - human_addr2((const struct sockaddr *)&ws->remote_addr, ws->remote_addr_len, ws->remote_ip_str, sizeof(ws->remote_ip_str), 0); + human_addr2((const struct sockaddr *)&ws->remote_addr, + ws->remote_addr_len, ws->remote_ip_str, + sizeof(ws->remote_ip_str), 0); } else { oclog(ws, LOG_DEBUG, "accepted connection"); } @@ -850,7 +890,8 @@ void vpn_server(struct worker_st *ws) ws->vhost = find_vhost(ws->vconfig, NULL); if (test_for_tcp_health_probe(ws) != 0) { - oclog(ws, LOG_DEBUG, "Received TCP health probe from load-balancer"); + oclog(ws, LOG_DEBUG, + "Received TCP health probe from load-balancer"); exit_worker_reason(ws, REASON_HEALTH_PROBE); } @@ -869,19 +910,22 @@ void vpn_server(struct worker_st *ws) #ifdef SIMULATE_CLIENT_HELLO_HOOK peek_client_hello(ws, session, ws->conn_fd); #else - gnutls_handshake_set_hook_function(session, GNUTLS_HANDSHAKE_CLIENT_HELLO, - GNUTLS_HOOK_PRE, hello_hook_func); + gnutls_handshake_set_hook_function( + session, GNUTLS_HANDSHAKE_CLIENT_HELLO, + GNUTLS_HOOK_PRE, hello_hook_func); #endif } - gnutls_transport_set_ptr(session, - (gnutls_transport_ptr_t) (long)ws->conn_fd); + gnutls_transport_set_ptr( + session, (gnutls_transport_ptr_t)(long)ws->conn_fd); set_resume_db_funcs(session); gnutls_db_set_ptr(session, ws); - gnutls_handshake_set_timeout(session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT); - gnutls_transport_set_pull_timeout_function(session, tls_pull_timeout); + gnutls_handshake_set_timeout(session, + GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT); + gnutls_transport_set_pull_timeout_function(session, + tls_pull_timeout); do { ret = gnutls_handshake(session); } while (ret < 0 && gnutls_error_is_fatal(ret) == 0); @@ -914,12 +958,13 @@ void vpn_server(struct worker_st *ws) http_req_init(ws); if (WSCONFIG(ws)->listen_proxy_proto) { - oclog(ws, LOG_DEBUG, "proxy-hdr: peer is %s\n", ws->remote_ip_str); + oclog(ws, LOG_DEBUG, "proxy-hdr: peer is %s\n", + ws->remote_ip_str); } ws->parser = &parser; - restart: +restart: if (requests_left-- <= 0) { oclog(ws, LOG_INFO, "maximum number of HTTP requests reached"); exit_worker(ws); @@ -941,24 +986,26 @@ void vpn_server(struct worker_st *ws) } lerr = llhttp_execute(&parser, (void *)ws->buffer, nrecvd); - if (lerr == HPE_PAUSED_UPGRADE && parser.method == HTTP_CONNECT) { + if (lerr == HPE_PAUSED_UPGRADE && + parser.method == HTTP_CONNECT) { llhttp_resume_after_upgrade(&parser); break; } else if (lerr != HPE_OK) { - oclog(ws, LOG_INFO, "error parsing HTTP request: %s", llhttp_errno_name(lerr)); + oclog(ws, LOG_INFO, "error parsing HTTP request: %s", + llhttp_errno_name(lerr)); exit_worker(ws); } } while (ws->req.headers_complete == 0); if ((parser.method == HTTP_GET || parser.method == HTTP_POST) && - (WSCONFIG(ws)->camouflage && ws->camouflage_check_passed == 0)) - { + (WSCONFIG(ws)->camouflage && ws->camouflage_check_passed == 0)) { check_camouflage_url(ws); - if (ws->camouflage_check_passed == 0) - { - oclog(ws, LOG_INFO, "Secret not found in URL, declining..."); + if (ws->camouflage_check_passed == 0) { + oclog(ws, LOG_INFO, + "Secret not found in URL, declining..."); if (WSCONFIG(ws)->camouflage_realm) - response_401(ws, parser.http_minor, WSCONFIG(ws)->camouflage_realm); + response_401(ws, parser.http_minor, + WSCONFIG(ws)->camouflage_realm); else response_404(ws, parser.http_minor); goto finish; @@ -969,13 +1016,14 @@ void vpn_server(struct worker_st *ws) oclog(ws, LOG_HTTP_DEBUG, "HTTP GET %s", ws->req.url); fn = http_get_url_handler(ws->req.url); if (fn == NULL) { - oclog(ws, LOG_HTTP_DEBUG, "unexpected URL %s", ws->req.url); + oclog(ws, LOG_HTTP_DEBUG, "unexpected URL %s", + ws->req.url); response_404(ws, parser.http_minor); goto finish; } ret = fn(ws, parser.http_minor); - if (ret == 0 - && (parser.http_major != 1 || parser.http_minor != 0)) + if (ret == 0 && + (parser.http_major != 1 || parser.http_minor != 0)) goto restart; } else if (parser.method == HTTP_POST) { @@ -991,11 +1039,12 @@ void vpn_server(struct worker_st *ws) exit_worker(ws); } - lerr = - llhttp_execute(&parser, (void *)ws->buffer, nrecvd); + lerr = llhttp_execute(&parser, (void *)ws->buffer, + nrecvd); if (lerr != HPE_OK) { oclog(ws, LOG_HTTP_DEBUG, - "error parsing HTTP POST request: %s", llhttp_errno_name(lerr)); + "error parsing HTTP POST request: %s", + llhttp_errno_name(lerr)); exit_worker(ws); } } @@ -1009,15 +1058,15 @@ void vpn_server(struct worker_st *ws) } ret = fn(ws, parser.http_minor); - if (ret == 0 - && (parser.http_major != 1 || parser.http_minor != 0)) + if (ret == 0 && + (parser.http_major != 1 || parser.http_minor != 0)) goto restart; } else if (parser.method == HTTP_CONNECT) { oclog(ws, LOG_HTTP_DEBUG, "HTTP CONNECT %s", ws->req.url); ret = connect_handler(ws); - if (ret == 0 - && (parser.http_major != 1 || parser.http_minor != 0)) + if (ret == 0 && + (parser.http_major != 1 || parser.http_minor != 0)) goto restart; } else { @@ -1026,54 +1075,53 @@ void vpn_server(struct worker_st *ws) response_404(ws, parser.http_minor); } - finish: +finish: llhttp_finish(&parser); cstp_close(ws); } -static -void data_mtu_send(worker_st * ws, unsigned mtu) +static void data_mtu_send(worker_st *ws, unsigned int mtu) { TunMtuMsg msg = TUN_MTU_MSG__INIT; msg.mtu = mtu; send_msg_to_main(ws, CMD_TUN_MTU, &msg, - (pack_size_func) tun_mtu_msg__get_packed_size, - (pack_func) tun_mtu_msg__pack); + (pack_size_func)tun_mtu_msg__get_packed_size, + (pack_func)tun_mtu_msg__pack); oclog(ws, LOG_DEBUG, "setting data MTU to %u", msg.mtu); } -static -void session_info_send(worker_st * ws) +static void session_info_send(worker_st *ws) { SessionInfoMsg msg = SESSION_INFO_MSG__INIT; if (ws->session) { msg.tls_ciphersuite = gnutls_session_get_desc(ws->session); if (ws->cstp_selected_comp) - msg.cstp_compr = (char*)ws->cstp_selected_comp->name; + msg.cstp_compr = (char *)ws->cstp_selected_comp->name; } - if (DTLS_ACTIVE(ws)->udp_state != UP_DISABLED && DTLS_ACTIVE(ws)->dtls_session) { + if (DTLS_ACTIVE(ws)->udp_state != UP_DISABLED && + DTLS_ACTIVE(ws)->dtls_session) { msg.dtls_ciphersuite = - gnutls_session_get_desc(DTLS_ACTIVE(ws)->dtls_session); + gnutls_session_get_desc(DTLS_ACTIVE(ws)->dtls_session); if (ws->dtls_selected_comp) - msg.dtls_compr = (char*)ws->dtls_selected_comp->name; + msg.dtls_compr = (char *)ws->dtls_selected_comp->name; } if (WSCONFIG(ws)->listen_proxy_proto) { - msg.our_addr.data = (uint8_t*)&ws->our_addr; + msg.our_addr.data = (uint8_t *)&ws->our_addr; msg.our_addr.len = ws->our_addr_len; msg.has_our_addr = 1; - msg.remote_addr.data = (uint8_t*)&ws->remote_addr; + msg.remote_addr.data = (uint8_t *)&ws->remote_addr; msg.remote_addr.len = ws->remote_addr_len; msg.has_remote_addr = 1; } send_msg_to_main(ws, CMD_SESSION_INFO, &msg, - (pack_size_func) session_info_msg__get_packed_size, - (pack_func) session_info_msg__pack); + (pack_size_func)session_info_msg__get_packed_size, + (pack_func)session_info_msg__pack); gnutls_free(msg.tls_ciphersuite); gnutls_free(msg.dtls_ciphersuite); @@ -1084,8 +1132,8 @@ void session_info_send(worker_st * ws) * @ws: a worker structure * @mtu: the link MTU */ -static -void link_mtu_set(struct worker_st * ws, struct dtls_st * dtls, unsigned mtu) +static void link_mtu_set(struct worker_st *ws, struct dtls_st *dtls, + unsigned int mtu) { if (ws->link_mtu == mtu || mtu > sizeof(ws->buffer)) return; @@ -1105,11 +1153,10 @@ void link_mtu_set(struct worker_st * ws, struct dtls_st * dtls, unsigned mtu) * @ws: a worker structure * @mtu: the "plaintext" data MTU (not including the DTLS protocol byte) */ -static -void data_mtu_set(worker_st * ws, struct dtls_st * dtls, unsigned mtu) +static void data_mtu_set(worker_st *ws, struct dtls_st *dtls, unsigned int mtu) { if (dtls->dtls_session) { - gnutls_dtls_set_data_mtu(dtls->dtls_session, mtu+1); + gnutls_dtls_set_data_mtu(dtls->dtls_session, mtu + 1); mtu = gnutls_dtls_get_mtu(dtls->dtls_session); if (mtu <= 0 || mtu == ws->link_mtu) @@ -1120,7 +1167,7 @@ void data_mtu_set(worker_st * ws, struct dtls_st * dtls, unsigned mtu) } } -static void disable_mtu_disc(worker_st *ws, struct dtls_st * dtls) +static void disable_mtu_disc(worker_st *ws, struct dtls_st *dtls) { oclog(ws, LOG_DEBUG, "disabling MTU discovery on UDP socket"); set_mtu_disc(dtls->dtls_tptr.fd, ws->proto, 0); @@ -1133,14 +1180,13 @@ static void disable_mtu_disc(worker_st *ws, struct dtls_st * dtls) * * Returns -1 on failure. */ -static -int mtu_not_ok(worker_st * ws, struct dtls_st * dtls) +static int mtu_not_ok(worker_st *ws, struct dtls_st *dtls) { if (WSCONFIG(ws)->try_mtu == 0 || dtls->dtls_session == NULL) return 0; if (ws->proto == AF_INET) { - const unsigned min = MIN_MTU(ws); + const unsigned int min = MIN_MTU(ws); ws->last_bad_mtu = ws->link_mtu; @@ -1153,7 +1199,8 @@ int mtu_not_ok(worker_st * ws, struct dtls_st * dtls) } if (ws->last_good_mtu >= ws->link_mtu) { - ws->last_good_mtu = MAX(((2 * (ws->link_mtu)) / 3), min); + ws->last_good_mtu = + MAX(((2 * (ws->link_mtu)) / 3), min); } link_mtu_set(ws, dtls, ws->last_good_mtu); @@ -1164,20 +1211,26 @@ int mtu_not_ok(worker_st * ws, struct dtls_st * dtls) struct ip6_mtuinfo mtuinfo; socklen_t len = sizeof(mtuinfo); - if (getsockopt(dtls->dtls_tptr.fd, IPPROTO_IPV6, IPV6_PATHMTU, &mtuinfo, &len) < 0 || mtuinfo.ip6m_mtu < 1280) { - oclog(ws, LOG_INFO, "cannot obtain IPv6 MTU (was %u); disabling MTU discovery", + if (getsockopt(dtls->dtls_tptr.fd, IPPROTO_IPV6, IPV6_PATHMTU, + &mtuinfo, &len) < 0 || + mtuinfo.ip6m_mtu < 1280) { + oclog(ws, LOG_INFO, + "cannot obtain IPv6 MTU (was %u); disabling MTU discovery", ws->link_mtu); disable_mtu_disc(ws, dtls); link_mtu_set(ws, dtls, MIN_MTU(ws)); return 0; } - oclog(ws, LOG_DEBUG, "setting (via IPV6_PATHMTU) connection MTU to %u", mtuinfo.ip6m_mtu); + oclog(ws, LOG_DEBUG, + "setting (via IPV6_PATHMTU) connection MTU to %u", + mtuinfo.ip6m_mtu); link_mtu_set(ws, dtls, mtuinfo.ip6m_mtu); if (mtuinfo.ip6m_mtu > ws->adv_link_mtu) { - oclog(ws, LOG_INFO, "the discovered IPv6 MTU (%u) is larger than the advertised (%u); disabling MTU discovery", - (unsigned)mtuinfo.ip6m_mtu, ws->adv_link_mtu); + oclog(ws, LOG_INFO, + "the discovered IPv6 MTU (%u) is larger than the advertised (%u); disabling MTU discovery", + (unsigned int)mtuinfo.ip6m_mtu, ws->adv_link_mtu); return 0; } #else @@ -1193,9 +1246,11 @@ int mtu_not_ok(worker_st * ws, struct dtls_st * dtls) * @ws: a worker structure * @mtu: the current "plaintext" data MTU */ -static void mtu_discovery_init(worker_st * ws, struct dtls_st * dtls, unsigned mtu) +static void mtu_discovery_init(worker_st *ws, struct dtls_st *dtls, + unsigned int mtu) { - const unsigned min = MIN_MTU(ws); + const unsigned int min = MIN_MTU(ws); + if (mtu <= min) { oclog(ws, LOG_INFO, "our initial MTU is too low; disabling MTU discovery"); @@ -1210,8 +1265,7 @@ static void mtu_discovery_init(worker_st * ws, struct dtls_st * dtls, unsigned m ws->last_bad_mtu = mtu; } -static -void mtu_ok(worker_st * ws, struct dtls_st * dtls) +static void mtu_ok(worker_st *ws, struct dtls_st *dtls) { unsigned int c; @@ -1228,11 +1282,13 @@ void mtu_ok(worker_st * ws, struct dtls_st * dtls) link_mtu_set(ws, dtls, c); } -#define FUZZ(x, diff, rnd) { \ - if (x > diff) { \ - int16_t r = rnd; \ - x += r % diff; \ - }} +#define FUZZ(x, diff, rnd) \ + { \ + if (x > diff) { \ + int16_t r = rnd; \ + x += r % diff; \ + } \ + } int get_pmtu_approx(worker_st *ws) { @@ -1241,6 +1297,7 @@ int get_pmtu_approx(worker_st *ws) #if defined(__linux__) && defined(TCP_INFO) struct tcp_info ti; + sl = sizeof(ti); ret = getsockopt(ws->conn_fd, IPPROTO_TCP, TCP_INFO, &ti, &sl); @@ -1269,8 +1326,8 @@ int get_pmtu_approx(worker_st *ws) #endif } -static -int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) +static int periodic_check(worker_st *ws, struct timespec *tnow, + unsigned int dpd) { int max, ret; time_t now = tnow->tv_sec; @@ -1303,7 +1360,8 @@ int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) } if (ws->user_config->session_timeout_secs > 0) { - if (now - ws->session_start_time > ws->user_config->session_timeout_secs) { + if (now - ws->session_start_time > + ws->user_config->session_timeout_secs) { oclog(ws, LOG_NOTICE, "session timeout reached for process (%d secs)", (int)(now - ws->session_start_time)); @@ -1320,7 +1378,8 @@ int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) } #if defined(CAPTURE_LATENCY_SUPPORT) - if (now - ws->latency.last_stats_msg >= LATENCY_WORKER_AGGREGATION_TIME) { + if (now - ws->latency.last_stats_msg >= + LATENCY_WORKER_AGGREGATION_TIME) { send_latency_stats_delta_to_main(ws, now); } #endif @@ -1328,15 +1387,16 @@ int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) /* check DPD. Otherwise exit */ if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && now - ws->last_msg_udp > DPD_TRIES * dpd && dpd > 0) { - unsigned data_mtu = DATA_MTU(ws, ws->link_mtu); + unsigned int data_mtu = DATA_MTU(ws, ws->link_mtu); + oclog(ws, LOG_NOTICE, "have not received any UDP message or DPD for long (%d secs, DPD is %d)", (int)(now - ws->last_msg_udp), dpd); - memset(ws->buffer+1, 0, data_mtu); + memset(ws->buffer + 1, 0, data_mtu); ws->buffer[0] = AC_PKT_DPD_OUT; - ret = dtls_send(DTLS_ACTIVE(ws), ws->buffer, data_mtu+1); + ret = dtls_send(DTLS_ACTIVE(ws), ws->buffer, data_mtu + 1); DTLS_FATAL_ERR_CMD(ret, exit_worker_reason(ws, REASON_ERROR)); if (now - ws->last_msg_udp > DPD_MAX_TRIES * dpd) { @@ -1359,7 +1419,8 @@ int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) ws->buffer[7] = 0; ret = cstp_send(ws, ws->buffer, 8); - CSTP_FATAL_ERR_CMD(ws, ret, exit_worker_reason(ws, REASON_ERROR)); + CSTP_FATAL_ERR_CMD(ws, ret, + exit_worker_reason(ws, REASON_ERROR)); if (now - ws->last_msg_tcp > DPD_MAX_TRIES * dpd) { oclog(ws, LOG_NOTICE, @@ -1368,16 +1429,17 @@ int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) } } - if (ws->conn_type != SOCK_TYPE_UNIX && DTLS_ACTIVE(ws)->udp_state != UP_DISABLED) { + if (ws->conn_type != SOCK_TYPE_UNIX && + DTLS_ACTIVE(ws)->udp_state != UP_DISABLED) { max = get_pmtu_approx(ws); if (max > 0 && max < ws->link_mtu) { - oclog(ws, LOG_DEBUG, "reducing MTU due to TCP/PMTU to %u", - max); + oclog(ws, LOG_DEBUG, + "reducing MTU due to TCP/PMTU to %u", max); link_mtu_set(ws, DTLS_ACTIVE(ws), max); } } - cleanup: +cleanup: ws->last_periodic_check = now; return 0; @@ -1386,20 +1448,20 @@ int periodic_check(worker_st * ws, struct timespec *tnow, unsigned dpd) /* Disable any TCP queuing on the TLS port. This allows a connection that works over * TCP instead of UDP to still be interactive. */ -static void set_no_delay(worker_st * ws, int fd) +static void set_no_delay(worker_st *ws, int fd) { int flag = 1; int ret; ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)); if (ret == -1) - oclog(ws, LOG_DEBUG, - "setsockopt(TCP_NODELAY) to %x, failed.", (unsigned)flag); + oclog(ws, LOG_DEBUG, "setsockopt(TCP_NODELAY) to %x, failed.", + (unsigned int)flag); } #define TOSCLASS(x) (IPTOS_CLASS_CS##x) -static void set_net_priority(worker_st * ws, int fd, int priority) +static void set_net_priority(worker_st *ws, int fd, int priority) { int t; int ret; @@ -1409,7 +1471,8 @@ static void set_net_priority(worker_st * ws, int fd, int priority) ret = setsockopt(fd, IPPROTO_IP, IP_TOS, &t, sizeof(t)); if (ret == -1) oclog(ws, LOG_DEBUG, - "setsockopt(IP_TOS) to %x, failed.", (unsigned)t); + "setsockopt(IP_TOS) to %x, failed.", + (unsigned int)t); return; } @@ -1428,9 +1491,14 @@ static void set_net_priority(worker_st * ws, int fd, int priority) #endif } -#define SEND_ERR(x) { if (x<0) goto send_error; } +#define SEND_ERR(x) \ + { \ + if (x < 0) \ + goto send_error; \ + } -static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec *tnow) +static int dtls_mainloop(worker_st *ws, struct dtls_st *dtls, + struct timespec *tnow) { int ret; gnutls_datum_t data; @@ -1440,16 +1508,15 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec case UP_ACTIVE: case UP_INACTIVE: ret = dtls_recv_packet(dtls, &data, &packet); - oclog(ws, LOG_TRANSFER_DEBUG, - "received %d byte(s) (DTLS)", ret); + oclog(ws, LOG_TRANSFER_DEBUG, "received %d byte(s) (DTLS)", + ret); DTLS_FATAL_ERR_CMD(ret, exit_worker_reason(ws, REASON_ERROR)); if (ret == GNUTLS_E_REHANDSHAKE) { - if (dtls->last_dtls_rehandshake > 0 && tnow->tv_sec - dtls->last_dtls_rehandshake < - WSCONFIG(ws)->rekey_time / 2) { + WSCONFIG(ws)->rekey_time / 2) { oclog(ws, LOG_INFO, "client requested DTLS rehandshake too soon"); ret = -1; @@ -1464,11 +1531,12 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec do { ret = gnutls_handshake(dtls->dtls_session); - } while (ret == GNUTLS_E_AGAIN - || ret == GNUTLS_E_INTERRUPTED); + } while (ret == GNUTLS_E_AGAIN || + ret == GNUTLS_E_INTERRUPTED); GNUTLS_ALERT_PRINT(ws, dtls->dtls_session, ret); - DTLS_FATAL_ERR_CMD(ret, exit_worker_reason(ws, REASON_ERROR)); + DTLS_FATAL_ERR_CMD( + ret, exit_worker_reason(ws, REASON_ERROR)); oclog(ws, LOG_DEBUG, "DTLS rehandshake completed"); dtls->last_dtls_rehandshake = tnow->tv_sec; @@ -1477,11 +1545,11 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec * to active */ dtls->udp_state = UP_ACTIVE; - if (bandwidth_update - (&ws->b_rx, data.size - CSTP_DTLS_OVERHEAD, tnow) != 0) { - ret = - parse_dtls_data(ws, data.data, data.size, - tnow->tv_sec); + if (bandwidth_update(&ws->b_rx, + data.size - CSTP_DTLS_OVERHEAD, + tnow) != 0) { + ret = parse_dtls_data(ws, data.data, data.size, + tnow->tv_sec); if (ret < 0) { oclog(ws, LOG_INFO, "error parsing DTLS data"); @@ -1489,8 +1557,8 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec } } } else - oclog(ws, LOG_TRANSFER_DEBUG, - "no data received (%d)", ret); + oclog(ws, LOG_TRANSFER_DEBUG, "no data received (%d)", + ret); ws->udp_recv_time = tnow->tv_sec; break; @@ -1501,20 +1569,21 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec goto cleanup; } - gnutls_dtls_set_mtu(dtls->dtls_session, ws->link_mtu - ws->dtls_proto_overhead); + gnutls_dtls_set_mtu(dtls->dtls_session, + ws->link_mtu - ws->dtls_proto_overhead); mtu_discovery_init(ws, dtls, ws->link_mtu); break; case UP_HANDSHAKE: - hsk_restart: +hsk_restart: ret = gnutls_handshake(dtls->dtls_session); if (ret < 0 && gnutls_error_is_fatal(ret) != 0) { if (ret == GNUTLS_E_FATAL_ALERT_RECEIVED) oclog(ws, LOG_ERR, "error in DTLS handshake: %s: %s\n", gnutls_strerror(ret), - gnutls_alert_get_name - (gnutls_alert_get(dtls->dtls_session))); + gnutls_alert_get_name(gnutls_alert_get( + dtls->dtls_session))); else oclog(ws, LOG_ERR, "error in DTLS handshake: %s\n", @@ -1529,20 +1598,20 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec mtu_not_ok(ws, dtls); goto hsk_restart; } else if (ret == 0) { - unsigned data_mtu; + unsigned int data_mtu; /* gnutls_dtls_get_data_mtu() already subtracts the crypto overhead */ data_mtu = - gnutls_dtls_get_data_mtu(dtls->dtls_session) - - CSTP_DTLS_OVERHEAD; + gnutls_dtls_get_data_mtu(dtls->dtls_session) - + CSTP_DTLS_OVERHEAD; dtls->udp_state = UP_ACTIVE; oclog(ws, LOG_DEBUG, "DTLS handshake completed (link MTU: %u, data MTU: %u)\n", ws->link_mtu, data_mtu); ws->dtls_active_session++; - oclog(ws, LOG_DEBUG, - "Main DTLS session %d active", ws->dtls_active_session); + oclog(ws, LOG_DEBUG, "Main DTLS session %d active", + ws->dtls_active_session); session_info_send(ws); } @@ -1552,7 +1621,7 @@ static int dtls_mainloop(worker_st * ws, struct dtls_st * dtls, struct timespec } ret = 0; - cleanup: +cleanup: packet_deinit(packet); return ret; } @@ -1572,25 +1641,29 @@ static int tls_mainloop(struct worker_st *ws, struct timespec *tnow) CSTP_FATAL_ERR_CMD(ws, ret, exit_worker_reason(ws, REASON_ERROR)); - if (ret == 0) { /* disconnect */ + if (ret == 0) { /* disconnect */ oclog(ws, LOG_DEBUG, "client disconnected"); ret = -1; goto cleanup; } else if (ret >= 8) { - oclog(ws, LOG_TRANSFER_DEBUG, "received %d byte(s) (TLS)", data.size); + oclog(ws, LOG_TRANSFER_DEBUG, "received %d byte(s) (TLS)", + data.size); if (bandwidth_update(&ws->b_rx, data.size - 8, tnow) != 0) { - ret = parse_cstp_data(ws, data.data, data.size, tnow->tv_sec); + ret = parse_cstp_data(ws, data.data, data.size, + tnow->tv_sec); if (ret < 0) { oclog(ws, LOG_ERR, "error parsing CSTP data"); goto cleanup; } - if ((ret == AC_PKT_DATA || ret == AC_PKT_COMPRESSED) && DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE) { + if ((ret == AC_PKT_DATA || ret == AC_PKT_COMPRESSED) && + DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE) { /* client switched to TLS for some reason */ if (tnow->tv_sec - ws->udp_recv_time > UDP_SWITCH_TIME) - DTLS_ACTIVE(ws)->udp_state = UP_INACTIVE; + DTLS_ACTIVE(ws)->udp_state = + UP_INACTIVE; } } @@ -1598,7 +1671,7 @@ static int tls_mainloop(struct worker_st *ws, struct timespec *tnow) /* rekey? */ if (ws->last_tls_rehandshake > 0 && tnow->tv_sec - ws->last_tls_rehandshake < - WSCONFIG(ws)->rekey_time / 2) { + WSCONFIG(ws)->rekey_time / 2) { oclog(ws, LOG_INFO, "client requested TLS rehandshake too soon"); ret = -1; @@ -1618,7 +1691,7 @@ static int tls_mainloop(struct worker_st *ws, struct timespec *tnow) } ret = 0; - cleanup: +cleanup: packet_deinit(packet); return ret; } @@ -1629,6 +1702,7 @@ static bool is_data(const uint8_t *data, size_t size) { if (size > 20) { uint8_t version = data[0] >> 4; + if (version == 0x04) { if (data[9] == 0x01 || data[9] == 0x02) /* ICMP/IGMP */ return 0; @@ -1643,7 +1717,7 @@ static bool is_data(const uint8_t *data, size_t size) static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) { int ret, l, e; - unsigned tls_retry; + unsigned int tls_retry; int dtls_type = AC_PKT_DATA; int cstp_type = AC_PKT_DATA; gnutls_datum_t dtls_to_send; @@ -1655,8 +1729,8 @@ static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) if (e != EAGAIN && e != EINTR) { oclog(ws, LOG_ERR, - "received corrupt data from tun (%d): %s", - l, strerror(e)); + "received corrupt data from tun (%d): %s", l, + strerror(e)); return -1; } @@ -1676,34 +1750,46 @@ static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) if (WSCONFIG(ws)->switch_to_tcp_timeout && DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && - tnow->tv_sec > ws->udp_recv_time + WSCONFIG(ws)->switch_to_tcp_timeout) { - oclog(ws, LOG_DEBUG, "No UDP data received for %li seconds, using TCP instead\n", - tnow->tv_sec - ws->udp_recv_time); + tnow->tv_sec > + ws->udp_recv_time + WSCONFIG(ws)->switch_to_tcp_timeout) { + oclog(ws, LOG_DEBUG, + "No UDP data received for %li seconds, using TCP instead\n", + tnow->tv_sec - ws->udp_recv_time); DTLS_ACTIVE(ws)->udp_state = UP_INACTIVE; } #ifdef ENABLE_COMPRESSION - if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && ws->dtls_selected_comp != NULL && l > WSCONFIG(ws)->no_compress_limit) { + if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && + ws->dtls_selected_comp != NULL && + l > WSCONFIG(ws)->no_compress_limit) { /* otherwise don't compress */ - ret = ws->dtls_selected_comp->compress(ws->decomp+8, sizeof(ws->decomp)-8, ws->buffer+8, l); - oclog(ws, LOG_TRANSFER_DEBUG, "compressed %d to %d\n", (int)l, ret); + ret = ws->dtls_selected_comp->compress(ws->decomp + 8, + sizeof(ws->decomp) - 8, + ws->buffer + 8, l); + oclog(ws, LOG_TRANSFER_DEBUG, "compressed %d to %d\n", (int)l, + ret); if (ret > 0 && ret < l) { dtls_to_send.data = ws->decomp; dtls_to_send.size = ret; dtls_type = AC_PKT_COMPRESSED; if (ws->cstp_selected_comp) { - if (ws->cstp_selected_comp->id == ws->dtls_selected_comp->id) { + if (ws->cstp_selected_comp->id == + ws->dtls_selected_comp->id) { cstp_to_send.data = ws->decomp; cstp_to_send.size = ret; cstp_type = AC_PKT_COMPRESSED; } } } - } else if (ws->cstp_selected_comp != NULL && l > WSCONFIG(ws)->no_compress_limit) { + } else if (ws->cstp_selected_comp != NULL && + l > WSCONFIG(ws)->no_compress_limit) { /* otherwise don't compress */ - ret = ws->cstp_selected_comp->compress(ws->decomp+8, sizeof(ws->decomp)-8, ws->buffer+8, l); - oclog(ws, LOG_TRANSFER_DEBUG, "compressed %d to %d\n", (int)l, ret); + ret = ws->cstp_selected_comp->compress(ws->decomp + 8, + sizeof(ws->decomp) - 8, + ws->buffer + 8, l); + oclog(ws, LOG_TRANSFER_DEBUG, "compressed %d to %d\n", (int)l, + ret); if (ret > 0 && ret < l) { cstp_to_send.data = ws->decomp; cstp_to_send.size = ret; @@ -1713,19 +1799,19 @@ static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) #endif /* only transmit if allowed */ - if (bandwidth_update(&ws->b_tx, dtls_to_send.size, tnow) - != 0) { + if (bandwidth_update(&ws->b_tx, dtls_to_send.size, tnow) != 0) { tls_retry = 0; oclog(ws, LOG_TRANSFER_DEBUG, "sending %d byte(s)\n", l); if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE) { - ws->tun_bytes_out += dtls_to_send.size; dtls_to_send.data[7] = dtls_type; - ret = dtls_send(DTLS_ACTIVE(ws), dtls_to_send.data + 7, dtls_to_send.size + 1); - DTLS_FATAL_ERR_CMD(ret, exit_worker_reason(ws, REASON_ERROR)); + ret = dtls_send(DTLS_ACTIVE(ws), dtls_to_send.data + 7, + dtls_to_send.size + 1); + DTLS_FATAL_ERR_CMD( + ret, exit_worker_reason(ws, REASON_ERROR)); if (ret == GNUTLS_E_LARGE_PACKET) { mtu_not_ok(ws, DTLS_ACTIVE(ws)); @@ -1733,7 +1819,7 @@ static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) oclog(ws, LOG_TRANSFER_DEBUG, "retrying (TLS) %d\n", l); tls_retry = 1; - } else if (ret >= 1+DATA_MTU(ws, ws->link_mtu) && + } else if (ret >= 1 + DATA_MTU(ws, ws->link_mtu) && WSCONFIG(ws)->try_mtu != 0) { mtu_ok(ws, DTLS_ACTIVE(ws)); } @@ -1751,8 +1837,10 @@ static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) ws->tun_bytes_out += cstp_to_send.size; - ret = cstp_send(ws, cstp_to_send.data, cstp_to_send.size + 8); - CSTP_FATAL_ERR_CMD(ws, ret, exit_worker_reason(ws, REASON_ERROR)); + ret = cstp_send(ws, cstp_to_send.data, + cstp_to_send.size + 8); + CSTP_FATAL_ERR_CMD( + ws, ret, exit_worker_reason(ws, REASON_ERROR)); } if (is_data(ws->buffer + 8, l)) /* do not account ICMP */ @@ -1762,8 +1850,7 @@ static int tun_mainloop(struct worker_st *ws, struct timespec *tnow) return 0; } -static -char *replace_vals(worker_st *ws, const char *txt) +static char *replace_vals(worker_st *ws, const char *txt) { str_st str; int ret; @@ -1786,15 +1873,14 @@ char *replace_vals(worker_st *ws, const char *txt) return NULL; } - return (char*)str.data; + return (char *)str.data; } -static int send_routes(worker_st *ws, struct http_req_st *req, - char **routes, unsigned routes_size, - bool include) +static int send_routes(worker_st *ws, struct http_req_st *req, char **routes, + unsigned int routes_size, bool include) { - unsigned i; - unsigned ip6; + unsigned int i; + unsigned int ip6; const char *txt; int ret; @@ -1816,13 +1902,11 @@ static int send_routes(worker_st *ws, struct http_req_st *req, oclog(ws, LOG_DEBUG, "%s route %s", txt, routes[i]); if (ip6 != 0 && ws->full_ipv6) { - ret = cstp_printf(ws, - "X-CSTP-Split-%s-IP6: %s\r\n", - txt, routes[i]); + ret = cstp_printf(ws, "X-CSTP-Split-%s-IP6: %s\r\n", + txt, routes[i]); } else { - ret = cstp_printf(ws, - "X-CSTP-Split-%s: %s\r\n", - txt, routes[i]); + ret = cstp_printf(ws, "X-CSTP-Split-%s: %s\r\n", txt, + routes[i]); } if (ret < 0) return ret; @@ -1834,31 +1918,38 @@ static int send_routes(worker_st *ws, struct http_req_st *req, * use poll() to see whether a call to recv() would block, * there are certain cases in Linux where recv() blocks even * though poll() notified of data */ -static void set_socket_timeout(worker_st * ws, int fd) +static void set_socket_timeout(worker_st *ws, int fd) { struct timeval tval; int ret; tval.tv_sec = DEFAULT_SOCKET_TIMEOUT; tval.tv_usec = 0; - ret = - setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tval, - sizeof(tval)); + ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tval, sizeof(tval)); if (ret == -1) { int e = errno; - oclog(ws, LOG_DEBUG, - "setsockopt(%s, SO_RCVTIMEO) failed: %s", (fd==ws->conn_fd)?"ΤCP":"UDP", strerror(e)); + + oclog(ws, LOG_DEBUG, "setsockopt(%s, SO_RCVTIMEO) failed: %s", + (fd == ws->conn_fd) ? "ΤCP" : "UDP", strerror(e)); } } /* wild but conservative guess; this ciphersuite has the largest overhead */ -#define MAX_CSTP_CRYPTO_OVERHEAD (CSTP_OVERHEAD+tls_get_overhead(GNUTLS_TLS1_0, GNUTLS_CIPHER_AES_128_CBC, GNUTLS_MAC_SHA1)) -#define MAX_DTLS_CRYPTO_OVERHEAD (CSTP_DTLS_OVERHEAD+tls_get_overhead(GNUTLS_DTLS1_0, GNUTLS_CIPHER_AES_128_CBC, GNUTLS_MAC_SHA1)) -#define MAX_DTLS_PROTO_OVERHEAD(ws) ((ws->proto == AF_INET)?(IP_HEADER_SIZE+UDP_HEADER_SIZE):(IPV6_HEADER_SIZE+UDP_HEADER_SIZE)) +#define MAX_CSTP_CRYPTO_OVERHEAD \ + (CSTP_OVERHEAD + tls_get_overhead(GNUTLS_TLS1_0, \ + GNUTLS_CIPHER_AES_128_CBC, \ + GNUTLS_MAC_SHA1)) +#define MAX_DTLS_CRYPTO_OVERHEAD \ + (CSTP_DTLS_OVERHEAD + tls_get_overhead(GNUTLS_DTLS1_0, \ + GNUTLS_CIPHER_AES_128_CBC, \ + GNUTLS_MAC_SHA1)) +#define MAX_DTLS_PROTO_OVERHEAD(ws) \ + ((ws->proto == AF_INET) ? (IP_HEADER_SIZE + UDP_HEADER_SIZE) : \ + (IPV6_HEADER_SIZE + UDP_HEADER_SIZE)) /* Calculate MTU for CSTP and DTLS channels. */ -static void calc_mtu_values(worker_st * ws) +static void calc_mtu_values(worker_st *ws) { /* assume that if IPv6 is used over TCP then the same would be used over UDP */ if (ws->proto == AF_INET) { @@ -1874,10 +1965,12 @@ static void calc_mtu_values(worker_st * ws) if (ws->session == NULL) { ws->cstp_crypto_overhead = MAX_CSTP_CRYPTO_OVERHEAD; } else { - ws->cstp_crypto_overhead = CSTP_OVERHEAD + - tls_get_overhead(gnutls_protocol_get_version(ws->session), - gnutls_cipher_get(ws->session), - gnutls_mac_get(ws->session)); + ws->cstp_crypto_overhead = + CSTP_OVERHEAD + + tls_get_overhead( + gnutls_protocol_get_version(ws->session), + gnutls_cipher_get(ws->session), + gnutls_mac_get(ws->session)); } /* link MTU is the device MTU */ @@ -1887,25 +1980,23 @@ static void calc_mtu_values(worker_st * ws) /* crypto overhead for DTLS */ if (ws->req.use_psk) { if (ws->session == NULL) { - ws->dtls_crypto_overhead = MAX_DTLS_CRYPTO_OVERHEAD; + ws->dtls_crypto_overhead = + MAX_DTLS_CRYPTO_OVERHEAD; } else { ws->dtls_crypto_overhead = tls_get_overhead( - GNUTLS_DTLS1_0, - gnutls_cipher_get(ws->session), - gnutls_mac_get(ws->session)); + GNUTLS_DTLS1_0, + gnutls_cipher_get(ws->session), + gnutls_mac_get(ws->session)); } } else if (ws->req.selected_ciphersuite) { - ws->dtls_crypto_overhead = - tls_get_overhead(ws->req. - selected_ciphersuite->gnutls_version, - ws->req. - selected_ciphersuite->gnutls_cipher, - ws->req.selected_ciphersuite->gnutls_mac); + ws->dtls_crypto_overhead = tls_get_overhead( + ws->req.selected_ciphersuite->gnutls_version, + ws->req.selected_ciphersuite->gnutls_cipher, + ws->req.selected_ciphersuite->gnutls_mac); } ws->dtls_crypto_overhead += CSTP_DTLS_OVERHEAD; - oclog(ws, LOG_DEBUG, - "DTLS overhead is %u", + oclog(ws, LOG_DEBUG, "DTLS overhead is %u", ws->dtls_proto_overhead + ws->dtls_crypto_overhead); } @@ -1925,23 +2016,22 @@ static void calc_mtu_values(worker_st * ws) * tunnels. * */ -static int connect_handler(worker_st * ws) +static int connect_handler(worker_st *ws) { struct http_req_st *req = &ws->req; int max, ret, t; char *p; - unsigned rnd; - unsigned i; - unsigned ip6; + unsigned int rnd; + unsigned int i; + unsigned int ip6; time_t now = time(NULL); ret = gnutls_rnd(GNUTLS_RND_NONCE, &rnd, sizeof(rnd)); if (ret < 0) { - oclog(ws, LOG_ERR, - "error in the random generator: %s", gnutls_strerror(ret)); + oclog(ws, LOG_ERR, "error in the random generator: %s", + gnutls_strerror(ret)); cstp_puts(ws, "HTTP/1.1 503 Service Unavailable\r\n"); - cstp_puts(ws, - "X-Reason: Server error\r\n\r\n"); + cstp_puts(ws, "X-Reason: Server error\r\n\r\n"); return -1; } @@ -1951,7 +2041,8 @@ static int connect_handler(worker_st * ws) /* The Clavister Android VPN client has a defect and * asks for CSCOSSLC/tunnel instead of /CSCOSSLC/tunnel */ - if (strcmp(req->url, "/CSCOSSLC/tunnel") != 0 && strcmp(req->url, "CSCOSSLC/tunnel") != 0) { + if (strcmp(req->url, "/CSCOSSLC/tunnel") != 0 && + strcmp(req->url, "CSCOSSLC/tunnel") != 0) { oclog(ws, LOG_INFO, "bad connect request: '%s'\n", req->url); response_404(ws, 1); cstp_fatal_close(ws, GNUTLS_A_ACCESS_DENIED); @@ -1962,8 +2053,7 @@ static int connect_handler(worker_st * ws) oclog(ws, LOG_ERR, "no networks are configured; rejecting client"); cstp_puts(ws, "HTTP/1.1 503 Service Unavailable\r\n"); - cstp_puts(ws, - "X-Reason: Server configuration error\r\n\r\n"); + cstp_puts(ws, "X-Reason: Server configuration error\r\n\r\n"); return -1; } @@ -1972,14 +2062,14 @@ static int connect_handler(worker_st * ws) oclog(ws, LOG_ERR, "no networks are configured; rejecting client"); cstp_puts(ws, "HTTP/1.1 503 Service Unavailable\r\n"); - cstp_puts(ws, - "X-Reason: Server configuration error\r\n\r\n"); + cstp_puts(ws, "X-Reason: Server configuration error\r\n\r\n"); return -1; } /* override any hostname sent by the peer if we have one already configured */ if (ws->user_config->hostname) { - strlcpy(ws->req.hostname, ws->user_config->hostname, sizeof(ws->req.hostname)); + strlcpy(ws->req.hostname, ws->user_config->hostname, + sizeof(ws->req.hostname)); } FUZZ(ws->user_config->interim_update_secs, 5, rnd); @@ -2000,7 +2090,7 @@ static int connect_handler(worker_st * ws) ret = cstp_puts(ws, "X-CSTP-Version: 1\r\n"); SEND_ERR(ret); - ret = cstp_puts(ws, "X-CSTP-Server-Name: "PACKAGE_NAME"\r\n"); + ret = cstp_puts(ws, "X-CSTP-Server-Name: " PACKAGE_NAME "\r\n"); SEND_ERR(ret); if (req->is_mobile) { @@ -2010,22 +2100,21 @@ static int connect_handler(worker_st * ws) /* Notify back the client about the accepted hostname */ if (ws->req.hostname[0] != 0) { - ret = cstp_printf(ws, "X-CSTP-Hostname: %s\r\n", ws->req.hostname); + ret = cstp_printf(ws, "X-CSTP-Hostname: %s\r\n", + ws->req.hostname); SEND_ERR(ret); } oclog(ws, LOG_INFO, "suggesting DPD of %d secs", ws->user_config->dpd); if (ws->user_config->dpd > 0) { - ret = - cstp_printf(ws, "X-CSTP-DPD: %u\r\n", - ws->user_config->dpd); + ret = cstp_printf(ws, "X-CSTP-DPD: %u\r\n", + ws->user_config->dpd); SEND_ERR(ret); } if (WSCONFIG(ws)->default_domain) { - ret = - cstp_printf(ws, "X-CSTP-Default-Domain: %s\r\n", - WSCONFIG(ws)->default_domain); + ret = cstp_printf(ws, "X-CSTP-Default-Domain: %s\r\n", + WSCONFIG(ws)->default_domain); SEND_ERR(ret); } @@ -2051,8 +2140,12 @@ static int connect_handler(worker_st * ws) } else if (req->tunnel_mtu > 0) { /* Old clients didn't send their link MTU, they send the plaintext MTU * they can transfer. */ - ws->vinfo.mtu = MIN(ws->vinfo.mtu, req->tunnel_mtu + MAX_DTLS_PROTO_OVERHEAD(ws) + MAX_DTLS_CRYPTO_OVERHEAD); - oclog(ws, LOG_INFO, "peer's data MTU is %u / link is %u", req->tunnel_mtu, ws->vinfo.mtu); + ws->vinfo.mtu = + MIN(ws->vinfo.mtu, req->tunnel_mtu + + MAX_DTLS_PROTO_OVERHEAD(ws) + + MAX_DTLS_CRYPTO_OVERHEAD); + oclog(ws, LOG_INFO, "peer's data MTU is %u / link is %u", + req->tunnel_mtu, ws->vinfo.mtu); } /* Attempt to use the TCP connection maximum segment size to set a more @@ -2060,80 +2153,83 @@ static int connect_handler(worker_st * ws) if (ws->conn_type != SOCK_TYPE_UNIX) { max = get_pmtu_approx(ws); if (max > 0 && max < ws->vinfo.mtu) { - oclog(ws, LOG_DEBUG, "reducing MTU due to TCP/PMTU to %u", - max); + oclog(ws, LOG_DEBUG, + "reducing MTU due to TCP/PMTU to %u", max); link_mtu_set(ws, DTLS_ACTIVE(ws), max); } } calc_mtu_values(ws); - if (DATA_MTU(ws, ws->link_mtu) < 1280 && ws->vinfo.ipv6 && req->no_ipv6 == 0) { - oclog(ws, LOG_INFO, "Connection MTU (link: %u, data: %u) is not sufficient for IPv6 (1280)", ws->link_mtu, DATA_MTU(ws, ws->link_mtu)); + if (DATA_MTU(ws, ws->link_mtu) < 1280 && ws->vinfo.ipv6 && + req->no_ipv6 == 0) { + oclog(ws, LOG_INFO, + "Connection MTU (link: %u, data: %u) is not sufficient for IPv6 (1280)", + ws->link_mtu, DATA_MTU(ws, ws->link_mtu)); req->no_ipv6 = 1; } /* Send IP addresses */ if (ws->vinfo.ipv4 && req->no_ipv4 == 0) { oclog(ws, LOG_NOTICE, "sending IPv4 %s", ws->vinfo.ipv4); - ret = - cstp_printf(ws, "X-CSTP-Address: %s\r\n", - ws->vinfo.ipv4); + ret = cstp_printf(ws, "X-CSTP-Address: %s\r\n", ws->vinfo.ipv4); SEND_ERR(ret); if (ws->user_config->ipv4_netmask) { - ret = - cstp_printf(ws, "X-CSTP-Netmask: %s\r\n", - ws->user_config->ipv4_netmask); + ret = cstp_printf(ws, "X-CSTP-Netmask: %s\r\n", + ws->user_config->ipv4_netmask); SEND_ERR(ret); } } - if (ws->vinfo.ipv6 && req->no_ipv6 == 0 && ws->user_config->ipv6_prefix != 0) { - oclog(ws, LOG_NOTICE, "sending IPv6 %s/%u", ws->vinfo.ipv6, ws->user_config->ipv6_subnet_prefix); + if (ws->vinfo.ipv6 && req->no_ipv6 == 0 && + ws->user_config->ipv6_prefix != 0) { + oclog(ws, LOG_NOTICE, "sending IPv6 %s/%u", ws->vinfo.ipv6, + ws->user_config->ipv6_subnet_prefix); if (ws->full_ipv6 && ws->user_config->ipv6_subnet_prefix) { - ret = - cstp_printf(ws, - "X-CSTP-Address-IP6: %s/%u\r\n", - ws->vinfo.ipv6, ws->user_config->ipv6_subnet_prefix); + ret = cstp_printf(ws, "X-CSTP-Address-IP6: %s/%u\r\n", + ws->vinfo.ipv6, + ws->user_config->ipv6_subnet_prefix); SEND_ERR(ret); } else { const char *net; - ret = - cstp_printf(ws, "X-CSTP-Address: %s\r\n", - ws->vinfo.ipv6); + ret = cstp_printf(ws, "X-CSTP-Address: %s\r\n", + ws->vinfo.ipv6); SEND_ERR(ret); net = ws->user_config->ipv6_net; if (net == NULL) net = ws->vinfo.ipv6; - ret = - cstp_printf(ws, "X-CSTP-Netmask: %s/%u\r\n", - net, ws->user_config->ipv6_subnet_prefix); + ret = cstp_printf(ws, "X-CSTP-Netmask: %s/%u\r\n", net, + ws->user_config->ipv6_subnet_prefix); SEND_ERR(ret); } } if (ws->full_ipv6 == 0) { req->no_ipv6 = 1; - oclog(ws, LOG_INFO, "IPv6 routes/DNS disabled because IPv6 support was not requested."); + oclog(ws, LOG_INFO, + "IPv6 routes/DNS disabled because IPv6 support was not requested."); } else { switch (req->user_agent_type) { case AGENT_OPENCONNECT_V3: req->no_ipv6 = 1; - oclog(ws, LOG_INFO, "IPv6 routes/DNS disabled because the agent is known not to support them."); + oclog(ws, LOG_INFO, + "IPv6 routes/DNS disabled because the agent is known not to support them."); break; case AGENT_OPENCONNECT: case AGENT_ANYCONNECT: case AGENT_OPENCONNECT_CLAVISTER: case AGENT_ANYLINK: - oclog(ws, LOG_DEBUG, "Enabling IPv6 routes/DNS because the agent is known to support them."); + oclog(ws, LOG_DEBUG, + "Enabling IPv6 routes/DNS because the agent is known to support them."); break; case AGENT_UNKNOWN: default: - oclog(ws, LOG_NOTICE, "Enabling IPv6 routes/DNS although the agent is unknown."); + oclog(ws, LOG_NOTICE, + "Enabling IPv6 routes/DNS although the agent is unknown."); break; } } @@ -2151,16 +2247,14 @@ static int connect_handler(worker_st * ws) oclog(ws, LOG_INFO, "adding DNS %s", ws->user_config->dns[i]); if (req->user_agent_type == AGENT_ANYCONNECT) { - ret = - cstp_printf(ws, "X-CSTP-%s: %s\r\n", - ip6 ? "DNS-IP6" : "DNS", - ws->user_config->dns[i]); + ret = cstp_printf(ws, "X-CSTP-%s: %s\r\n", + ip6 ? "DNS-IP6" : "DNS", + ws->user_config->dns[i]); } else { /* openconnect does not require the split * of DNS and DNS-IP6 and only recent versions * understand the IP6 variant. */ - ret = - cstp_printf(ws, "X-CSTP-DNS: %s\r\n", - ws->user_config->dns[i]); + ret = cstp_printf(ws, "X-CSTP-DNS: %s\r\n", + ws->user_config->dns[i]); } SEND_ERR(ret); } @@ -2177,9 +2271,8 @@ static int connect_handler(worker_st * ws) continue; oclog(ws, LOG_INFO, "adding NBNS %s", ws->user_config->nbns[i]); - ret = - cstp_printf(ws, "X-CSTP-NBNS: %s\r\n", - ws->user_config->nbns[i]); + ret = cstp_printf(ws, "X-CSTP-NBNS: %s\r\n", + ws->user_config->nbns[i]); SEND_ERR(ret); } @@ -2196,9 +2289,8 @@ static int connect_handler(worker_st * ws) oclog(ws, LOG_INFO, "adding split DNS %s", ws->user_config->split_dns[i]); - ret = - cstp_printf(ws, "X-CSTP-Split-DNS: %s\r\n", - ws->user_config->split_dns[i]); + ret = cstp_printf(ws, "X-CSTP-Split-DNS: %s\r\n", + ws->user_config->split_dns[i]); SEND_ERR(ret); } @@ -2206,13 +2298,13 @@ static int connect_handler(worker_st * ws) if (ws->full_ipv6 && req->is_ios && (ws->user_config->n_routes == 0 || ws->default_route == 0)) { oclog(ws, LOG_INFO, "adding special split DNS for Apple"); - ret = - cstp_printf(ws, "X-CSTP-Split-Include-IP6: 2000::/3\r\n"); + ret = cstp_printf(ws, "X-CSTP-Split-Include-IP6: 2000::/3\r\n"); SEND_ERR(ret); } if (ws->default_route == 0) { - ret = send_routes(ws, req, ws->user_config->routes, ws->user_config->n_routes, 1); + ret = send_routes(ws, req, ws->user_config->routes, + ws->user_config->n_routes, 1); SEND_ERR(ret); } else { @@ -2234,54 +2326,48 @@ static int connect_handler(worker_st * ws) } SEND_ERR(ret); - ret = send_routes(ws, req, ws->user_config->no_routes, ws->user_config->n_no_routes, 0); + ret = send_routes(ws, req, ws->user_config->no_routes, + ws->user_config->n_no_routes, 0); SEND_ERR(ret); - ret = - cstp_printf(ws, "X-CSTP-Keepalive: %u\r\n", - ws->user_config->keepalive); + ret = cstp_printf(ws, "X-CSTP-Keepalive: %u\r\n", + ws->user_config->keepalive); SEND_ERR(ret); if (WSCONFIG(ws)->idle_timeout > 0) { - ret = - cstp_printf(ws, - "X-CSTP-Idle-Timeout: %u\r\n", - (unsigned)WSCONFIG(ws)->idle_timeout); + ret = cstp_printf(ws, "X-CSTP-Idle-Timeout: %u\r\n", + (unsigned int)WSCONFIG(ws)->idle_timeout); } else { ret = cstp_puts(ws, "X-CSTP-Idle-Timeout: none\r\n"); } SEND_ERR(ret); - ret = - cstp_puts(ws, - "X-CSTP-Smartcard-Removal-Disconnect: true\r\n"); + ret = cstp_puts(ws, "X-CSTP-Smartcard-Removal-Disconnect: true\r\n"); SEND_ERR(ret); if (WSCONFIG(ws)->is_dyndns != 0) { - ret = - cstp_puts(ws, - "X-CSTP-DynDNS: true\r\n"); + ret = cstp_puts(ws, "X-CSTP-DynDNS: true\r\n"); SEND_ERR(ret); } if (WSCONFIG(ws)->rekey_time > 0) { - unsigned method; + unsigned int method; - ret = - cstp_printf(ws, "X-CSTP-Rekey-Time: %u\r\n", - (unsigned)(WSCONFIG(ws)->rekey_time)); + ret = cstp_printf(ws, "X-CSTP-Rekey-Time: %u\r\n", + (unsigned int)(WSCONFIG(ws)->rekey_time)); SEND_ERR(ret); /* if the peer isn't patched for safe renegotiation, always * require him to open a new tunnel. */ - if (ws->session != NULL && gnutls_safe_renegotiation_status(ws->session) != 0) + if (ws->session != NULL && + gnutls_safe_renegotiation_status(ws->session) != 0) method = WSCONFIG(ws)->rekey_method; else method = REKEY_METHOD_NEW_TUNNEL; ret = cstp_printf(ws, "X-CSTP-Rekey-Method: %s\r\n", - (method == - REKEY_METHOD_SSL) ? "ssl" : "new-tunnel"); + (method == REKEY_METHOD_SSL) ? "ssl" : + "new-tunnel"); SEND_ERR(ret); } else { ret = cstp_puts(ws, "X-CSTP-Rekey-Method: none\r\n"); @@ -2290,10 +2376,10 @@ static int connect_handler(worker_st * ws) if (WSCONFIG(ws)->proxy_url != NULL) { char *url = replace_vals(ws, WSCONFIG(ws)->proxy_url); + if (url != NULL) { - ret = - cstp_printf(ws, "X-CSTP-MSIE-Proxy-Pac-URL: %s\r\n", - url); + ret = cstp_printf( + ws, "X-CSTP-MSIE-Proxy-Pac-URL: %s\r\n", url); SEND_ERR(ret); talloc_free(url); } @@ -2303,8 +2389,11 @@ static int connect_handler(worker_st * ws) ret = cstp_puts(ws, "X-CSTP-Session-Timeout: none\r\n"); SEND_ERR(ret); } else { - time_t expiration = ws->session_start_time + ws->user_config->session_timeout_secs; - ret = cstp_printf(ws, "X-CSTP-Session-Timeout: %u\r\n" + time_t expiration = ws->session_start_time + + ws->user_config->session_timeout_secs; + + ret = cstp_printf(ws, + "X-CSTP-Session-Timeout: %u\r\n" "X-CSTP-Session-Timeout-Remaining: %ld\r\n", ws->user_config->session_timeout_secs, MAX(expiration - now, 0)); @@ -2312,9 +2401,9 @@ static int connect_handler(worker_st * ws) } ret = cstp_puts(ws, "X-CSTP-Disconnected-Timeout: none\r\n" - "X-CSTP-Keep: true\r\n" - "X-CSTP-TCP-Keepalive: true\r\n" - "X-CSTP-License: accept\r\n"); + "X-CSTP-Keep: true\r\n" + "X-CSTP-TCP-Keepalive: true\r\n" + "X-CSTP-License: accept\r\n"); SEND_ERR(ret); for (i = 0; i < WSCONFIG(ws)->custom_header_size; i++) { @@ -2322,22 +2411,19 @@ static int connect_handler(worker_st * ws) if (h) { oclog(ws, LOG_INFO, "adding custom header '%s'", h); - ret = - cstp_printf(ws, "%s\r\n", h); + ret = cstp_printf(ws, "%s\r\n", h); SEND_ERR(ret); talloc_free(h); } } - /* set TCP socket options */ if (WSCONFIG(ws)->output_buffer > 0) { t = ws->link_mtu; t *= WSCONFIG(ws)->output_buffer; - ret = - setsockopt(ws->conn_fd, SOL_SOCKET, SO_SNDBUF, &t, - sizeof(t)); + ret = setsockopt(ws->conn_fd, SOL_SOCKET, SO_SNDBUF, &t, + sizeof(t)); if (ret == -1) oclog(ws, LOG_DEBUG, "setsockopt(TCP, SO_SNDBUF) to %u, failed.", t); @@ -2349,37 +2435,32 @@ static int connect_handler(worker_st * ws) set_no_delay(ws, ws->conn_fd); if (DTLS_ACTIVE(ws)->udp_state != UP_DISABLED) { - if (ws->user_config->dpd > 0) { - ret = - cstp_printf(ws, "X-DTLS-DPD: %u\r\n", - ws->user_config->dpd); + ret = cstp_printf(ws, "X-DTLS-DPD: %u\r\n", + ws->user_config->dpd); SEND_ERR(ret); } - ret = - cstp_printf(ws, "X-DTLS-Port: %u\r\n", - WSPCONFIG(ws)->udp_port); + ret = cstp_printf(ws, "X-DTLS-Port: %u\r\n", + WSPCONFIG(ws)->udp_port); SEND_ERR(ret); if (WSCONFIG(ws)->rekey_time > 0) { - ret = - cstp_printf(ws, "X-DTLS-Rekey-Time: %u\r\n", - (unsigned)(WSCONFIG(ws)->rekey_time + 10)); + ret = cstp_printf( + ws, "X-DTLS-Rekey-Time: %u\r\n", + (unsigned int)(WSCONFIG(ws)->rekey_time + 10)); SEND_ERR(ret); /* This is our private extension */ if (WSCONFIG(ws)->rekey_method == REKEY_METHOD_SSL) { - ret = - cstp_puts(ws, - "X-DTLS-Rekey-Method: ssl\r\n"); + ret = cstp_puts(ws, + "X-DTLS-Rekey-Method: ssl\r\n"); SEND_ERR(ret); } } - ret = - cstp_printf(ws, "X-DTLS-Keepalive: %u\r\n", - ws->user_config->keepalive); + ret = cstp_printf(ws, "X-DTLS-Keepalive: %u\r\n", + ws->user_config->keepalive); SEND_ERR(ret); p = (char *)ws->buffer; @@ -2391,40 +2472,44 @@ static int connect_handler(worker_st * ws) if (ws->req.use_psk || !WSCONFIG(ws)->dtls_legacy) { oclog(ws, LOG_INFO, "X-DTLS-App-ID: %s", ws->buffer); - ret = - cstp_printf(ws, "X-DTLS-App-ID: %s\r\n", - ws->buffer); + ret = cstp_printf(ws, "X-DTLS-App-ID: %s\r\n", + ws->buffer); SEND_ERR(ret); - oclog(ws, LOG_INFO, "DTLS ciphersuite: "DTLS_PROTO_INDICATOR); - ret = - cstp_printf(ws, "X-DTLS-CipherSuite: "DTLS_PROTO_INDICATOR"\r\n"); + oclog(ws, LOG_INFO, + "DTLS ciphersuite: " DTLS_PROTO_INDICATOR); + ret = cstp_printf( + ws, "X-DTLS-CipherSuite: " DTLS_PROTO_INDICATOR + "\r\n"); } else if (ws->req.selected_ciphersuite) { - oclog(ws, LOG_INFO, "X-DTLS-Session-ID: %s", ws->buffer); + oclog(ws, LOG_INFO, "X-DTLS-Session-ID: %s", + ws->buffer); - ret = - cstp_printf(ws, "X-DTLS-Session-ID: %s\r\n", - ws->buffer); + ret = cstp_printf(ws, "X-DTLS-Session-ID: %s\r\n", + ws->buffer); SEND_ERR(ret); oclog(ws, LOG_INFO, "DTLS ciphersuite: %s", ws->req.selected_ciphersuite->oc_name); - ret = - cstp_printf(ws, "X-DTLS%s-CipherSuite: %s\r\n", - (ws->req.selected_ciphersuite->dtls12_mode!=0)?"12":"", - ws->req.selected_ciphersuite->oc_name); + ret = cstp_printf( + ws, "X-DTLS%s-CipherSuite: %s\r\n", + (ws->req.selected_ciphersuite->dtls12_mode != + 0) ? + "12" : + "", + ws->req.selected_ciphersuite->oc_name); SEND_ERR(ret); /* only send the X-DTLS-MTU in the legacy protocol, as there * the DTLS ciphersuite/version is negotiated and we cannot predict * the actual tunnel size */ - ret = - cstp_printf(ws, "X-DTLS-MTU: %u\r\n", DATA_MTU(ws, ws->link_mtu)); + ret = cstp_printf(ws, "X-DTLS-MTU: %u\r\n", + DATA_MTU(ws, ws->link_mtu)); SEND_ERR(ret); - oclog(ws, LOG_INFO, "DTLS data MTU %u", DATA_MTU(ws, ws->link_mtu)); + oclog(ws, LOG_INFO, "DTLS data MTU %u", + DATA_MTU(ws, ws->link_mtu)); } SEND_ERR(ret); - } /* hack for openconnect. It uses only a single MTU value */ @@ -2435,9 +2520,8 @@ static int connect_handler(worker_st * ws) ret = cstp_printf(ws, "X-CSTP-MTU: %u\r\n", DATA_MTU(ws, ws->link_mtu)); SEND_ERR(ret); - if (ws->buffer_size < ws->link_mtu+16) { - oclog(ws, LOG_ERR, - "buffer size is smaller than MTU (%u < %u)", + if (ws->buffer_size < ws->link_mtu + 16) { + oclog(ws, LOG_ERR, "buffer size is smaller than MTU (%u < %u)", ws->buffer_size, ws->link_mtu); goto exit; } @@ -2445,26 +2529,25 @@ static int connect_handler(worker_st * ws) data_mtu_send(ws, DATA_MTU(ws, ws->link_mtu)); if (WSCONFIG(ws)->banner) { - ret = - cstp_printf(ws, "X-CSTP-Banner: %s\r\n", - WSCONFIG(ws)->banner); + ret = cstp_printf(ws, "X-CSTP-Banner: %s\r\n", + WSCONFIG(ws)->banner); SEND_ERR(ret); } /* send any compression methods */ if (ws->dtls_selected_comp) { - oclog(ws, LOG_INFO, "selected DTLS compression method %s\n", ws->dtls_selected_comp->name); - ret = - cstp_printf(ws, "X-DTLS-Content-Encoding: %s\r\n", - ws->dtls_selected_comp->name); + oclog(ws, LOG_INFO, "selected DTLS compression method %s\n", + ws->dtls_selected_comp->name); + ret = cstp_printf(ws, "X-DTLS-Content-Encoding: %s\r\n", + ws->dtls_selected_comp->name); SEND_ERR(ret); } if (ws->cstp_selected_comp) { - oclog(ws, LOG_INFO, "selected CSTP compression method %s\n", ws->cstp_selected_comp->name); - ret = - cstp_printf(ws, "X-CSTP-Content-Encoding: %s\r\n", - ws->cstp_selected_comp->name); + oclog(ws, LOG_INFO, "selected CSTP compression method %s\n", + ws->cstp_selected_comp->name); + ret = cstp_printf(ws, "X-CSTP-Content-Encoding: %s\r\n", + ws->cstp_selected_comp->name); SEND_ERR(ret); } @@ -2475,26 +2558,27 @@ static int connect_handler(worker_st * ws) SEND_ERR(ret); ret = worker_event_loop(ws); - if (ret != 0) - { + if (ret != 0) { goto exit; } return 0; - exit: +exit: cstp_close(ws); /*gnutls_deinit(ws->session); */ - if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && DTLS_ACTIVE(ws)->dtls_session) { + if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && + DTLS_ACTIVE(ws)->dtls_session) { dtls_close(DTLS_ACTIVE(ws)); } - if (DTLS_INACTIVE(ws)->udp_state == UP_ACTIVE && DTLS_INACTIVE(ws)->dtls_session) { + if (DTLS_INACTIVE(ws)->udp_state == UP_ACTIVE && + DTLS_INACTIVE(ws)->dtls_session) { dtls_close(DTLS_INACTIVE(ws)); } exit_worker_reason(ws, terminate_reason); - send_error: +send_error: oclog(ws, LOG_DEBUG, "error sending data\n"); exit_worker(ws); @@ -2502,12 +2586,12 @@ static int connect_handler(worker_st * ws) } static int parse_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, - time_t now, unsigned is_dtls) + time_t now, unsigned int is_dtls) { int ret, e; uint8_t *plain; ssize_t plain_size; - unsigned head; + unsigned int head; if (is_dtls == 0) { /* CSTP */ plain = buf + 8; @@ -2536,29 +2620,34 @@ static int parse_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, ret); if (ret < 0) { - oclog(ws, LOG_ERR, "could not send data: %d", ret); + oclog(ws, LOG_ERR, "could not send data: %d", + ret); return -1; } } else { /* Use DPD for MTU discovery in DTLS */ buf[0] = AC_PKT_DPD_RESP; - if (buf_size-CSTP_DTLS_OVERHEAD > DATA_MTU(ws, ws->link_mtu)) { + if (buf_size - CSTP_DTLS_OVERHEAD > + DATA_MTU(ws, ws->link_mtu)) { /* peer is doing MTU discovery */ - data_mtu_set(ws, DTLS_ACTIVE(ws), buf_size-CSTP_DTLS_OVERHEAD); + data_mtu_set(ws, DTLS_ACTIVE(ws), + buf_size - CSTP_DTLS_OVERHEAD); } ret = dtls_send(DTLS_ACTIVE(ws), buf, buf_size); if (ret == GNUTLS_E_LARGE_PACKET) { oclog(ws, LOG_TRANSFER_DEBUG, - "could not send DPD of %d bytes", (int)buf_size); + "could not send DPD of %d bytes", + (int)buf_size); mtu_not_ok(ws, DTLS_ACTIVE(ws)); ret = dtls_send(DTLS_ACTIVE(ws), buf, 1); } if (ret < 0) { oclog(ws, LOG_TRANSFER_DEBUG, - "received DTLS DPD; error in sending response: %s", gnutls_strerror(ret)); + "received DTLS DPD; error in sending response: %s", + gnutls_strerror(ret)); } else { oclog(ws, LOG_TRANSFER_DEBUG, "received DTLS DPD; sent response (%d bytes)", @@ -2573,12 +2662,14 @@ static int parse_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, * user disconnect. In anyconnect clients it may indicate * an intention to reconnect (e.g., because network was * changed). We separate the error codes to ensure we do - * do not interpret the intention incorrectly (see #281). */ + * not interpret the intention incorrectly (see #281). */ if (plain_size > 0 && plain[0] == 0xb0) { exit_worker_reason(ws, REASON_USER_DISCONNECT); } else { if (plain_size > 0) { - oclog_hex(ws, LOG_DEBUG, "bye packet with unknown payload", plain, plain_size, 0); + oclog_hex(ws, LOG_DEBUG, + "bye packet with unknown payload", + plain, plain_size, 0); return -1; } @@ -2589,24 +2680,33 @@ static int parse_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, /* decompress */ if (is_dtls == 0) { /* CSTP */ if (ws->cstp_selected_comp == NULL) { - oclog(ws, LOG_ERR, "received compressed data but no compression was negotiated"); + oclog(ws, LOG_ERR, + "received compressed data but no compression was negotiated"); return -1; } - plain_size = ws->cstp_selected_comp->decompress(ws->decomp, sizeof(ws->decomp), plain, plain_size); - oclog(ws, LOG_DEBUG, "decompressed %d to %d\n", (int)buf_size-8, (int)plain_size); + plain_size = ws->cstp_selected_comp->decompress( + ws->decomp, sizeof(ws->decomp), plain, + plain_size); + oclog(ws, LOG_DEBUG, "decompressed %d to %d\n", + (int)buf_size - 8, (int)plain_size); } else { /* DTLS */ if (ws->dtls_selected_comp == NULL) { - oclog(ws, LOG_ERR, "received compressed data but no compression was negotiated"); + oclog(ws, LOG_ERR, + "received compressed data but no compression was negotiated"); return -1; } - plain_size = ws->dtls_selected_comp->decompress(ws->decomp, sizeof(ws->decomp), plain, plain_size); - oclog(ws, LOG_DEBUG, "decompressed %d to %d\n", (int)buf_size-1, (int)plain_size); + plain_size = ws->dtls_selected_comp->decompress( + ws->decomp, sizeof(ws->decomp), plain, + plain_size); + oclog(ws, LOG_DEBUG, "decompressed %d to %d\n", + (int)buf_size - 1, (int)plain_size); } if (plain_size <= 0) { - oclog(ws, LOG_ERR, "decompression error %d", (int)plain_size); + oclog(ws, LOG_ERR, "decompression error %d", + (int)plain_size); return -1; } plain = ws->decomp; @@ -2629,14 +2729,14 @@ static int parse_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, break; default: oclog(ws, LOG_DEBUG, "received unknown packet %u/size: %u", - (unsigned)head, (unsigned)buf_size); + (unsigned int)head, (unsigned int)buf_size); } return 0; } -static int parse_cstp_data(struct worker_st *ws, - uint8_t * buf, size_t buf_size, time_t now) +static int parse_cstp_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, + time_t now) { int pktlen, ret; @@ -2647,16 +2747,17 @@ static int parse_cstp_data(struct worker_st *ws, return -1; } - if (buf[0] != 'S' || buf[1] != 'T' || - buf[2] != 'F' || buf[3] != 1 || buf[7]) { + if (buf[0] != 'S' || buf[1] != 'T' || buf[2] != 'F' || buf[3] != 1 || + buf[7]) { oclog(ws, LOG_INFO, "can't recognise CSTP header"); return -1; } pktlen = (buf[4] << 8) + buf[5]; if (buf_size != 8 + pktlen) { - oclog(ws, LOG_INFO, "unexpected CSTP length (have %u, should be %d)", - (unsigned)pktlen, (unsigned)buf_size-8); + oclog(ws, LOG_INFO, + "unexpected CSTP length (have %u, should be %d)", + (unsigned int)pktlen, (unsigned int)buf_size - 8); return -1; } @@ -2674,8 +2775,8 @@ static int parse_cstp_data(struct worker_st *ws, return ret; } -static int parse_dtls_data(struct worker_st *ws, - uint8_t * buf, size_t buf_size, time_t now) +static int parse_dtls_data(struct worker_st *ws, uint8_t *buf, size_t buf_size, + time_t now) { int ret; @@ -2686,8 +2787,7 @@ static int parse_dtls_data(struct worker_st *ws, return -1; } - ret = - parse_data(ws, buf, buf_size, now, 1); + ret = parse_data(ws, buf, buf_size, now, 1); ws->last_msg_udp = now; return ret; } @@ -2696,6 +2796,7 @@ static int test_for_tcp_health_probe(struct worker_st *ws) { int ret; uint8_t buffer[1]; + ret = recv(ws->conn_fd, buffer, sizeof(buffer), MSG_PEEK); // If we get back an error, assume this was a tcp health probe @@ -2705,9 +2806,9 @@ static int test_for_tcp_health_probe(struct worker_st *ws) return 1; } -static void syserr_cb (const char *msg) +static void syserr_cb(const char *msg) { - struct worker_st * ws = ev_userdata(worker_loop); + struct worker_st *ws = ev_userdata(worker_loop); int err = errno; oclog(ws, LOG_ERR, "libev fatal error: %s / %s", msg, strerror(err)); @@ -2716,7 +2817,7 @@ static void syserr_cb (const char *msg) exit_worker_reason(ws, terminate_reason); } -static void cstp_send_terminate(struct worker_st * ws) +static void cstp_send_terminate(struct worker_st *ws) { ws->buffer[0] = 'S'; ws->buffer[1] = 'T'; @@ -2728,16 +2829,17 @@ static void cstp_send_terminate(struct worker_st * ws) ws->buffer[7] = 0; oclog(ws, LOG_TRANSFER_DEBUG, - "sending disconnect message in TLS channel"); + "sending disconnect message in TLS channel"); cstp_send(ws, ws->buffer, 8); exit_worker_reason(ws, terminate_reason); } -static void command_watcher_cb (EV_P_ ev_io *w, int revents) +static void command_watcher_cb(EV_P_ ev_io *w, int revents) { struct worker_st *ws = ev_userdata(worker_loop); int ret = handle_commands_from_main(ws); + if (ret == ERR_NO_CMD_FD) { terminate_reason = REASON_ERROR; cstp_send_terminate(ws); @@ -2756,11 +2858,12 @@ static void command_watcher_cb (EV_P_ ev_io *w, int revents) } } -static void tls_watcher_cb (EV_P_ ev_io * w, int revents) +static void tls_watcher_cb(EV_P_ ev_io *w, int revents) { struct timespec tnow; struct worker_st *ws = ev_userdata(loop); int ret; + gettime(&tnow); ret = tls_mainloop(ws, &tnow); @@ -2771,11 +2874,12 @@ static void tls_watcher_cb (EV_P_ ev_io * w, int revents) } } -static void tun_watcher_cb (EV_P_ ev_io * w, int revents) +static void tun_watcher_cb(EV_P_ ev_io *w, int revents) { struct timespec tnow; struct worker_st *ws = ev_userdata(loop); int ret; + gettime(&tnow); ret = tun_mainloop(ws, &tnow); @@ -2786,12 +2890,13 @@ static void tun_watcher_cb (EV_P_ ev_io * w, int revents) } } -static void dtls_watcher_cb (EV_P_ ev_io * w, int revents) +static void dtls_watcher_cb(EV_P_ ev_io *w, int revents) { struct timespec tnow; struct worker_st *ws = ev_userdata(loop); - struct dtls_st * dtls = (struct dtls_st*)w; + struct dtls_st *dtls = (struct dtls_st *)w; int ret; + gettime(&tnow); ret = dtls_mainloop(ws, dtls, &tnow); @@ -2813,14 +2918,14 @@ static void dtls_watcher_cb (EV_P_ ev_io * w, int revents) static void term_sig_watcher_cb(struct ev_loop *loop, ev_signal *w, int revents) { struct worker_st *ws = ev_userdata(loop); + cstp_send_terminate(ws); } -static void invoke_dtls_if_needed(struct dtls_st * dtls) +static void invoke_dtls_if_needed(struct dtls_st *dtls) { - if ((dtls->udp_state > UP_WAIT_FD) && - (dtls->dtls_session != NULL) && - (gnutls_record_check_pending(dtls->dtls_session))) { + if ((dtls->udp_state > UP_WAIT_FD) && (dtls->dtls_session != NULL) && + (gnutls_record_check_pending(dtls->dtls_session))) { ev_invoke(worker_loop, &dtls->io, EV_READ); } } @@ -2841,8 +2946,7 @@ static void periodic_check_watcher_cb(EV_P_ ev_timer *w, int revents) if (terminate) cstp_send_terminate(ws); - if (gnutls_record_check_pending(ws->session)) - { + if (gnutls_record_check_pending(ws->session)) { ev_invoke(loop, &tls_watcher, EV_READ); } @@ -2850,12 +2954,12 @@ static void periodic_check_watcher_cb(EV_P_ ev_timer *w, int revents) invoke_dtls_if_needed(DTLS_INACTIVE(ws)); } -static int worker_event_loop(struct worker_st * ws) +static int worker_event_loop(struct worker_st *ws) { struct timespec tnow; #if defined(__linux__) && defined(HAVE_LIBSECCOMP) - worker_loop = ev_default_loop(EVFLAG_NOENV|EVBACKEND_EPOLL); + worker_loop = ev_default_loop(EVFLAG_NOENV | EVBACKEND_EPOLL); #else worker_loop = EV_DEFAULT; #endif @@ -2866,18 +2970,18 @@ static int worker_event_loop(struct worker_st * ws) ocsignal(SIGALRM, SIG_DFL); ev_init(&alarm_sig_watcher, term_sig_watcher_cb); - ev_signal_set (&alarm_sig_watcher, SIGALRM); - ev_signal_start (worker_loop, &alarm_sig_watcher); + ev_signal_set(&alarm_sig_watcher, SIGALRM); + ev_signal_start(worker_loop, &alarm_sig_watcher); - ev_init (&int_sig_watcher, term_sig_watcher_cb); - ev_signal_set (&int_sig_watcher, SIGINT); - ev_signal_start (worker_loop, &int_sig_watcher); + ev_init(&int_sig_watcher, term_sig_watcher_cb); + ev_signal_set(&int_sig_watcher, SIGINT); + ev_signal_start(worker_loop, &int_sig_watcher); - ev_init (&term_sig_watcher, term_sig_watcher_cb); - ev_signal_set (&term_sig_watcher, SIGTERM); - ev_signal_start (worker_loop, &term_sig_watcher); + ev_init(&term_sig_watcher, term_sig_watcher_cb); + ev_signal_set(&term_sig_watcher, SIGTERM); + ev_signal_start(worker_loop, &term_sig_watcher); - ev_set_userdata (worker_loop, ws); + ev_set_userdata(worker_loop, ws); ev_set_syserr_cb(syserr_cb); ev_init(&command_watcher, command_watcher_cb); @@ -2895,11 +2999,11 @@ static int worker_event_loop(struct worker_st * ws) ev_io_set(&tun_watcher, ws->tun_fd, EV_READ); ev_io_start(worker_loop, &tun_watcher); - ev_init (&period_check_watcher, periodic_check_watcher_cb); - ev_timer_set(&period_check_watcher, WORKER_MAINTENANCE_TIME, WORKER_MAINTENANCE_TIME); + ev_init(&period_check_watcher, periodic_check_watcher_cb); + ev_timer_set(&period_check_watcher, WORKER_MAINTENANCE_TIME, + WORKER_MAINTENANCE_TIME); ev_timer_start(worker_loop, &period_check_watcher); - /* start dead peer detection */ gettime(&tnow); ws->last_msg_tcp = ws->last_msg_udp = ws->last_nc_msg = tnow.tv_sec; @@ -2907,21 +3011,21 @@ static int worker_event_loop(struct worker_st * ws) bandwidth_init(&ws->b_rx, ws->user_config->rx_per_sec); bandwidth_init(&ws->b_tx, ws->user_config->tx_per_sec); - ev_run(worker_loop, 0); - if (terminate != 0) - { + if (terminate != 0) { goto exit; } return 0; - exit: +exit: cstp_close(ws); /*gnutls_deinit(ws->session); */ - if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && DTLS_ACTIVE(ws)->dtls_session) { + if (DTLS_ACTIVE(ws)->udp_state == UP_ACTIVE && + DTLS_ACTIVE(ws)->dtls_session) { dtls_close(DTLS_ACTIVE(ws)); } - if (DTLS_INACTIVE(ws)->udp_state == UP_ACTIVE && DTLS_INACTIVE(ws)->dtls_session) { + if (DTLS_INACTIVE(ws)->udp_state == UP_ACTIVE && + DTLS_INACTIVE(ws)->dtls_session) { dtls_close(DTLS_INACTIVE(ws)); } diff --git a/src/worker.c b/src/worker.c index dddce128..42da038b 100644 --- a/src/worker.c +++ b/src/worker.c @@ -40,16 +40,16 @@ #include extern const asn1_static_node kkdcp_asn1_tab[]; -asn1_node _kkdcp_pkix1_asn = NULL; +asn1_node _kkdcp_pkix1_asn; #endif extern struct snapshot_t *config_snapshot; -int syslog_open = 0; +int syslog_open; sigset_t sig_default_set; -static unsigned allow_broken_clients = 0; +static unsigned int allow_broken_clients; -static int set_ws_from_env(worker_st * ws); +static int set_ws_from_env(worker_st *ws); extern char secmod_socket_file_name_socket_file[_POSIX_PATH_MAX]; @@ -203,9 +203,9 @@ int main(int argc, char **argv) extern char **pam_auth_group_list; extern char **gssapi_auth_group_list; extern char **plain_auth_group_list; -extern unsigned pam_auth_group_list_size; -extern unsigned gssapi_auth_group_list_size; -extern unsigned plain_auth_group_list_size; +extern unsigned int pam_auth_group_list_size; +extern unsigned int gssapi_auth_group_list_size; +extern unsigned int plain_auth_group_list_size; static int clone_array(void *pool, char **input_array, size_t input_array_size, char ***output_array) @@ -213,6 +213,7 @@ static int clone_array(void *pool, char **input_array, size_t input_array_size, int ret = 0; int index; char **array = talloc_zero_array(pool, char *, input_array_size); + if (array == NULL) { goto cleanup; } @@ -227,7 +228,7 @@ static int clone_array(void *pool, char **input_array, size_t input_array_size, *output_array = array; array = NULL; ret = 1; - cleanup: +cleanup: if (array != NULL) { for (index = 0; index < input_array_size; index++) { if (array[index] != NULL) { @@ -239,7 +240,7 @@ static int clone_array(void *pool, char **input_array, size_t input_array_size, return ret; } -static int set_ws_from_env(worker_st * ws) +static int set_ws_from_env(worker_st *ws) { PROTOBUF_ALLOCATOR(pa, ws); WorkerStartupMsg *msg = NULL; @@ -251,14 +252,15 @@ static int set_ws_from_env(worker_st * ws) size_t index; if (string_buffer == NULL) { - fprintf(stderr, "This application must be called from ocserv (no env variable set)\n"); + fprintf(stderr, + "This application must be called from ocserv (no env variable set)\n"); goto cleanup; } string_size = strlen(string_buffer); - if (!oc_base64_decode_alloc - (ws, string_buffer, string_size, (char **)&msg_buffer, &msg_size)) { + if (!oc_base64_decode_alloc(ws, string_buffer, string_size, + (char **)&msg_buffer, &msg_size)) { fprintf(stderr, "oc_base64_decode_alloc failed\n"); goto cleanup; } @@ -291,7 +293,7 @@ static int set_ws_from_env(worker_st * ws) ws->cmd_fd = msg->cmd_fd; ws->conn_fd = msg->conn_fd; - ws->conn_type = (sock_type_t) msg->conn_type; + ws->conn_type = (sock_type_t)msg->conn_type; ws->session_start_time = msg->session_start_time; ws->remote_addr_len = msg->remote_addr.len; memcpy(&ws->remote_addr, msg->remote_addr.data, msg->remote_addr.len); @@ -310,31 +312,31 @@ static int set_ws_from_env(worker_st * ws) for (index = 0; index < msg->n_snapshot_entries; index++) { int fd = msg->snapshot_entries[index]->file_descriptor; const char *file_name = msg->snapshot_entries[index]->file_name; + if (snapshot_restore_entry(config_snapshot, fd, file_name) != 0) goto cleanup; } - if (!clone_array - (ws, msg->pam_auth_group_list, msg->n_pam_auth_group_list, - &pam_auth_group_list)) + if (!clone_array(ws, msg->pam_auth_group_list, + msg->n_pam_auth_group_list, &pam_auth_group_list)) goto cleanup; - pam_auth_group_list_size = (unsigned)msg->n_pam_auth_group_list; + pam_auth_group_list_size = (unsigned int)msg->n_pam_auth_group_list; - if (!clone_array - (ws, msg->plain_auth_group_list, msg->n_plain_auth_group_list, - &plain_auth_group_list)) + if (!clone_array(ws, msg->plain_auth_group_list, + msg->n_plain_auth_group_list, &plain_auth_group_list)) goto cleanup; - plain_auth_group_list_size = (unsigned)msg->n_plain_auth_group_list; + plain_auth_group_list_size = (unsigned int)msg->n_plain_auth_group_list; - if (!clone_array - (ws, msg->gssapi_auth_group_list, msg->n_gssapi_auth_group_list, - &gssapi_auth_group_list)) + if (!clone_array(ws, msg->gssapi_auth_group_list, + msg->n_gssapi_auth_group_list, + &gssapi_auth_group_list)) goto cleanup; - gssapi_auth_group_list_size = (unsigned)msg->n_gssapi_auth_group_list; + gssapi_auth_group_list_size = + (unsigned int)msg->n_gssapi_auth_group_list; ret = 1; - cleanup: +cleanup: if (msg_buffer) talloc_free(msg_buffer); diff --git a/src/worker.h b/src/worker.h index 2eb6466e..097098a2 100644 --- a/src/worker.h +++ b/src/worker.h @@ -76,11 +76,7 @@ enum { HEADER_AUTHORIZATION }; -enum { - HTTP_HEADER_INIT = 0, - HTTP_HEADER_RECV, - HTTP_HEADER_VALUE_RECV -}; +enum { HTTP_HEADER_INIT = 0, HTTP_HEADER_RECV, HTTP_HEADER_VALUE_RECV }; enum { S_AUTH_INACTIVE = 0, @@ -100,30 +96,34 @@ enum { AGENT_SVC_IPPHONE }; -typedef int (*decompress_fn)(void* dst, int maxDstSize, const void* src, int src_size); -typedef int (*compress_fn)(void* dst, int dst_size, const void* src, int src_size); +typedef int (*decompress_fn)(void *dst, int maxDstSize, const void *src, + int src_size); +typedef int (*compress_fn)(void *dst, int dst_size, const void *src, + int src_size); typedef struct compression_method_st { comp_type_t id; const char *name; decompress_fn decompress; compress_fn compress; - unsigned server_prio; /* the highest the more we want to negotiate that */ + unsigned int + server_prio; /* the highest the more we want to negotiate that */ } compression_method_st; typedef struct dtls_ciphersuite_st { - const char* oc_name; - const char* gnutls_name; /* the gnutls priority string to set */ - unsigned dtls12_mode; - unsigned server_prio; /* the highest the more we want to negotiate that */ - unsigned gnutls_cipher; - unsigned gnutls_kx; - unsigned gnutls_mac; - unsigned gnutls_version; + const char *oc_name; + const char *gnutls_name; /* the gnutls priority string to set */ + unsigned int dtls12_mode; + unsigned int + server_prio; /* the highest the more we want to negotiate that */ + unsigned int gnutls_cipher; + unsigned int gnutls_kx; + unsigned int gnutls_mac; + unsigned int gnutls_version; } dtls_ciphersuite_st; #ifdef HAVE_GSSAPI -# include +#include /* main has initialized that for us */ extern asn1_node _kkdcp_pkix1_asn; #endif @@ -139,7 +139,7 @@ struct http_req_st { char devplatform[MAX_AGENT_NAME]; /* Device-Platform */ char hostname[MAX_HOSTNAME_SIZE]; char user_agent[MAX_AGENT_NAME]; - unsigned user_agent_type; + unsigned int user_agent_type; unsigned int next_header; @@ -154,18 +154,18 @@ struct http_req_st { unsigned int body_length; const dtls_ciphersuite_st *selected_ciphersuite; - unsigned use_psk; /* i.e., ignore selected_ciphersuite */ + unsigned int use_psk; /* i.e., ignore selected_ciphersuite */ unsigned int headers_complete; unsigned int message_complete; - unsigned link_mtu; - unsigned tunnel_mtu; + unsigned int link_mtu; + unsigned int tunnel_mtu; - unsigned no_ipv4; - unsigned no_ipv6; + unsigned int no_ipv4; + unsigned int no_ipv6; char *authorization; - unsigned authorization_size; + unsigned int authorization_size; }; typedef struct dtls_transport_ptr { @@ -187,7 +187,8 @@ typedef struct dtls_st { /* Given a base MTU, this macro provides the DTLS plaintext data we can send; * the output value does not include the DTLS header */ -#define DATA_MTU(ws,mtu) (mtu-ws->dtls_crypto_overhead-ws->dtls_proto_overhead) +#define DATA_MTU(ws, mtu) \ + (mtu - ws->dtls_crypto_overhead - ws->dtls_proto_overhead) typedef struct worker_st { gnutls_session_t session; @@ -218,12 +219,12 @@ typedef struct worker_st { unsigned int auth_state; /* S_AUTH */ - struct sockaddr_un secmod_addr; /* sec-mod unix address */ + struct sockaddr_un secmod_addr; /* sec-mod unix address */ socklen_t secmod_addr_len; - struct sockaddr_storage our_addr; /* our address */ + struct sockaddr_storage our_addr; /* our address */ socklen_t our_addr_len; - struct sockaddr_storage remote_addr; /* peer's address */ + struct sockaddr_storage remote_addr; /* peer's address */ socklen_t remote_addr_len; char our_ip_str[MAX_IP_STR]; char remote_ip_str[MAX_IP_STR]; @@ -259,8 +260,8 @@ typedef struct worker_st { time_t last_stats_msg; /* for mtu trials */ - unsigned last_good_mtu; - unsigned last_bad_mtu; + unsigned int last_good_mtu; + unsigned int last_bad_mtu; /* bandwidth stats */ bandwidth_st b_tx; @@ -269,24 +270,26 @@ typedef struct worker_st { /* ws->link_mtu: The MTU of the link of the connecting. The plaintext * data we can send to the client (i.e., MTU of the tun device, * can be accessed using the DATA_MTU() macro and this value. */ - unsigned link_mtu; - unsigned adv_link_mtu; /* the MTU advertised on connection setup */ + unsigned int link_mtu; + unsigned int adv_link_mtu; /* the MTU advertised on connection setup */ - unsigned cstp_crypto_overhead; /* estimated overhead of DTLS ciphersuite + DTLS CSTP HEADER */ - unsigned cstp_proto_overhead; /* UDP + IP header size */ + unsigned int + cstp_crypto_overhead; /* estimated overhead of DTLS ciphersuite + DTLS CSTP HEADER */ + unsigned int cstp_proto_overhead; /* UDP + IP header size */ - unsigned dtls_crypto_overhead; /* estimated overhead of DTLS ciphersuite + DTLS CSTP HEADER */ - unsigned dtls_proto_overhead; /* UDP + IP header size */ + unsigned int + dtls_crypto_overhead; /* estimated overhead of DTLS ciphersuite + DTLS CSTP HEADER */ + unsigned int dtls_proto_overhead; /* UDP + IP header size */ /* Indicates whether the new IPv6 headers will * be sent or the old */ - unsigned full_ipv6; + unsigned int full_ipv6; /* Buffer used by worker */ - uint8_t buffer[16*1024]; + uint8_t buffer[16 * 1024]; /* Buffer used for decompression */ - uint8_t decomp[16*1024]; - unsigned buffer_size; + uint8_t decomp[16 * 1024]; + unsigned int buffer_size; /* the following are set only if authentication is complete */ @@ -295,7 +298,7 @@ typedef struct worker_st { char cert_username[MAX_USERNAME_SIZE]; char **cert_groups; - unsigned cert_groups_size; + unsigned int cert_groups_size; char hostname[MAX_HOSTNAME_SIZE]; uint8_t cookie[SID_SIZE]; @@ -306,11 +309,11 @@ typedef struct worker_st { uint8_t master_secret[TLS_MASTER_SIZE]; uint8_t session_id[GNUTLS_MAX_SESSION_ID]; - unsigned cert_auth_ok; + unsigned int cert_auth_ok; int tun_fd; /* ban points to be sent on exit */ - unsigned ban_points; + unsigned int ban_points; /* tun device stats */ uint64_t tun_bytes_in; @@ -318,7 +321,7 @@ typedef struct worker_st { /* information on the tun device addresses and network */ struct vpn_st vinfo; - unsigned default_route; + unsigned int default_route; void *main_pool; /* to be used only on deinitialization */ @@ -333,73 +336,72 @@ typedef struct worker_st { uint32_t samples[LATENCY_SAMPLE_SIZE]; } latency; #endif - bool camouflage_check_passed; + bool camouflage_check_passed; } worker_st; -void vpn_server(struct worker_st* ws); +void vpn_server(struct worker_st *ws); -int auth_cookie(worker_st *ws, void* cookie, size_t cookie_size); +int auth_cookie(worker_st *ws, void *cookie, size_t cookie_size); int auth_user_deinit(worker_st *ws); -int get_auth_handler(worker_st *server, unsigned http_ver); -int post_auth_handler(worker_st *server, unsigned http_ver); -int post_kkdcp_handler(worker_st *server, unsigned http_ver); -int get_cert_handler(worker_st * ws, unsigned http_ver); -int get_cert_der_handler(worker_st * ws, unsigned http_ver); -int get_ca_handler(worker_st * ws, unsigned http_ver); -int get_ca_der_handler(worker_st * ws, unsigned http_ver); -int get_svc_handler(worker_st *ws, unsigned http_ver); -int post_svc_handler(worker_st *ws, unsigned http_ver); +int get_auth_handler(worker_st *server, unsigned int http_ver); +int post_auth_handler(worker_st *server, unsigned int http_ver); +int post_kkdcp_handler(worker_st *server, unsigned int http_ver); +int get_cert_handler(worker_st *ws, unsigned int http_ver); +int get_cert_der_handler(worker_st *ws, unsigned int http_ver); +int get_ca_handler(worker_st *ws, unsigned int http_ver); +int get_ca_der_handler(worker_st *ws, unsigned int http_ver); +int get_svc_handler(worker_st *ws, unsigned int http_ver); +int post_svc_handler(worker_st *ws, unsigned int http_ver); - -int response_404(worker_st *ws, unsigned http_ver); -int response_401(worker_st *ws, unsigned http_ver, char* realm); -int get_empty_handler(worker_st *server, unsigned http_ver); +int response_404(worker_st *ws, unsigned int http_ver); +int response_401(worker_st *ws, unsigned int http_ver, char *realm); +int get_empty_handler(worker_st *server, unsigned int http_ver); #ifdef ANYCONNECT_CLIENT_COMPAT -int get_config_handler(worker_st *ws, unsigned http_ver); +int get_config_handler(worker_st *ws, unsigned int http_ver); #endif -int get_string_handler(worker_st *ws, unsigned http_ver); -int get_dl_handler(worker_st *ws, unsigned http_ver); -int get_cert_names(worker_st * ws, const gnutls_datum_t * raw); +int get_string_handler(worker_st *ws, unsigned int http_ver); +int get_dl_handler(worker_st *ws, unsigned int http_ver); +int get_cert_names(worker_st *ws, const gnutls_datum_t *raw); void set_resume_db_funcs(gnutls_session_t); -typedef int (*url_handler_fn) (worker_st *, unsigned http_ver); -int http_url_cb(llhttp_t * parser, const char *at, size_t length); -int http_header_value_cb(llhttp_t * parser, const char *at, size_t length); -int http_header_field_cb(llhttp_t * parser, const char *at, size_t length); -int http_header_complete_cb(llhttp_t * parser); -int http_message_complete_cb(llhttp_t * parser); -int http_body_cb(llhttp_t * parser, const char *at, size_t length); -void http_req_deinit(worker_st * ws); -void http_req_reset(worker_st * ws); -void http_req_init(worker_st * ws); +typedef int (*url_handler_fn)(worker_st *, unsigned int http_ver); +int http_url_cb(llhttp_t *parser, const char *at, size_t length); +int http_header_value_cb(llhttp_t *parser, const char *at, size_t length); +int http_header_field_cb(llhttp_t *parser, const char *at, size_t length); +int http_header_complete_cb(llhttp_t *parser); +int http_message_complete_cb(llhttp_t *parser); +int http_body_cb(llhttp_t *parser, const char *at, size_t length); +void http_req_deinit(worker_st *ws); +void http_req_reset(worker_st *ws); +void http_req_init(worker_st *ws); -unsigned valid_hostname(const char *host); +unsigned int valid_hostname(const char *host); url_handler_fn http_get_url_handler(const char *url); -url_handler_fn http_post_url_handler(worker_st * ws, const char *url); -url_handler_fn http_post_known_service_check(worker_st * ws, const char *url); +url_handler_fn http_post_url_handler(worker_st *ws, const char *url); +url_handler_fn http_post_known_service_check(worker_st *ws, const char *url); -int complete_vpn_info(worker_st * ws, - struct vpn_st* vinfo); +int complete_vpn_info(worker_st *ws, struct vpn_st *vinfo); int send_tun_mtu(worker_st *ws, unsigned int mtu); int handle_commands_from_main(struct worker_st *ws); int disable_system_calls(struct worker_st *ws); void ocsigaltstack(struct worker_st *ws); -void exit_worker(worker_st * ws); -void exit_worker_reason(worker_st * ws, unsigned reason); +void exit_worker(worker_st *ws); +void exit_worker_reason(worker_st *ws, unsigned int reason); -int ws_switch_auth_to(struct worker_st *ws, unsigned auth); +int ws_switch_auth_to(struct worker_st *ws, unsigned int auth); int ws_switch_auth_to_next(struct worker_st *ws); -void ws_add_score_to_ip(worker_st *ws, unsigned points, unsigned final, unsigned discon_reason); +void ws_add_score_to_ip(worker_st *ws, unsigned int points, unsigned int final, + unsigned int discon_reason); -int connect_to_secmod(worker_st * ws); -inline static -int send_msg_to_secmod(worker_st * ws, int sd, uint8_t cmd, - const void *msg, pack_size_func get_size, pack_func pack) +int connect_to_secmod(worker_st *ws); +inline static int send_msg_to_secmod(worker_st *ws, int sd, uint8_t cmd, + const void *msg, pack_size_func get_size, + pack_func pack) { oclog(ws, LOG_DEBUG, "sending message '%s' to secmod", cmd_request_to_str(cmd)); @@ -407,18 +409,18 @@ int send_msg_to_secmod(worker_st * ws, int sd, uint8_t cmd, return send_msg(ws, sd, cmd, msg, get_size, pack); } -int recv_auth_reply(worker_st * ws, int sd, char **txt, unsigned *pcounter); -int get_cert_info(worker_st * ws); -int parse_reply(worker_st * ws, char *body, unsigned body_length, - const char *field, unsigned field_size, - const char *xml_field, unsigned xml_field_size, +int recv_auth_reply(worker_st *ws, int sd, char **txt, unsigned int *pcounter); +int get_cert_info(worker_st *ws); +int parse_reply(worker_st *ws, char *body, unsigned int body_length, + const char *field, unsigned int field_size, + const char *xml_field, unsigned int xml_field_size, char **value); -inline static -int send_msg_to_main(worker_st *ws, uint8_t cmd, - const void* msg, pack_size_func get_size, pack_func pack) +inline static int send_msg_to_main(worker_st *ws, uint8_t cmd, const void *msg, + pack_size_func get_size, pack_func pack) { - oclog(ws, LOG_DEBUG, "sending message '%s' to main", cmd_request_to_str(cmd)); + oclog(ws, LOG_DEBUG, "sending message '%s' to main", + cmd_request_to_str(cmd)); return send_msg(ws, ws->cmd_fd, cmd, msg, get_size, pack); } @@ -426,7 +428,7 @@ int parse_proxy_proto_header(struct worker_st *ws, int fd); void cookie_authenticate_or_exit(worker_st *ws); -int add_owasp_headers(worker_st * ws); +int add_owasp_headers(worker_st *ws); /* after that time (secs) of inactivity in the UDP part, connection switches to * TCP (if activity occurs there). diff --git a/tests/ban-ips.c b/tests/ban-ips.c index e8af5137..303de3a1 100644 --- a/tests/ban-ips.c +++ b/tests/ban-ips.c @@ -30,11 +30,10 @@ #include "../src/ip-util.h" #include "../src/main-ban.c" -int syslog_open = 0; +int syslog_open; /* Test the IP banning functionality */ -static -unsigned check_if_banned_str(main_server_st *s, const char *ip) +static unsigned int check_if_banned_str(main_server_st *s, const char *ip) { struct sockaddr_storage addr; int ret; @@ -51,7 +50,10 @@ unsigned check_if_banned_str(main_server_st *s, const char *ip) fprintf(stderr, "cannot convert IP: %s\n", ip); exit(1); } - return check_if_banned(s, &addr, addr.ss_family==AF_INET?sizeof(struct sockaddr_in):sizeof(struct sockaddr_in6)); + return check_if_banned(s, &addr, + addr.ss_family == AF_INET ? + sizeof(struct sockaddr_in) : + sizeof(struct sockaddr_in6)); } int main(void) @@ -111,37 +113,43 @@ int main(void) /* a single /64 */ add_str_ip_to_ban_list(s, "fc8e:899a:0624:5a89:1a45:63d8:1c92:0bc1", 5); - add_str_ip_to_ban_list(s, "fc8e:899a:0624:5a89:1a45:63d9:1c92:0bc1", 10); + add_str_ip_to_ban_list(s, "fc8e:899a:0624:5a89:1a45:63d9:1c92:0bc1", + 10); add_str_ip_to_ban_list(s, "fc8e:899a:0624:5a89:1a45:63d8:1c93:0bc1", 5); add_str_ip_to_ban_list(s, "fdd9:1ce6:1bee:bdea:5d8c:0840:8666:5942", 5); - add_str_ip_to_ban_list(s, "fdc0:c81f:22ab:23a2:4479:f107:1855:bf50", 40); + add_str_ip_to_ban_list(s, "fdc0:c81f:22ab:23a2:4479:f107:1855:bf50", + 40); /* check /64 */ - if (check_if_banned_str(s, "fc8e:899a:0624:5a89:1a45:63d8:1c93:0bc1") == 0) { + if (check_if_banned_str(s, "fc8e:899a:0624:5a89:1a45:63d8:1c93:0bc1") == + 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } - if (check_if_banned_str(s, "fc8e:899a:0624:5a89:1a46:63d9:1c93:0bc1") == 0) { + if (check_if_banned_str(s, "fc8e:899a:0624:5a89:1a46:63d9:1c93:0bc1") == + 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } /* check individual */ - if (check_if_banned_str(s, "fdd9:1ce6:1bee:bdea:5d8c:0840:8666:5942") != 0) { + if (check_if_banned_str(s, "fdd9:1ce6:1bee:bdea:5d8c:0840:8666:5942") != + 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } - if (check_if_banned_str(s, "fdc0:c81f:22ab:23a2:4479:f107:1855:bf50") == 0) { + if (check_if_banned_str(s, "fdc0:c81f:22ab:23a2:4479:f107:1855:bf50") == + 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } /* check expiration of entries */ - sleep(GETCONFIG(s)->min_reauth_time+1); + sleep(GETCONFIG(s)->min_reauth_time + 1); if (check_if_banned_str(s, "192.168.1.1") != 0) { fprintf(stderr, "error in %d\n", __LINE__); @@ -158,18 +166,20 @@ int main(void) exit(1); } - if (check_if_banned_str(s, "fdc0:c81f:22ab:23a2:4479:f107:1855:bf50") != 0) { + if (check_if_banned_str(s, "fdc0:c81f:22ab:23a2:4479:f107:1855:bf50") != + 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } /* check cleanup */ - sleep(GETCONFIG(s)->min_reauth_time+1); + sleep(GETCONFIG(s)->min_reauth_time + 1); cleanup_banned_entries(s); if (main_ban_db_elems(s) != 0) { - fprintf(stderr, "error in %d: have %d entries\n", __LINE__, main_ban_db_elems(s)); + fprintf(stderr, "error in %d: have %d entries\n", __LINE__, + main_ban_db_elems(s)); exit(1); } diff --git a/tests/cstp-recv.c b/tests/cstp-recv.c index 1a3c2163..2f1aa117 100644 --- a/tests/cstp-recv.c +++ b/tests/cstp-recv.c @@ -30,15 +30,15 @@ /* Unit test for _cstp_recv_packet(). I checks whether * CSTP packets are received and decoded as expected. */ -static unsigned verbose = 0; +static unsigned int verbose; #define UNDER_TEST #define force_write write #include "../src/tlslib.c" -int syslog_open = 0; +int syslog_open; -int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) +int get_cert_names(worker_st *ws, const gnutls_datum_t *raw) { return 0; } @@ -48,13 +48,14 @@ int get_cert_names(worker_st * ws, const gnutls_datum_t * raw) void writer(int fd) { - unsigned size, i, j; - unsigned char buf[MAX_SIZE+8]; + unsigned int size, i, j; + unsigned char buf[MAX_SIZE + 8]; memset(buf, 0, sizeof(buf)); - for (i=0;i= 0); + for (i = 0; i < ITERATIONS; i++) { + assert(gnutls_rnd(GNUTLS_RND_NONCE, &size, + sizeof(unsigned int)) >= 0); size %= MAX_SIZE; size++; /* non-zero */ @@ -66,8 +67,8 @@ void writer(int fd) if (verbose) fprintf(stderr, "sending %d\n", size); - for (j=0;j sizeof(openid_configuration_file)) { exit(1); } - retval = - snprintf(keys_file, sizeof(keys_file), "%s/keys.json", - output_folder); + retval = snprintf(keys_file, sizeof(keys_file), "%s/keys.json", + output_folder); if (retval < 0 || retval > sizeof(openid_configuration_file)) { exit(1); } - retval = - snprintf(openid_configuration_uri, sizeof(openid_configuration_uri), - "file://localhost%s", openid_configuration_file); + retval = snprintf(openid_configuration_uri, + sizeof(openid_configuration_uri), + "file://localhost%s", openid_configuration_file); if (retval < 0 || retval > sizeof(openid_configuration_file)) { exit(1); } - retval = - snprintf(keys_uri, sizeof(keys_uri), "file://localhost%s", - keys_file); + retval = snprintf(keys_uri, sizeof(keys_uri), "file://localhost%s", + keys_file); if (retval < 0 || retval > sizeof(openid_configuration_file)) { exit(1); } - json_t *oidc_config = - create_oidc_config(openid_configuration_uri, "preferred_username", - "SomeAudience", "SomeIssuer"); + json_t *oidc_config = create_oidc_config(openid_configuration_uri, + "preferred_username", + "SomeAudience", "SomeIssuer"); json_t *openid_configuration = create_openid_configuration(keys_uri); json_t *keys = create_keys(key); @@ -272,8 +278,8 @@ int main(int argc, char **argv) if (!getcwd(working_directory, sizeof(working_directory))) { return 1; } - strncat(working_directory, "/data", sizeof(working_directory)-1); - working_directory[sizeof(working_directory)-1] = 0; + strncat(working_directory, "/data", sizeof(working_directory) - 1); + working_directory[sizeof(working_directory) - 1] = 0; cjose_jwk_t *key = create_key(kid); diff --git a/tests/html-escape.c b/tests/html-escape.c index 5d5a327e..1e4a656c 100644 --- a/tests/html-escape.c +++ b/tests/html-escape.c @@ -27,10 +27,10 @@ #include "../src/html.c" #include "../src/common/common.h" -int syslog_open = 0; +int syslog_open; + +static char *strings[] = { -static char *strings[] = -{ "hello there", "hi bro\n", "small ascii\x10\x01\x03\x04\x18\x20\x21\x1f end", @@ -43,8 +43,8 @@ static char *strings[] = "Ahoy matey!" }; -static char *encoded_strings[] = -{ +static char *encoded_strings[] = { + "hello there", "hi bro ", "small ascii ! end", @@ -60,17 +60,21 @@ static char *encoded_strings[] = int main(void) { char *dec; - unsigned i; - unsigned len; + unsigned int i; + unsigned int len; - for (i=0;iproto != PROTO_ICMP || fw_ports[1]->proto != PROTO_TCP || fw_ports[2]->proto != PROTO_UDP || - fw_ports[3]->proto != PROTO_SCTP || fw_ports[4]->proto != PROTO_TCP || - fw_ports[5]->proto != PROTO_UDP || fw_ports[6]->proto != PROTO_ICMPv6) { - + if (fw_ports[0]->proto != PROTO_ICMP || + fw_ports[1]->proto != PROTO_TCP || + fw_ports[2]->proto != PROTO_UDP || + fw_ports[3]->proto != PROTO_SCTP || + fw_ports[4]->proto != PROTO_TCP || + fw_ports[5]->proto != PROTO_UDP || + fw_ports[6]->proto != PROTO_ICMPv6) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } if (fw_ports[1]->port != 88 || fw_ports[2]->port != 90 || - fw_ports[3]->port != 70 || fw_ports[4]->port != 443 || - fw_ports[5]->port != 80) { - + fw_ports[3]->port != 70 || fw_ports[4]->port != 443 || + fw_ports[5]->port != 80) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } @@ -70,7 +76,8 @@ int main(void) size_t n_fw_ports = 0; void *pool = talloc_new(NULL); - strcpy(p, "icmp(), tcp(88), udp(90), sctp(70), tcp(443), udp(80), icmpv6()"); + strcpy(p, + "icmp(), tcp(88), udp(90), sctp(70), tcp(443), udp(80), icmpv6()"); ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p); if (ret < 0) { @@ -82,7 +89,8 @@ int main(void) /* check spacing tolerance */ reset(fw_ports, n_fw_ports); - strcpy(p, "icmp ( ), tcp ( 88 ), udp ( 90 ), sctp ( 70 ) , tcp ( 443 ) , udp(80) , icmpv6 ( ) "); + strcpy(p, + "icmp ( ), tcp ( 88 ), udp ( 90 ), sctp ( 70 ) , tcp ( 443 ) , udp(80) , icmpv6 ( ) "); ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p); if (ret < 0) { @@ -111,7 +119,8 @@ int main(void) } reset(fw_ports, n_fw_ports); - strcpy(p, "!(icmp(), tcp(88), udp(90), sctp(70), tcp(443), udp(80), icmpv6())"); + strcpy(p, + "!(icmp(), tcp(88), udp(90), sctp(70), tcp(443), udp(80), icmpv6())"); ret = cfg_parse_ports(pool, &fw_ports, &n_fw_ports, p); if (ret < 0) { diff --git a/tests/proxyproto-v1.c b/tests/proxyproto-v1.c index defb4214..7df4ffe7 100644 --- a/tests/proxyproto-v1.c +++ b/tests/proxyproto-v1.c @@ -35,21 +35,24 @@ #define force_read_timeout(fd, buf, count, time) read(fd, buf, count) #include "../src/worker-proxyproto.c" -static unsigned try(const char *src, unsigned src_port, const char *dst, unsigned dst_port) +static unsigned int try(const char *src, unsigned int src_port, const char *dst, + unsigned int dst_port) { char str[256]; struct worker_st ws; - unsigned ipv6 = 0; + unsigned int ipv6 = 0; int ret; memset(&ws, 0, sizeof(ws)); if (strchr(src, ':') != NULL) { /* ipv6 */ - snprintf(str, sizeof(str), "TCP6 %s %s %u %u\r\n", src, dst, src_port, dst_port); + snprintf(str, sizeof(str), "TCP6 %s %s %u %u\r\n", src, dst, + src_port, dst_port); ipv6 = 1; } else { - snprintf(str, sizeof(str), "TCP4 %s %s %u %u\r\n", src, dst, src_port, dst_port); + snprintf(str, sizeof(str), "TCP4 %s %s %u %u\r\n", src, dst, + src_port, dst_port); } ret = parse_proxy_proto_header_v1(&ws, str); @@ -60,21 +63,25 @@ static unsigned try(const char *src, unsigned src_port, const char *dst, unsigne /* check if output values are right */ if (ipv6) { - struct sockaddr_in6 *sa_src = (void*)&ws.remote_addr; - struct sockaddr_in6 *sa_dst = (void*)&ws.our_addr; + struct sockaddr_in6 *sa_src = (void *)&ws.remote_addr; + struct sockaddr_in6 *sa_dst = (void *)&ws.our_addr; if (ws.remote_addr_len != sizeof(struct sockaddr_in6) || - ws.our_addr_len != sizeof(struct sockaddr_in6)) { + ws.our_addr_len != sizeof(struct sockaddr_in6)) { fprintf(stderr, "error in %d for %s\n", __LINE__, str); return 0; } - if (strcmp(inet_ntop(AF_INET6, (void*)&sa_src->sin6_addr, str, sizeof(str)), src) != 0) { + if (strcmp(inet_ntop(AF_INET6, (void *)&sa_src->sin6_addr, str, + sizeof(str)), + src) != 0) { fprintf(stderr, "error in %d for %s\n", __LINE__, str); return 0; } - if (strcmp(inet_ntop(AF_INET6, (void*)&sa_dst->sin6_addr, str, sizeof(str)), dst) != 0) { + if (strcmp(inet_ntop(AF_INET6, (void *)&sa_dst->sin6_addr, str, + sizeof(str)), + dst) != 0) { fprintf(stderr, "error in %d for %s\n", __LINE__, str); return 0; } @@ -89,21 +96,25 @@ static unsigned try(const char *src, unsigned src_port, const char *dst, unsigne return 0; } } else { - struct sockaddr_in *sa_src = (void*)&ws.remote_addr; - struct sockaddr_in *sa_dst = (void*)&ws.our_addr; + struct sockaddr_in *sa_src = (void *)&ws.remote_addr; + struct sockaddr_in *sa_dst = (void *)&ws.our_addr; if (ws.remote_addr_len != sizeof(struct sockaddr_in) || - ws.our_addr_len != sizeof(struct sockaddr_in)) { + ws.our_addr_len != sizeof(struct sockaddr_in)) { fprintf(stderr, "error in %d for %s\n", __LINE__, str); return 0; } - if (strcmp(inet_ntop(AF_INET, (void*)&sa_src->sin_addr, str, sizeof(str)), src) != 0) { + if (strcmp(inet_ntop(AF_INET, (void *)&sa_src->sin_addr, str, + sizeof(str)), + src) != 0) { fprintf(stderr, "error in %d for %s\n", __LINE__, str); return 0; } - if (strcmp(inet_ntop(AF_INET, (void*)&sa_dst->sin_addr, str, sizeof(str)), dst) != 0) { + if (strcmp(inet_ntop(AF_INET, (void *)&sa_dst->sin_addr, str, + sizeof(str)), + dst) != 0) { fprintf(stderr, "error in %d for %s\n", __LINE__, str); return 0; } @@ -126,7 +137,8 @@ int main(int argc, char **argv) { assert(try("127.0.0.1", 99, "127.0.0.1", 100) == 1); assert(try("192.168.5.1", 1099, "172.52.3.1", 3100) == 1); - assert(try("fcd0:4d89:c36:ca3f::", 1099, "fdce:e8e5:8c8e:4294::", 3100) == 1); + assert(try("fcd0:4d89:c36:ca3f::", 1099, + "fdce:e8e5:8c8e:4294::", 3100) == 1); assert(try("xxx.0.0.1", 99, "127.0.0.1", 100) == 0); assert(try("127.0.0.1", 99, "xxx.0.0.1", 100) == 0); assert(try("901.0.0.1", 99, "127.0.0.1", 100) == 0); diff --git a/tests/str-test.c b/tests/str-test.c index de0f0bab..579900d4 100644 --- a/tests/str-test.c +++ b/tests/str-test.c @@ -47,8 +47,8 @@ int main(void) exit(1); } - if (str.length != sizeof(STR1)-1 || - strncmp((char*)str.data, STR1, sizeof(STR1)-1) != 0) { + if (str.length != sizeof(STR1) - 1 || + strncmp((char *)str.data, STR1, sizeof(STR1) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } @@ -64,9 +64,13 @@ int main(void) STR_TAB_TERM(7); /* check proper operation */ -#define STR2 "This is one route1, and one route2, while a route3 was replaced by dev1 and dev2 and dev1. That's all u1." +#define STR2 \ + "This is one route1, and one route2, while a route3 was replaced by dev1 and dev2 and dev1. That's all u1." str_reset(&str); - if (str_append_str(&str, "This is one %R, and one %{R}, while a %{R2} was replaced by %{D} and %D and %{D}. That's all %U.") != 0) { + if (str_append_str( + &str, + "This is one %R, and one %{R}, while a %{R2} was replaced by %{D} and %D and %{D}. That's all %U.") != + 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } @@ -76,12 +80,12 @@ int main(void) exit(1); } - if (str.length != sizeof(STR2)-1) { + if (str.length != sizeof(STR2) - 1) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } - if (strncmp((char*)str.data, STR2, sizeof(STR2)-1) != 0) { + if (strncmp((char *)str.data, STR2, sizeof(STR2) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } @@ -104,12 +108,12 @@ int main(void) exit(1); } - if (str.length != sizeof(STR3_OUT)-1) { + if (str.length != sizeof(STR3_OUT) - 1) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } - if (strncmp((char*)str.data, STR3_OUT, sizeof(STR3_OUT)-1) != 0) { + if (strncmp((char *)str.data, STR3_OUT, sizeof(STR3_OUT) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } diff --git a/tests/str-test2.c b/tests/str-test2.c index 5215a664..f383953f 100644 --- a/tests/str-test2.c +++ b/tests/str-test2.c @@ -29,20 +29,20 @@ int main(void) { char str[64]; - strcpy(str, STR1" "); + strcpy(str, STR1 " "); trim_trailing_whitespace(str); - if (strncmp(str, STR1, sizeof(STR1)-1) != 0) { + if (strncmp(str, STR1, sizeof(STR1) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } - strcpy(str, STR1" "); + strcpy(str, STR1 " "); trim_trailing_whitespace(str); - if (strncmp(str, STR1, sizeof(STR1)-1) != 0) { + if (strncmp(str, STR1, sizeof(STR1) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } @@ -51,16 +51,16 @@ int main(void) trim_trailing_whitespace(str); - if (strncmp(str, STR1, sizeof(STR1)-1) != 0) { + if (strncmp(str, STR1, sizeof(STR1) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } - strcpy(str, " "STR1); + strcpy(str, " " STR1); trim_trailing_whitespace(str); - if (strncmp(str, " "STR1, sizeof(" "STR1)-1) != 0) { + if (strncmp(str, " " STR1, sizeof(" " STR1) - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } @@ -69,7 +69,7 @@ int main(void) trim_trailing_whitespace(str); - if (strncmp(str, "", sizeof("")-1) != 0) { + if (strncmp(str, "", sizeof("") - 1) != 0) { fprintf(stderr, "error in %d\n", __LINE__); exit(1); } diff --git a/tests/url-escape.c b/tests/url-escape.c index 7dee5442..fa087b43 100644 --- a/tests/url-escape.c +++ b/tests/url-escape.c @@ -26,39 +26,40 @@ #include "../src/html.h" #include "../src/html.c" -int syslog_open = 0; +int syslog_open; -static char *strings[] = -{ - "Laguna+Beach", - "_+-.~%2C", - "Laguna%25%2B%40Beach" +static char *strings[] = { + + "Laguna+Beach", "_+-.~%2C", "Laguna%25%2B%40Beach" }; -static char *decoded_strings[] = -{ - "Laguna Beach", - "_ -.~,", - "Laguna%+@Beach" +static char *decoded_strings[] = { + + "Laguna Beach", "_ -.~,", "Laguna%+@Beach" }; int main(void) { char *dec, *url; - unsigned i; - unsigned len; + unsigned int i; + unsigned int len; - for (i=0;i