Explorar el Código

tls: clang-format for coherent indentation and coding style

Victor Seva hace 2 años
padre
commit
d253dcd8b6

+ 67 - 73
src/modules/tls/fixed_c_zlib.h

@@ -43,19 +43,19 @@
 
 
 /* alloc functions for zlib initialization */
-static void* comp_calloc(void* foo, unsigned int no, unsigned int size)
+static void *comp_calloc(void *foo, unsigned int no, unsigned int size)
 {
 	void *p;
 
-	p=OPENSSL_malloc(no*size);
-	if (p)
-		memset(p, 0, no*size);
+	p = OPENSSL_malloc(no * size);
+	if(p)
+		memset(p, 0, no * size);
 	return p;
 }
 
 
 /* alloc functions for zlib initialization */
-static void comp_free(void* foo, void* p)
+static void comp_free(void *foo, void *p)
 {
 	OPENSSL_free(p);
 }
@@ -69,15 +69,15 @@ static int zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out,
 		unsigned int olen, unsigned char *in, unsigned int ilen);
 
 
-static COMP_METHOD zlib_method={
-	NID_zlib_compression,
-	LN_zlib_compression,
-	zlib_stateful_init,
-	zlib_stateful_finish,
-	zlib_stateful_compress_block,
-	zlib_stateful_expand_block,
-	NULL,
-	NULL,
+static COMP_METHOD zlib_method = {
+		NID_zlib_compression,
+		LN_zlib_compression,
+		zlib_stateful_init,
+		zlib_stateful_finish,
+		zlib_stateful_compress_block,
+		zlib_stateful_expand_block,
+		NULL,
+		NULL,
 };
 
 
@@ -87,57 +87,56 @@ struct zlib_state
 	z_stream ostream;
 };
 
-static int* pzlib_stateful_ex_idx = 0;
+static int *pzlib_stateful_ex_idx = 0;
 #define zlib_stateful_ex_idx (*pzlib_stateful_ex_idx)
 
 static void zlib_stateful_free_ex_data(void *obj, void *item,
-		CRYPTO_EX_DATA *ad, int ind,long argl, void *argp);
+		CRYPTO_EX_DATA *ad, int ind, long argl, void *argp);
 
 int fixed_c_zlib_init()
 {
-	if (pzlib_stateful_ex_idx==0){
-		if ((pzlib_stateful_ex_idx=OPENSSL_malloc(sizeof(int)))!=0){
+	if(pzlib_stateful_ex_idx == 0) {
+		if((pzlib_stateful_ex_idx = OPENSSL_malloc(sizeof(int))) != 0) {
 			/* good side effect: it makes sure the ex_data hash
 			 * in crypto/ex_data.c is created before fork
 			 * (else each process would have its own copy :-( ) */
 			CRYPTO_w_lock(CRYPTO_LOCK_COMP);
-			zlib_stateful_ex_idx =
-				CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_COMP,
-						0,NULL,NULL,NULL,zlib_stateful_free_ex_data);
+			zlib_stateful_ex_idx = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_COMP,
+					0, NULL, NULL, NULL, zlib_stateful_free_ex_data);
 			CRYPTO_w_unlock(CRYPTO_LOCK_COMP);
 			return 0;
-		} else return -1;
+		} else
+			return -1;
 	}
 	return -1;
 }
 
 
-
 static void zlib_stateful_free_ex_data(void *obj, void *item,
-		CRYPTO_EX_DATA *ad, int ind,long argl, void *argp)
+		CRYPTO_EX_DATA *ad, int ind, long argl, void *argp)
 {
 	struct zlib_state *state = (struct zlib_state *)item;
-	if (state)
-	{
+	if(state) {
 		inflateEnd(&state->istream);
 		deflateEnd(&state->ostream);
 		OPENSSL_free(state);
-	}
-	else LM_CRIT("WARNING: zlib_stateful_free_ex(%p, %p, %p, %d, %ld, %p)"
-			": cannot free, null item/state\n", obj, item, ad, ind, argl, argp);
+	} else
+		LM_CRIT("WARNING: zlib_stateful_free_ex(%p, %p, %p, %d, %ld, %p)"
+				": cannot free, null item/state\n",
+				obj, item, ad, ind, argl, argp);
 }
 
 static int zlib_stateful_init(COMP_CTX *ctx)
 {
 	int err;
 	struct zlib_state *state =
-		(struct zlib_state *)OPENSSL_malloc(sizeof(struct zlib_state));
+			(struct zlib_state *)OPENSSL_malloc(sizeof(struct zlib_state));
 	int inflate_init, deflate_init;
 
-	if (state == NULL)
+	if(state == NULL)
 		goto err;
-	inflate_init=0;
-	deflate_init=0;
+	inflate_init = 0;
+	deflate_init = 0;
 
 	state->istream.zalloc = comp_calloc;
 	state->istream.zfree = comp_free;
@@ -146,11 +145,10 @@ static int zlib_stateful_init(COMP_CTX *ctx)
 	state->istream.next_out = Z_NULL;
 	state->istream.avail_in = 0;
 	state->istream.avail_out = 0;
-	err = inflateInit_(&state->istream,
-			ZLIB_VERSION, sizeof(z_stream));
-	if (err != Z_OK)
+	err = inflateInit_(&state->istream, ZLIB_VERSION, sizeof(z_stream));
+	if(err != Z_OK)
 		goto err;
-	inflate_init=1;
+	inflate_init = 1;
 
 	state->ostream.zalloc = comp_calloc;
 	state->ostream.zfree = comp_free;
@@ -159,36 +157,34 @@ static int zlib_stateful_init(COMP_CTX *ctx)
 	state->ostream.next_out = Z_NULL;
 	state->ostream.avail_in = 0;
 	state->ostream.avail_out = 0;
-	err = deflateInit_(&state->ostream,Z_DEFAULT_COMPRESSION,
-			ZLIB_VERSION, sizeof(z_stream));
-	if (err != Z_OK)
+	err = deflateInit_(&state->ostream, Z_DEFAULT_COMPRESSION, ZLIB_VERSION,
+			sizeof(z_stream));
+	if(err != Z_OK)
 		goto err;
-	deflate_init=1;
+	deflate_init = 1;
 
-	if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_COMP,ctx,&ctx->ex_data))
+	if(!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_COMP, ctx, &ctx->ex_data))
 		goto err;
-	if (zlib_stateful_ex_idx == -1)
-	{
+	if(zlib_stateful_ex_idx == -1) {
 		CRYPTO_w_lock(CRYPTO_LOCK_COMP);
-		if (zlib_stateful_ex_idx == -1)
-			zlib_stateful_ex_idx =
-				CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_COMP,
-						0,NULL,NULL,NULL,zlib_stateful_free_ex_data);
+		if(zlib_stateful_ex_idx == -1)
+			zlib_stateful_ex_idx = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_COMP,
+					0, NULL, NULL, NULL, zlib_stateful_free_ex_data);
 		CRYPTO_w_unlock(CRYPTO_LOCK_COMP);
-		if (zlib_stateful_ex_idx == -1)
+		if(zlib_stateful_ex_idx == -1)
 			goto err_ex_data;
 	}
-	if (!CRYPTO_set_ex_data(&ctx->ex_data,zlib_stateful_ex_idx,state))
+	if(!CRYPTO_set_ex_data(&ctx->ex_data, zlib_stateful_ex_idx, state))
 		goto err_ex_data;
 	return 1;
 err_ex_data:
-	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_COMP,ctx,&ctx->ex_data);
+	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_COMP, ctx, &ctx->ex_data);
 err:
-	if (state){
+	if(state) {
 		/* ctx->ex_data freed from outside */
-		if (inflate_init)
+		if(inflate_init)
 			inflateEnd(&state->istream);
-		if (deflate_init)
+		if(deflate_init)
 			deflateEnd(&state->ostream);
 		OPENSSL_free(state);
 	}
@@ -197,32 +193,31 @@ err:
 
 static void zlib_stateful_finish(COMP_CTX *ctx)
 {
-	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_COMP,ctx,&ctx->ex_data);
+	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_COMP, ctx, &ctx->ex_data);
 }
 
 static int zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out,
 		unsigned int olen, unsigned char *in, unsigned int ilen)
 {
 	int err = Z_OK;
-	struct zlib_state *state =
-		(struct zlib_state *)CRYPTO_get_ex_data(&ctx->ex_data,
-				zlib_stateful_ex_idx);
+	struct zlib_state *state = (struct zlib_state *)CRYPTO_get_ex_data(
+			&ctx->ex_data, zlib_stateful_ex_idx);
 
-	if (state == NULL)
+	if(state == NULL)
 		return -1;
 
 	state->ostream.next_in = in;
 	state->ostream.avail_in = ilen;
 	state->ostream.next_out = out;
 	state->ostream.avail_out = olen;
-	if (ilen > 0)
+	if(ilen > 0)
 		err = deflate(&state->ostream, Z_SYNC_FLUSH);
-	if (err != Z_OK)
+	if(err != Z_OK)
 		return -1;
 #ifdef DEBUG_ZLIB
-	fprintf(stderr,"compress(%4d)->%4d %s\n",
-			ilen,olen - state->ostream.avail_out,
-			(ilen != olen - state->ostream.avail_out)?"zlib":"clear");
+	fprintf(stderr, "compress(%4d)->%4d %s\n", ilen,
+			olen - state->ostream.avail_out,
+			(ilen != olen - state->ostream.avail_out) ? "zlib" : "clear");
 #endif
 	return olen - state->ostream.avail_out;
 }
@@ -232,25 +227,24 @@ static int zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out,
 {
 	int err = Z_OK;
 
-	struct zlib_state *state =
-		(struct zlib_state *)CRYPTO_get_ex_data(&ctx->ex_data,
-				zlib_stateful_ex_idx);
+	struct zlib_state *state = (struct zlib_state *)CRYPTO_get_ex_data(
+			&ctx->ex_data, zlib_stateful_ex_idx);
 
-	if (state == NULL)
+	if(state == NULL)
 		return 0;
 
 	state->istream.next_in = in;
 	state->istream.avail_in = ilen;
 	state->istream.next_out = out;
 	state->istream.avail_out = olen;
-	if (ilen > 0)
+	if(ilen > 0)
 		err = inflate(&state->istream, Z_SYNC_FLUSH);
-	if (err != Z_OK)
+	if(err != Z_OK)
 		return -1;
 #ifdef DEBUG_ZLIB
-	fprintf(stderr,"expand(%4d)->%4d %s\n",
-			ilen,olen - state->istream.avail_out,
-			(ilen != olen - state->istream.avail_out)?"zlib":"clear");
+	fprintf(stderr, "expand(%4d)->%4d %s\n", ilen,
+			olen - state->istream.avail_out,
+			(ilen != olen - state->istream.avail_out) ? "zlib" : "clear");
 #endif
 	return olen - state->istream.avail_out;
 }

+ 112 - 115
src/modules/tls/sbufq.h

@@ -33,18 +33,20 @@
 #include <string.h>
 
 
-struct sbuf_elem {
-	struct sbuf_elem* next;
+struct sbuf_elem
+{
+	struct sbuf_elem *next;
 	unsigned int b_size; /**< buf size */
-	char buf[1]; /**< variable size buffer */
+	char buf[1];		 /**< variable size buffer */
 };
 
-struct sbuffer_queue {
-	struct sbuf_elem* first;
-	struct sbuf_elem* last;
-	ticks_t last_chg; /**< last change (creation time or partial flush)*/
-	unsigned int queued; /**< total size */
-	unsigned int offset; /**< offset in the first buffer where unflushed data
+struct sbuffer_queue
+{
+	struct sbuf_elem *first;
+	struct sbuf_elem *last;
+	ticks_t last_chg;		/**< last change (creation time or partial flush)*/
+	unsigned int queued;	/**< total size */
+	unsigned int offset;	/**< offset in the first buffer where unflushed data
 							starts */
 	unsigned int last_used; /**< how much of the last buffer is used */
 };
@@ -55,9 +57,8 @@ struct sbuffer_queue {
 #define F_BUFQ_ERROR_FLUSH 2
 
 
-#define sbufq_empty(bq) ((bq)->first==0)
-#define sbufq_non_empty(bq) ((bq)->first!=0)
-
+#define sbufq_empty(bq) ((bq)->first == 0)
+#define sbufq_non_empty(bq) ((bq)->first != 0)
 
 
 /** adds/appends data to a buffer queue.
@@ -69,54 +70,54 @@ struct sbuffer_queue {
  * @param min_buf_size - min size to allocate for new buffer elements
  * @return 0 on success, -1 on error (mem. allocation)
  */
-inline static int sbufq_add(struct sbuffer_queue* q, const void* data,
-							unsigned int size, unsigned int min_buf_size)
+inline static int sbufq_add(struct sbuffer_queue *q, const void *data,
+		unsigned int size, unsigned int min_buf_size)
 {
-	struct sbuf_elem* b;
+	struct sbuf_elem *b;
 	unsigned int last_free;
 	unsigned int b_size;
 	unsigned int crt_size;
 
-	if (likely(q->last==0)) {
-		b_size=MAX_unsigned(min_buf_size, size);
-		b=shm_malloc(sizeof(*b)+b_size-sizeof(b->buf));
-		if (unlikely(b==0))
+	if(likely(q->last == 0)) {
+		b_size = MAX_unsigned(min_buf_size, size);
+		b = shm_malloc(sizeof(*b) + b_size - sizeof(b->buf));
+		if(unlikely(b == 0))
 			goto error;
-		b->b_size=b_size;
-		b->next=0;
-		q->last=b;
-		q->first=b;
-		q->last_used=0;
-		q->offset=0;
-		q->last_chg=get_ticks_raw();
-		last_free=b_size;
-		crt_size=size;
+		b->b_size = b_size;
+		b->next = 0;
+		q->last = b;
+		q->first = b;
+		q->last_used = 0;
+		q->offset = 0;
+		q->last_chg = get_ticks_raw();
+		last_free = b_size;
+		crt_size = size;
 		goto data_cpy;
-	}else{
-		b=q->last;
+	} else {
+		b = q->last;
 	}
 
-	while(size){
-		last_free=b->b_size-q->last_used;
-		if (last_free==0){
-			b_size=MAX_unsigned(min_buf_size, size);
-			b=shm_malloc(sizeof(*b)+b_size-sizeof(b->buf));
-			if (unlikely(b==0))
+	while(size) {
+		last_free = b->b_size - q->last_used;
+		if(last_free == 0) {
+			b_size = MAX_unsigned(min_buf_size, size);
+			b = shm_malloc(sizeof(*b) + b_size - sizeof(b->buf));
+			if(unlikely(b == 0))
 				goto error;
-			b->b_size=b_size;
-			b->next=0;
-			q->last->next=b;
-			q->last=b;
-			q->last_used=0;
-			last_free=b->b_size;
+			b->b_size = b_size;
+			b->next = 0;
+			q->last->next = b;
+			q->last = b;
+			q->last_used = 0;
+			last_free = b->b_size;
 		}
-		crt_size=MIN_unsigned(last_free, size);
-data_cpy:
-		memcpy(b->buf+q->last_used, data, crt_size);
-		q->last_used+=crt_size;
-		size-=crt_size;
-		data+=crt_size;
-		q->queued+=crt_size;
+		crt_size = MIN_unsigned(last_free, size);
+	data_cpy:
+		memcpy(b->buf + q->last_used, data, crt_size);
+		q->last_used += crt_size;
+		size -= crt_size;
+		data += crt_size;
+		q->queued += crt_size;
 	}
 	return 0;
 error:
@@ -124,7 +125,6 @@ error:
 }
 
 
-
 /** inserts data (at the beginning) in a buffer queue.
  * Note: should never be called after sbufq_run().
  * WARNING: it does no attempt to synchronize access/lock. If needed it should
@@ -135,37 +135,39 @@ error:
  * @param min_buf_size - min size to allocate for new buffer elements
  * @return 0 on success, -1 on error (mem. allocation)
  */
-inline static int sbufq_insert(struct sbuffer_queue* q, const void* data,
-							unsigned int size, unsigned int min_buf_size)
+inline static int sbufq_insert(struct sbuffer_queue *q, const void *data,
+		unsigned int size, unsigned int min_buf_size)
 {
-	struct sbuf_elem* b;
+	struct sbuf_elem *b;
 
-	if (likely(q->first==0)) /* if empty, use sbufq_add */
+	if(likely(q->first == 0)) /* if empty, use sbufq_add */
 		return sbufq_add(q, data, size, min_buf_size);
 
-	if (unlikely(q->offset)){
-		LOG(L_CRIT, "BUG: non-null offset %d (bad call, should"
-				"never be called after sbufq_run())\n", q->offset);
+	if(unlikely(q->offset)) {
+		LOG(L_CRIT,
+				"BUG: non-null offset %d (bad call, should"
+				"never be called after sbufq_run())\n",
+				q->offset);
 		goto error;
 	}
-	if ((q->first==q->last) && ((q->last->b_size-q->last_used)>=size)){
+	if((q->first == q->last) && ((q->last->b_size - q->last_used) >= size)) {
 		/* one block with enough space in it for size bytes */
-		memmove(q->first->buf+size, q->first->buf, size);
+		memmove(q->first->buf + size, q->first->buf, size);
 		memcpy(q->first->buf, data, size);
-		q->last_used+=size;
-	}else{
+		q->last_used += size;
+	} else {
 		/* create a size bytes block directly */
-		b=shm_malloc(sizeof(*b)+size-sizeof(b->buf));
-		if (unlikely(b==0))
+		b = shm_malloc(sizeof(*b) + size - sizeof(b->buf));
+		if(unlikely(b == 0))
 			goto error;
-		b->b_size=size;
+		b->b_size = size;
 		/* insert it */
-		b->next=q->first;
-		q->first=b;
+		b->next = q->first;
+		q->first = b;
 		memcpy(b->buf, data, size);
 	}
 
-	q->queued+=size;
+	q->queued += size;
 	return 0;
 error:
 	return -1;
@@ -180,30 +182,29 @@ error:
  * @param q - buffer queue
  * @return - number of bytes that used to be queued (>=0).
  */
-inline static unsigned int sbufq_destroy(struct  sbuffer_queue* q)
+inline static unsigned int sbufq_destroy(struct sbuffer_queue *q)
 {
-	struct sbuf_elem* b;
-	struct sbuf_elem* next_b;
+	struct sbuf_elem *b;
+	struct sbuf_elem *next_b;
 	int unqueued;
 
-	unqueued=0;
-	if (likely(q->first)){
-		b=q->first;
-		do{
-			next_b=b->next;
-			unqueued+=(b==q->last)?q->last_used:b->b_size;
-			if (b==q->first)
-				unqueued-=q->offset;
+	unqueued = 0;
+	if(likely(q->first)) {
+		b = q->first;
+		do {
+			next_b = b->next;
+			unqueued += (b == q->last) ? q->last_used : b->b_size;
+			if(b == q->first)
+				unqueued -= q->offset;
 			shm_free(b);
-			b=next_b;
-		}while(b);
+			b = next_b;
+		} while(b);
 	}
 	memset(q, 0, sizeof(*q));
 	return unqueued;
 }
 
 
-
 /** tries to flush the queue.
  * Tries to flush as much as possible from the given queue, using the
  * given callback.
@@ -227,57 +228,53 @@ inline static unsigned int sbufq_destroy(struct  sbuffer_queue* q)
  *            always set and it should be used to check for errors, since
  *            a flush_f() failure will not result in a negative return.
  */
-inline static int sbufq_flush(struct sbuffer_queue* q, int* flags,
-								int (*flush_f)(void* p1, void* p2,
-												const void* buf,
-												unsigned size),
-								void* flush_p1, void* flush_p2)
+inline static int sbufq_flush(struct sbuffer_queue *q, int *flags,
+		int (*flush_f)(void *p1, void *p2, const void *buf, unsigned size),
+		void *flush_p1, void *flush_p2)
 {
 	struct sbuf_elem *b;
 	int n;
 	int ret;
 	int block_size;
-	char* buf;
-
-	*flags=0;
-	ret=0;
-	while(q->first){
-		block_size=((q->first==q->last)?q->last_used:q->first->b_size)-
-						q->offset;
-		buf=q->first->buf+q->offset;
-		n=flush_f(flush_p1, flush_p2, buf, block_size);
-		if (likely(n>0)){
-			ret+=n;
-			if (likely(n==block_size)){
-				b=q->first;
-				q->first=q->first->next;
+	char *buf;
+
+	*flags = 0;
+	ret = 0;
+	while(q->first) {
+		block_size = ((q->first == q->last) ? q->last_used : q->first->b_size)
+					 - q->offset;
+		buf = q->first->buf + q->offset;
+		n = flush_f(flush_p1, flush_p2, buf, block_size);
+		if(likely(n > 0)) {
+			ret += n;
+			if(likely(n == block_size)) {
+				b = q->first;
+				q->first = q->first->next;
 				shm_free(b);
-				q->offset=0;
-				q->queued-=block_size;
-			}else{
-				q->offset+=n;
-				q->queued-=n;
+				q->offset = 0;
+				q->queued -= block_size;
+			} else {
+				q->offset += n;
+				q->queued -= n;
 				/* no break: if we are here n < block_size => partial write
 				   => the write should be retried */
 			}
-		}else{
-			if (unlikely(n<0))
-				*flags|=F_BUFQ_ERROR_FLUSH;
+		} else {
+			if(unlikely(n < 0))
+				*flags |= F_BUFQ_ERROR_FLUSH;
 			break;
 		}
 	}
-	if (likely(q->first==0)){
-		q->last=0;
-		q->last_used=0;
-		q->offset=0;
-		*flags|=F_BUFQ_EMPTY;
+	if(likely(q->first == 0)) {
+		q->last = 0;
+		q->last_used = 0;
+		q->offset = 0;
+		*flags |= F_BUFQ_EMPTY;
 	}
 	return ret;
 }
 
 
-
-
 #endif /*__sbufq_h*/
 
 /* vi: set ts=4 sw=4 tw=79:ai:cindent: */

+ 80 - 86
src/modules/tls/tls_bio.c

@@ -30,61 +30,61 @@
 
 /* 0xf2 should be unused (as of openssl 1.0.0 max.
    internal defined BIO is 23) */
-#define BIO_TYPE_TLS_MBUF	(BIO_TYPE_SOURCE_SINK | 0xf2)
+#define BIO_TYPE_TLS_MBUF (BIO_TYPE_SOURCE_SINK | 0xf2)
 
 /* debugging */
 #ifdef NO_TLS_BIO_DEBUG
 #undef TLS_BIO_DEBUG
 #endif
 #ifdef TLS_BIO_DEBUG
-	#ifdef __SUNPRO_C
-		#define TLS_BIO_DBG(...) \
-			LOG_FP(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug),\
-					"tls_BIO: " LOC_INFO,  __VA_ARGS__)
-	#else
-		#define TLS_BIO_DBG(args...) \
-			LOG_FP(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug),\
-					"tls_BIO: " LOC_INFO, ## args)
-	#endif /* __SUNPRO_c */
-#else /* TLS_BIO_DEBUG */
-	#ifdef __SUNPRO_C
-		#define TLS_BIO_DBG(...)
-	#else
-		#define TLS_BIO_DBG(fmt, args...)
-	#endif /* __SUNPRO_c */
+#ifdef __SUNPRO_C
+#define TLS_BIO_DBG(...)                                   \
+	LOG_FP(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug), \
+			"tls_BIO: " LOC_INFO, __VA_ARGS__)
+#else
+#define TLS_BIO_DBG(args...)                               \
+	LOG_FP(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug), \
+			"tls_BIO: " LOC_INFO, ##args)
+#endif /* __SUNPRO_c */
+#else  /* TLS_BIO_DEBUG */
+#ifdef __SUNPRO_C
+#define TLS_BIO_DBG(...)
+#else
+#define TLS_BIO_DBG(fmt, args...)
+#endif /* __SUNPRO_c */
 #endif /* TLS_BIO_DEBUG */
 
 
-static int tls_bio_mbuf_new(BIO* b);
-static int tls_bio_mbuf_free(BIO* b);
-static int tls_bio_mbuf_write(BIO* b, const char* buf, int num);
-static int tls_bio_mbuf_read(BIO* b, char* buf, int num);
-static int tls_bio_mbuf_puts(BIO* b, const char* s);
-static long tls_bio_mbuf_ctrl(BIO* b, int cmd, long arg1, void* arg2);
+static int tls_bio_mbuf_new(BIO *b);
+static int tls_bio_mbuf_free(BIO *b);
+static int tls_bio_mbuf_write(BIO *b, const char *buf, int num);
+static int tls_bio_mbuf_read(BIO *b, char *buf, int num);
+static int tls_bio_mbuf_puts(BIO *b, const char *s);
+static long tls_bio_mbuf_ctrl(BIO *b, int cmd, long arg1, void *arg2);
 
 
 #if OPENSSL_VERSION_NUMBER < 0x010100000L || defined(LIBRESSL_VERSION_NUMBER)
 static BIO_METHOD tls_mbuf_method = {
-	BIO_TYPE_TLS_MBUF,	/* type */
-	"sr_tls_mbuf",		/* name */
-	tls_bio_mbuf_write,	/* write function */
-	tls_bio_mbuf_read,	/* read function */
-	tls_bio_mbuf_puts,	/* puts function */
-	0,					/* gets function */
-	tls_bio_mbuf_ctrl,	/* ctrl function */
-	tls_bio_mbuf_new,	/* create(new) function */
-	tls_bio_mbuf_free,	/* destroy(free) function */
-	0					/* ctrl callback */
+		BIO_TYPE_TLS_MBUF,	/* type */
+		"sr_tls_mbuf",		/* name */
+		tls_bio_mbuf_write, /* write function */
+		tls_bio_mbuf_read,	/* read function */
+		tls_bio_mbuf_puts,	/* puts function */
+		0,					/* gets function */
+		tls_bio_mbuf_ctrl,	/* ctrl function */
+		tls_bio_mbuf_new,	/* create(new) function */
+		tls_bio_mbuf_free,	/* destroy(free) function */
+		0					/* ctrl callback */
 };
 
 static void *CRYPTO_zalloc(size_t num, const char *file, int line)
 {
 	void *ret = CRYPTO_malloc(num, file, line);
-	if (ret != NULL)
+	if(ret != NULL)
 		memset(ret, 0, num);
 	return ret;
 }
-# define OPENSSL_zalloc(num) CRYPTO_zalloc(num, __FILE__, __LINE__)
+#define OPENSSL_zalloc(num) CRYPTO_zalloc(num, __FILE__, __LINE__)
 
 #if LIBRESSL_VERSION_NUMBER < 0x20700000L
 static void *BIO_get_data(BIO *b)
@@ -107,7 +107,7 @@ static BIO_METHOD *tls_mbuf_method = NULL;
 
 
 /** returns a custom tls_mbuf BIO. */
-BIO_METHOD* tls_BIO_mbuf(void)
+BIO_METHOD *tls_BIO_mbuf(void)
 {
 #if OPENSSL_VERSION_NUMBER < 0x010100000L || defined(LIBRESSL_VERSION_NUMBER)
 	return &tls_mbuf_method;
@@ -116,7 +116,7 @@ BIO_METHOD* tls_BIO_mbuf(void)
 		return tls_mbuf_method;
 	}
 	tls_mbuf_method = BIO_meth_new(BIO_TYPE_TLS_MBUF, "sr_tls_mbuf");
-	if(tls_mbuf_method==NULL) {
+	if(tls_mbuf_method == NULL) {
 		LM_ERR("cannot get a new bio method structure\n");
 		return NULL;
 	}
@@ -133,19 +133,18 @@ BIO_METHOD* tls_BIO_mbuf(void)
 }
 
 
-
 /** create an initialize a new tls_BIO_mbuf.
  * @return new BIO on success (!=0), 0 on error.
  */
-BIO* tls_BIO_new_mbuf(struct tls_mbuf* rd, struct tls_mbuf* wr)
+BIO *tls_BIO_new_mbuf(struct tls_mbuf *rd, struct tls_mbuf *wr)
 {
-	BIO* ret;
+	BIO *ret;
 
 	TLS_BIO_DBG("tls_BIO_new_mbuf called (%p, %p)\n", rd, wr);
 	ret = BIO_new(tls_BIO_mbuf());
-	if (unlikely(ret == 0))
+	if(unlikely(ret == 0))
 		return 0;
-	if (unlikely(tls_BIO_mbuf_set(ret, rd, wr) == 0)) {
+	if(unlikely(tls_BIO_mbuf_set(ret, rd, wr) == 0)) {
 		BIO_free(ret);
 		return 0;
 	}
@@ -153,17 +152,16 @@ BIO* tls_BIO_new_mbuf(struct tls_mbuf* rd, struct tls_mbuf* wr)
 }
 
 
-
 /** sets the read and write mbuf for an  mbuf BIO.
  * @return 1 on success, 0 on error (openssl BIO convention).
  */
-int tls_BIO_mbuf_set(BIO* b, struct tls_mbuf* rd, struct tls_mbuf* wr)
+int tls_BIO_mbuf_set(BIO *b, struct tls_mbuf *rd, struct tls_mbuf *wr)
 {
-	struct tls_bio_mbuf_data* d;
+	struct tls_bio_mbuf_data *d;
 
 	TLS_BIO_DBG("tls_BIO_mbuf_set called (%p => %p, %p)\n", b, rd, wr);
 	d = BIO_get_data(b);
-	if (unlikely(d == 0)){
+	if(unlikely(d == 0)) {
 		BUG("null BIO ptr data\n");
 		return 0;
 	}
@@ -174,40 +172,38 @@ int tls_BIO_mbuf_set(BIO* b, struct tls_mbuf* rd, struct tls_mbuf* wr)
 }
 
 
-
 /** create a new BIO.
  * (internal openssl use via the tls_mbuf method)
  * @return 1 on success, 0 on error.
  */
-static int tls_bio_mbuf_new(BIO* b)
+static int tls_bio_mbuf_new(BIO *b)
 {
-	struct tls_bio_mbuf_data* d;
+	struct tls_bio_mbuf_data *d;
 
 	TLS_BIO_DBG("tls_bio_mbuf_new called (%p)\n", b);
 	BIO_set_init(b, 0);
 	BIO_set_data(b, NULL);
 	d = OPENSSL_zalloc(sizeof(*d));
-	if (unlikely(d == 0))
+	if(unlikely(d == 0))
 		return 0;
 	BIO_set_data(b, d);
 	return 1;
 }
 
 
-
 /** destroy a tls mbuf BIO.
  * (internal openssl use via the tls_mbuf method)
  * @return 1 on success, 0 on error.
  */
-static int tls_bio_mbuf_free(BIO* b)
+static int tls_bio_mbuf_free(BIO *b)
 {
 	TLS_BIO_DBG("tls_bio_mbuf_free called (%p)\n", b);
-	if (unlikely( b == 0))
-			return 0;
+	if(unlikely(b == 0))
+		return 0;
 	do {
-		struct tls_bio_mbuf_data* d;
+		struct tls_bio_mbuf_data *d;
 		d = BIO_get_data(b);
-		if (likely(d)) {
+		if(likely(d)) {
 			OPENSSL_free(d);
 			BIO_set_data(b, NULL);
 			BIO_set_init(b, 0);
@@ -217,52 +213,51 @@ static int tls_bio_mbuf_free(BIO* b)
 }
 
 
-
 /** read from a mbuf.
  * (internal openssl use via the tls_mbuf method)
  * @return bytes read on success (0< ret <=dst_len), -1 on empty buffer & sets
  *  should_retry_read, -1 on some other errors (w/o should_retry_read set).
  */
-static int tls_bio_mbuf_read(BIO* b, char* dst, int dst_len)
+static int tls_bio_mbuf_read(BIO *b, char *dst, int dst_len)
 {
-	struct tls_bio_mbuf_data* d;
-	struct tls_mbuf* rd;
+	struct tls_bio_mbuf_data *d;
+	struct tls_mbuf *rd;
 	int ret;
 
 	ret = 0;
-	if (likely(dst)) {
+	if(likely(dst)) {
 		d = BIO_get_data(b);
 		BIO_clear_retry_flags(b);
-		if (unlikely(d == 0 || d->rd->buf == 0)) {
-			if (d == 0)
+		if(unlikely(d == 0 || d->rd->buf == 0)) {
+			if(d == 0)
 				BUG("tls_BIO_mbuf %p: read called with null b->ptr\n", b);
 			else {
 				/* this form of calling read with a null buffer is used
 				   as a shortcut when no data is available =>
 				   simulate EAGIAN/WANT_READ */
 				TLS_BIO_DBG("read (%p, %p, %d) called with null read buffer"
-						"(%p->%p) => simulating EAGAIN/WANT_READ\n",
+							"(%p->%p) => simulating EAGAIN/WANT_READ\n",
 						b, dst, dst_len, d, d->rd);
 				BIO_set_retry_read(b);
 			}
 			return -1;
 		}
 		rd = d->rd;
-		if (unlikely(rd->used == rd->pos && dst_len)) {
+		if(unlikely(rd->used == rd->pos && dst_len)) {
 			/* mimic non-blocking read behaviour */
 			TLS_BIO_DBG("read (%p, %p, %d) called with full rd (%d)"
 						" => simulating EAGAIN/WANT_READ\n",
-						b, dst, dst_len, rd->used);
+					b, dst, dst_len, rd->used);
 			BIO_set_retry_read(b);
 			return -1;
 		}
 		ret = MIN_int(rd->used - rd->pos, dst_len);
 		/* copy data from rd.buf into dst */
-		memcpy(dst, rd->buf+rd->pos, ret);
+		memcpy(dst, rd->buf + rd->pos, ret);
 		TLS_BIO_DBG("read(%p, %p, %d) called with rd=%p pos=%d => %d bytes\n",
-						b, dst, dst_len, rd->buf, rd->pos, ret);
+				b, dst, dst_len, rd->buf, rd->pos, ret);
 		rd->pos += ret;
-/*		if (unlikely(rd->pos < rd->used))
+		/*		if (unlikely(rd->pos < rd->used))
 			BIO_set_retry_read(b);
 */
 	}
@@ -270,46 +265,47 @@ static int tls_bio_mbuf_read(BIO* b, char* dst, int dst_len)
 }
 
 
-
 /** write to a mbuf.
  * (internal openssl use via the tls_mbuf method)
  * @return bytes written on success (0<= ret <=src_len), -1 on error or buffer
  * full (in this case sets should_retry_write).
  */
-static int tls_bio_mbuf_write(BIO* b, const char* src, int src_len)
+static int tls_bio_mbuf_write(BIO *b, const char *src, int src_len)
 {
-	struct tls_bio_mbuf_data* d;
-	struct tls_mbuf* wr;
+	struct tls_bio_mbuf_data *d;
+	struct tls_mbuf *wr;
 	int ret;
 
 	ret = 0;
 	d = BIO_get_data(b);
 	BIO_clear_retry_flags(b);
-	if (unlikely(d == 0 || d->wr->buf == 0)) {
-		if (d == 0)
+	if(unlikely(d == 0 || d->wr->buf == 0)) {
+		if(d == 0)
 			BUG("tls_BIO_mbuf %p: write called with null b->ptr\n", b);
 		else {
 			/* this form of calling write with a null buffer is used
 			   as a shortcut when no data is available =>
 			   simulate EAGAIN/WANT_WRITE */
 			TLS_BIO_DBG("write (%p, %p, %d) called with null buffer"
-					" => simulating WANT_WRITE\n", b, src, src_len);
+						" => simulating WANT_WRITE\n",
+					b, src, src_len);
 			BIO_set_retry_write(b);
 		}
 		return -1;
 	}
 	wr = d->wr;
-	if (unlikely(wr->size == wr->used && src_len)) {
+	if(unlikely(wr->size == wr->used && src_len)) {
 		/* mimic non-blocking socket behaviour */
 		TLS_BIO_DBG("write (%p, %p, %d) called with full wr buffer (%d)"
-					" => simulating WANT_WRITE\n", b, src, src_len, wr->used);
+					" => simulating WANT_WRITE\n",
+				b, src, src_len, wr->used);
 		BIO_set_retry_write(b);
 		return -1;
 	}
 	ret = MIN_int(wr->size - wr->used, src_len);
 	memcpy(wr->buf + wr->used, src, ret);
 	wr->used += ret;
-/*	if (unlikely(ret < src_len))
+	/*	if (unlikely(ret < src_len))
 		BIO_set_retry_write();
 */
 	TLS_BIO_DBG("write called (%p, %p, %d) => %d\n", b, src, src_len, ret);
@@ -317,11 +313,10 @@ static int tls_bio_mbuf_write(BIO* b, const char* src, int src_len)
 }
 
 
-
-static long tls_bio_mbuf_ctrl(BIO* b, int cmd, long arg1, void* arg2)
+static long tls_bio_mbuf_ctrl(BIO *b, int cmd, long arg1, void *arg2)
 {
 	long ret;
-	ret=0;
+	ret = 0;
 	switch(cmd) {
 		case BIO_C_SET_FD:
 		case BIO_C_GET_FD:
@@ -345,19 +340,18 @@ static long tls_bio_mbuf_ctrl(BIO* b, int cmd, long arg1, void* arg2)
 			ret = 0;
 			break;
 	}
-	TLS_BIO_DBG("ctrl called (%p, %d, %ld, %p) => %ld\n",
-				b, cmd, arg1, arg2, ret);
+	TLS_BIO_DBG(
+			"ctrl called (%p, %d, %ld, %p) => %ld\n", b, cmd, arg1, arg2, ret);
 	return ret;
 }
 
 
-
-static int tls_bio_mbuf_puts(BIO* b, const char* s)
+static int tls_bio_mbuf_puts(BIO *b, const char *s)
 {
 	int len;
 
 	TLS_BIO_DBG("puts called (%p, %s)\n", b, s);
-	len=strlen(s);
+	len = strlen(s);
 	return tls_bio_mbuf_write(b, s, len);
 }
 

+ 15 - 15
src/modules/tls/tls_bio.h

@@ -27,23 +27,24 @@
 #include <openssl/bio.h>
 
 /* memory buffer used for tls I/O */
-struct tls_mbuf {
-	unsigned char* buf;
+struct tls_mbuf
+{
+	unsigned char *buf;
 	int pos;  /**< current position in the buffer while reading or writing*/
 	int used; /**< how much it's used  (read or write)*/
 	int size; /**< total buffer size (fixed) */
 };
 
-struct tls_bio_mbuf_data {
-	struct tls_mbuf* rd;
-	struct tls_mbuf* wr;
+struct tls_bio_mbuf_data
+{
+	struct tls_mbuf *rd;
+	struct tls_mbuf *wr;
 };
 
 
-BIO_METHOD* tls_BIO_mbuf(void);
-BIO* tls_BIO_new_mbuf(struct tls_mbuf* rd, struct tls_mbuf* wr);
-int tls_BIO_mbuf_set(BIO* b, struct tls_mbuf* rd, struct tls_mbuf* wr);
-
+BIO_METHOD *tls_BIO_mbuf(void);
+BIO *tls_BIO_new_mbuf(struct tls_mbuf *rd, struct tls_mbuf *wr);
+int tls_BIO_mbuf_set(BIO *b, struct tls_mbuf *rd, struct tls_mbuf *wr);
 
 
 /** initialize an mbuf structure.
@@ -53,15 +54,14 @@ int tls_BIO_mbuf_set(BIO* b, struct tls_mbuf* rd, struct tls_mbuf* wr);
  * WARNING: the buffer will not be copied, but referenced.
  */
 #define tls_mbuf_init(mb, b, sz) \
-	do { \
-		(mb)->buf = (b); \
-		(mb)->size = (sz); \
-		(mb)->pos = 0; \
-		(mb)->used = 0; \
+	do {                         \
+		(mb)->buf = (b);         \
+		(mb)->size = (sz);       \
+		(mb)->pos = 0;           \
+		(mb)->used = 0;          \
 	} while(0)
 
 
-
 #endif /*__tls_bio_h*/
 
 /* vi: set ts=4 sw=4 tw=79:ai:cindent: */

+ 171 - 164
src/modules/tls/tls_cfg.c

@@ -33,80 +33,80 @@
 #include "../../core/dprint.h"
 
 struct cfg_group_tls default_tls_cfg = {
-	0, /* tls_force_run */
-	STR_STATIC_INIT("TLSv1"), /* method */
-	STR_NULL, /* server name (sni) */
-	0, /* server name (sni) mode */
-	STR_NULL, /* server id */
-	0, /* verify_certificate */
-	9, /* verify_depth */
-	0, /* require_certificate */
-	STR_STATIC_INIT("off"), /* verify_client */
-	STR_NULL, /* private_key (default value set in fix_tls_cfg) */
-	STR_NULL, /* ca_list (default value set in fix_tls_cfg) */
-	STR_NULL, /* ca_path (default value set in fix_tls_cfg) */
-	STR_NULL, /* crl (default value set in fix_tls_cfg) */
-	STR_NULL, /* certificate (default value set in fix_tls_cfg) */
-	STR_NULL, /* cipher_list (default value set in fix_tls_cfg) */
-	0, /* session_cache */
-	STR_STATIC_INIT("kamailio-tls-5.x.y"), /* session_id */
-	STR_NULL, /* config_file */
-	3, /* log  (L_DBG)*/
-	3, /* debug (L_DBG) */
-	600, /* con_lifetime (s)*/
-	1, /* disable_compression */
+		0,						  /* tls_force_run */
+		STR_STATIC_INIT("TLSv1"), /* method */
+		STR_NULL,				  /* server name (sni) */
+		0,						  /* server name (sni) mode */
+		STR_NULL,				  /* server id */
+		0,						  /* verify_certificate */
+		9,						  /* verify_depth */
+		0,						  /* require_certificate */
+		STR_STATIC_INIT("off"),	  /* verify_client */
+		STR_NULL, /* private_key (default value set in fix_tls_cfg) */
+		STR_NULL, /* ca_list (default value set in fix_tls_cfg) */
+		STR_NULL, /* ca_path (default value set in fix_tls_cfg) */
+		STR_NULL, /* crl (default value set in fix_tls_cfg) */
+		STR_NULL, /* certificate (default value set in fix_tls_cfg) */
+		STR_NULL, /* cipher_list (default value set in fix_tls_cfg) */
+		0,		  /* session_cache */
+		STR_STATIC_INIT("kamailio-tls-5.x.y"), /* session_id */
+		STR_NULL,							   /* config_file */
+		3,									   /* log  (L_DBG)*/
+		3,									   /* debug (L_DBG) */
+		600,								   /* con_lifetime (s)*/
+		1,									   /* disable_compression */
 #if OPENSSL_VERSION_NUMBER >= 0x01000000L
-	1, /* ssl_release_buffers (on, avoid extra buffering) */
+		1, /* ssl_release_buffers (on, avoid extra buffering) */
 #else
-	-1, /* ssl_release_buffers: old openssl, leave it untouched */
+		-1, /* ssl_release_buffers: old openssl, leave it untouched */
 #endif /* openssl >= 1.0.0 */
-#if OPENSSL_VERSION_NUMBER >= 0x01000000L && ! defined OPENSSL_NO_BUF_FREELISTS
-	0, /* ssl_freelist_max  (immediately free) */
+#if OPENSSL_VERSION_NUMBER >= 0x01000000L && !defined OPENSSL_NO_BUF_FREELISTS
+		0, /* ssl_freelist_max  (immediately free) */
 #else
-	-1, /* ssl_freelist_max: old openssl, leave it untouched */
-#endif /* openssl >= 1.0.0 */
-	-1, /* ssl_max_send_fragment (use the default: 16k), requires openssl
+		-1, /* ssl_freelist_max: old openssl, leave it untouched */
+#endif		/* openssl >= 1.0.0 */
+		-1, /* ssl_max_send_fragment (use the default: 16k), requires openssl
 		   > 0.9.9 */
-	0, /* ssl_read_ahead (off, not needed, we have our own buffering BIO)*/
-	-1, /* low_mem_threshold1 */
-	-1, /* low_mem_threshold2 */
-	10*1024*1024, /* ct_wq_max: 10 Mb by default */
-	64*1024, /* con_ct_wq_max: 64Kb by default */
-	4096, /* ct_wq_blk_size */
-	0 /* send_close_notify (off by default)*/
+		0,	/* ssl_read_ahead (off, not needed, we have our own buffering BIO)*/
+		-1, /* low_mem_threshold1 */
+		-1, /* low_mem_threshold2 */
+		10 * 1024 * 1024, /* ct_wq_max: 10 Mb by default */
+		64 * 1024,		  /* con_ct_wq_max: 64Kb by default */
+		4096,			  /* ct_wq_blk_size */
+		0				  /* send_close_notify (off by default)*/
 };
 
-volatile void* tls_cfg = &default_tls_cfg;
+volatile void *tls_cfg = &default_tls_cfg;
 
 
 /* if *to<0 to=default_val, else if to>max_val to=max_val */
-static void fix_timeout(char* name, int* to, int default_val, unsigned max_val)
+static void fix_timeout(char *name, int *to, int default_val, unsigned max_val)
 {
-	if (*to < 0) *to=default_val;
-	else if ((unsigned)*to > max_val){
-		WARN("%s: timeout too big (%u), the maximum value is %u\n",
-				name, *to, max_val);
-		*to=max_val;
+	if(*to < 0)
+		*to = default_val;
+	else if((unsigned)*to > max_val) {
+		WARN("%s: timeout too big (%u), the maximum value is %u\n", name, *to,
+				max_val);
+		*to = max_val;
 	}
 }
 
 
-static int fix_con_lt(void* cfg_h, str* gname, str* name, void** val)
+static int fix_con_lt(void *cfg_h, str *gname, str *name, void **val)
 {
 	int v;
-	v=S_TO_TICKS((int)(long)*val);
-	fix_timeout("tls.connection_timeout", &v,
-					MAX_TLS_CON_LIFETIME, MAX_TLS_CON_LIFETIME);
-	*val=(void*)(long)v;
+	v = S_TO_TICKS((int)(long)*val);
+	fix_timeout("tls.connection_timeout", &v, MAX_TLS_CON_LIFETIME,
+			MAX_TLS_CON_LIFETIME);
+	*val = (void *)(long)v;
 	return 0;
 }
 
 
-
 /** cfg framework callback for fixing pathnames. */
-static int fix_rel_pathname(void* cfg_h, str* gname, str* name, void** val)
+static int fix_rel_pathname(void *cfg_h, str *gname, str *name, void **val)
 {
-	str* f;
+	str *f;
 	str new_f;
 	/* the cfg framework will immediately "clone" the value so
 	   we can pass a pointer to a temporary static buffer to it
@@ -117,15 +117,15 @@ static int fix_rel_pathname(void* cfg_h, str* gname, str* name, void** val)
 	f = *val;
 	/* use absolute paths, except when the path starts with
 	   '.' (in this case leave it as it is) */
-	if (f && f->s && f->len && *f->s != '.' && *f->s != '/') {
+	if(f && f->s && f->len && *f->s != '.' && *f->s != '/') {
 		new_f.s = get_abs_pathname(0, f);
-		if (new_f.s == 0)
+		if(new_f.s == 0)
 			return -1;
 		new_f.len = strlen(new_f.s);
-		if (new_f.len >= MAX_PATH_SIZE) {
-			ERR("%.*s.%.*s path too long (%d bytes): \"%.*s\"\n",
-					gname->len, gname->s, name->len, name->s,
-					new_f.len, new_f.len, new_f.s);
+		if(new_f.len >= MAX_PATH_SIZE) {
+			ERR("%.*s.%.*s path too long (%d bytes): \"%.*s\"\n", gname->len,
+					gname->s, name->len, name->s, new_f.len, new_f.len,
+					new_f.s);
 			pkg_free(new_f.s);
 			return -1;
 		}
@@ -138,97 +138,105 @@ static int fix_rel_pathname(void* cfg_h, str* gname, str* name, void** val)
 }
 
 
-
-cfg_def_t	tls_cfg_def[] = {
-	{"force_run", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
-		"force loading the tls module even when initial sanity checks fail"},
-	{"method",   CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"TLS method used (TLSv1.3, TLSv1.2, TLSv1.1, TLSv1, SSLv3, SSLv2, SSLv23)"},
-	{"server_name",   CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"Server name (SNI)"},
-	{"server_name_mode", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
-		"Server name (SNI) mode" },
-	{"server_id",   CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"Server id (match tls profile for outgoing connections)"},
-	{"verify_certificate", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
-		"if enabled the certificates will be verified" },
-	{"verify_depth", CFG_VAR_INT | CFG_READONLY, 0, 100, 0, 0,
-		"sets how far up the certificate chain will the certificate"
-		" verification go in the search for a trusted CA" },
-	{"require_certificate", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
-		"if enabled a certificate will be required from clients" },
-	{"verify_client", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"set to off (default), on, optional, or optional_no_ca" },
-	{"private_key", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"name of the file containing the private key (pem format), if not"
-		" contained in the certificate file" },
-	{"ca_list", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"name of the file containing the trusted CA list (pem format)" },
-	{"ca_path", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"name of the directory containing the trusted CA files (pem format)" },
-	{"crl", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"name of the file containing the CRL  (certificare revocation list"
-			" in pem format)" },
-	{"certificate", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"name of the file containing the certificate (pem format)" },
-	{"cipher_list", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"list of the accepted ciphers (strings separated by colons)" },
-	{"session_cache", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
-		"enables or disables the session cache" },
-	{"session_id", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
-		"string used for the session id" },
-	{"config", CFG_VAR_STR, 0, 0, fix_rel_pathname, 0,
-		"tls config file name (used for the per domain options)" },
-	{"log", CFG_VAR_INT | CFG_ATOMIC, 0, 1000, 0, 0,
-		"tls info messages log level" },
-	{"debug", CFG_VAR_INT | CFG_ATOMIC, 0, 1000, 0, 0,
-		"tls debug messages log level" },
-	{"connection_timeout", CFG_VAR_INT | CFG_ATOMIC,
-							-1, MAX_TLS_CON_LIFETIME, fix_con_lt, 0,
-		"initial connection lifetime (in s) (obsolete)" },
-	{"disable_compression", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
-		"if set disable the built-in OpenSSL compression" },
-	{"ssl_release_buffers", CFG_VAR_INT | CFG_READONLY, -1, 1, 0, 0,
-		"quickly release internal OpenSSL read or write buffers."
-	    " Works only for OpenSSL >= 1.0."},
-	{"ssl_free_list_max", CFG_VAR_INT | CFG_READONLY, -1, 1<<30, 0, 0,
-		"maximum number of free/cached memory chunks that OpenSSL"
-		" will keep per connection. Works only for OpenSSL >= 1.0."},
-	{"ssl_max_send_fragment", CFG_VAR_INT | CFG_READONLY, -1, 65536, 0, 0,
-		"sets the maximum number of bytes (clear text) send into one TLS"
-		" record. Valid values are between 512 and 16384."
-		" Works only for OpenSSL >= 0.9.9"},
-	{"ssl_read_ahead", CFG_VAR_INT | CFG_READONLY, -1, 1, 0, 0,
-		"Enables read ahead, reducing the number of BIO read calls done"
-		" internally by the OpenSSL library. Note that in newer tls"
-	    " module versions it is better to have read ahead disabled, since"
-		" everything it is buffered in memory anyway"},
-	{"low_mem_threshold1", CFG_VAR_INT | CFG_ATOMIC, -1, 1<<30, 0, 0,
-		"sets the minimum amount of free memory for accepting new TLS"
-		" connections (KB)"},
-	{"low_mem_threshold2", CFG_VAR_INT | CFG_ATOMIC, -1, 1<<30, 0, 0,
-		"sets the minimum amount of free memory after which no more TLS"
-		" operations will be attempted (even on existing connections)" },
-	{"ct_wq_max", CFG_VAR_INT | CFG_ATOMIC, 0, 1<<30, 0, 0,
-		"maximum bytes queued globally for write when write has to wait due"
-		" to TLS-level renegotiation (SSL_ERROR_WANT_READ) or initial TLS"
-		" connection establishment (it is different from tcp.wq_max,"
-		" which works at the TCP connection level)"},
-	{"con_ct_wq_max", CFG_VAR_INT | CFG_ATOMIC, 0, 4*1024*1024, 0, 0,
-		"maximum bytes queued for write per connection when write has to wait"
-		" due to TLS-level renegotiation (SSL_ERROR_WANT_READ) or initial TLS"
-		" connection establishment (it is different from tcp.conn_wq_max,"
-		" which works at the TCP connection level)"},
-	{"ct_wq_blk_size", CFG_VAR_INT | CFG_ATOMIC, 1, 65536, 0, 0,
-		"internal TLS pre-write (clear-text) queue minimum block size"
-		" (advanced tunning or debugging for now)"},
-	{"send_close_notify", CFG_VAR_INT | CFG_ATOMIC, 0, 1, 0, 0,
-		"enable/disable sending a close notify TLS shutdown alert"
-			" before closing the corresponding TCP connection."
-			"Note that having it enabled has a performance impact."},
-	{0, 0, 0, 0, 0, 0}
-};
-
+cfg_def_t tls_cfg_def[] = {{"force_run", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
+								   "force loading the tls module even when "
+								   "initial sanity checks fail"},
+		{"method", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"TLS method used (TLSv1.3, TLSv1.2, TLSv1.1, TLSv1, SSLv3, "
+				"SSLv2, SSLv23)"},
+		{"server_name", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"Server name (SNI)"},
+		{"server_name_mode", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
+				"Server name (SNI) mode"},
+		{"server_id", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"Server id (match tls profile for outgoing connections)"},
+		{"verify_certificate", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
+				"if enabled the certificates will be verified"},
+		{"verify_depth", CFG_VAR_INT | CFG_READONLY, 0, 100, 0, 0,
+				"sets how far up the certificate chain will the certificate"
+				" verification go in the search for a trusted CA"},
+		{"require_certificate", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
+				"if enabled a certificate will be required from clients"},
+		{"verify_client", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"set to off (default), on, optional, or optional_no_ca"},
+		{"private_key", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"name of the file containing the private key (pem format), if "
+				"not"
+				" contained in the certificate file"},
+		{"ca_list", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"name of the file containing the trusted CA list (pem format)"},
+		{"ca_path", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"name of the directory containing the trusted CA files (pem "
+				"format)"},
+		{"crl", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"name of the file containing the CRL  (certificare revocation "
+				"list"
+				" in pem format)"},
+		{"certificate", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"name of the file containing the certificate (pem format)"},
+		{"cipher_list", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"list of the accepted ciphers (strings separated by colons)"},
+		{"session_cache", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
+				"enables or disables the session cache"},
+		{"session_id", CFG_VAR_STR | CFG_READONLY, 0, 0, 0, 0,
+				"string used for the session id"},
+		{"config", CFG_VAR_STR, 0, 0, fix_rel_pathname, 0,
+				"tls config file name (used for the per domain options)"},
+		{"log", CFG_VAR_INT | CFG_ATOMIC, 0, 1000, 0, 0,
+				"tls info messages log level"},
+		{"debug", CFG_VAR_INT | CFG_ATOMIC, 0, 1000, 0, 0,
+				"tls debug messages log level"},
+		{"connection_timeout", CFG_VAR_INT | CFG_ATOMIC, -1,
+				MAX_TLS_CON_LIFETIME, fix_con_lt, 0,
+				"initial connection lifetime (in s) (obsolete)"},
+		{"disable_compression", CFG_VAR_INT | CFG_READONLY, 0, 1, 0, 0,
+				"if set disable the built-in OpenSSL compression"},
+		{"ssl_release_buffers", CFG_VAR_INT | CFG_READONLY, -1, 1, 0, 0,
+				"quickly release internal OpenSSL read or write buffers."
+				" Works only for OpenSSL >= 1.0."},
+		{"ssl_free_list_max", CFG_VAR_INT | CFG_READONLY, -1, 1 << 30, 0, 0,
+				"maximum number of free/cached memory chunks that OpenSSL"
+				" will keep per connection. Works only for OpenSSL >= 1.0."},
+		{"ssl_max_send_fragment", CFG_VAR_INT | CFG_READONLY, -1, 65536, 0, 0,
+				"sets the maximum number of bytes (clear text) send into one "
+				"TLS"
+				" record. Valid values are between 512 and 16384."
+				" Works only for OpenSSL >= 0.9.9"},
+		{"ssl_read_ahead", CFG_VAR_INT | CFG_READONLY, -1, 1, 0, 0,
+				"Enables read ahead, reducing the number of BIO read calls done"
+				" internally by the OpenSSL library. Note that in newer tls"
+				" module versions it is better to have read ahead disabled, "
+				"since"
+				" everything it is buffered in memory anyway"},
+		{"low_mem_threshold1", CFG_VAR_INT | CFG_ATOMIC, -1, 1 << 30, 0, 0,
+				"sets the minimum amount of free memory for accepting new TLS"
+				" connections (KB)"},
+		{"low_mem_threshold2", CFG_VAR_INT | CFG_ATOMIC, -1, 1 << 30, 0, 0,
+				"sets the minimum amount of free memory after which no more TLS"
+				" operations will be attempted (even on existing connections)"},
+		{"ct_wq_max", CFG_VAR_INT | CFG_ATOMIC, 0, 1 << 30, 0, 0,
+				"maximum bytes queued globally for write when write has to "
+				"wait due"
+				" to TLS-level renegotiation (SSL_ERROR_WANT_READ) or initial "
+				"TLS"
+				" connection establishment (it is different from tcp.wq_max,"
+				" which works at the TCP connection level)"},
+		{"con_ct_wq_max", CFG_VAR_INT | CFG_ATOMIC, 0, 4 * 1024 * 1024, 0, 0,
+				"maximum bytes queued for write per connection when write has "
+				"to wait"
+				" due to TLS-level renegotiation (SSL_ERROR_WANT_READ) or "
+				"initial TLS"
+				" connection establishment (it is different from "
+				"tcp.conn_wq_max,"
+				" which works at the TCP connection level)"},
+		{"ct_wq_blk_size", CFG_VAR_INT | CFG_ATOMIC, 1, 65536, 0, 0,
+				"internal TLS pre-write (clear-text) queue minimum block size"
+				" (advanced tunning or debugging for now)"},
+		{"send_close_notify", CFG_VAR_INT | CFG_ATOMIC, 0, 1, 0, 0,
+				"enable/disable sending a close notify TLS shutdown alert"
+				" before closing the corresponding TCP connection."
+				"Note that having it enabled has a performance impact."},
+		{0, 0, 0, 0, 0, 0}};
 
 
 /** fix pathnames.
@@ -240,21 +248,23 @@ cfg_def_t	tls_cfg_def[] = {
  * @param def - default value used if path->s is empty (path->s == 0).
  * @return  0 on success, -1 on error.
  */
-static int fix_initial_pathname(str* path, char* def)
+static int fix_initial_pathname(str *path, char *def)
 {
 	str new_path;
-	if (path->s && path->len && *path->s != '.' && *path->s != '/') {
+	if(path->s && path->len && *path->s != '.' && *path->s != '/') {
 		new_path.s = get_abs_pathname(0, path);
-		if (new_path.s == 0) return -1;
+		if(new_path.s == 0)
+			return -1;
 		new_path.len = strlen(new_path.s);
 		pkg_free(path->s);
 		*path = new_path;
-	} else if (path->s == 0 && def) {
+	} else if(path->s == 0 && def) {
 		/* use defaults */
 		new_path.len = strlen(def);
 		new_path.s = def;
 		new_path.s = get_abs_pathname(0, &new_path);
-		if (new_path.s == 0) return -1;
+		if(new_path.s == 0)
+			return -1;
 		new_path.len = strlen(new_path.s);
 		*path = new_path;
 	}
@@ -262,36 +272,33 @@ static int fix_initial_pathname(str* path, char* def)
 }
 
 
-
 /** fix the tls cfg, prior to registering.
   * @return < 0 on error, 0 on success
   */
-int fix_tls_cfg(struct cfg_group_tls* cfg)
+int fix_tls_cfg(struct cfg_group_tls *cfg)
 {
 	cfg->con_lifetime = S_TO_TICKS(cfg->con_lifetime);
 	fix_timeout("tls_connection_timeout", &cfg->con_lifetime,
-						MAX_TLS_CON_LIFETIME, MAX_TLS_CON_LIFETIME);
+			MAX_TLS_CON_LIFETIME, MAX_TLS_CON_LIFETIME);
 	/* Update relative paths of files configured through modparams, relative
 	 * pathnames will be converted to absolute and the directory of the main
 	 * SER configuration file will be used as reference.
 	 */
-	if (fix_initial_pathname(&cfg->config_file, 0) < 0)
+	if(fix_initial_pathname(&cfg->config_file, 0) < 0)
 		return -1;
-	if (fix_initial_pathname(&cfg->private_key, TLS_PKEY_FILE) < 0)
+	if(fix_initial_pathname(&cfg->private_key, TLS_PKEY_FILE) < 0)
 		return -1;
-	if (fix_initial_pathname(&cfg->ca_list, TLS_CA_FILE) < 0 )
+	if(fix_initial_pathname(&cfg->ca_list, TLS_CA_FILE) < 0)
 		return -1;
-	if (fix_initial_pathname(&cfg->ca_path, TLS_CA_PATH) < 0 )
+	if(fix_initial_pathname(&cfg->ca_path, TLS_CA_PATH) < 0)
 		return -1;
-	if (fix_initial_pathname(&cfg->crl, TLS_CRL_FILE) < 0 )
+	if(fix_initial_pathname(&cfg->crl, TLS_CRL_FILE) < 0)
 		return -1;
-	if (fix_initial_pathname(&cfg->certificate, TLS_CERT_FILE) < 0)
+	if(fix_initial_pathname(&cfg->certificate, TLS_CERT_FILE) < 0)
 		return -1;
 
 	return 0;
 }
 
 
-
-
 /* vi: set ts=4 sw=4 tw=79:ai:cindent: */

+ 7 - 6
src/modules/tls/tls_cfg.h

@@ -34,10 +34,11 @@
 /* maximum accepted lifetime (maximum possible is  ~ MAXINT/2)
  *  (it should be kept in sync w/ MAX_TCP_CON_LIFETIME from tcp_main.c:
  *   MAX_TLS_CON_LIFETIME <= MAX_TCP_CON_LIFETIME )*/
-#define MAX_TLS_CON_LIFETIME	((1U<<(sizeof(ticks_t)*8-1))-1)
+#define MAX_TLS_CON_LIFETIME ((1U << (sizeof(ticks_t) * 8 - 1)) - 1)
 
 
-struct cfg_group_tls {
+struct cfg_group_tls
+{
 	int force_run;
 	str method;
 	str server_name;
@@ -91,8 +92,8 @@ struct cfg_group_tls {
 	int ssl_read_ahead;
 	int low_mem_threshold1;
 	int low_mem_threshold2;
-	int ct_wq_max; /* maximum overall tls write clear text queued bytes */
-	int con_ct_wq_max; /* maximum clear text write queued bytes per con */
+	int ct_wq_max;		/* maximum overall tls write clear text queued bytes */
+	int con_ct_wq_max;	/* maximum clear text write queued bytes per con */
 	int ct_wq_blk_size; /* minimum block size for the clear text write queue */
 	int send_close_notify; /* if set try to be nice and send a shutdown alert
 						    before closing the tcp connection */
@@ -100,11 +101,11 @@ struct cfg_group_tls {
 
 
 extern struct cfg_group_tls default_tls_cfg;
-extern volatile void* tls_cfg;
+extern volatile void *tls_cfg;
 extern cfg_def_t tls_cfg_def[];
 
 
-extern int fix_tls_cfg(struct cfg_group_tls* cfg);
+extern int fix_tls_cfg(struct cfg_group_tls *cfg);
 
 #endif /*__tls_cfg_h*/
 

+ 196 - 189
src/modules/tls/tls_config.c

@@ -42,152 +42,140 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 
-static tls_domains_cfg_t* _ksr_tls_cfg = NULL;
-static tls_domain_t* _ksr_tls_domain = NULL;
+static tls_domains_cfg_t *_ksr_tls_cfg = NULL;
+static tls_domain_t *_ksr_tls_domain = NULL;
 
-static int parse_ipv6(struct ip_addr* ip, cfg_token_t* token,
-		cfg_parser_t* st)
+static int parse_ipv6(struct ip_addr *ip, cfg_token_t *token, cfg_parser_t *st)
 {
 	int ret;
 	cfg_token_t t;
-	struct ip_addr* ipv6;
+	struct ip_addr *ipv6;
 	str ip6_str;
-	char ip6_buff[IP_ADDR_MAX_STR_SIZE+3];
+	char ip6_buff[IP_ADDR_MAX_STR_SIZE + 3];
 
 	ip6_buff[0] = '\0';
 	while(1) {
 		ret = cfg_get_token(&t, st, 0);
-		if (ret != 0) goto err;
-		if (t.type == ']') break;
-		if (t.type != CFG_TOKEN_ALPHA && t.type != ':') goto err;
+		if(ret != 0)
+			goto err;
+		if(t.type == ']')
+			break;
+		if(t.type != CFG_TOKEN_ALPHA && t.type != ':')
+			goto err;
 		strncat(ip6_buff, t.val.s, t.val.len);
 	}
 	ip6_str.s = ip6_buff;
 	ip6_str.len = strlen(ip6_buff);
 	LM_DBG("found IPv6 address [%.*s]\n", ip6_str.len, ip6_str.s);
 	ipv6 = str2ip6(&ip6_str);
-	if (ipv6 == 0) goto err;
+	if(ipv6 == 0)
+		goto err;
 	*ip = *ipv6;
 	return 0;
 
 err:
-	LM_ERR("%s:%d:%d: Invalid IPv6 address\n",
-			st->file, token->start.line, token->start.col);
+	LM_ERR("%s:%d:%d: Invalid IPv6 address\n", st->file, token->start.line,
+			token->start.col);
 	return -1;
 }
 
 
-static int parse_ipv4(struct ip_addr* ip, cfg_token_t* token,
-		cfg_parser_t* st)
+static int parse_ipv4(struct ip_addr *ip, cfg_token_t *token, cfg_parser_t *st)
 {
 	int ret, i;
-	cfg_token_t  t;
+	cfg_token_t t;
 	unsigned int v;
 
 	ip->af = AF_INET;
 	ip->len = 4;
 
-	if (str2int(&token->val, &v) < 0) goto err;
-	if (v > 255) goto err;
+	if(str2int(&token->val, &v) < 0)
+		goto err;
+	if(v > 255)
+		goto err;
 
 	ip->u.addr[0] = v;
 
 	for(i = 1; i < 4; i++) {
 		ret = cfg_get_token(&t, st, 0);
-		if (ret < 0) return -1;
-		if (ret > 0 || t.type != '.')  goto err;
+		if(ret < 0)
+			return -1;
+		if(ret > 0 || t.type != '.')
+			goto err;
 
 		ret = cfg_get_token(&t, st, 0);
-		if (ret < 0) return -1;
-		if (ret > 0 || t.type != CFG_TOKEN_ALPHA) goto err;
-		if (str2int(&t.val, &v) < 0)  goto err;
-		if (v > 255) goto err;
+		if(ret < 0)
+			return -1;
+		if(ret > 0 || t.type != CFG_TOKEN_ALPHA)
+			goto err;
+		if(str2int(&t.val, &v) < 0)
+			goto err;
+		if(v > 255)
+			goto err;
 		ip->u.addr[i] = v;
 	}
 
 	return 0;
 err:
-	LM_ERR("%s:%d:%d: Invalid IPv4 address\n",
-			st->file, token->start.line, token->start.col);
+	LM_ERR("%s:%d:%d: Invalid IPv4 address\n", st->file, token->start.line,
+			token->start.col);
 	return -1;
 }
 
 
-static cfg_option_t methods[] = {
-	{"SSLv2",   .val = TLS_USE_SSLv2},
-	{"SSLv3",   .val = TLS_USE_SSLv3},
-	{"SSLv23",  .val = TLS_USE_SSLv23},
-	{"TLSv1",   .val = TLS_USE_TLSv1},
-	{"TLSv1.0", .val = TLS_USE_TLSv1},
-	{"TLSv1+",  .val = TLS_USE_TLSv1_PLUS},
-	{"TLSv1.0+", .val = TLS_USE_TLSv1_PLUS},
-	{"TLSv1.1",  .val = TLS_USE_TLSv1_1},
-	{"TLSv1.1+", .val = TLS_USE_TLSv1_1_PLUS},
-	{"TLSv1.2",  .val = TLS_USE_TLSv1_2},
-	{"TLSv1.2+", .val = TLS_USE_TLSv1_2_PLUS},
-	{"TLSv1.3",  .val = TLS_USE_TLSv1_3},
-	{"TLSv1.3+", .val = TLS_USE_TLSv1_3_PLUS},
-	{0}
-};
-
-
-static cfg_option_t domain_types[] = {
-	{"server", .val = TLS_DOMAIN_SRV},
-	{"srv",    .val = TLS_DOMAIN_SRV},
-	{"s",      .val = TLS_DOMAIN_SRV},
-	{"client", .val = TLS_DOMAIN_CLI},
-	{"cli",    .val = TLS_DOMAIN_CLI},
-	{"c",      .val = TLS_DOMAIN_CLI},
-	{0}
-};
-
-
-static cfg_option_t token_default[] = {
-	{"default"},
-	{"def"},
-	{"*"},
-	{0}
-};
-
-static cfg_option_t ksr_tls_token_any[] = {
-	{"any"},
-	{"all"},
-	{0}
-};
+static cfg_option_t methods[] = {{"SSLv2", .val = TLS_USE_SSLv2},
+		{"SSLv3", .val = TLS_USE_SSLv3}, {"SSLv23", .val = TLS_USE_SSLv23},
+		{"TLSv1", .val = TLS_USE_TLSv1}, {"TLSv1.0", .val = TLS_USE_TLSv1},
+		{"TLSv1+", .val = TLS_USE_TLSv1_PLUS},
+		{"TLSv1.0+", .val = TLS_USE_TLSv1_PLUS},
+		{"TLSv1.1", .val = TLS_USE_TLSv1_1},
+		{"TLSv1.1+", .val = TLS_USE_TLSv1_1_PLUS},
+		{"TLSv1.2", .val = TLS_USE_TLSv1_2},
+		{"TLSv1.2+", .val = TLS_USE_TLSv1_2_PLUS},
+		{"TLSv1.3", .val = TLS_USE_TLSv1_3},
+		{"TLSv1.3+", .val = TLS_USE_TLSv1_3_PLUS}, {0}};
+
+
+static cfg_option_t domain_types[] = {{"server", .val = TLS_DOMAIN_SRV},
+		{"srv", .val = TLS_DOMAIN_SRV}, {"s", .val = TLS_DOMAIN_SRV},
+		{"client", .val = TLS_DOMAIN_CLI}, {"cli", .val = TLS_DOMAIN_CLI},
+		{"c", .val = TLS_DOMAIN_CLI}, {0}};
+
+
+static cfg_option_t token_default[] = {{"default"}, {"def"}, {"*"}, {0}};
+
+static cfg_option_t ksr_tls_token_any[] = {{"any"}, {"all"}, {0}};
 
 
 static cfg_option_t verify_client_params[] = {
-	{"off",            .val = TLS_VERIFY_CLIENT_OFF},
-	{"on",             .val = TLS_VERIFY_CLIENT_ON},
-	{"optional",       .val = TLS_VERIFY_CLIENT_OPTIONAL},
-	{"optional_no_ca", .val = TLS_VERIFY_CLIENT_OPTIONAL_NO_CA},
-	{0}
-};
+		{"off", .val = TLS_VERIFY_CLIENT_OFF},
+		{"on", .val = TLS_VERIFY_CLIENT_ON},
+		{"optional", .val = TLS_VERIFY_CLIENT_OPTIONAL},
+		{"optional_no_ca", .val = TLS_VERIFY_CLIENT_OPTIONAL_NO_CA}, {0}};
 
 
 static cfg_option_t options[] = {
-	{"method",              .param = methods, .f = cfg_parse_enum_opt},
-	{"tls_method",          .param = methods, .f = cfg_parse_enum_opt},
-	{"verify_certificate",  .f = cfg_parse_bool_opt},
-	{"verify_cert",         .f = cfg_parse_bool_opt},
-	{"verify_depth",        .f = cfg_parse_int_opt},
-	{"require_certificate", .f = cfg_parse_bool_opt},
-	{"require_cert",        .f = cfg_parse_bool_opt},
-	{"private_key",         .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"pkey_file",           .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"calist_file",         .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"certificate",         .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"cert_file",           .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"cipher_list",         .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"ca_list",             .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"crl",                 .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"server_name",         .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"server_name_mode",    .f = cfg_parse_int_opt},
-	{"server_id",           .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{"verify_client",       .param = verify_client_params, .f = cfg_parse_enum_opt},
-	{"ca_path",             .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
-	{0}
-};
+		{"method", .param = methods, .f = cfg_parse_enum_opt},
+		{"tls_method", .param = methods, .f = cfg_parse_enum_opt},
+		{"verify_certificate", .f = cfg_parse_bool_opt},
+		{"verify_cert", .f = cfg_parse_bool_opt},
+		{"verify_depth", .f = cfg_parse_int_opt},
+		{"require_certificate", .f = cfg_parse_bool_opt},
+		{"require_cert", .f = cfg_parse_bool_opt},
+		{"private_key", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"pkey_file", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"calist_file", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"certificate", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"cert_file", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"cipher_list", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"ca_list", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"crl", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"server_name", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"server_name_mode", .f = cfg_parse_int_opt},
+		{"server_id", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM},
+		{"verify_client", .param = verify_client_params,
+				.f = cfg_parse_enum_opt},
+		{"ca_path", .f = cfg_parse_str_opt, .flags = CFG_STR_SHMMEM}, {0}};
 
 
 static void update_opt_variables(void)
@@ -219,91 +207,97 @@ static void update_opt_variables(void)
 }
 
 
-static int ksr_tls_parse_hostport(int* type, struct ip_addr* ip, unsigned int* port,
-		cfg_token_t* token, cfg_parser_t* st)
+static int ksr_tls_parse_hostport(int *type, struct ip_addr *ip,
+		unsigned int *port, cfg_token_t *token, cfg_parser_t *st)
 {
 	int ret;
 	cfg_token_t t;
-	cfg_option_t* opt;
+	cfg_option_t *opt;
 
 	ret = cfg_get_token(&t, st, 0);
-	if (ret < 0) return -1;
-	if (ret > 0) {
-		LM_ERR("%s:%d:%d: Missing IP address\n", st->file,
-				token->start.line, token->start.col);
+	if(ret < 0)
+		return -1;
+	if(ret > 0) {
+		LM_ERR("%s:%d:%d: Missing IP address\n", st->file, token->start.line,
+				token->start.col);
 		return -1;
 	}
 
-	if (t.type == '[') {
-		if (parse_ipv6(ip, &t, st) < 0) return -1;
-	} else if (t.type == CFG_TOKEN_ALPHA) {
+	if(t.type == '[') {
+		if(parse_ipv6(ip, &t, st) < 0)
+			return -1;
+	} else if(t.type == CFG_TOKEN_ALPHA) {
 		opt = cfg_lookup_token(token_default, &t.val);
-		if (opt) {
+		if(opt) {
 			*type = TLS_DOMAIN_DEF;
 			/* Default domain */
 			return 0;
 		} else {
 			opt = cfg_lookup_token(ksr_tls_token_any, &t.val);
-			if (opt) {
+			if(opt) {
 				*type = TLS_DOMAIN_ANY;
 				/* Default domain */
 				return 0;
 			} else {
-				if (parse_ipv4(ip, &t, st) < 0) return -1;
+				if(parse_ipv4(ip, &t, st) < 0)
+					return -1;
 			}
 		}
 	} else {
-		LM_ERR("%s:%d:%d: Syntax error, IP address expected\n",
-				st->file, t.start.line, t.start.col);
+		LM_ERR("%s:%d:%d: Syntax error, IP address expected\n", st->file,
+				t.start.line, t.start.col);
 		return -1;
 	}
 	*type = 0;
 
 	/* Parse port */
 	ret = cfg_get_token(&t, st, 0);
-	if (ret < 0) return -1;
-	if (ret > 0) {
+	if(ret < 0)
+		return -1;
+	if(ret > 0) {
 		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n", st->file, st->line,
 				st->col);
 		return -1;
 	}
 
-	if (t.type != ':') {
-		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n",
-				st->file, t.start.line, t.start.col);
+	if(t.type != ':') {
+		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n", st->file, t.start.line,
+				t.start.col);
 		return -1;
 	}
 
 	ret = cfg_get_token(&t, st, 0);
-	if (ret < 0) return -1;
-	if (ret > 0) {
+	if(ret < 0)
+		return -1;
+	if(ret > 0) {
 		LM_ERR("%s:%d:%d: Premature end of file, port number missing\n",
 				st->file, t.start.line, t.start.col);
 		return -1;
 	}
 
-	if (t.type != CFG_TOKEN_ALPHA || (str2int(&t.val, port) < 0)) {
-		LM_ERR("%s:%d:%d: Invalid port number '%.*s'\n",
-				st->file, t.start.line, t.start.col, STR_FMT(&t.val));
+	if(t.type != CFG_TOKEN_ALPHA || (str2int(&t.val, port) < 0)) {
+		LM_ERR("%s:%d:%d: Invalid port number '%.*s'\n", st->file, t.start.line,
+				t.start.col, STR_FMT(&t.val));
 		return -1;
 	}
 	return 0;
 }
 
 
-static int ksr_tls_parse_domain(void* param, cfg_parser_t* st, unsigned int flags)
+static int ksr_tls_parse_domain(
+		void *param, cfg_parser_t *st, unsigned int flags)
 {
 	cfg_token_t t;
 	int ret;
-	cfg_option_t* opt;
+	cfg_option_t *opt;
 
 	int type;
 	struct ip_addr ip;
 	unsigned int port;
 
-	if(_ksr_tls_cfg!=NULL && _ksr_tls_domain!=NULL) {
+	if(_ksr_tls_cfg != NULL && _ksr_tls_domain != NULL) {
 		/* Make sure the previous domain is not a duplicate */
-		if (ksr_tls_domain_duplicated(_ksr_tls_cfg, _ksr_tls_domain)) {
+		if(ksr_tls_domain_duplicated(_ksr_tls_cfg, _ksr_tls_domain)) {
 			return -1;
 		}
 	}
@@ -311,65 +305,71 @@ static int ksr_tls_parse_domain(void* param, cfg_parser_t* st, unsigned int flag
 	memset(&ip, 0, sizeof(struct ip_addr));
 
 	ret = cfg_get_token(&t, st, 0);
-	if (ret < 0) return -1;
-	if (ret > 0) {
-		LM_ERR("%s:%d:%d: TLS domain type missing\n",
-				st->file, st->line, st->col);
+	if(ret < 0)
+		return -1;
+	if(ret > 0) {
+		LM_ERR("%s:%d:%d: TLS domain type missing\n", st->file, st->line,
+				st->col);
 		return -1;
 	}
 
-	if (t.type != CFG_TOKEN_ALPHA ||
-			((opt = cfg_lookup_token(domain_types, &t.val)) == NULL)) {
-		LM_ERR("%s:%d:%d: Invalid TLS domain type %d:'%.*s'\n",
-				st->file, t.start.line, t.start.col, t.type, STR_FMT(&t.val));
+	if(t.type != CFG_TOKEN_ALPHA
+			|| ((opt = cfg_lookup_token(domain_types, &t.val)) == NULL)) {
+		LM_ERR("%s:%d:%d: Invalid TLS domain type %d:'%.*s'\n", st->file,
+				t.start.line, t.start.col, t.type, STR_FMT(&t.val));
 		return -1;
 	}
 
 	ret = cfg_get_token(&t, st, 0);
-	if (ret < 0) return -1;
-	if (ret > 0) {
-		LM_ERR("%s:%d:%d: TLS domain IP address missing\n",
-				st->file, st->line, st->col);
+	if(ret < 0)
+		return -1;
+	if(ret > 0) {
+		LM_ERR("%s:%d:%d: TLS domain IP address missing\n", st->file, st->line,
+				st->col);
 		return -1;
 	}
-	if (t.type != ':') {
-		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n",
-				st->file, t.start.line, t.start.col);
+	if(t.type != ':') {
+		LM_ERR("%s:%d:%d: Syntax error, ':' expected\n", st->file, t.start.line,
+				t.start.col);
 		return -1;
 	}
 
 	port = 0;
-	if (ksr_tls_parse_hostport(&type, &ip, &port, &t, st) < 0) return -1;
+	if(ksr_tls_parse_hostport(&type, &ip, &port, &t, st) < 0)
+		return -1;
 
 	ret = cfg_get_token(&t, st, 0);
-	if (ret < 0) return -1;
-	if (ret > 0) {
-		LM_ERR("%s:%d:%d: Closing ']' missing\n",
-				st->file, st->line, st->col);
+	if(ret < 0)
+		return -1;
+	if(ret > 0) {
+		LM_ERR("%s:%d:%d: Closing ']' missing\n", st->file, st->line, st->col);
 		return -1;
 	}
-	if (t.type != ']') {
-		LM_ERR("%s:%d:%d: Syntax error, ']' expected\n",
-				st->file, t.start.line, t.start.col);
+	if(t.type != ']') {
+		LM_ERR("%s:%d:%d: Syntax error, ']' expected\n", st->file, t.start.line,
+				t.start.col);
 		return -1;
 	}
 
-	if (cfg_eat_eol(st, flags)) return -1;
+	if(cfg_eat_eol(st, flags))
+		return -1;
 
-	if ((_ksr_tls_domain = tls_new_domain(opt->val | type, &ip, port)) == NULL) {
-		LM_ERR("%s:%d: Cannot create TLS domain structure\n", st->file, st->line);
+	if((_ksr_tls_domain = tls_new_domain(opt->val | type, &ip, port)) == NULL) {
+		LM_ERR("%s:%d: Cannot create TLS domain structure\n", st->file,
+				st->line);
 		return -1;
 	}
 
 	ret = tls_add_domain(_ksr_tls_cfg, _ksr_tls_domain);
-	if (ret < 0) {
+	if(ret < 0) {
 		LM_ERR("%s:%d: Error while creating TLS domain structure\n", st->file,
 				st->line);
 		tls_free_domain(_ksr_tls_domain);
 		_ksr_tls_domain = NULL;
 		return -1;
-	} else if (ret == 1) {
-		LM_ERR("%s:%d: Duplicate TLS domain (appears earlier in the config file)\n",
+	} else if(ret == 1) {
+		LM_ERR("%s:%d: Duplicate TLS domain (appears earlier in the config "
+			   "file)\n",
 				st->file, st->line);
 		tls_free_domain(_ksr_tls_domain);
 		_ksr_tls_domain = NULL;
@@ -386,9 +386,9 @@ static int ksr_tls_parse_domain(void* param, cfg_parser_t* st, unsigned int flag
 /*
  * Create configuration structures from configuration file
  */
-tls_domains_cfg_t* tls_load_config(str* filename)
+tls_domains_cfg_t *tls_load_config(str *filename)
 {
-	cfg_parser_t* parser;
+	cfg_parser_t *parser;
 	str empty;
 	struct stat file_status;
 	char tmp_name[13] = "configXXXXXX";
@@ -404,53 +404,53 @@ tls_domains_cfg_t* tls_load_config(str* filename)
 	in_fd = out_fd = filename_is_directory = 0;
 	file_path = (char *)0;
 
-	if ((_ksr_tls_cfg = tls_new_cfg()) == NULL) goto error;
+	if((_ksr_tls_cfg = tls_new_cfg()) == NULL)
+		goto error;
 
-	if (stat(filename->s, &file_status) != 0) {
+	if(stat(filename->s, &file_status) != 0) {
 		LM_ERR("cannot stat config file %s\n", filename->s);
 		goto error;
 	}
-	if (S_ISDIR(file_status.st_mode)) {
+	if(S_ISDIR(file_status.st_mode)) {
 		filename_is_directory = 1;
 		dir = opendir(filename->s);
-		if (dir == NULL) {
+		if(dir == NULL) {
 			LM_ERR("cannot open directory file %s\n", filename->s);
 			goto error;
 		}
 		out_fd = mkstemp(&(tmp_name[0]));
-		if (out_fd == -1) {
+		if(out_fd == -1) {
 			LM_ERR("cannot make tmp file %s\n", &(tmp_name[0]));
 			goto error;
 		}
-		while ((ent = readdir(dir)) != NULL) {
-			if(file_path) pkg_free(file_path);
+		while((ent = readdir(dir)) != NULL) {
+			if(file_path)
+				pkg_free(file_path);
 			file_path = pkg_malloc(filename->len + 1 + 256);
 			memcpy(file_path, filename->s, filename->len);
 			file_path[filename->len] = '/';
 			strcpy(file_path + filename->len + 1, ent->d_name);
-			if (stat(file_path, &file_status) != 0) {
-				LM_ERR("cannot get status of config file %s\n",
-						file_path);
+			if(stat(file_path, &file_status) != 0) {
+				LM_ERR("cannot get status of config file %s\n", file_path);
 				goto error;
 			}
-			if (S_ISREG(file_status.st_mode)) {
+			if(S_ISREG(file_status.st_mode)) {
 				in_fd = open(file_path, O_RDONLY);
-				if (in_fd == -1) {
-					LM_ERR("cannot open config file %s\n",
-							file_path);
+				if(in_fd == -1) {
+					LM_ERR("cannot open config file %s\n", file_path);
 					goto error;
 				}
 				pkg_free(file_path);
 				file_path = NULL;
-				while (read(in_fd, &ch, 1)) {
-					if (write(out_fd, &ch, 1)<0) {
+				while(read(in_fd, &ch, 1)) {
+					if(write(out_fd, &ch, 1) < 0) {
 						LM_ERR("write error: %s\n", strerror(errno));
 					}
 				}
 				close(in_fd);
 				in_fd = 0;
 				ch = '\n';
-				if (write(out_fd, &ch, 1)<0) {
+				if(write(out_fd, &ch, 1) < 0) {
 					LM_ERR("write error: %s\n", strerror(errno));
 				}
 			}
@@ -463,37 +463,42 @@ tls_domains_cfg_t* tls_load_config(str* filename)
 
 	empty.s = 0;
 	empty.len = 0;
-	if (filename_is_directory) {
+	if(filename_is_directory) {
 		filename_str.s = &(tmp_name[0]);
 		filename_str.len = strlen(&(tmp_name[0]));
-		if ((parser = cfg_parser_init(&empty, &filename_str)) == NULL) {
+		if((parser = cfg_parser_init(&empty, &filename_str)) == NULL) {
 			LM_ERR("Error while initializing configuration file parser.\n");
 			unlink(&(tmp_name[0]));
 			goto error;
 		}
 		unlink(&(tmp_name[0]));
 	} else {
-		if ((parser = cfg_parser_init(&empty, filename)) == NULL) {
+		if((parser = cfg_parser_init(&empty, filename)) == NULL) {
 			LM_ERR("Error while initializing configuration file parser.\n");
 			goto error;
 		}
 	}
 
 	cfg_section_parser(parser, ksr_tls_parse_domain, NULL);
-	if (sr_cfg_parse(parser)) goto error;
+	if(sr_cfg_parse(parser))
+		goto error;
 	cfg_parser_close(parser);
-	if (file_path) pkg_free(file_path);
+	if(file_path)
+		pkg_free(file_path);
 	return _ksr_tls_cfg;
 
 error:
-	if (dir) closedir(dir);
-	if (out_fd > 0) {
+	if(dir)
+		closedir(dir);
+	if(out_fd > 0) {
 		close(out_fd);
 		unlink(&(tmp_name[0]));
 	}
-	if (file_path) pkg_free(file_path);
-	if (parser) cfg_parser_close(parser);
-	if (_ksr_tls_cfg) {
+	if(file_path)
+		pkg_free(file_path);
+	if(parser)
+		cfg_parser_close(parser);
+	if(_ksr_tls_cfg) {
 		tls_free_cfg(_ksr_tls_cfg);
 		_ksr_tls_cfg = NULL;
 	}
@@ -504,17 +509,18 @@ error:
 /*
  * Convert TLS method string to integer
  */
-int tls_parse_method(str* method)
+int tls_parse_method(str *method)
 {
-	cfg_option_t* opt;
+	cfg_option_t *opt;
 
-	if (!method) {
+	if(!method) {
 		LM_BUG("Invalid parameter value\n");
 		return -1;
 	}
 
 	opt = cfg_lookup_token(methods, method);
-	if (!opt) return -1;
+	if(!opt)
+		return -1;
 
 #if OPENSSL_VERSION_NUMBER < 0x1000100fL
 	if(opt->val == TLS_USE_TLSv1_1 || opt->val == TLS_USE_TLSv1_1_PLUS) {
@@ -544,17 +550,18 @@ int tls_parse_method(str* method)
 /*
  * Convert TLS verify_client string to integer
  */
-int tls_parse_verify_client(str* verify_client)
+int tls_parse_verify_client(str *verify_client)
 {
-	cfg_option_t* opt;
+	cfg_option_t *opt;
 
-	if (!verify_client) {
+	if(!verify_client) {
 		LM_BUG("Invalid parameter value\n");
 		return -1;
 	}
 
 	opt = cfg_lookup_token(verify_client_params, verify_client);
-	if (!opt) return -1;
+	if(!opt)
+		return -1;
 
 	return opt->val;
 }

+ 3 - 3
src/modules/tls/tls_config.h

@@ -37,16 +37,16 @@
 #endif
 #endif
 
-tls_domains_cfg_t* tls_load_config(str* filename);
+tls_domains_cfg_t *tls_load_config(str *filename);
 
 /*
  * Convert TLS method string to integer
  */
-int tls_parse_method(str* method);
+int tls_parse_method(str *method);
 
 /*
  * Convert TLS verify_client string to integer
  */
-int tls_parse_verify_client(str* verify_client);
+int tls_parse_verify_client(str *verify_client);
 
 #endif /* _TLS_CONFIG_H */

+ 14 - 19
src/modules/tls/tls_ct_q.h

@@ -34,8 +34,8 @@
 typedef struct sbuffer_queue tls_ct_q;
 
 
-#define tls_ct_q_empty(bq) ((bq)==0 || (bq)->first==0)
-#define tls_ct_q_non_empty(bq) ((bq) && (bq)->first!=0)
+#define tls_ct_q_empty(bq) ((bq) == 0 || (bq)->first == 0)
+#define tls_ct_q_non_empty(bq) ((bq) && (bq)->first != 0)
 
 
 /**
@@ -48,15 +48,15 @@ typedef struct sbuffer_queue tls_ct_q;
  * @param min_buf_size - min size to allocate for new buffer elements
  * @return 0 on success, -1 on error (mem. allocation)
  */
-inline static int tls_ct_q_add(tls_ct_q** ct_q, const void* data,
-								unsigned int size, unsigned int min_buf_size)
+inline static int tls_ct_q_add(tls_ct_q **ct_q, const void *data,
+		unsigned int size, unsigned int min_buf_size)
 {
-	tls_ct_q* q;
+	tls_ct_q *q;
 
 	q = *ct_q;
-	if (likely(q == 0)){
-		q=shm_malloc(sizeof(tls_ct_q));
-		if (unlikely(q==0))
+	if(likely(q == 0)) {
+		q = shm_malloc(sizeof(tls_ct_q));
+		if(unlikely(q == 0))
 			goto error;
 		memset(q, 0, sizeof(tls_ct_q));
 		*ct_q = q;
@@ -67,7 +67,6 @@ error:
 }
 
 
-
 /**
  * @brief Destroy a buffer queue
  *
@@ -77,12 +76,12 @@ error:
  * @param **ct_q - double pointer to the queue
  * @return - number of bytes that used to be queued (>=0).
  */
-inline static unsigned int tls_ct_q_destroy(tls_ct_q** ct_q)
+inline static unsigned int tls_ct_q_destroy(tls_ct_q **ct_q)
 {
 	unsigned int ret;
 
 	ret = 0;
-	if (likely(ct_q && *ct_q)) {
+	if(likely(ct_q && *ct_q)) {
 		ret = sbufq_destroy(*ct_q);
 		shm_free(*ct_q);
 		*ct_q = 0;
@@ -91,7 +90,6 @@ inline static unsigned int tls_ct_q_destroy(tls_ct_q** ct_q)
 }
 
 
-
 /**
  * @brief Tries to flush the tls clear text queue
  *
@@ -117,17 +115,14 @@ inline static unsigned int tls_ct_q_destroy(tls_ct_q** ct_q)
  *            always set and it should be used to check for errors, since
  *            a flush_f() failure will not result in a negative return.
  */
-inline static int tls_ct_q_flush(tls_ct_q** tc_q, int* flags,
-								int (*flush_f)(void* p1, void* p2,
-												const void* buf,
-												unsigned size),
-								void* flush_p1, void* flush_p2)
+inline static int tls_ct_q_flush(tls_ct_q **tc_q, int *flags,
+		int (*flush_f)(void *p1, void *p2, const void *buf, unsigned size),
+		void *flush_p1, void *flush_p2)
 {
-	return *tc_q?sbufq_flush(*tc_q, flags, flush_f, flush_p1, flush_p2):0;
+	return *tc_q ? sbufq_flush(*tc_q, flags, flush_f, flush_p1, flush_p2) : 0;
 }
 
 
-
 #endif /*__tls_ct_q_h*/
 
 /* vi: set ts=4 sw=4 tw=79:ai:cindent: */

+ 29 - 36
src/modules/tls/tls_ct_wrq.c

@@ -34,12 +34,11 @@
 #include <openssl/ssl.h>
 
 
-atomic_t* tls_total_ct_wq; /* total clear text bytes queued for a future
+atomic_t *tls_total_ct_wq; /* total clear text bytes queued for a future
 							  SSL_write() (due to renegotiations/
 							  SSL_WRITE_WANTS_READ ).*/
 
 
-
 /**
  * @brief Init clear text write queues support
  * @return 0 on success, < 0 on error.
@@ -47,27 +46,25 @@ atomic_t* tls_total_ct_wq; /* total clear text bytes queued for a future
 int tls_ct_wq_init()
 {
 	tls_total_ct_wq = shm_malloc(sizeof(*tls_total_ct_wq));
-	if (unlikely(tls_total_ct_wq == 0))
+	if(unlikely(tls_total_ct_wq == 0))
 		return -1;
 	atomic_set(tls_total_ct_wq, 0);
 	return 0;
 }
 
 
-
 /**
  * @brief Destroy clear text write queues support
  */
 void tls_ct_wq_destroy()
 {
-	if (tls_total_ct_wq) {
+	if(tls_total_ct_wq) {
 		shm_free(tls_total_ct_wq);
 		tls_total_ct_wq = 0;
 	}
 }
 
 
-
 /**
  * @brief Total number of written queued bytes in all the SSL connections
  * @return total number of written queued bytes in all SSL connections
@@ -78,7 +75,6 @@ unsigned int tls_ct_wq_total_bytes()
 }
 
 
-
 /**
  * @brief Callback for tls_ct_q_flush()
  *
@@ -90,42 +86,41 @@ unsigned int tls_ct_wq_total_bytes()
  * handled outside)
  * @warning the SSL context must have the wbio and rbio previously set!
  */
-static int ssl_flush(void* tcp_c, void* error, const void* buf, unsigned size)
+static int ssl_flush(void *tcp_c, void *error, const void *buf, unsigned size)
 {
 	int n;
 	int ssl_error;
-	struct tls_extra_data* tls_c;
-	SSL* ssl;
+	struct tls_extra_data *tls_c;
+	SSL *ssl;
 
-	tls_c = ((struct tcp_connection*)tcp_c)->extra_data;
+	tls_c = ((struct tcp_connection *)tcp_c)->extra_data;
 	ssl = tls_c->ssl;
 	ssl_error = SSL_ERROR_NONE;
-	if (unlikely(tls_c->state == S_TLS_CONNECTING)) {
+	if(unlikely(tls_c->state == S_TLS_CONNECTING)) {
 		n = tls_connect(tcp_c, &ssl_error);
-		if (unlikely(n>=1)) {
+		if(unlikely(n >= 1)) {
 			n = SSL_write(ssl, buf, size);
-			if (unlikely(n <= 0))
+			if(unlikely(n <= 0))
 				ssl_error = SSL_get_error(ssl, n);
 		}
-	} else if (unlikely(tls_c->state == S_TLS_ACCEPTING)) {
+	} else if(unlikely(tls_c->state == S_TLS_ACCEPTING)) {
 		n = tls_accept(tcp_c, &ssl_error);
-		if (unlikely(n>=1)) {
+		if(unlikely(n >= 1)) {
 			n = SSL_write(ssl, buf, size);
-			if (unlikely(n <= 0))
+			if(unlikely(n <= 0))
 				ssl_error = SSL_get_error(ssl, n);
 		}
 	} else {
 		n = SSL_write(ssl, buf, size);
-		if (unlikely(n <= 0))
+		if(unlikely(n <= 0))
 			ssl_error = SSL_get_error(ssl, n);
 	}
 
-	*(long*)error = ssl_error;
+	*(long *)error = ssl_error;
 	return n;
 }
 
 
-
 /**
  * @brief Wrapper over tls_ct_q_flush()
  *
@@ -138,22 +133,21 @@ static int ssl_flush(void* tcp_c, void* error, const void* buf, unsigned size)
  * @return -1 on internal error, or the number of bytes flushed on success
  *         (>=0).
  */
-int tls_ct_wq_flush(struct tcp_connection* c, tls_ct_q** ct_q,
-					int* flags, int* ssl_err)
+int tls_ct_wq_flush(
+		struct tcp_connection *c, tls_ct_q **ct_q, int *flags, int *ssl_err)
 {
 	int ret;
 	long error;
 
 	error = SSL_ERROR_NONE;
-	ret = tls_ct_q_flush(ct_q,  flags, ssl_flush, c, &error);
+	ret = tls_ct_q_flush(ct_q, flags, ssl_flush, c, &error);
 	*ssl_err = (int)error;
-	if (likely(ret > 0))
+	if(likely(ret > 0))
 		atomic_add(tls_total_ct_wq, -ret);
 	return ret;
 }
 
 
-
 /**
  * @brief Wrapper over tls_ct_q_add()
  *
@@ -166,25 +160,24 @@ int tls_ct_wq_flush(struct tcp_connection* c, tls_ct_q** ct_q,
  * @return 0 on success, < 0 on error (-1 memory allocation, -2 queue size
  *         too big).
  */
-int tls_ct_wq_add(tls_ct_q** ct_q, const void* data, unsigned int size)
+int tls_ct_wq_add(tls_ct_q **ct_q, const void *data, unsigned int size)
 {
 	int ret;
 
-	if (unlikely( (*ct_q && (((*ct_q)->queued + size) >
-						cfg_get(tls, tls_cfg, con_ct_wq_max))) ||
-				(atomic_get(tls_total_ct_wq) + size) >
-						cfg_get(tls, tls_cfg, ct_wq_max))) {
+	if(unlikely((*ct_q
+						&& (((*ct_q)->queued + size)
+								> cfg_get(tls, tls_cfg, con_ct_wq_max)))
+				|| (atomic_get(tls_total_ct_wq) + size)
+						   > cfg_get(tls, tls_cfg, ct_wq_max))) {
 		return -2;
 	}
-	ret = tls_ct_q_add(ct_q, data, size,
-						cfg_get(tls, tls_cfg, ct_wq_blk_size));
-	if (likely(ret >= 0))
+	ret = tls_ct_q_add(ct_q, data, size, cfg_get(tls, tls_cfg, ct_wq_blk_size));
+	if(likely(ret >= 0))
 		atomic_add(tls_total_ct_wq, size);
 	return ret;
 }
 
 
-
 /**
  * @brief Wrapper over tls_ct_q_destroy()
  * Wrapper over tls_ct_q_destroy(), besides doing a tls_ct_q_destroy it
@@ -192,11 +185,11 @@ int tls_ct_wq_add(tls_ct_q** ct_q, const void* data, unsigned int size)
  * @param ct_q clear text queue
  * @return number of bytes that used to be queued (>=0),
  */
-unsigned int tls_ct_wq_free(tls_ct_q** ct_q)
+unsigned int tls_ct_wq_free(tls_ct_q **ct_q)
 {
 	unsigned int ret;
 
-	if (likely((ret = tls_ct_q_destroy(ct_q)) > 0))
+	if(likely((ret = tls_ct_q_destroy(ct_q)) > 0))
 		atomic_add(tls_total_ct_wq, -ret);
 	return ret;
 }

+ 6 - 7
src/modules/tls/tls_ct_wrq.h

@@ -33,7 +33,6 @@
 #include "../../core/tcp_conn.h"
 
 
-
 /**
  * @brief Init clear text write queues support
  * @return 0 on success, < 0 on error.
@@ -52,8 +51,8 @@ void tls_ct_wq_destroy();
  */
 unsigned int tls_ct_wq_total_bytes();
 
-#define tls_ct_wq_empty(tc_q) (*(tc_q)==0 || (*(tc_q))->first==0)
-#define tls_ct_wq_non_empty(bq) (*(tc_q) && (*(tc_q))->first!=0)
+#define tls_ct_wq_empty(tc_q) (*(tc_q) == 0 || (*(tc_q))->first == 0)
+#define tls_ct_wq_non_empty(bq) (*(tc_q) && (*(tc_q))->first != 0)
 
 /**
  * @brief Wrapper over tls_ct_q_flush()
@@ -67,8 +66,8 @@ unsigned int tls_ct_wq_total_bytes();
  * @return -1 on internal error, or the number of bytes flushed on success
  *         (>=0).
  */
-int tls_ct_wq_flush(struct tcp_connection* c, tls_ct_q** tc_q,
-					int* flags, int* ssl_err);
+int tls_ct_wq_flush(
+		struct tcp_connection *c, tls_ct_q **tc_q, int *flags, int *ssl_err);
 
 /**
  * @brief Wrapper over tls_ct_q_add()
@@ -82,7 +81,7 @@ int tls_ct_wq_flush(struct tcp_connection* c, tls_ct_q** tc_q,
  * @return 0 on success, < 0 on error (-1 memory allocation, -2 queue size
  *         too big).
  */
-int tls_ct_wq_add(tls_ct_q** ct_q, const void* data, unsigned int size);
+int tls_ct_wq_add(tls_ct_q **ct_q, const void *data, unsigned int size);
 
 /**
  * @brief Wrapper over tls_ct_q_destroy()
@@ -91,7 +90,7 @@ int tls_ct_wq_add(tls_ct_q** ct_q, const void* data, unsigned int size);
  * @param ct_q clear text queue
  * @return number of bytes that used to be queued (>=0),
  */
-unsigned int tls_ct_wq_free(tls_ct_q** ct_q);
+unsigned int tls_ct_wq_free(tls_ct_q **ct_q);
 
 #endif /*__tls_ct_wrq_h*/
 

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 262 - 244
src/modules/tls/tls_domain.c


+ 42 - 39
src/modules/tls/tls_domain.h

@@ -34,12 +34,12 @@
 #include <openssl/ssl.h>
 
 
-#define TLS_OP_SSLv2_PLUS   0
-#define TLS_OP_SSLv3_PLUS   (TLS_OP_SSLv2_PLUS   | SSL_OP_NO_SSLv2)
-#define TLS_OP_TLSv1_PLUS   (TLS_OP_SSLv3_PLUS   | SSL_OP_NO_SSLv3)
+#define TLS_OP_SSLv2_PLUS 0
+#define TLS_OP_SSLv3_PLUS (TLS_OP_SSLv2_PLUS | SSL_OP_NO_SSLv2)
+#define TLS_OP_TLSv1_PLUS (TLS_OP_SSLv3_PLUS | SSL_OP_NO_SSLv3)
 
 #ifdef SSL_OP_NO_TLSv1
-#define TLS_OP_TLSv1_1_PLUS (TLS_OP_TLSv1_PLUS   | SSL_OP_NO_TLSv1)
+#define TLS_OP_TLSv1_1_PLUS (TLS_OP_TLSv1_PLUS | SSL_OP_NO_TLSv1)
 
 #ifdef SSL_OP_NO_TLSv1_1
 #define TLS_OP_TLSv1_2_PLUS (TLS_OP_TLSv1_1_PLUS | SSL_OP_NO_TLSv1_1)
@@ -54,31 +54,32 @@
 /**
  * Available TLS methods
  */
-enum tls_method {
+enum tls_method
+{
 	TLS_METHOD_UNSPEC = 0,
 	TLS_USE_SSLv23_cli,
 	TLS_USE_SSLv23_srv,
-	TLS_USE_SSLv23,     /* any SSL/TLS version */
+	TLS_USE_SSLv23, /* any SSL/TLS version */
 	TLS_USE_SSLv2_cli,
 	TLS_USE_SSLv2_srv,
-	TLS_USE_SSLv2,      /* only SSLv2 (deprecated) */
+	TLS_USE_SSLv2, /* only SSLv2 (deprecated) */
 	TLS_USE_SSLv3_cli,
 	TLS_USE_SSLv3_srv,
-	TLS_USE_SSLv3,      /* only SSLv3 (insecure) */
+	TLS_USE_SSLv3, /* only SSLv3 (insecure) */
 	TLS_USE_TLSv1_cli,
 	TLS_USE_TLSv1_srv,
-	TLS_USE_TLSv1,      /* only TLSv1.0 */
+	TLS_USE_TLSv1, /* only TLSv1.0 */
 	TLS_USE_TLSv1_1_cli,
 	TLS_USE_TLSv1_1_srv,
-	TLS_USE_TLSv1_1,    /* only TLSv1.1 */
+	TLS_USE_TLSv1_1, /* only TLSv1.1 */
 	TLS_USE_TLSv1_2_cli,
 	TLS_USE_TLSv1_2_srv,
-	TLS_USE_TLSv1_2,    /* only TLSv1.2 */
+	TLS_USE_TLSv1_2, /* only TLSv1.2 */
 	TLS_USE_TLSv1_3_cli,
 	TLS_USE_TLSv1_3_srv,
-	TLS_USE_TLSv1_3,    /* only TLSv1.3 */
-	TLS_USE_TLSvRANGE,    /* placeholder - TLSvX ranges must be after it */
-	TLS_USE_TLSv1_PLUS,   /* TLSv1.0 or greater */
+	TLS_USE_TLSv1_3,	  /* only TLSv1.3 */
+	TLS_USE_TLSvRANGE,	  /* placeholder - TLSvX ranges must be after it */
+	TLS_USE_TLSv1_PLUS,	  /* TLSv1.0 or greater */
 	TLS_USE_TLSv1_1_PLUS, /* TLSv1.1 or greater */
 	TLS_USE_TLSv1_2_PLUS, /* TLSv1.2 or greater */
 	TLS_USE_TLSv1_3_PLUS, /* TLSv1.3 or greater */
@@ -89,7 +90,8 @@ enum tls_method {
 /**
  * TLS configuration domain type
  */
-enum tls_domain_type {
+enum tls_domain_type
+{
 	TLS_DOMAIN_DEF = (1 << 0), /**< Default domain */
 	TLS_DOMAIN_SRV = (1 << 1), /**< Server domain */
 	TLS_DOMAIN_CLI = (1 << 2), /**< Client domain */
@@ -104,7 +106,8 @@ enum tls_domain_type {
 /**
  * TLS "verify_client" options
  */
-enum tls_verify_client_options {
+enum tls_verify_client_options
+{
 	TLS_VERIFY_CLIENT_OFF = 0,
 	TLS_VERIFY_CLIENT_ON = 1,
 	TLS_VERIFY_CLIENT_OPTIONAL = 2,
@@ -115,11 +118,12 @@ enum tls_verify_client_options {
 /**
  * separate configuration per ip:port
  */
-typedef struct tls_domain {
+typedef struct tls_domain
+{
 	int type;
 	struct ip_addr ip;
 	unsigned short port;
-	SSL_CTX** ctx;
+	SSL_CTX **ctx;
 	str cert_file;
 	str pkey_file;
 	int verify_cert;
@@ -134,20 +138,21 @@ typedef struct tls_domain {
 	int server_name_mode;
 	str server_id;
 	int verify_client;
-	struct tls_domain* next;
+	struct tls_domain *next;
 } tls_domain_t;
 
 
 /**
  * TLS configuration structures
  */
-typedef struct tls_domains_cfg {
-	tls_domain_t* srv_default; /**< Default server domain */
-	tls_domain_t* cli_default; /**< Default client domain */
-	tls_domain_t* srv_list;    /**< Server domain list */
-	tls_domain_t* cli_list;    /**< Client domain list */
-	struct tls_domains_cfg* next; /**< Next element in the garbage list */
-	atomic_t ref_count;        /**< How many connections use this configuration */
+typedef struct tls_domains_cfg
+{
+	tls_domain_t *srv_default;	  /**< Default server domain */
+	tls_domain_t *cli_default;	  /**< Default client domain */
+	tls_domain_t *srv_list;		  /**< Server domain list */
+	tls_domain_t *cli_list;		  /**< Client domain list */
+	struct tls_domains_cfg *next; /**< Next element in the garbage list */
+	atomic_t ref_count; /**< How many connections use this configuration */
 } tls_domains_cfg_t;
 
 
@@ -160,15 +165,14 @@ typedef struct tls_domains_cfg {
  * @param port domain port
  * @return new domain
  */
-tls_domain_t *tls_new_domain(int type, struct ip_addr *ip,
-			     unsigned short port);
+tls_domain_t *tls_new_domain(int type, struct ip_addr *ip, unsigned short port);
 
 
 /**
  * @brief Free all memory used by TLS configuration domain
  * @param d freed domain
  */
-void tls_free_domain(tls_domain_t* d);
+void tls_free_domain(tls_domain_t *d);
 
 
 /**
@@ -176,8 +180,7 @@ void tls_free_domain(tls_domain_t* d);
  * @param d printed domain
  * @return printed domain, with zero termination
  */
-char* tls_domain_str(tls_domain_t* d);
-
+char *tls_domain_str(tls_domain_t *d);
 
 
 /**
@@ -186,7 +189,7 @@ char* tls_domain_str(tls_domain_t* d);
  * Create new configuration structure in new allocated shared memory.
  * @return configuration structure or zero on error
  */
-tls_domains_cfg_t* tls_new_cfg(void);
+tls_domains_cfg_t *tls_new_cfg(void);
 
 
 /**
@@ -195,7 +198,7 @@ tls_domains_cfg_t* tls_new_cfg(void);
  * @param d TLS domain
  * @return 1 if domain already exists, 0 after addition, -1 on error
  */
-int tls_add_domain(tls_domains_cfg_t* cfg, tls_domain_t* d);
+int tls_add_domain(tls_domains_cfg_t *cfg, tls_domain_t *d);
 
 
 /**
@@ -208,8 +211,8 @@ int tls_add_domain(tls_domains_cfg_t* cfg, tls_domain_t* d);
  * @param cli_defaults command line interface defaults
  * @return 0 on success, -1 on error
  */
-int tls_fix_domains_cfg(tls_domains_cfg_t* cfg, tls_domain_t* srv_defaults,
-				tls_domain_t* cli_defaults);
+int tls_fix_domains_cfg(tls_domains_cfg_t *cfg, tls_domain_t *srv_defaults,
+		tls_domain_t *cli_defaults);
 
 
 /**
@@ -221,15 +224,15 @@ int tls_fix_domains_cfg(tls_domains_cfg_t* cfg, tls_domain_t* srv_defaults,
  * @param sname server name
  * @return found configuration or default, if not found
  */
-tls_domain_t* tls_lookup_cfg(tls_domains_cfg_t* cfg, int type,
-			struct ip_addr* ip, unsigned short port, str *sname, str *srvid);
+tls_domain_t *tls_lookup_cfg(tls_domains_cfg_t *cfg, int type,
+		struct ip_addr *ip, unsigned short port, str *sname, str *srvid);
 
 
 /**
  * @brief Free TLS configuration structure
  * @param cfg freed configuration
  */
-void tls_free_cfg(tls_domains_cfg_t* cfg);
+void tls_free_cfg(tls_domains_cfg_t *cfg);
 
 
 /**
@@ -240,6 +243,6 @@ void tls_destroy_cfg(void);
 /**
  * @brief Check if a TLS configuration domain exists
  */
-int ksr_tls_domain_duplicated(tls_domains_cfg_t* cfg, tls_domain_t* d);
+int ksr_tls_domain_duplicated(tls_domains_cfg_t *cfg, tls_domain_t *d);
 
 #endif /* _TLS_DOMAIN_H */

+ 116 - 96
src/modules/tls/tls_dump_vf.c

@@ -46,102 +46,122 @@ void tls_dump_verification_failure(long verification_result)
 
 	tls_log = cfg_get(tls, tls_cfg, log);
 	switch(verification_result) {
-	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
-		LOG(tls_log, "verification failure: unable to get issuer certificate\n");
-		break;
-	case X509_V_ERR_UNABLE_TO_GET_CRL:
-		LOG(tls_log, "verification failure: unable to get certificate CRL\n");
-		break;
-	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
-		LOG(tls_log, "verification failure: unable to decrypt certificate's signature\n");
-		break;
-	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
-		LOG(tls_log, "verification failure: unable to decrypt CRL's signature\n");
-		break;
-	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
-		LOG(tls_log, "verification failure: unable to decode issuer public key\n");
-		break;
-	case X509_V_ERR_CERT_SIGNATURE_FAILURE:
-		LOG(tls_log, "verification failure: certificate signature failure\n");
-		break;
-	case X509_V_ERR_CRL_SIGNATURE_FAILURE:
-		LOG(tls_log, "verification failure: CRL signature failure\n");
-		break;
-	case X509_V_ERR_CERT_NOT_YET_VALID:
-		LOG(tls_log, "verification failure: certificate is not yet valid\n");
-		break;
-	case X509_V_ERR_CERT_HAS_EXPIRED:
-		LOG(tls_log, "verification failure: certificate has expired\n");
-		break;
-	case X509_V_ERR_CRL_NOT_YET_VALID:
-		LOG(tls_log, "verification failure: CRL is not yet valid\n");
-		break;
-	case X509_V_ERR_CRL_HAS_EXPIRED:
-		LOG(tls_log, "verification failure: CRL has expired\n");
-		break;
-	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
-		LOG(tls_log, "verification failure: format error in certificate's notBefore field\n");
-		break;
-	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
-		LOG(tls_log, "verification failure: format error in certificate's notAfter field\n");
-		break;
-	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
-		LOG(tls_log, "verification failure: format error in CRL's lastUpdate field\n");
-		break;
-	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
-		LOG(tls_log, "verification failure: format error in CRL's nextUpdate field\n");
-		break;
-	case X509_V_ERR_OUT_OF_MEM:
-		LOG(tls_log, "verification failure: out of memory\n");
-		break;
-	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
-		LOG(tls_log, "verification failure: self signed certificate\n");
-		break;
-	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
-		LOG(tls_log, "verification failure: self signed certificate in certificate chain\n");
-		break;
-	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
-		LOG(tls_log, "verification failure: unable to get local issuer certificate\n");
-		break;
-	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
-		LOG(tls_log, "verification failure: unable to verify the first certificate\n");
-		break;
-	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
-		LOG(tls_log, "verification failure: certificate chain too long\n");
-		break;
-	case X509_V_ERR_CERT_REVOKED:
-		LOG(tls_log, "verification failure: certificate revoked\n");
-		break;
-	case X509_V_ERR_INVALID_CA:
-		LOG(tls_log, "verification failure: invalid CA certificate\n");
-		break;
-	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
-		LOG(tls_log, "verification failure: path length constraint exceeded\n");
-		break;
-	case X509_V_ERR_INVALID_PURPOSE:
-		LOG(tls_log, "verification failure: unsupported certificate purpose\n");
-		break;
-	case X509_V_ERR_CERT_UNTRUSTED:
-		LOG(tls_log, "verification failure: certificate not trusted\n");
-		break;
-	case X509_V_ERR_CERT_REJECTED:
-		LOG(tls_log, "verification failure: certificate rejected\n");
-		break;
-	case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
-		LOG(tls_log, "verification failure: subject issuer mismatch\n");
-		break;
-	case X509_V_ERR_AKID_SKID_MISMATCH:
-		LOG(tls_log, "verification failure: authority and subject key identifier mismatch\n");
-		break;
-	case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
-		LOG(tls_log, "verification failure: authority and issuer serial number mismatch\n");
-		break;
-	case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
-		LOG(tls_log, "verification failure: key usage does not include certificate signing\n");
-		break;
-	case X509_V_ERR_APPLICATION_VERIFICATION:
-		LOG(tls_log, "verification failure: application verification failure\n");
-		break;
+		case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
+			LOG(tls_log,
+					"verification failure: unable to get issuer certificate\n");
+			break;
+		case X509_V_ERR_UNABLE_TO_GET_CRL:
+			LOG(tls_log,
+					"verification failure: unable to get certificate CRL\n");
+			break;
+		case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
+			LOG(tls_log, "verification failure: unable to decrypt "
+						 "certificate's signature\n");
+			break;
+		case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
+			LOG(tls_log, "verification failure: unable to decrypt CRL's "
+						 "signature\n");
+			break;
+		case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
+			LOG(tls_log, "verification failure: unable to decode issuer public "
+						 "key\n");
+			break;
+		case X509_V_ERR_CERT_SIGNATURE_FAILURE:
+			LOG(tls_log,
+					"verification failure: certificate signature failure\n");
+			break;
+		case X509_V_ERR_CRL_SIGNATURE_FAILURE:
+			LOG(tls_log, "verification failure: CRL signature failure\n");
+			break;
+		case X509_V_ERR_CERT_NOT_YET_VALID:
+			LOG(tls_log,
+					"verification failure: certificate is not yet valid\n");
+			break;
+		case X509_V_ERR_CERT_HAS_EXPIRED:
+			LOG(tls_log, "verification failure: certificate has expired\n");
+			break;
+		case X509_V_ERR_CRL_NOT_YET_VALID:
+			LOG(tls_log, "verification failure: CRL is not yet valid\n");
+			break;
+		case X509_V_ERR_CRL_HAS_EXPIRED:
+			LOG(tls_log, "verification failure: CRL has expired\n");
+			break;
+		case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
+			LOG(tls_log, "verification failure: format error in certificate's "
+						 "notBefore field\n");
+			break;
+		case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
+			LOG(tls_log, "verification failure: format error in certificate's "
+						 "notAfter field\n");
+			break;
+		case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
+			LOG(tls_log, "verification failure: format error in CRL's "
+						 "lastUpdate field\n");
+			break;
+		case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
+			LOG(tls_log, "verification failure: format error in CRL's "
+						 "nextUpdate field\n");
+			break;
+		case X509_V_ERR_OUT_OF_MEM:
+			LOG(tls_log, "verification failure: out of memory\n");
+			break;
+		case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
+			LOG(tls_log, "verification failure: self signed certificate\n");
+			break;
+		case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
+			LOG(tls_log, "verification failure: self signed certificate in "
+						 "certificate chain\n");
+			break;
+		case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
+			LOG(tls_log, "verification failure: unable to get local issuer "
+						 "certificate\n");
+			break;
+		case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
+			LOG(tls_log, "verification failure: unable to verify the first "
+						 "certificate\n");
+			break;
+		case X509_V_ERR_CERT_CHAIN_TOO_LONG:
+			LOG(tls_log, "verification failure: certificate chain too long\n");
+			break;
+		case X509_V_ERR_CERT_REVOKED:
+			LOG(tls_log, "verification failure: certificate revoked\n");
+			break;
+		case X509_V_ERR_INVALID_CA:
+			LOG(tls_log, "verification failure: invalid CA certificate\n");
+			break;
+		case X509_V_ERR_PATH_LENGTH_EXCEEDED:
+			LOG(tls_log,
+					"verification failure: path length constraint exceeded\n");
+			break;
+		case X509_V_ERR_INVALID_PURPOSE:
+			LOG(tls_log,
+					"verification failure: unsupported certificate purpose\n");
+			break;
+		case X509_V_ERR_CERT_UNTRUSTED:
+			LOG(tls_log, "verification failure: certificate not trusted\n");
+			break;
+		case X509_V_ERR_CERT_REJECTED:
+			LOG(tls_log, "verification failure: certificate rejected\n");
+			break;
+		case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
+			LOG(tls_log, "verification failure: subject issuer mismatch\n");
+			break;
+		case X509_V_ERR_AKID_SKID_MISMATCH:
+			LOG(tls_log, "verification failure: authority and subject key "
+						 "identifier mismatch\n");
+			break;
+		case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
+			LOG(tls_log, "verification failure: authority and issuer serial "
+						 "number mismatch\n");
+			break;
+		case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
+			LOG(tls_log, "verification failure: key usage does not include "
+						 "certificate signing\n");
+			break;
+		case X509_V_ERR_APPLICATION_VERIFICATION:
+			LOG(tls_log,
+					"verification failure: application verification failure\n");
+			break;
 	}
 }
 

+ 238 - 229
src/modules/tls/tls_init.c

@@ -33,7 +33,6 @@
  */
 
 
-
 #include <stdio.h>
 #include <sys/types.h>
 #include <netinet/in_systm.h>
@@ -73,13 +72,13 @@ pthread_mutex_t ksr_tls_lock_shm;
  */
 int ksr_tls_lock_init(void)
 {
-	if(!(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)) {
+	if(!(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)) {
 		return 0;
 	}
-    if (pthread_mutex_init(&ksr_tls_lock_shm, NULL) != 0) {
-        LM_ERR("mutex init failed\n");
-        return -1;
-    }
+	if(pthread_mutex_init(&ksr_tls_lock_shm, NULL) != 0) {
+		LM_ERR("mutex init failed\n");
+		return -1;
+	}
 	return 0;
 }
 
@@ -88,39 +87,39 @@ int ksr_tls_lock_init(void)
  */
 void ksr_tls_lock_destroy(void)
 {
-	if(!(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)) {
+	if(!(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)) {
 		return;
 	}
-    pthread_mutex_destroy(&ksr_tls_lock_shm);
+	pthread_mutex_destroy(&ksr_tls_lock_shm);
 	return;
 }
 
 #if OPENSSL_VERSION_NUMBER < 0x00907000L
-#    warning ""
-#    warning "==============================================================="
-#    warning " Your version of OpenSSL is < 0.9.7."
-#    warning " Upgrade for better compatibility, features and security fixes!"
-#    warning "==============================================================="
-#    warning ""
+#warning ""
+#warning "==============================================================="
+#warning " Your version of OpenSSL is < 0.9.7."
+#warning " Upgrade for better compatibility, features and security fixes!"
+#warning "==============================================================="
+#warning ""
 #endif
 
 /* replace openssl zlib compression with our version if necessary
  * (the openssl zlib compression uses the wrong malloc, see
  *  openssl #1468): 0.9.8-dev < version  <0.9.8e-beta1 */
-#if OPENSSL_VERSION_NUMBER >= 0x00908000L  /* 0.9.8-dev */ && \
-							  OPENSSL_VERSION_NUMBER <  0x00908051L  /* 0.9.8.e-beta1 */
-#    ifndef OPENSSL_NO_COMP
-#        warning "openssl zlib compression bug workaround enabled"
-#    endif
-#    define TLS_FIX_ZLIB_COMPRESSION
-#    include "fixed_c_zlib.h"
+#if OPENSSL_VERSION_NUMBER >= 0x00908000L		/* 0.9.8-dev */ \
+		&& OPENSSL_VERSION_NUMBER < 0x00908051L /* 0.9.8.e-beta1 */
+#ifndef OPENSSL_NO_COMP
+#warning "openssl zlib compression bug workaround enabled"
+#endif
+#define TLS_FIX_ZLIB_COMPRESSION
+#include "fixed_c_zlib.h"
 #endif
 
 #ifdef TLS_KSSL_WORKAROUND
 #if OPENSSL_VERSION_NUMBER < 0x00908050L
-#	warning "openssl lib compiled with kerberos support which introduces a bug\
+#warning "openssl lib compiled with kerberos support which introduces a bug\
 	(wrong malloc/free used in kssl.c) -- attempting workaround"
-#	warning "NOTE: if you don't link libssl statically don't try running the \
+#warning "NOTE: if you don't link libssl statically don't try running the \
 	compiled code on a system with a differently compiled openssl (it's safer \
 			to compile on the  _target_ system)"
 #endif /* OPENSSL_VERSION_NUMBER */
@@ -128,11 +127,10 @@ void ksr_tls_lock_destroy(void)
 
 /* openssl < 1. 0 */
 #if OPENSSL_VERSION_NUMBER < 0x01000000L
-#	warning "openssl < 1.0: no TLS extensions or server name support"
+#warning "openssl < 1.0: no TLS extensions or server name support"
 #endif /* OPENSSL_VERSION < 1.0 */
 
 
-
 #ifndef OPENSSL_NO_COMP
 #define TLS_COMP_SUPPORT
 #else
@@ -147,18 +145,18 @@ void ksr_tls_lock_destroy(void)
 
 
 #ifdef TLS_KSSL_WORKAROUND
-int openssl_kssl_malloc_bug=0; /* is openssl bug #1467 present ? */
+int openssl_kssl_malloc_bug = 0; /* is openssl bug #1467 present ? */
 #endif
 
 #if OPENSSL_VERSION_NUMBER < 0x10100000L
-const SSL_METHOD* ssl_methods[TLS_METHOD_MAX];
+const SSL_METHOD *ssl_methods[TLS_METHOD_MAX];
 #else
 sr_tls_methods_t sr_tls_methods[TLS_METHOD_MAX];
 #endif
 
 #ifdef NO_TLS_MALLOC_DBG
 #undef TLS_MALLOC_DBG /* extra malloc debug info from openssl */
-#endif /* NO_TLS_MALLOC_DBG */
+#endif				  /* NO_TLS_MALLOC_DBG */
 
 /*
  * Wrappers around SER shared memory functions
@@ -174,145 +172,154 @@ sr_tls_methods_t sr_tls_methods[TLS_METHOD_MAX];
 */
 
 
-
 #ifndef LIBRESSL_VERSION_NUMBER
-inline static char* buf_append(char* buf, char* end, char* str, int str_len)
+inline static char *buf_append(char *buf, char *end, char *str, int str_len)
 {
-	if ( (buf+str_len)<end){
+	if((buf + str_len) < end) {
 		memcpy(buf, str, str_len);
-		return buf+str_len;
+		return buf + str_len;
 	}
 	return 0;
 }
 
 
-inline static int backtrace2str(char* buf, int size)
+inline static int backtrace2str(char *buf, int size)
 {
-	void* bt[32];
+	void *bt[32];
 	int bt_size, i;
-	char** bt_strs;
-	char* p;
-	char* end;
-	char* next;
-	char* s;
-	char* e;
-
-	p=buf; end=buf+size;
-	bt_size=backtrace(bt, sizeof(bt)/sizeof(bt[0]));
-	bt_strs=backtrace_symbols(bt, bt_size);
-	if (bt_strs){
-		p=buf; end=buf+size;
+	char **bt_strs;
+	char *p;
+	char *end;
+	char *next;
+	char *s;
+	char *e;
+
+	p = buf;
+	end = buf + size;
+	bt_size = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
+	bt_strs = backtrace_symbols(bt, bt_size);
+	if(bt_strs) {
+		p = buf;
+		end = buf + size;
 		/*if (bt_size>16) bt_size=16;*/ /* go up only 12 entries */
-		for (i=3; i< bt_size; i++){
+		for(i = 3; i < bt_size; i++) {
 			/* try to isolate only the function name*/
-			s=strchr(bt_strs[i], '(');
-			if (s && ((e=strchr(s, ')'))!=0)){
+			s = strchr(bt_strs[i], '(');
+			if(s && ((e = strchr(s, ')')) != 0)) {
 				s++;
-			}else if ((s=strchr(bt_strs[i], '['))!=0){
-				e=s+strlen(s);
-			}else{
-				s=bt_strs[i]; e=s+strlen(s); /* add the whole string */
+			} else if((s = strchr(bt_strs[i], '[')) != 0) {
+				e = s + strlen(s);
+			} else {
+				s = bt_strs[i];
+				e = s + strlen(s); /* add the whole string */
 			}
-			next=buf_append(p, end, s, (int)(long)(e-s));
-			if (next==0) break;
-			else p=next;
-			if (p<end){
-				*p=':'; /* separator */
+			next = buf_append(p, end, s, (int)(long)(e - s));
+			if(next == 0)
+				break;
+			else
+				p = next;
+			if(p < end) {
+				*p = ':'; /* separator */
 				p++;
-			}else break;
+			} else
+				break;
 		}
-		if (p==buf){
-			*p=0;
+		if(p == buf) {
+			*p = 0;
 			p++;
-		}else
-			*(p-1)=0;
+		} else
+			*(p - 1) = 0;
 		free(bt_strs);
 	}
-	return (int)(long)(p-buf);
+	return (int)(long)(p - buf);
 }
 
-static void* ser_malloc(size_t size, const char* file, int line)
+static void *ser_malloc(size_t size, const char *file, int line)
 {
-	void  *p;
+	void *p;
 	char bt_buf[1024];
 	int s;
 #ifdef RAND_NULL_MALLOC
-	static ticks_t st=0;
+	static ticks_t st = 0;
 #endif
 
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
 
 #ifdef RAND_NULL_MALLOC
 	/* start random null returns only after
 	 * NULL_GRACE_PERIOD from first call */
-	if (st==0) st=get_ticks();
-	if (((get_ticks()-st)<NULL_GRACE_PERIOD) || (random()%RAND_NULL_MALLOC)){
+	if(st == 0)
+		st = get_ticks();
+	if(((get_ticks() - st) < NULL_GRACE_PERIOD)
+			|| (random() % RAND_NULL_MALLOC)) {
 #endif
-		s=backtrace2str(bt_buf, sizeof(bt_buf));
+		s = backtrace2str(bt_buf, sizeof(bt_buf));
 		/* ugly hack: keep the bt inside the alloc'ed fragment */
-		p=_shm_malloc(size+s, file, "via ser_malloc", line);
-		if (p==0){
-			LM_CRIT("tls - ser_malloc(%d)[%s:%d]==null, bt: %s\n",
-					size, file, line, bt_buf);
-		}else{
-			memcpy(p+size, bt_buf, s);
-			((struct qm_frag*)((char*)p-sizeof(struct qm_frag)))->func=
-				p+size;
+		p = _shm_malloc(size + s, file, "via ser_malloc", line);
+		if(p == 0) {
+			LM_CRIT("tls - ser_malloc(%d)[%s:%d]==null, bt: %s\n", size, file,
+					line, bt_buf);
+		} else {
+			memcpy(p + size, bt_buf, s);
+			((struct qm_frag *)((char *)p - sizeof(struct qm_frag)))->func =
+					p + size;
 		}
 #ifdef RAND_NULL_MALLOC
-	}else{
-		p=0;
+	} else {
+		p = 0;
 		backtrace2str(bt_buf, sizeof(bt_buf));
 		LM_CRIT("tls - random ser_malloc(%d)[%s:%d] returning null - bt: %s\n",
 				size, file, line, bt_buf);
 	}
 #endif
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 	return p;
 }
 
 
-static void* ser_realloc(void *ptr, size_t size, const char* file, int line)
+static void *ser_realloc(void *ptr, size_t size, const char *file, int line)
 {
-	void  *p;
+	void *p;
 	char bt_buf[1024];
 	int s;
 #ifdef RAND_NULL_MALLOC
-	static ticks_t st=0;
+	static ticks_t st = 0;
 #endif
 
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
 
 #ifdef RAND_NULL_MALLOC
 	/* start random null returns only after
 	 * NULL_GRACE_PERIOD from first call */
-	if (st==0) st=get_ticks();
-	if (((get_ticks()-st)<NULL_GRACE_PERIOD) || (random()%RAND_NULL_MALLOC)){
-#endif
-		s=backtrace2str(bt_buf, sizeof(bt_buf));
-		p=_shm_realloc(ptr, size+s, file, "via ser_realloc", line);
-		if (p==0){
-			LM_CRIT("tls - ser_realloc(%p, %d)[%s:%d]==null, bt: %s\n",
-					ptr, size, file, line, bt_buf);
-		}else{
-			memcpy(p+size, bt_buf, s);
-			((struct qm_frag*)((char*)p-sizeof(struct qm_frag)))->func=
-				p+size;
+	if(st == 0)
+		st = get_ticks();
+	if(((get_ticks() - st) < NULL_GRACE_PERIOD)
+			|| (random() % RAND_NULL_MALLOC)) {
+#endif
+		s = backtrace2str(bt_buf, sizeof(bt_buf));
+		p = _shm_realloc(ptr, size + s, file, "via ser_realloc", line);
+		if(p == 0) {
+			LM_CRIT("tls - ser_realloc(%p, %d)[%s:%d]==null, bt: %s\n", ptr,
+					size, file, line, bt_buf);
+		} else {
+			memcpy(p + size, bt_buf, s);
+			((struct qm_frag *)((char *)p - sizeof(struct qm_frag)))->func =
+					p + size;
 		}
 #ifdef RAND_NULL_MALLOC
-	}else{
-		p=0;
+	} else {
+		p = 0;
 		backtrace2str(bt_buf, sizeof(bt_buf));
 		LM_CRIT("tls - random ser_realloc(%p, %d)[%s:%d]"
-				" returning null - bt: %s\n", ptr, size, file, line,
-				bt_buf);
+				" returning null - bt: %s\n",
+				ptr, size, file, line, bt_buf);
 	}
 #endif
 
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 
 	return p;
@@ -324,49 +331,49 @@ static void* ser_realloc(void *ptr, size_t size, const char* file, int line)
 #ifndef LIBRESSL_VERSION_NUMBER
 
 #if OPENSSL_VERSION_NUMBER < 0x010100000L
-static void* ser_malloc(size_t size)
+static void *ser_malloc(size_t size)
 {
 	void *p;
 
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
 	p = shm_malloc(size);
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 	return p;
 }
 
 
-static void* ser_realloc(void *ptr, size_t size)
+static void *ser_realloc(void *ptr, size_t size)
 {
 	void *p;
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
 	p = shm_realloc(ptr, size);
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 	return p;
 }
 #else
-static void* ser_malloc(size_t size, const char *fname, int fline)
+static void *ser_malloc(size_t size, const char *fname, int fline)
 {
 	void *p;
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
 	p = shm_malloc(size);
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 	return p;
 }
 
 
-static void* ser_realloc(void *ptr, size_t size, const char *fname, int fline)
+static void *ser_realloc(void *ptr, size_t size, const char *fname, int fline)
 {
 	void *p;
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
 	p = shm_realloc(ptr, size);
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 	return p;
 }
@@ -384,23 +391,23 @@ static void ser_free(void *ptr)
 	 * As shm_free() aborts on null pointers, we have to check for null pointer
 	 * here in the wrapper function.
 	 */
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
-	if (ptr) {
+	if(ptr) {
 		shm_free(ptr);
 	}
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 }
 #else
 static void ser_free(void *ptr, const char *fname, int fline)
 {
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_lock(&ksr_tls_lock_shm);
-	if (ptr) {
+	if(ptr) {
 		shm_free(ptr);
 	}
-	if(ksr_tls_init_mode&TLS_MODE_PTHREAD_LOCK_SHM)
+	if(ksr_tls_init_mode & TLS_MODE_PTHREAD_LOCK_SHM)
 		pthread_mutex_unlock(&ksr_tls_lock_shm);
 }
 #endif
@@ -417,7 +424,7 @@ int tls_h_init_si_f(struct socket_info *si)
 	 * reuse tcp initialization
 	 */
 	ret = tcp_init(si);
-	if (ret != 0) {
+	if(ret != 0) {
 		LM_ERR("Error while initializing TCP part of TLS socket %.*s:%d\n",
 				si->address_str.len, si->address_str.s, si->port_no);
 		goto error;
@@ -427,7 +434,7 @@ int tls_h_init_si_f(struct socket_info *si)
 	return 0;
 
 error:
-	if (si->socket != -1) {
+	if(si->socket != -1) {
 		close(si->socket);
 		si->socket = -1;
 	}
@@ -435,7 +442,6 @@ error:
 }
 
 
-
 /*
  * initialize ssl methods
  */
@@ -482,14 +488,14 @@ static void init_ssl_methods(void)
 #endif
 
 	/* ranges of TLS versions (require a minimum TLS version) */
-	ssl_methods[TLS_USE_TLSv1_PLUS - 1] = (void*)TLS_OP_TLSv1_PLUS;
+	ssl_methods[TLS_USE_TLSv1_PLUS - 1] = (void *)TLS_OP_TLSv1_PLUS;
 
 #if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(LIBRESSL_VERSION_NUMBER)
-	ssl_methods[TLS_USE_TLSv1_1_PLUS - 1] = (void*)TLS_OP_TLSv1_1_PLUS;
+	ssl_methods[TLS_USE_TLSv1_1_PLUS - 1] = (void *)TLS_OP_TLSv1_1_PLUS;
 #endif
 
 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(LIBRESSL_VERSION_NUMBER)
-	ssl_methods[TLS_USE_TLSv1_2_PLUS - 1] = (void*)TLS_OP_TLSv1_2_PLUS;
+	ssl_methods[TLS_USE_TLSv1_2_PLUS - 1] = (void *)TLS_OP_TLSv1_2_PLUS;
 #endif
 
 #else
@@ -583,53 +589,52 @@ static int init_tls_compression(void)
 #if OPENSSL_VERSION_NUMBER < 0x010100000L
 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
 	int n, r;
-	STACK_OF(SSL_COMP)* comp_methods;
-	SSL_COMP* zlib_comp;
+	STACK_OF(SSL_COMP) * comp_methods;
+	SSL_COMP *zlib_comp;
 	long ssl_version;
 
 	/* disabling compression */
-#	ifndef SSL_COMP_ZLIB_IDX
-#		define SSL_COMP_ZLIB_IDX 1 /* openssl/ssl/ssl_ciph.c:84 */
-#	endif
+#ifndef SSL_COMP_ZLIB_IDX
+#define SSL_COMP_ZLIB_IDX 1 /* openssl/ssl/ssl_ciph.c:84 */
+#endif
 	comp_methods = SSL_COMP_get_compression_methods();
-	if (comp_methods == 0) {
+	if(comp_methods == 0) {
 		LM_INFO("compression support disabled in the"
 				" openssl lib\n");
 		goto end; /* nothing to do, exit */
-	} else if (cfg_get(tls, tls_cfg, disable_compression)){
+	} else if(cfg_get(tls, tls_cfg, disable_compression)) {
 		LM_INFO("disabling compression...\n");
 		sk_SSL_COMP_zero(comp_methods);
-	}else{
-		ssl_version=SSLeay();
+	} else {
+		ssl_version = SSLeay();
 		/* replace openssl zlib compression with our version if necessary
 		 * (the openssl zlib compression uses the wrong malloc, see
 		 *  openssl #1468): 0.9.8-dev < version  <0.9.8e-beta1 */
-		if ((ssl_version >= 0x00908000L) && (ssl_version < 0x00908051L)){
+		if((ssl_version >= 0x00908000L) && (ssl_version < 0x00908051L)) {
 			/* the above SSL_COMP_get_compression_methods() call has the side
 			 * effect of initializing the compression stack (if not already
 			 * initialized) => after it zlib is initialized and in the stack */
 			/* find zlib_comp (cannot use ssl3_comp_find, not exported) */
 			n = sk_SSL_COMP_num(comp_methods);
 			zlib_comp = 0;
-			for (r = 0; r < n; r++) {
+			for(r = 0; r < n; r++) {
 				zlib_comp = sk_SSL_COMP_value(comp_methods, r);
-				LM_DBG("found compression method %p id %d\n",
-						zlib_comp, zlib_comp->id);
-				if (zlib_comp->id == SSL_COMP_ZLIB_IDX) {
-					LM_DBG("found zlib compression (%d)\n",
-							SSL_COMP_ZLIB_IDX);
+				LM_DBG("found compression method %p id %d\n", zlib_comp,
+						zlib_comp->id);
+				if(zlib_comp->id == SSL_COMP_ZLIB_IDX) {
+					LM_DBG("found zlib compression (%d)\n", SSL_COMP_ZLIB_IDX);
 					break /* found */;
 				} else {
 					zlib_comp = 0;
 				}
 			}
-			if (zlib_comp == 0) {
+			if(zlib_comp == 0) {
 				LM_INFO("no openssl zlib compression found\n");
-			}else{
+			} else {
 				LM_WARN("detected openssl lib with "
 						"known zlib compression bug: \"%s\" (0x%08lx)\n",
 						SSLeay_version(SSLEAY_VERSION), ssl_version);
-#	ifdef TLS_FIX_ZLIB_COMPRESSION
+#ifdef TLS_FIX_ZLIB_COMPRESSION
 				LM_WARN("enabling openssl zlib compression "
 						"bug workaround (replacing zlib COMP method with "
 						"our own version)\n");
@@ -644,7 +649,7 @@ static int init_tls_compression(void)
 				 */
 				CRYPTO_cleanup_all_ex_data();
 
-				if (fixed_c_zlib_init() != 0) {
+				if(fixed_c_zlib_init() != 0) {
 					LM_CRIT("BUG: failed to initialize zlib"
 							" compression fix, disabling compression...\n");
 					sk_SSL_COMP_zero(comp_methods); /* delete compression */
@@ -652,12 +657,12 @@ static int init_tls_compression(void)
 				}
 				/* "fix" it */
 				zlib_comp->method = &zlib_method;
-#	else
+#else
 				LM_WARN("disabling openssl zlib compression \n");
-				zlib_comp=sk_SSL_COMP_delete(comp_methods, r);
-				if (zlib_comp)
+				zlib_comp = sk_SSL_COMP_delete(comp_methods, r);
+				if(zlib_comp)
 					OPENSSL_free(zlib_comp);
-#	endif
+#endif
 			}
 		}
 	}
@@ -695,31 +700,31 @@ int tls_pre_init(void)
 	 * CRYPTO_malloc will set allow_customize in openssl to 0
 	 */
 	CRYPTO_get_mem_functions(&mf, &rf, &ff);
-	LM_DBG("initial memory functions - malloc: %p realloc: %p free: %p\n",
-			mf, rf, ff);
+	LM_DBG("initial memory functions - malloc: %p realloc: %p free: %p\n", mf,
+			rf, ff);
 	mf = NULL;
 	rf = NULL;
 	ff = NULL;
 #ifdef TLS_MALLOC_DBG
-	if (!CRYPTO_set_mem_ex_functions(ser_malloc, ser_realloc, ser_free)) {
+	if(!CRYPTO_set_mem_ex_functions(ser_malloc, ser_realloc, ser_free)) {
 #else
-	if (!CRYPTO_set_mem_functions(ser_malloc, ser_realloc, ser_free)) {
+	if(!CRYPTO_set_mem_functions(ser_malloc, ser_realloc, ser_free)) {
 #endif
 		LM_ERR("Unable to set the memory allocation functions\n");
 		CRYPTO_get_mem_functions(&mf, &rf, &ff);
-		LM_ERR("libssl current mem functions - m: %p r: %p f: %p\n",
-					mf, rf, ff);
-		LM_ERR("module mem functions - m: %p r: %p f: %p\n",
-					ser_malloc, ser_realloc, ser_free);
+		LM_ERR("libssl current mem functions - m: %p r: %p f: %p\n", mf, rf,
+				ff);
+		LM_ERR("module mem functions - m: %p r: %p f: %p\n", ser_malloc,
+				ser_realloc, ser_free);
 		LM_ERR("Be sure tls module is loaded before any other module using"
-				" libssl (can be loaded first to be safe)\n");
+			   " libssl (can be loaded first to be safe)\n");
 		return -1;
 	}
 	LM_DBG("updated memory functions - malloc: %p realloc: %p free: %p\n",
 			ser_malloc, ser_realloc, ser_free);
 #endif /* LIBRESSL_VERSION_NUMBER */
 
-	if (tls_init_locks()<0)
+	if(tls_init_locks() < 0)
 		return -1;
 
 	init_tls_compression();
@@ -733,7 +738,7 @@ int tls_pre_init(void)
  */
 int tls_h_mod_pre_init_f(void)
 {
-	if(tls_mod_preinitialized==1) {
+	if(tls_mod_preinitialized == 1) {
 		LM_DBG("already mod pre-initialized\n");
 		return 0;
 	}
@@ -746,7 +751,7 @@ int tls_h_mod_pre_init_f(void)
 	SSL_library_init();
 #endif
 	SSL_load_error_strings();
-	tls_mod_preinitialized=1;
+	tls_mod_preinitialized = 1;
 	return 0;
 }
 
@@ -763,13 +768,13 @@ int tls_h_mod_init_f(void)
 	int lib_zlib;
 	int kerberos_support;
 	int comp_support;
-	const char* lib_cflags;
+	const char *lib_cflags;
 #endif
 	int low_mem_threshold1;
 	int low_mem_threshold2;
 	str tls_grp;
 	str s;
-	cfg_ctx_t* cfg_ctx;
+	cfg_ctx_t *cfg_ctx;
 
 	if(tls_mod_initialized == 1) {
 		LM_DBG("already initialized\n");
@@ -782,27 +787,27 @@ int tls_h_mod_init_f(void)
 #endif
 
 #if OPENSSL_VERSION_NUMBER < 0x010100000L
-	ssl_version=SSLeay();
-	ssl_version_txt=SSLeay_version(SSLEAY_VERSION);
+	ssl_version = SSLeay();
+	ssl_version_txt = SSLeay_version(SSLEAY_VERSION);
 #else
-	ssl_version=OpenSSL_version_num();
-	ssl_version_txt=OpenSSL_version(OPENSSL_VERSION);
+	ssl_version = OpenSSL_version_num();
+	ssl_version_txt = OpenSSL_version(OPENSSL_VERSION);
 #endif
 
 	/* check if version have the same major minor and fix level
 	 * (e.g. 0.9.8a & 0.9.8c are ok, but 0.9.8 and 0.9.9x are not)
 	 * - values is represented as 0xMMNNFFPPS: major minor fix patch status
 	 *   0x00090705f == 0.9.7e release */
-	if ((ssl_version>>12)!=(OPENSSL_VERSION_NUMBER>>12)){
+	if((ssl_version >> 12) != (OPENSSL_VERSION_NUMBER >> 12)) {
 		LM_CRIT("installed openssl library"
 				" version is too different from the library the " NAME " tls"
 				" module was compiled with: installed \"%s\" (0x%08lx),"
 				" compiled \"%s\" (0x%08lx).\n"
 				" Please make sure a compatible version is used"
 				" (tls_force_run in kamailio.cfg will override this check)\n",
-				ssl_version_txt, ssl_version,
-				OPENSSL_VERSION_TEXT, (long)OPENSSL_VERSION_NUMBER);
-		if (cfg_get(tls, tls_cfg, force_run))
+				ssl_version_txt, ssl_version, OPENSSL_VERSION_TEXT,
+				(long)OPENSSL_VERSION_NUMBER);
+		if(cfg_get(tls, tls_cfg, force_run))
 			LM_WARN("tls_force_run turned on, ignoring "
 					" openssl version mismatch\n");
 		else
@@ -813,57 +818,60 @@ int tls_h_mod_init_f(void)
 #if OPENSSL_VERSION_NUMBER < 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
 
 #ifdef TLS_KERBEROS_SUPPORT
-	kerberos_support=1;
+	kerberos_support = 1;
 #else
-	kerberos_support=0;
+	kerberos_support = 0;
 #endif
 #ifdef TLS_COMP_SUPPORT
-	comp_support=1;
+	comp_support = 1;
 #else
-	comp_support=0;
+	comp_support = 0;
 #endif
 	/* attempt to guess if the library was compiled with kerberos or
 	 * compression support from the cflags */
-	lib_cflags=SSLeay_version(SSLEAY_CFLAGS);
-	lib_kerberos=0;
-	lib_zlib=0;
-	if ((lib_cflags==0) || strstr(lib_cflags, "not available")){
-		lib_kerberos=-1;
-		lib_zlib=-1;
-	}else{
-		if (strstr(lib_cflags, "-DZLIB"))
-			lib_zlib=1;
-		if (strstr(lib_cflags, "-DKRB5_"))
-			lib_kerberos=1;
+	lib_cflags = SSLeay_version(SSLEAY_CFLAGS);
+	lib_kerberos = 0;
+	lib_zlib = 0;
+	if((lib_cflags == 0) || strstr(lib_cflags, "not available")) {
+		lib_kerberos = -1;
+		lib_zlib = -1;
+	} else {
+		if(strstr(lib_cflags, "-DZLIB"))
+			lib_zlib = 1;
+		if(strstr(lib_cflags, "-DKRB5_"))
+			lib_kerberos = 1;
 	}
 	LM_INFO("compiled  with  openssl  version "
 			"\"%s\" (0x%08lx), kerberos support: %s, compression: %s\n",
 			OPENSSL_VERSION_TEXT, (long)OPENSSL_VERSION_NUMBER,
-			kerberos_support?"on":"off", comp_support?"on":"off");
+			kerberos_support ? "on" : "off", comp_support ? "on" : "off");
 	LM_INFO("installed openssl library version "
 			"\"%s\" (0x%08lx), kerberos support: %s, "
 			" zlib compression: %s"
 			"\n %s\n",
 			SSLeay_version(SSLEAY_VERSION), ssl_version,
-			(lib_kerberos==1)?"on":(lib_kerberos==0)?"off":"unknown",
-			(lib_zlib==1)?"on":(lib_zlib==0)?"off":"unknown",
+			(lib_kerberos == 1)	  ? "on"
+			: (lib_kerberos == 0) ? "off"
+								  : "unknown",
+			(lib_zlib == 1)	  ? "on"
+			: (lib_zlib == 0) ? "off"
+							  : "unknown",
 			SSLeay_version(SSLEAY_CFLAGS));
-	if (lib_kerberos!=kerberos_support){
-		if (lib_kerberos!=-1){
+	if(lib_kerberos != kerberos_support) {
+		if(lib_kerberos != -1) {
 			LM_CRIT("openssl compile options"
 					" mismatch: library has kerberos support"
 					" %s and Kamailio tls %s (unstable configuration)\n"
 					" (tls_force_run in " NAME ".cfg will override this"
 					" check)\n",
-					lib_kerberos?"enabled":"disabled",
-					kerberos_support?"enabled":"disabled"
-			   );
-			if (cfg_get(tls, tls_cfg, force_run))
+					lib_kerberos ? "enabled" : "disabled",
+					kerberos_support ? "enabled" : "disabled");
+			if(cfg_get(tls, tls_cfg, force_run))
 				LM_WARN("tls_force_run turned on, "
 						"ignoring kerberos support mismatch\n");
 			else
 				return -1; /* exit, is safer */
-		}else{
+		} else {
 			LM_WARN("openssl  compile options"
 					" missing -- cannot detect if kerberos support is"
 					" enabled. Possible unstable configuration\n");
@@ -874,9 +882,9 @@ int tls_h_mod_init_f(void)
 	/* if openssl compiled with kerberos support, and openssl < 0.9.8e-dev
 	 * or openssl between 0.9.9-dev and 0.9.9-beta1 apply workaround for
 	 * openssl bug #1467 */
-	if (ssl_version < 0x00908050L ||
-			(ssl_version >= 0x00909000L && ssl_version < 0x00909001L)){
-		openssl_kssl_malloc_bug=1;
+	if(ssl_version < 0x00908050L
+			|| (ssl_version >= 0x00909000L && ssl_version < 0x00909001L)) {
+		openssl_kssl_malloc_bug = 1;
 		LM_WARN("openssl kerberos malloc bug detected, "
 				" kerberos support will be disabled...\n");
 	}
@@ -887,18 +895,18 @@ int tls_h_mod_init_f(void)
 	/* set free memory threshold for openssl bug #1491 workaround */
 	low_mem_threshold1 = cfg_get(tls, tls_cfg, low_mem_threshold1);
 	low_mem_threshold2 = cfg_get(tls, tls_cfg, low_mem_threshold2);
-	if (low_mem_threshold1<0){
+	if(low_mem_threshold1 < 0) {
 		/* default */
-		low_mem_threshold1=512*1024*get_max_procs();
-	}else
-		low_mem_threshold1*=1024; /* KB */
-	if (low_mem_threshold2<0){
+		low_mem_threshold1 = 512 * 1024 * get_max_procs();
+	} else
+		low_mem_threshold1 *= 1024; /* KB */
+	if(low_mem_threshold2 < 0) {
 		/* default */
-		low_mem_threshold2=256*1024*get_max_procs();
-	}else
-		low_mem_threshold2*=1024; /* KB */
-	if ((low_mem_threshold1==0) || (low_mem_threshold2==0))
-	 LM_WARN("tls: openssl bug #1491 (crash/mem leaks on low memory)"
+		low_mem_threshold2 = 256 * 1024 * get_max_procs();
+	} else
+		low_mem_threshold2 *= 1024; /* KB */
+	if((low_mem_threshold1 == 0) || (low_mem_threshold2 == 0))
+		LM_WARN("tls: openssl bug #1491 (crash/mem leaks on low memory)"
 				" workaround disabled\n");
 	else
 		LM_WARN("openssl bug #1491 (crash/mem leaks on low memory)"
@@ -906,18 +914,18 @@ int tls_h_mod_init_f(void)
 				" preemptively) with free memory thresholds %d and %d bytes\n",
 				low_mem_threshold1, low_mem_threshold2);
 
-	if (shm_available()==(unsigned long)(-1)){
+	if(shm_available() == (unsigned long)(-1)) {
 		LM_WARN(NAME " is compiled without MALLOC_STATS support:"
-				" the workaround for low mem. openssl bugs will _not_ "
-				"work\n");
-		low_mem_threshold1=0;
-		low_mem_threshold2=0;
+					 " the workaround for low mem. openssl bugs will _not_ "
+					 "work\n");
+		low_mem_threshold1 = 0;
+		low_mem_threshold2 = 0;
 	}
-	if ((low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1))
+	if((low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1))
 			|| (low_mem_threshold2
-				!= cfg_get(tls, tls_cfg, low_mem_threshold2))) {
+					!= cfg_get(tls, tls_cfg, low_mem_threshold2))) {
 		/* ugly hack to set the initial values for the mem thresholds */
-		if (cfg_register_ctx(&cfg_ctx, 0)) {
+		if(cfg_register_ctx(&cfg_ctx, 0)) {
 			LM_ERR("failed to register cfg context\n");
 			return -1;
 		}
@@ -925,18 +933,18 @@ int tls_h_mod_init_f(void)
 		tls_grp.len = strlen(tls_grp.s);
 		s.s = "low_mem_threshold1";
 		s.len = strlen(s.s);
-		if (low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1) &&
-				cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
-					low_mem_threshold1)) {
+		if(low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1)
+				&& cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
+						low_mem_threshold1)) {
 			LM_ERR("failed to set tls.low_mem_threshold1 to %d\n",
 					low_mem_threshold1);
 			return -1;
 		}
 		s.s = "low_mem_threshold2";
 		s.len = strlen(s.s);
-		if (low_mem_threshold2 != cfg_get(tls, tls_cfg, low_mem_threshold2) &&
-				cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
-					low_mem_threshold2)) {
+		if(low_mem_threshold2 != cfg_get(tls, tls_cfg, low_mem_threshold2)
+				&& cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
+						low_mem_threshold2)) {
 			LM_ERR("failed to set tls.low_mem_threshold1 to %d\n",
 					low_mem_threshold2);
 			return -1;
@@ -953,15 +961,16 @@ int tls_h_mod_init_f(void)
  * Make sure that all server domains in the configuration have corresponding
  * listening socket in SER
  */
-int tls_check_sockets(tls_domains_cfg_t* cfg)
+int tls_check_sockets(tls_domains_cfg_t *cfg)
 {
-	tls_domain_t* d;
+	tls_domain_t *d;
 
-	if (!cfg) return 0;
+	if(!cfg)
+		return 0;
 
 	d = cfg->srv_list;
 	while(d) {
-		if (d->ip.len && !find_si(&d->ip, d->port, PROTO_TLS)) {
+		if(d->ip.len && !find_si(&d->ip, d->port, PROTO_TLS)) {
 			LM_ERR("%s: No listening socket found\n", tls_domain_str(d));
 			return -1;
 		}

+ 6 - 5
src/modules/tls/tls_init.h

@@ -46,10 +46,11 @@ extern int openssl_kssl_malloc_bug; /* is openssl bug #1467 present ? */
 
 
 #if OPENSSL_VERSION_NUMBER < 0x10100000L
-extern const SSL_METHOD* ssl_methods[];
+extern const SSL_METHOD *ssl_methods[];
 #else
-typedef struct sr_tls_methods_s {
-	const SSL_METHOD* TLSMethod;
+typedef struct sr_tls_methods_s
+{
+	const SSL_METHOD *TLSMethod;
 	int TLSMethodMin;
 	int TLSMethodMax;
 } sr_tls_methods_t;
@@ -57,7 +58,7 @@ extern sr_tls_methods_t sr_tls_methods[];
 #endif
 
 #define TLS_MODE_PTHREAD_LOCK_SHM (1)
-#define TLS_MODE_FORK_PREPARE (1<<1)
+#define TLS_MODE_FORK_PREPARE (1 << 1)
 
 /*
  * just once, pre-initialize the tls subsystem
@@ -90,7 +91,7 @@ int tls_h_init_si_f(struct socket_info *si);
  * Make sure that all server domains in the configuration have corresponding
  * listening socket in SER
  */
-int tls_check_sockets(tls_domains_cfg_t* cfg);
+int tls_check_sockets(tls_domains_cfg_t *cfg);
 
 int ksr_tls_lock_init(void);
 void ksr_tls_lock_destroy(void);

+ 42 - 39
src/modules/tls/tls_locking.c

@@ -29,32 +29,35 @@
 #include "../../core/dprint.h"
 #include "../../core/locking.h"
 
-static int n_static_locks=0;
-static gen_lock_set_t* static_locks=0;
+static int n_static_locks = 0;
+static gen_lock_set_t *static_locks = 0;
 
 /* OpenSSL is thread-safe since 1.1.0 */
 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
 
 /* "dynamic" locks */
 
-struct CRYPTO_dynlock_value{
+struct CRYPTO_dynlock_value
+{
 	gen_lock_t lock;
 };
 
 
-static struct CRYPTO_dynlock_value* dyn_create_f(const char* file, int line)
+static struct CRYPTO_dynlock_value *dyn_create_f(const char *file, int line)
 {
-	struct CRYPTO_dynlock_value* l;
+	struct CRYPTO_dynlock_value *l;
 
-	l=shm_malloc(sizeof(struct CRYPTO_dynlock_value));
-	if (l==0){
+	l = shm_malloc(sizeof(struct CRYPTO_dynlock_value));
+	if(l == 0) {
 		LM_CRIT("dyn create locking callback out of shm."
-				" memory (called from %s:%d)\n", file, line);
+				" memory (called from %s:%d)\n",
+				file, line);
 		goto error;
 	}
-	if (lock_init(&l->lock)==0){
+	if(lock_init(&l->lock) == 0) {
 		LM_CRIT("dyn create locking callback: lock "
-				"initialization failed (called from %s:%d)\n", file, line);
+				"initialization failed (called from %s:%d)\n",
+				file, line);
 		shm_free(l);
 		goto error;
 	}
@@ -64,30 +67,31 @@ error:
 }
 
 
-static void dyn_lock_f(int mode, struct CRYPTO_dynlock_value* l,
-						const char* file, int line)
+static void dyn_lock_f(
+		int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
 {
-	if (l==0){
+	if(l == 0) {
 		LM_CRIT("dyn lock locking callback: null lock"
-				" (called from %s:%d)\n", file, line);
+				" (called from %s:%d)\n",
+				file, line);
 		/* try to continue */
 		return;
 	}
-	if (mode & CRYPTO_LOCK){
+	if(mode & CRYPTO_LOCK) {
 		lock_get(&l->lock);
-	}else{
+	} else {
 		lock_release(&l->lock);
 	}
 }
 
 
-
-static void dyn_destroy_f(struct CRYPTO_dynlock_value *l,
-							const char* file, int line)
+static void dyn_destroy_f(
+		struct CRYPTO_dynlock_value *l, const char *file, int line)
 {
-	if (l==0){
+	if(l == 0) {
 		LM_CRIT("dyn destroy locking callback: null lock"
-				" (called from %s:%d)\n", file, line);
+				" (called from %s:%d)\n",
+				file, line);
 		return;
 	}
 	lock_destroy(&l->lock);
@@ -95,22 +99,21 @@ static void dyn_destroy_f(struct CRYPTO_dynlock_value *l,
 }
 
 
-
 /* normal locking callback */
-static void locking_f(int mode, int n, const char* file, int line)
+static void locking_f(int mode, int n, const char *file, int line)
 {
-	if (n<0 || n>=n_static_locks){
+	if(n < 0 || n >= n_static_locks) {
 		LM_CRIT("locking (callback): invalid lock number: "
 				" %d (range 0 - %d), called from %s:%d\n",
 				n, n_static_locks, file, line);
 		abort(); /* quick crash :-) */
 	}
-	if (mode & CRYPTO_LOCK){
+	if(mode & CRYPTO_LOCK) {
 #ifdef EXTRA_DEBUG
 		LM_DBG("lock get (%d): %d (%s:%d)\n", mode, n, file, line);
 #endif
 		lock_set_get(static_locks, n);
-	}else{
+	} else {
 		lock_set_release(static_locks, n);
 #ifdef EXTRA_DEBUG
 		LM_DBG("lock release (%d): %d (%s:%d)\n", mode, n, file, line);
@@ -123,11 +126,11 @@ static void locking_f(int mode, int n, const char* file, int line)
 
 void tls_destroy_locks()
 {
-	if (static_locks){
+	if(static_locks) {
 		lock_set_destroy(static_locks);
 		lock_set_dealloc(static_locks);
-		static_locks=0;
-		n_static_locks=0;
+		static_locks = 0;
+		n_static_locks = 0;
 	}
 }
 
@@ -143,27 +146,27 @@ int tls_init_locks()
 /* OpenSSL is no longer supporting to set locking callbacks since 1.1.0 */
 #if OPENSSL_VERSION_NUMBER < 0x10100000L
 	/* init "static" tls locks */
-	n_static_locks=CRYPTO_num_locks();
-	if (n_static_locks<0){
+	n_static_locks = CRYPTO_num_locks();
+	if(n_static_locks < 0) {
 		LM_CRIT("bad CRYPTO_num_locks %d\n", n_static_locks);
-		n_static_locks=0;
+		n_static_locks = 0;
 	}
-	if (n_static_locks){
-		if (CRYPTO_get_locking_callback()!=NULL) {
+	if(n_static_locks) {
+		if(CRYPTO_get_locking_callback() != NULL) {
 			LM_CRIT("ssl locking callback already set\n");
 			return -1;
 		}
-		static_locks=lock_set_alloc(n_static_locks);
-		if (static_locks==0){
+		static_locks = lock_set_alloc(n_static_locks);
+		if(static_locks == 0) {
 			LM_CRIT("could not allocate lockset with %d locks\n",
 					n_static_locks);
 			goto error;
 		}
-		if (lock_set_init(static_locks)==0){
+		if(lock_set_init(static_locks) == 0) {
 			LM_CRIT("lock set init failed (%d locks)\n", n_static_locks);
 			lock_set_dealloc(static_locks);
-			static_locks=0;
-			n_static_locks=0;
+			static_locks = 0;
+			n_static_locks = 0;
 			goto error;
 		}
 		CRYPTO_set_locking_callback(locking_f);

+ 162 - 144
src/modules/tls/tls_map.c

@@ -11,185 +11,203 @@
 #include "../../core/mem/mem.h"
 #include "tls_map.h"
 
-struct map_node_t {
-  unsigned hash;
-  void *value;
-  map_node_t *next;
-  /* char key[]; */
-  /* char value[]; */
+struct map_node_t
+{
+	unsigned hash;
+	void *value;
+	map_node_t *next;
+	/* char key[]; */
+	/* char value[]; */
 };
 
 
-static unsigned map_hash(const char *str) {
-  unsigned hash = 5381;
-  while (*str) {
-    hash = ((hash << 5) + hash) ^ *str++;
-  }
-  return hash;
+static unsigned map_hash(const char *str)
+{
+	unsigned hash = 5381;
+	while(*str) {
+		hash = ((hash << 5) + hash) ^ *str++;
+	}
+	return hash;
 }
 
 
-static map_node_t *map_newnode(const char *key, void *value, int vsize) {
-  map_node_t *node;
-  int ksize = strlen(key) + 1;
-  int voffset = ksize + ((sizeof(void*) - ksize) % sizeof(void*));
-  node = pkg_malloc(sizeof(*node) + voffset + vsize);
-  if (!node) return NULL;
-  memcpy(node + 1, key, ksize);
-  node->hash = map_hash(key);
-  node->value = ((char*) (node + 1)) + voffset;
-  memcpy(node->value, value, vsize);
-  return node;
+static map_node_t *map_newnode(const char *key, void *value, int vsize)
+{
+	map_node_t *node;
+	int ksize = strlen(key) + 1;
+	int voffset = ksize + ((sizeof(void *) - ksize) % sizeof(void *));
+	node = pkg_malloc(sizeof(*node) + voffset + vsize);
+	if(!node)
+		return NULL;
+	memcpy(node + 1, key, ksize);
+	node->hash = map_hash(key);
+	node->value = ((char *)(node + 1)) + voffset;
+	memcpy(node->value, value, vsize);
+	return node;
 }
 
 
-static int map_bucketidx(map_base_t *m, unsigned hash) {
-  /* If the implementation is changed to allow a non-power-of-2 bucket count,
+static int map_bucketidx(map_base_t *m, unsigned hash)
+{
+	/* If the implementation is changed to allow a non-power-of-2 bucket count,
    * the line below should be changed to use mod instead of AND */
-  return hash & (m->nbuckets - 1);
+	return hash & (m->nbuckets - 1);
 }
 
 
-static void map_addnode(map_base_t *m, map_node_t *node) {
-  int n = map_bucketidx(m, node->hash);
-  node->next = m->buckets[n];
-  m->buckets[n] = node;
+static void map_addnode(map_base_t *m, map_node_t *node)
+{
+	int n = map_bucketidx(m, node->hash);
+	node->next = m->buckets[n];
+	m->buckets[n] = node;
 }
 
 
-static int map_resize(map_base_t *m, int nbuckets) {
-  map_node_t *nodes, *node, *next;
-  map_node_t **buckets;
-  int i;
-  /* Chain all nodes together */
-  nodes = NULL;
-  i = m->nbuckets;
-  while (i--) {
-    node = (m->buckets)[i];
-    while (node) {
-      next = node->next;
-      node->next = nodes;
-      nodes = node;
-      node = next;
-    }
-  }
-  /* Reset buckets */
-  buckets = realloc(m->buckets, sizeof(*m->buckets) * nbuckets);
-  if (buckets != NULL) {
-    m->buckets = buckets;
-    m->nbuckets = nbuckets;
-  }
-  if (m->buckets) {
-    memset(m->buckets, 0, sizeof(*m->buckets) * m->nbuckets);
-    /* Re-add nodes to buckets */
-    node = nodes;
-    while (node) {
-      next = node->next;
-      map_addnode(m, node);
-      node = next;
-    }
-  }
-  /* Return error code if realloc() failed */
-  return (buckets == NULL) ? -1 : 0;
+static int map_resize(map_base_t *m, int nbuckets)
+{
+	map_node_t *nodes, *node, *next;
+	map_node_t **buckets;
+	int i;
+	/* Chain all nodes together */
+	nodes = NULL;
+	i = m->nbuckets;
+	while(i--) {
+		node = (m->buckets)[i];
+		while(node) {
+			next = node->next;
+			node->next = nodes;
+			nodes = node;
+			node = next;
+		}
+	}
+	/* Reset buckets */
+	buckets = realloc(m->buckets, sizeof(*m->buckets) * nbuckets);
+	if(buckets != NULL) {
+		m->buckets = buckets;
+		m->nbuckets = nbuckets;
+	}
+	if(m->buckets) {
+		memset(m->buckets, 0, sizeof(*m->buckets) * m->nbuckets);
+		/* Re-add nodes to buckets */
+		node = nodes;
+		while(node) {
+			next = node->next;
+			map_addnode(m, node);
+			node = next;
+		}
+	}
+	/* Return error code if realloc() failed */
+	return (buckets == NULL) ? -1 : 0;
 }
 
 
-static map_node_t **map_getref(map_base_t *m, const char *key) {
-  unsigned hash = map_hash(key);
-  map_node_t **next;
-  if (m->nbuckets > 0) {
-    next = &m->buckets[map_bucketidx(m, hash)];
-    while (*next) {
-      if ((*next)->hash == hash && !strcmp((char*) (*next + 1), key)) {
-        return next;
-      }
-      next = &(*next)->next;
-    }
-  }
-  return NULL;
+static map_node_t **map_getref(map_base_t *m, const char *key)
+{
+	unsigned hash = map_hash(key);
+	map_node_t **next;
+	if(m->nbuckets > 0) {
+		next = &m->buckets[map_bucketidx(m, hash)];
+		while(*next) {
+			if((*next)->hash == hash && !strcmp((char *)(*next + 1), key)) {
+				return next;
+			}
+			next = &(*next)->next;
+		}
+	}
+	return NULL;
 }
 
 
-void map_deinit_(map_base_t *m) {
-  map_node_t *next, *node;
-  int i;
-  i = m->nbuckets;
-  while (i--) {
-    node = m->buckets[i];
-    while (node) {
-      next = node->next;
-      pkg_free(node);
-      node = next;
-    }
-  }
-  pkg_free(m->buckets);
+void map_deinit_(map_base_t *m)
+{
+	map_node_t *next, *node;
+	int i;
+	i = m->nbuckets;
+	while(i--) {
+		node = m->buckets[i];
+		while(node) {
+			next = node->next;
+			pkg_free(node);
+			node = next;
+		}
+	}
+	pkg_free(m->buckets);
 }
 
 
-void *map_get_(map_base_t *m, const char *key) {
-  map_node_t **next = map_getref(m, key);
-  return next ? (*next)->value : NULL;
+void *map_get_(map_base_t *m, const char *key)
+{
+	map_node_t **next = map_getref(m, key);
+	return next ? (*next)->value : NULL;
 }
 
 
-int map_set_(map_base_t *m, const char *key, void *value, int vsize) {
-  int n, err;
-  map_node_t **next, *node;
-  /* Find & replace existing node */
-  next = map_getref(m, key);
-  if (next) {
-    memcpy((*next)->value, value, vsize);
-    return 0;
-  }
-  /* Add new node */
-  node = map_newnode(key, value, vsize);
-  if (node == NULL) goto fail;
-  if (m->nnodes >= m->nbuckets) {
-    n = (m->nbuckets > 0) ? (m->nbuckets << 1) : 1;
-    err = map_resize(m, n);
-    if (err) goto fail;
-  }
-  map_addnode(m, node);
-  m->nnodes++;
-  return 0;
-  fail:
-  if (node) pkg_free(node);
-  return -1;
+int map_set_(map_base_t *m, const char *key, void *value, int vsize)
+{
+	int n, err;
+	map_node_t **next, *node;
+	/* Find & replace existing node */
+	next = map_getref(m, key);
+	if(next) {
+		memcpy((*next)->value, value, vsize);
+		return 0;
+	}
+	/* Add new node */
+	node = map_newnode(key, value, vsize);
+	if(node == NULL)
+		goto fail;
+	if(m->nnodes >= m->nbuckets) {
+		n = (m->nbuckets > 0) ? (m->nbuckets << 1) : 1;
+		err = map_resize(m, n);
+		if(err)
+			goto fail;
+	}
+	map_addnode(m, node);
+	m->nnodes++;
+	return 0;
+fail:
+	if(node)
+		pkg_free(node);
+	return -1;
 }
 
 
-void map_remove_(map_base_t *m, const char *key) {
-  map_node_t *node;
-  map_node_t **next = map_getref(m, key);
-  if (next) {
-    node = *next;
-    *next = (*next)->next;
-    pkg_free(node);
-    m->nnodes--;
-  }
+void map_remove_(map_base_t *m, const char *key)
+{
+	map_node_t *node;
+	map_node_t **next = map_getref(m, key);
+	if(next) {
+		node = *next;
+		*next = (*next)->next;
+		pkg_free(node);
+		m->nnodes--;
+	}
 }
 
 
-map_iter_t map_iter_(void) {
-  map_iter_t iter;
-  iter.bucketidx = -1;
-  iter.node = NULL;
-  return iter;
+map_iter_t map_iter_(void)
+{
+	map_iter_t iter;
+	iter.bucketidx = -1;
+	iter.node = NULL;
+	return iter;
 }
 
 
-const char *map_next_(map_base_t *m, map_iter_t *iter) {
-  if (iter->node) {
-    iter->node = iter->node->next;
-    if (iter->node == NULL) goto nextBucket;
-  } else {
-    nextBucket:
-    do {
-      if (++iter->bucketidx >= m->nbuckets) {
-        return NULL;
-      }
-      iter->node = m->buckets[iter->bucketidx];
-    } while (iter->node == NULL);
-  }
-  return (char*) (iter->node + 1);
+const char *map_next_(map_base_t *m, map_iter_t *iter)
+{
+	if(iter->node) {
+		iter->node = iter->node->next;
+		if(iter->node == NULL)
+			goto nextBucket;
+	} else {
+	nextBucket:
+		do {
+			if(++iter->bucketidx >= m->nbuckets) {
+				return NULL;
+			}
+			iter->node = m->buckets[iter->bucketidx];
+		} while(iter->node == NULL);
+	}
+	return (char *)(iter->node + 1);
 }

+ 25 - 25
src/modules/tls/tls_map.h

@@ -15,48 +15,48 @@
 struct map_node_t;
 typedef struct map_node_t map_node_t;
 
-typedef struct {
-  map_node_t **buckets;
-  unsigned nbuckets, nnodes;
+typedef struct
+{
+	map_node_t **buckets;
+	unsigned nbuckets, nnodes;
 } map_base_t;
 
-typedef struct {
-  unsigned bucketidx;
-  map_node_t *node;
+typedef struct
+{
+	unsigned bucketidx;
+	map_node_t *node;
 } map_iter_t;
 
 
-#define map_t(T)\
-  struct { map_base_t base; T *ref; T tmp; }
+#define map_t(T)         \
+	struct               \
+	{                    \
+		map_base_t base; \
+		T *ref;          \
+		T tmp;           \
+	}
 
 
-#define map_init(m)\
-  memset(m, 0, sizeof(*(m)))
+#define map_init(m) memset(m, 0, sizeof(*(m)))
 
 
-#define map_deinit(m)\
-  map_deinit_(&(m)->base)
+#define map_deinit(m) map_deinit_(&(m)->base)
 
 
-#define map_get(m, key)\
-  ( (m)->ref = map_get_(&(m)->base, key) )
+#define map_get(m, key) ((m)->ref = map_get_(&(m)->base, key))
 
 
-#define map_set(m, key, value)\
-  ( (m)->tmp = (value),\
-    map_set_(&(m)->base, key, &(m)->tmp, sizeof((m)->tmp)) )
+#define map_set(m, key, value) \
+	((m)->tmp = (value), map_set_(&(m)->base, key, &(m)->tmp, sizeof((m)->tmp)))
 
 
-#define map_remove(m, key)\
-  map_remove_(&(m)->base, key)
+#define map_remove(m, key) map_remove_(&(m)->base, key)
 
 
-#define map_iter(m)\
-  map_iter_()
+#define map_iter(m) map_iter_()
 
 
-#define map_next(m, iter)\
-  map_next_(&(m)->base, iter)
+#define map_next(m, iter) map_next_(&(m)->base, iter)
 
 
 void map_deinit_(map_base_t *m);
@@ -67,8 +67,8 @@ map_iter_t map_iter_(void);
 const char *map_next_(map_base_t *m, map_iter_t *iter);
 
 
-typedef map_t(void*) map_void_t;
-typedef map_t(char*) map_str_t;
+typedef map_t(void *) map_void_t;
+typedef map_t(char *) map_str_t;
 typedef map_t(int) map_int_t;
 typedef map_t(char) map_char_t;
 typedef map_t(float) map_float_t;

+ 234 - 224
src/modules/tls/tls_mod.c

@@ -54,10 +54,10 @@
 #include "tls_rand.h"
 
 #ifndef TLS_HOOKS
-	#error "TLS_HOOKS must be defined, or the tls module won't work"
+#error "TLS_HOOKS must be defined, or the tls module won't work"
 #endif
 #ifdef CORE_TLS
-	#error "conflict: CORE_TLS must _not_ be defined"
+#error "conflict: CORE_TLS must _not_ be defined"
 #endif
 
 /*
@@ -80,10 +80,10 @@ static int mod_init(void);
 static int mod_child(int rank);
 static void mod_destroy(void);
 
-static int w_is_peer_verified(struct sip_msg* msg, char* p1, char* p2);
-static int w_tls_set_connect_server_id(sip_msg_t* msg, char* psrvid, char* p2);
+static int w_is_peer_verified(struct sip_msg *msg, char *p1, char *p2);
+static int w_tls_set_connect_server_id(sip_msg_t *msg, char *psrvid, char *p2);
 
-int ksr_rand_engine_param(modparam_t type, void* val);
+int ksr_rand_engine_param(modparam_t type, void *val);
 
 MODULE_VERSION
 
@@ -94,25 +94,25 @@ str sr_tls_xavp_cfg = {0, 0};
  * Default settings when modparams are used
  */
 static tls_domain_t mod_params = {
-	TLS_DOMAIN_DEF | TLS_DOMAIN_SRV,   /* Domain Type */
-	{},               /* IP address */
-	0,                /* Port number */
-	0,                /* SSL ctx */
-	STR_STATIC_INIT(TLS_CERT_FILE),    /* Certificate file */
-	STR_STATIC_INIT(TLS_PKEY_FILE),    /* Private key file */
-	0,                /* Verify certificate */
-	9,                /* Verify depth */
-	STR_STATIC_INIT(TLS_CA_FILE),      /* CA file */
-	STR_STATIC_INIT(TLS_CA_PATH),      /* CA path */
-	0,                /* Require certificate */
-	{0, 0},                /* Cipher list */
-	TLS_USE_TLSv1_PLUS,   /* TLS method */
-	STR_STATIC_INIT(TLS_CRL_FILE), /* Certificate revocation list */
-	{0, 0},           /* Server name (SNI) */
-	0,                /* Server name (SNI) mode */
-	{0, 0},           /* Server id */
-	TLS_VERIFY_CLIENT_OFF,             /* Verify client */
-	0                 /* next */
+		TLS_DOMAIN_DEF | TLS_DOMAIN_SRV, /* Domain Type */
+		{},								 /* IP address */
+		0,								 /* Port number */
+		0,								 /* SSL ctx */
+		STR_STATIC_INIT(TLS_CERT_FILE),	 /* Certificate file */
+		STR_STATIC_INIT(TLS_PKEY_FILE),	 /* Private key file */
+		0,								 /* Verify certificate */
+		9,								 /* Verify depth */
+		STR_STATIC_INIT(TLS_CA_FILE),	 /* CA file */
+		STR_STATIC_INIT(TLS_CA_PATH),	 /* CA path */
+		0,								 /* Require certificate */
+		{0, 0},							 /* Cipher list */
+		TLS_USE_TLSv1_PLUS,				 /* TLS method */
+		STR_STATIC_INIT(TLS_CRL_FILE),	 /* Certificate revocation list */
+		{0, 0},							 /* Server name (SNI) */
+		0,								 /* Server name (SNI) mode */
+		{0, 0},							 /* Server id */
+		TLS_VERIFY_CLIENT_OFF,			 /* Verify client */
+		0								 /* next */
 };
 
 
@@ -120,77 +120,77 @@ static tls_domain_t mod_params = {
  * Default settings for server domains when using external config file
  */
 tls_domain_t srv_defaults = {
-	TLS_DOMAIN_DEF | TLS_DOMAIN_SRV,   /* Domain Type */
-	{},               /* IP address */
-	0,                /* Port number */
-	0,                /* SSL ctx */
-	STR_STATIC_INIT(TLS_CERT_FILE),    /* Certificate file */
-	STR_STATIC_INIT(TLS_PKEY_FILE),    /* Private key file */
-	0,                /* Verify certificate */
-	9,                /* Verify depth */
-	STR_STATIC_INIT(TLS_CA_FILE),      /* CA file */
-	STR_STATIC_INIT(TLS_CA_PATH),      /* CA path */
-	0,                /* Require certificate */
-	{0, 0},                /* Cipher list */
-	TLS_USE_TLSv1_PLUS,    /* TLS method */
-	STR_STATIC_INIT(TLS_CRL_FILE), /* Certificate revocation list */
-	{0, 0},           /* Server name (SNI) */
-	0,                /* Server name (SNI) mode */
-	{0, 0},           /* Server id */
-	TLS_VERIFY_CLIENT_OFF,             /* Verify client */
-	0                 /* next */
+		TLS_DOMAIN_DEF | TLS_DOMAIN_SRV, /* Domain Type */
+		{},								 /* IP address */
+		0,								 /* Port number */
+		0,								 /* SSL ctx */
+		STR_STATIC_INIT(TLS_CERT_FILE),	 /* Certificate file */
+		STR_STATIC_INIT(TLS_PKEY_FILE),	 /* Private key file */
+		0,								 /* Verify certificate */
+		9,								 /* Verify depth */
+		STR_STATIC_INIT(TLS_CA_FILE),	 /* CA file */
+		STR_STATIC_INIT(TLS_CA_PATH),	 /* CA path */
+		0,								 /* Require certificate */
+		{0, 0},							 /* Cipher list */
+		TLS_USE_TLSv1_PLUS,				 /* TLS method */
+		STR_STATIC_INIT(TLS_CRL_FILE),	 /* Certificate revocation list */
+		{0, 0},							 /* Server name (SNI) */
+		0,								 /* Server name (SNI) mode */
+		{0, 0},							 /* Server id */
+		TLS_VERIFY_CLIENT_OFF,			 /* Verify client */
+		0								 /* next */
 };
 
 
 #ifndef OPENSSL_NO_ENGINE
 
-typedef struct tls_engine {
-        str engine;
-        str engine_config;
-        str engine_algorithms;
+typedef struct tls_engine
+{
+	str engine;
+	str engine_config;
+	str engine_algorithms;
 } tls_engine_t;
 #include <openssl/conf.h>
 #include <openssl/engine.h>
 
 static ENGINE *ksr_tls_engine;
 static tls_engine_t tls_engine_settings = {
-	STR_STATIC_INIT("NONE"),
-	STR_STATIC_INIT("NONE"),
-	STR_STATIC_INIT("ALL"),
+		STR_STATIC_INIT("NONE"),
+		STR_STATIC_INIT("NONE"),
+		STR_STATIC_INIT("ALL"),
 };
 #endif /* OPENSSL_NO_ENGINE */
 /*
  * Default settings for client domains when using external config file
  */
 tls_domain_t cli_defaults = {
-	TLS_DOMAIN_DEF | TLS_DOMAIN_CLI,   /* Domain Type */
-	{},               /* IP address */
-	0,                /* Port number */
-	0,                /* SSL ctx */
-	{0, 0},                /* Certificate file */
-	{0, 0},                /* Private key file */
-	0,                /* Verify certificate */
-	9,                /* Verify depth */
-	STR_STATIC_INIT(TLS_CA_FILE),      /* CA file */
-	STR_STATIC_INIT(TLS_CA_PATH),      /* CA path */
-	0,                /* Require certificate */
-	{0, 0},                /* Cipher list */
-	TLS_USE_TLSv1_PLUS,    /* TLS method */
-	{0, 0}, /* Certificate revocation list */
-	{0, 0},           /* Server name (SNI) */
-	0,                /* Server name (SNI) mode */
-	{0, 0},           /* Server id */
-	TLS_VERIFY_CLIENT_OFF,             /* Verify client */
-	0                 /* next */
+		TLS_DOMAIN_DEF | TLS_DOMAIN_CLI, /* Domain Type */
+		{},								 /* IP address */
+		0,								 /* Port number */
+		0,								 /* SSL ctx */
+		{0, 0},							 /* Certificate file */
+		{0, 0},							 /* Private key file */
+		0,								 /* Verify certificate */
+		9,								 /* Verify depth */
+		STR_STATIC_INIT(TLS_CA_FILE),	 /* CA file */
+		STR_STATIC_INIT(TLS_CA_PATH),	 /* CA path */
+		0,								 /* Require certificate */
+		{0, 0},							 /* Cipher list */
+		TLS_USE_TLSv1_PLUS,				 /* TLS method */
+		{0, 0},							 /* Certificate revocation list */
+		{0, 0},							 /* Server name (SNI) */
+		0,								 /* Server name (SNI) mode */
+		{0, 0},							 /* Server id */
+		TLS_VERIFY_CLIENT_OFF,			 /* Verify client */
+		0								 /* next */
 };
 
 
-
 /* Current TLS configuration */
-tls_domains_cfg_t** tls_domains_cfg = NULL;
+tls_domains_cfg_t **tls_domains_cfg = NULL;
 
 /* List lock, used by garbage collector */
-gen_lock_t* tls_domains_cfg_lock = NULL;
+gen_lock_t *tls_domains_cfg_lock = NULL;
 
 
 int sr_tls_renegotiation = 0;
@@ -200,63 +200,64 @@ int ksr_tls_init_mode = 0;
  * Exported functions
  */
 static cmd_export_t cmds[] = {
-	{"is_peer_verified", (cmd_function)w_is_peer_verified,   0, 0, 0,
-			REQUEST_ROUTE},
-	{"tls_set_connect_server_id", (cmd_function)w_tls_set_connect_server_id,
-		1, fixup_spve_null, fixup_free_spve_null, ANY_ROUTE},
-	{0,0,0,0,0,0}
-};
+		{"is_peer_verified", (cmd_function)w_is_peer_verified, 0, 0, 0,
+				REQUEST_ROUTE},
+		{"tls_set_connect_server_id", (cmd_function)w_tls_set_connect_server_id,
+				1, fixup_spve_null, fixup_free_spve_null, ANY_ROUTE},
+		{0, 0, 0, 0, 0, 0}};
 
 
 /*
  * Exported parameters
  */
 static param_export_t params[] = {
-	{"tls_method",          PARAM_STR,    &default_tls_cfg.method       },
-	{"server_name",         PARAM_STR,    &default_tls_cfg.server_name  },
-	{"verify_certificate",  PARAM_INT,    &default_tls_cfg.verify_cert  },
-	{"verify_depth",        PARAM_INT,    &default_tls_cfg.verify_depth },
-	{"require_certificate", PARAM_INT,    &default_tls_cfg.require_cert },
-	{"verify_client",       PARAM_STR,    &default_tls_cfg.verify_client},
-	{"private_key",         PARAM_STR,    &default_tls_cfg.private_key  },
-	{"ca_list",             PARAM_STR,    &default_tls_cfg.ca_list      },
-	{"ca_path",             PARAM_STR,    &default_tls_cfg.ca_path      },
-	{"certificate",         PARAM_STR,    &default_tls_cfg.certificate  },
-	{"crl",                 PARAM_STR,    &default_tls_cfg.crl          },
-	{"cipher_list",         PARAM_STR,    &default_tls_cfg.cipher_list  },
-	{"connection_timeout",  PARAM_INT,    &default_tls_cfg.con_lifetime },
+		{"tls_method", PARAM_STR, &default_tls_cfg.method},
+		{"server_name", PARAM_STR, &default_tls_cfg.server_name},
+		{"verify_certificate", PARAM_INT, &default_tls_cfg.verify_cert},
+		{"verify_depth", PARAM_INT, &default_tls_cfg.verify_depth},
+		{"require_certificate", PARAM_INT, &default_tls_cfg.require_cert},
+		{"verify_client", PARAM_STR, &default_tls_cfg.verify_client},
+		{"private_key", PARAM_STR, &default_tls_cfg.private_key},
+		{"ca_list", PARAM_STR, &default_tls_cfg.ca_list},
+		{"ca_path", PARAM_STR, &default_tls_cfg.ca_path},
+		{"certificate", PARAM_STR, &default_tls_cfg.certificate},
+		{"crl", PARAM_STR, &default_tls_cfg.crl},
+		{"cipher_list", PARAM_STR, &default_tls_cfg.cipher_list},
+		{"connection_timeout", PARAM_INT, &default_tls_cfg.con_lifetime},
 #ifndef OPENSSL_NO_ENGINE
-	{"engine",              PARAM_STR,    &tls_engine_settings.engine  },
-	{"engine_config",       PARAM_STR,    &tls_engine_settings.engine_config },
-	{"engine_algorithms",   PARAM_STR,    &tls_engine_settings.engine_algorithms },
+		{"engine", PARAM_STR, &tls_engine_settings.engine},
+		{"engine_config", PARAM_STR, &tls_engine_settings.engine_config},
+		{"engine_algorithms", PARAM_STR,
+				&tls_engine_settings.engine_algorithms},
 #endif /* OPENSSL_NO_ENGINE */
-	{"tls_log",             PARAM_INT,    &default_tls_cfg.log          },
-	{"tls_debug",           PARAM_INT,    &default_tls_cfg.debug        },
-	{"session_cache",       PARAM_INT,    &default_tls_cfg.session_cache},
-	{"session_id",          PARAM_STR,    &default_tls_cfg.session_id   },
-	{"config",              PARAM_STR,    &default_tls_cfg.config_file  },
-	{"tls_disable_compression", PARAM_INT,
-										&default_tls_cfg.disable_compression},
-	{"ssl_release_buffers",   PARAM_INT, &default_tls_cfg.ssl_release_buffers},
-	{"ssl_freelist_max_len",  PARAM_INT,  &default_tls_cfg.ssl_freelist_max},
-	{"ssl_max_send_fragment", PARAM_INT,
-										&default_tls_cfg.ssl_max_send_fragment},
-	{"ssl_read_ahead",        PARAM_INT,    &default_tls_cfg.ssl_read_ahead},
-	{"send_close_notify",   PARAM_INT,    &default_tls_cfg.send_close_notify},
-	{"con_ct_wq_max",      PARAM_INT,    &default_tls_cfg.con_ct_wq_max},
-	{"ct_wq_max",          PARAM_INT,    &default_tls_cfg.ct_wq_max},
-	{"ct_wq_blk_size",     PARAM_INT,    &default_tls_cfg.ct_wq_blk_size},
-	{"tls_force_run",       PARAM_INT,    &default_tls_cfg.force_run},
-	{"low_mem_threshold1",  PARAM_INT,    &default_tls_cfg.low_mem_threshold1},
-	{"low_mem_threshold2",  PARAM_INT,    &default_tls_cfg.low_mem_threshold2},
-	{"renegotiation",       PARAM_INT,    &sr_tls_renegotiation},
-	{"xavp_cfg",            PARAM_STR,    &sr_tls_xavp_cfg},
-	{"event_callback",      PARAM_STR,    &sr_tls_event_callback},
-	{"rand_engine",         PARAM_STR|USE_FUNC_PARAM, (void*)ksr_rand_engine_param},
-	{"init_mode",           PARAM_INT,    &ksr_tls_init_mode},
-
-	{0, 0, 0}
-};
+		{"tls_log", PARAM_INT, &default_tls_cfg.log},
+		{"tls_debug", PARAM_INT, &default_tls_cfg.debug},
+		{"session_cache", PARAM_INT, &default_tls_cfg.session_cache},
+		{"session_id", PARAM_STR, &default_tls_cfg.session_id},
+		{"config", PARAM_STR, &default_tls_cfg.config_file},
+		{"tls_disable_compression", PARAM_INT,
+				&default_tls_cfg.disable_compression},
+		{"ssl_release_buffers", PARAM_INT,
+				&default_tls_cfg.ssl_release_buffers},
+		{"ssl_freelist_max_len", PARAM_INT, &default_tls_cfg.ssl_freelist_max},
+		{"ssl_max_send_fragment", PARAM_INT,
+				&default_tls_cfg.ssl_max_send_fragment},
+		{"ssl_read_ahead", PARAM_INT, &default_tls_cfg.ssl_read_ahead},
+		{"send_close_notify", PARAM_INT, &default_tls_cfg.send_close_notify},
+		{"con_ct_wq_max", PARAM_INT, &default_tls_cfg.con_ct_wq_max},
+		{"ct_wq_max", PARAM_INT, &default_tls_cfg.ct_wq_max},
+		{"ct_wq_blk_size", PARAM_INT, &default_tls_cfg.ct_wq_blk_size},
+		{"tls_force_run", PARAM_INT, &default_tls_cfg.force_run},
+		{"low_mem_threshold1", PARAM_INT, &default_tls_cfg.low_mem_threshold1},
+		{"low_mem_threshold2", PARAM_INT, &default_tls_cfg.low_mem_threshold2},
+		{"renegotiation", PARAM_INT, &sr_tls_renegotiation},
+		{"xavp_cfg", PARAM_STR, &sr_tls_xavp_cfg},
+		{"event_callback", PARAM_STR, &sr_tls_event_callback},
+		{"rand_engine", PARAM_STR | USE_FUNC_PARAM,
+				(void *)ksr_rand_engine_param},
+		{"init_mode", PARAM_INT, &ksr_tls_init_mode},
+
+		{0, 0, 0}};
 
 #ifndef MOD_NAME
 #define MOD_NAME "tls"
@@ -266,34 +267,32 @@ static param_export_t params[] = {
  * Module interface
  */
 struct module_exports exports = {
-	MOD_NAME,        /* module name */
-	DEFAULT_DLFLAGS, /* dlopen flags */
-	cmds,            /* exported functions */
-	params,          /* exported parameters */
-	0,               /* exported rpc command */
-	tls_pv,          /* exported pseudo-variables */
-	0,               /* response handling function */
-	mod_init,        /* module init function */
-	mod_child,       /* child initi function */
-	mod_destroy      /* destroy function */
+		MOD_NAME,		 /* module name */
+		DEFAULT_DLFLAGS, /* dlopen flags */
+		cmds,			 /* exported functions */
+		params,			 /* exported parameters */
+		0,				 /* exported rpc command */
+		tls_pv,			 /* exported pseudo-variables */
+		0,				 /* response handling function */
+		mod_init,		 /* module init function */
+		mod_child,		 /* child initi function */
+		mod_destroy		 /* destroy function */
 };
 
 
-
 static struct tls_hooks tls_h = {
-	tls_h_read_f,
-	tls_h_encode_f,
-	tls_h_tcpconn_init_f,
-	tls_h_tcpconn_clean_f,
-	tls_h_tcpconn_close_f,
-	tls_h_init_si_f,
-	tls_h_mod_init_f,
-	tls_h_mod_destroy_f,
-	tls_h_mod_pre_init_f,
+		tls_h_read_f,
+		tls_h_encode_f,
+		tls_h_tcpconn_init_f,
+		tls_h_tcpconn_clean_f,
+		tls_h_tcpconn_close_f,
+		tls_h_init_si_f,
+		tls_h_mod_init_f,
+		tls_h_mod_destroy_f,
+		tls_h_mod_pre_init_f,
 };
 
 
-
 #if 0
 /*
  * Create TLS configuration from modparams
@@ -315,24 +314,24 @@ static int mod_init(void)
 	int method;
 	int verify_client;
 
-	if (tls_disable){
+	if(tls_disable) {
 		LM_WARN("tls support is disabled "
 				"(set enable_tls=1 in the config to enable it)\n");
 		return 0;
 	}
-	if (fix_tls_cfg(&default_tls_cfg) < 0 ) {
+	if(fix_tls_cfg(&default_tls_cfg) < 0) {
 		LM_ERR("initial tls configuration fixup failed\n");
 		return -1;
 	}
 	/* declare configuration */
-	if (cfg_declare("tls", tls_cfg_def, &default_tls_cfg,
-							cfg_sizeof(tls), (void **)&tls_cfg)) {
+	if(cfg_declare("tls", tls_cfg_def, &default_tls_cfg, cfg_sizeof(tls),
+			   (void **)&tls_cfg)) {
 		LM_ERR("failed to register the configuration\n");
 		return -1;
 	}
 	/* Convert tls_method parameter to integer */
 	method = tls_parse_method(&cfg_get(tls, tls_cfg, method));
-	if (method < 0) {
+	if(method < 0) {
 		LM_ERR("Invalid tls_method parameter value\n");
 		return -1;
 	}
@@ -348,16 +347,17 @@ static int mod_init(void)
 	mod_params.cipher_list = cfg_get(tls, tls_cfg, cipher_list);
 	mod_params.server_name = cfg_get(tls, tls_cfg, server_name);
 	/* Convert verify_client parameter to integer */
-	verify_client = tls_parse_verify_client(&cfg_get(tls, tls_cfg, verify_client));
-	if (verify_client < 0) {
+	verify_client =
+			tls_parse_verify_client(&cfg_get(tls, tls_cfg, verify_client));
+	if(verify_client < 0) {
 		LM_ERR("Invalid tls_method parameter value\n");
 		return -1;
 	}
 	mod_params.verify_client = verify_client;
 
 	tls_domains_cfg =
-			(tls_domains_cfg_t**)shm_malloc(sizeof(tls_domains_cfg_t*));
-	if (!tls_domains_cfg) {
+			(tls_domains_cfg_t **)shm_malloc(sizeof(tls_domains_cfg_t *));
+	if(!tls_domains_cfg) {
 		LM_ERR("Not enough shared memory left\n");
 		goto error;
 	}
@@ -365,7 +365,7 @@ static int mod_init(void)
 
 	register_select_table(tls_sel);
 	/* register the rpc interface */
-	if (rpc_register_array(tls_rpc)!=0) {
+	if(rpc_register_array(tls_rpc) != 0) {
 		LM_ERR("failed to register RPC commands\n");
 		goto error;
 	}
@@ -373,32 +373,33 @@ static int mod_init(void)
 	/* if (init_tls() < 0) return -1; */
 
 	tls_domains_cfg_lock = lock_alloc();
-	if (tls_domains_cfg_lock == 0) {
+	if(tls_domains_cfg_lock == 0) {
 		LM_ERR("Unable to create TLS configuration lock\n");
 		goto error;
 	}
-	if (lock_init(tls_domains_cfg_lock) == 0) {
+	if(lock_init(tls_domains_cfg_lock) == 0) {
 		lock_dealloc(tls_domains_cfg_lock);
 		ERR("Unable to initialize TLS configuration lock\n");
 		goto error;
 	}
-	if (tls_ct_wq_init() < 0) {
+	if(tls_ct_wq_init() < 0) {
 		LM_ERR("Unable to initialize TLS buffering\n");
 		goto error;
 	}
-	if (cfg_get(tls, tls_cfg, config_file).s) {
-		*tls_domains_cfg =
-			tls_load_config(&cfg_get(tls, tls_cfg, config_file));
-		if (!(*tls_domains_cfg)) goto error;
+	if(cfg_get(tls, tls_cfg, config_file).s) {
+		*tls_domains_cfg = tls_load_config(&cfg_get(tls, tls_cfg, config_file));
+		if(!(*tls_domains_cfg))
+			goto error;
 	} else {
 		*tls_domains_cfg = tls_new_cfg();
-		if (!(*tls_domains_cfg)) goto error;
+		if(!(*tls_domains_cfg))
+			goto error;
 	}
 
-	if (tls_check_sockets(*tls_domains_cfg) < 0)
+	if(tls_check_sockets(*tls_domains_cfg) < 0)
 		goto error;
 
-	if (ksr_tls_lock_init() < 0) {
+	if(ksr_tls_lock_init() < 0) {
 		goto error;
 	}
 
@@ -409,7 +410,7 @@ static int mod_init(void)
 #ifndef OPENSSL_NO_DH
 	LM_INFO("With Diffie Hellman\n");
 #endif
-	if(sr_tls_event_callback.s==NULL || sr_tls_event_callback.len<=0) {
+	if(sr_tls_event_callback.s == NULL || sr_tls_event_callback.len <= 0) {
 		tls_lookup_event_routes();
 	}
 #if OPENSSL_VERSION_NUMBER >= 0x010101000L
@@ -417,7 +418,7 @@ static int mod_init(void)
 	 * register the need to be called post-fork of all children
 	 * with the special rank PROC_POSTCHILDINIT
 	 */
-	if(ksr_tls_init_mode&TLS_MODE_FORK_PREPARE) {
+	if(ksr_tls_init_mode & TLS_MODE_FORK_PREPARE) {
 		ksr_module_set_flag(KSRMOD_FLAG_POSTCHILDINIT);
 	}
 #endif
@@ -430,28 +431,29 @@ error:
 
 #ifndef OPENSSL_NO_ENGINE
 static int tls_engine_init();
-int tls_fix_engine_keys(tls_domains_cfg_t*, tls_domain_t*, tls_domain_t*);
+int tls_fix_engine_keys(tls_domains_cfg_t *, tls_domain_t *, tls_domain_t *);
 #endif
 
 static int mod_child(int rank)
 {
-	if (tls_disable || (tls_domains_cfg==0))
+	if(tls_disable || (tls_domains_cfg == 0))
 		return 0;
 
 	/* fix tls config only from the main proc/PROC_INIT., when we know
 	 * the exact process number and before any other process starts*/
-	if (rank == PROC_INIT){
-		if (cfg_get(tls, tls_cfg, config_file).s){
-			if (tls_fix_domains_cfg(*tls_domains_cfg,
-									&srv_defaults, &cli_defaults) < 0)
+	if(rank == PROC_INIT) {
+		if(cfg_get(tls, tls_cfg, config_file).s) {
+			if(tls_fix_domains_cfg(
+					   *tls_domains_cfg, &srv_defaults, &cli_defaults)
+					< 0)
 				return -1;
-		}else{
-			if (tls_fix_domains_cfg(*tls_domains_cfg,
-									&mod_params, &mod_params) < 0)
+		} else {
+			if(tls_fix_domains_cfg(*tls_domains_cfg, &mod_params, &mod_params)
+					< 0)
 				return -1;
 		}
 #if OPENSSL_VERSION_NUMBER >= 0x010101000L
-		if(ksr_tls_init_mode&TLS_MODE_FORK_PREPARE) {
+		if(ksr_tls_init_mode & TLS_MODE_FORK_PREPARE) {
 			OPENSSL_fork_prepare();
 		}
 #endif
@@ -459,15 +461,15 @@ static int mod_child(int rank)
 	}
 
 #if OPENSSL_VERSION_NUMBER >= 0x010101000L
-	if(ksr_tls_init_mode&TLS_MODE_FORK_PREPARE) {
-		if(rank==PROC_POSTCHILDINIT) {
+	if(ksr_tls_init_mode & TLS_MODE_FORK_PREPARE) {
+		if(rank == PROC_POSTCHILDINIT) {
 			/*
 			 * this is called after forking of all child processes
 			 */
 			OPENSSL_fork_parent();
 			return 0;
 		}
-		if (!_ksr_is_main) {
+		if(!_ksr_is_main) {
 			OPENSSL_fork_child();
 		}
 	}
@@ -478,12 +480,14 @@ static int mod_child(int rank)
 	 * after the child is fork()ed we go through the TLS domains
 	 * and fix up private keys from engine
 	 */
-	if (!strncmp(tls_engine_settings.engine.s, "NONE", 4)) return 0;
+	if(!strncmp(tls_engine_settings.engine.s, "NONE", 4))
+		return 0;
 
-	if (rank > 0) {
-		if (tls_engine_init() < 0)
+	if(rank > 0) {
+		if(tls_engine_init() < 0)
 			return -1;
-		if (tls_fix_engine_keys(*tls_domains_cfg, &srv_defaults, &cli_defaults)<0)
+		if(tls_fix_engine_keys(*tls_domains_cfg, &srv_defaults, &cli_defaults)
+				< 0)
 			return -1;
 		LM_INFO("OpenSSL Engine loaded private keys in child: %d\n", rank);
 	}
@@ -499,15 +503,15 @@ static void mod_destroy(void)
 }
 
 
-int ksr_rand_engine_param(modparam_t type, void* val)
+int ksr_rand_engine_param(modparam_t type, void *val)
 {
 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
 	str *reng;
 
-	if(val==NULL) {
+	if(val == NULL) {
 		return -1;
 	}
-	reng = (str*)val;
+	reng = (str *)val;
 	LM_DBG("random engine: %.*s\n", reng->len, reng->s);
 	if(reng->len == 5 && strncasecmp(reng->s, "krand", 5) == 0) {
 		LM_DBG("setting krand random engine\n");
@@ -515,10 +519,10 @@ int ksr_rand_engine_param(modparam_t type, void* val)
 	} else if(reng->len == 8 && strncasecmp(reng->s, "fastrand", 8) == 0) {
 		LM_DBG("setting fastrand random engine\n");
 		RAND_set_rand_method(RAND_ksr_fastrand_method());
-	} else if (reng->len == 10 && strncasecmp(reng->s, "cryptorand", 10) == 0) {
+	} else if(reng->len == 10 && strncasecmp(reng->s, "cryptorand", 10) == 0) {
 		LM_DBG("setting cryptorand random engine\n");
 		RAND_set_rand_method(RAND_ksr_cryptorand_method());
-	} else if (reng->len == 8 && strncasecmp(reng->s, "kxlibssl", 8) == 0) {
+	} else if(reng->len == 8 && strncasecmp(reng->s, "kxlibssl", 8) == 0) {
 		LM_DBG("setting kxlibssl random engine\n");
 		RAND_set_rand_method(RAND_ksr_kxlibssl_method());
 	}
@@ -526,7 +530,7 @@ int ksr_rand_engine_param(modparam_t type, void* val)
 	return 0;
 }
 
-static int ki_is_peer_verified(sip_msg_t* msg)
+static int ki_is_peer_verified(sip_msg_t *msg)
 {
 	struct tcp_connection *c;
 	SSL *ssl;
@@ -534,7 +538,7 @@ static int ki_is_peer_verified(sip_msg_t* msg)
 	X509 *x509_cert;
 
 	LM_DBG("started...\n");
-	if (msg->rcv.proto != PROTO_TLS) {
+	if(msg->rcv.proto != PROTO_TLS) {
 		LM_ERR("proto != TLS --> peer can't be verified, return -1\n");
 		return -1;
 	}
@@ -542,8 +546,8 @@ static int ki_is_peer_verified(sip_msg_t* msg)
 	LM_DBG("trying to find TCP connection of received message...\n");
 
 	c = tcpconn_get(msg->rcv.proto_reserved1, 0, 0, 0,
-					cfg_get(tls, tls_cfg, con_lifetime));
-	if (!c) {
+			cfg_get(tls, tls_cfg, con_lifetime));
+	if(!c) {
 		LM_ERR("connection no longer exists\n");
 		return -1;
 	}
@@ -554,17 +558,17 @@ static int ki_is_peer_verified(sip_msg_t* msg)
 		return -1;
 	}
 
-	if (!c->extra_data) {
+	if(!c->extra_data) {
 		LM_ERR("no extra_data specified in TLS/TCP connection found."
-				" This should not happen... return -1\n");
+			   " This should not happen... return -1\n");
 		tcpconn_put(c);
 		return -1;
 	}
 
-	ssl = ((struct tls_extra_data*)c->extra_data)->ssl;
+	ssl = ((struct tls_extra_data *)c->extra_data)->ssl;
 
 	ssl_verify = SSL_get_verify_result(ssl);
-	if ( ssl_verify != X509_V_OK ) {
+	if(ssl_verify != X509_V_OK) {
 		LM_WARN("verification of presented certificate failed... return -1\n");
 		tcpconn_put(c);
 		return -1;
@@ -574,9 +578,9 @@ static int ki_is_peer_verified(sip_msg_t* msg)
 	 * Thus we have to check for the existence of a peer certificate
 	 */
 	x509_cert = SSL_get_peer_certificate(ssl);
-	if ( x509_cert == NULL ) {
+	if(x509_cert == NULL) {
 		LM_INFO("tlsops:is_peer_verified: WARNING: peer did not present "
-			"a certificate. Thus it could not be verified... return -1\n");
+				"a certificate. Thus it could not be verified... return -1\n");
 		tcpconn_put(c);
 		return -1;
 	}
@@ -586,29 +590,29 @@ static int ki_is_peer_verified(sip_msg_t* msg)
 	tcpconn_put(c);
 
 	LM_DBG("tlsops:is_peer_verified: peer is successfully verified"
-		"...done\n");
+		   "...done\n");
 	return 1;
 }
 
-static int w_is_peer_verified(struct sip_msg* msg, char* foo, char* foo2)
+static int w_is_peer_verified(struct sip_msg *msg, char *foo, char *foo2)
 {
 	return ki_is_peer_verified(msg);
 }
 
-static int ki_tls_set_connect_server_id(sip_msg_t* msg, str* srvid)
+static int ki_tls_set_connect_server_id(sip_msg_t *msg, str *srvid)
 {
-	if(ksr_tls_set_connect_server_id(srvid)<0) {
+	if(ksr_tls_set_connect_server_id(srvid) < 0) {
 		return -1;
 	}
 
 	return 1;
 }
 
-static int w_tls_set_connect_server_id(sip_msg_t* msg, char* psrvid, char* p2)
+static int w_tls_set_connect_server_id(sip_msg_t *msg, char *psrvid, char *p2)
 {
 	str ssrvid = STR_NULL;
 
-	if(fixup_get_svalue(msg, (gparam_t*)psrvid, &ssrvid)<0) {
+	if(fixup_get_svalue(msg, (gparam_t *)psrvid, &ssrvid) < 0) {
 		LM_ERR("failed to get server id parameter\n");
 		return -1;
 	}
@@ -619,7 +623,7 @@ static int w_tls_set_connect_server_id(sip_msg_t* msg, char* psrvid, char* p2)
 /**
  *
  */
-static sr_kemi_xval_t* ki_tls_cget(sip_msg_t *msg, str *aname)
+static sr_kemi_xval_t *ki_tls_cget(sip_msg_t *msg, str *aname)
 {
 	return ki_tls_cget_attr(msg, aname);
 }
@@ -654,17 +658,17 @@ static sr_kemi_t sr_kemi_tls_exports[] = {
  */
 int mod_register(char *path, int *dlflags, void *p1, void *p2)
 {
-	if (tls_disable) {
+	if(tls_disable) {
 		LM_WARN("tls support is disabled "
 				"(set enable_tls=1 in the config to enable it)\n");
 		return 0;
 	}
 
 	/* shm is used, be sure it is initialized */
-	if(!shm_initialized() && init_shm()<0)
+	if(!shm_initialized() && init_shm() < 0)
 		return -1;
 
-	if(tls_pre_init()<0)
+	if(tls_pre_init() < 0)
 		return -1;
 
 	register_tls_hooks(&tls_h);
@@ -680,7 +684,6 @@ int mod_register(char *path, int *dlflags, void *p1, void *p2)
 }
 
 
-
 #ifndef OPENSSL_NO_ENGINE
 /*
  * initialize OpenSSL engine in child process
@@ -693,20 +696,22 @@ static int tls_engine_init()
 	char *engine_id;
 	int rc;
 	long errline;
-	CONF* config;
-	STACK_OF(CONF_VALUE) *stack;
+	CONF *config;
+	STACK_OF(CONF_VALUE) * stack;
 	CONF_VALUE *confval;
 	ENGINE *e;
 
-	LM_INFO("With OpenSSL engine support %*s\n", tls_engine_settings.engine_config.len, tls_engine_settings.engine_config.s);
+	LM_INFO("With OpenSSL engine support %*s\n",
+			tls_engine_settings.engine_config.len,
+			tls_engine_settings.engine_config.s);
 
 	/*
 	 * #2839: don't use CONF_modules_load_file():
 	 * We are in the child process and the global engine linked-list
 	 * is initialized in the parent.
 	 */
-	e  = ENGINE_by_id("dynamic");
-	if (!e) {
+	e = ENGINE_by_id("dynamic");
+	if(!e) {
 		err = "Error loading dynamic engine";
 		goto error;
 	}
@@ -714,7 +719,7 @@ static int tls_engine_init()
 
 	config = NCONF_new(NULL);
 	rc = NCONF_load(config, tls_engine_settings.engine_config.s, &errline);
-	if (!rc) {
+	if(!rc) {
 		err = "Error loading OpenSSL configuration file";
 		goto error;
 	}
@@ -724,34 +729,38 @@ static int tls_engine_init()
 	engine_section = NCONF_get_string(config, engines_section, engine_id);
 	stack = NCONF_get_section(config, engine_section);
 
-	if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", NCONF_get_string(config, engine_section, "dynamic_path"), 0)) {
+	if(!ENGINE_ctrl_cmd_string(e, "SO_PATH",
+			   NCONF_get_string(config, engine_section, "dynamic_path"), 0)) {
 		err = "SO_PATH";
 		goto error;
 	}
-	if (!ENGINE_ctrl_cmd_string(e, "ID", engine_id, 0)) {
+	if(!ENGINE_ctrl_cmd_string(e, "ID", engine_id, 0)) {
 		err = "ID";
 		goto error;
 	}
-	if (!ENGINE_ctrl_cmd(e, "LOAD", 1, NULL, NULL, 0)) {
+	if(!ENGINE_ctrl_cmd(e, "LOAD", 1, NULL, NULL, 0)) {
 		err = "LOAD";
 		goto error;
 	}
 	while((confval = sk_CONF_VALUE_pop(stack))) {
-		if (strcmp(confval->name, "dynamic_path") == 0) continue;
-		LM_DBG("Configuring OpenSSL engine %s: %s(%s)\n", engine_id, confval->name, confval->value);
-		if (!ENGINE_ctrl_cmd_string(e, confval->name, confval->value, 0)) {
+		if(strcmp(confval->name, "dynamic_path") == 0)
+			continue;
+		LM_DBG("Configuring OpenSSL engine %s: %s(%s)\n", engine_id,
+				confval->name, confval->value);
+		if(!ENGINE_ctrl_cmd_string(e, confval->name, confval->value, 0)) {
 			err = confval->name;
 			goto error;
 		}
 	}
 
-	if (!ENGINE_init(e)) {
+	if(!ENGINE_init(e)) {
 		err = "ENGINE_init()";
 		goto error;
 	}
-	if (strncmp(tls_engine_settings.engine_algorithms.s, "NONE", 4)) {
-		rc = ENGINE_set_default_string(e, tls_engine_settings.engine_algorithms.s);
-		if (!rc) {
+	if(strncmp(tls_engine_settings.engine_algorithms.s, "NONE", 4)) {
+		rc = ENGINE_set_default_string(
+				e, tls_engine_settings.engine_algorithms.s);
+		if(!rc) {
 			err = "OpenSSL ENGINE could not set algorithms";
 			goto error;
 		}
@@ -764,7 +773,8 @@ error:
 	return -1;
 }
 
-EVP_PKEY *tls_engine_private_key(const char* key_id) {
+EVP_PKEY *tls_engine_private_key(const char *key_id)
+{
 	return ENGINE_load_private_key(ksr_tls_engine, key_id, NULL, NULL);
 }
 #endif

+ 2 - 3
src/modules/tls/tls_mod.h

@@ -22,7 +22,6 @@
  */
 
 
-
 #ifndef _TLS_MOD_H
 #define _TLS_MOD_H
 
@@ -32,8 +31,8 @@
 
 
 /* Current TLS configuration */
-extern tls_domains_cfg_t** tls_domains_cfg;
-extern gen_lock_t* tls_domains_cfg_lock;
+extern tls_domains_cfg_t **tls_domains_cfg;
+extern gen_lock_t *tls_domains_cfg_lock;
 
 extern tls_domain_t cli_defaults;
 extern tls_domain_t srv_defaults;

+ 24 - 42
src/modules/tls/tls_rand.c

@@ -46,9 +46,9 @@ static int ksr_krand_bytes(unsigned char *outdata, int size)
 {
 	int r;
 
-	if (size < 0) {
+	if(size < 0) {
 		return 0;
-	} else if (size == 0) {
+	} else if(size == 0) {
 		return 1;
 	}
 
@@ -58,7 +58,7 @@ static int ksr_krand_bytes(unsigned char *outdata, int size)
 		size -= sizeof(int);
 		outdata += sizeof(int);
 	}
-	if(size>0) {
+	if(size > 0) {
 		r = kam_rand();
 		memcpy(outdata, &r, size);
 	}
@@ -67,26 +67,20 @@ static int ksr_krand_bytes(unsigned char *outdata, int size)
 
 static int ksr_krand_pseudorand(unsigned char *outdata, int size)
 {
-    return ksr_krand_bytes(outdata, size);
+	return ksr_krand_bytes(outdata, size);
 }
 
 static int ksr_krand_status(void)
 {
-    return 1;
+	return 1;
 }
 
-const RAND_METHOD _ksr_krand_method = {
-    NULL,
-    ksr_krand_bytes,
-    NULL,
-    NULL,
-    ksr_krand_pseudorand,
-    ksr_krand_status
-};
+const RAND_METHOD _ksr_krand_method = {NULL, ksr_krand_bytes, NULL, NULL,
+		ksr_krand_pseudorand, ksr_krand_status};
 
 const RAND_METHOD *RAND_ksr_krand_method(void)
 {
-    return &_ksr_krand_method;
+	return &_ksr_krand_method;
 }
 
 /*
@@ -98,9 +92,9 @@ static int ksr_fastrand_bytes(unsigned char *outdata, int size)
 {
 	int r;
 
-	if (size < 0) {
+	if(size < 0) {
 		return 0;
-	} else if (size == 0) {
+	} else if(size == 0) {
 		return 1;
 	}
 
@@ -110,7 +104,7 @@ static int ksr_fastrand_bytes(unsigned char *outdata, int size)
 		size -= sizeof(int);
 		outdata += sizeof(int);
 	}
-	if(size>0) {
+	if(size > 0) {
 		r = fastrand();
 		memcpy(outdata, &r, size);
 	}
@@ -119,26 +113,20 @@ static int ksr_fastrand_bytes(unsigned char *outdata, int size)
 
 static int ksr_fastrand_pseudorand(unsigned char *outdata, int size)
 {
-    return ksr_fastrand_bytes(outdata, size);
+	return ksr_fastrand_bytes(outdata, size);
 }
 
 static int ksr_fastrand_status(void)
 {
-    return 1;
+	return 1;
 }
 
-const RAND_METHOD _ksr_fastrand_method = {
-    NULL,
-    ksr_fastrand_bytes,
-    NULL,
-    NULL,
-    ksr_fastrand_pseudorand,
-    ksr_fastrand_status
-};
+const RAND_METHOD _ksr_fastrand_method = {NULL, ksr_fastrand_bytes, NULL, NULL,
+		ksr_fastrand_pseudorand, ksr_fastrand_status};
 
 const RAND_METHOD *RAND_ksr_fastrand_method(void)
 {
-    return &_ksr_fastrand_method;
+	return &_ksr_fastrand_method;
 }
 
 /*
@@ -149,9 +137,9 @@ const RAND_METHOD *RAND_ksr_fastrand_method(void)
  */
 static int ksr_cryptorand_bytes(unsigned char *outdata, int size)
 {
-	if (size < 0) {
+	if(size < 0) {
 		return 0;
-	} else if (size == 0) {
+	} else if(size == 0) {
 		return 1;
 	}
 
@@ -161,25 +149,19 @@ static int ksr_cryptorand_bytes(unsigned char *outdata, int size)
 
 static int ksr_cryptorand_status(void)
 {
-    return 1;
+	return 1;
 }
 
 /*
  * We don't have a dedicated function for pseudo-random
  * bytes, just use the secure version as well for it.
  */
-const RAND_METHOD _ksr_cryptorand_method = {
-    NULL,
-    ksr_cryptorand_bytes,
-    NULL,
-    NULL,
-    ksr_cryptorand_bytes,
-    ksr_cryptorand_status
-};
+const RAND_METHOD _ksr_cryptorand_method = {NULL, ksr_cryptorand_bytes, NULL,
+		NULL, ksr_cryptorand_bytes, ksr_cryptorand_status};
 
 const RAND_METHOD *RAND_ksr_cryptorand_method(void)
 {
-    return &_ksr_cryptorand_method;
+	return &_ksr_cryptorand_method;
 }
 
 /**
@@ -197,7 +179,7 @@ void ksr_kxlibssl_init(void)
 		_ksr_kxlibssl_local_method = RAND_get_rand_method();
 	}
 	mypid = getpid();
-	if(_ksr_kxlibssl_local_lock==NULL || _ksr_kxlibssl_local_pid!=mypid) {
+	if(_ksr_kxlibssl_local_lock == NULL || _ksr_kxlibssl_local_pid != mypid) {
 		_ksr_kxlibssl_local_lock = lock_alloc();
 		if(_ksr_kxlibssl_local_lock == 0) {
 			LM_ERR("failed to allocate the lock\n");
@@ -369,6 +351,6 @@ const RAND_METHOD *RAND_ksr_kxlibssl_method(void)
 		_ksr_kxlibssl_method.status = ksr_kxlibssl_status;
 	}
 
-    return &_ksr_kxlibssl_method;
+	return &_ksr_kxlibssl_method;
 }
 #endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */

+ 121 - 142
src/modules/tls/tls_rpc.c

@@ -41,18 +41,15 @@
 #include "tls_rpc.h"
 #include "tls_cfg.h"
 
-static const char* tls_reload_doc[2] = {
-	"Reload TLS configuration file",
-	0
-};
+static const char *tls_reload_doc[2] = {"Reload TLS configuration file", 0};
 
-static void tls_reload(rpc_t* rpc, void* ctx)
+static void tls_reload(rpc_t *rpc, void *ctx)
 {
-	tls_domains_cfg_t* cfg;
+	tls_domains_cfg_t *cfg;
 	str tls_domains_cfg_file;
 
 	tls_domains_cfg_file = cfg_get(tls, tls_cfg, config_file);
-	if (!tls_domains_cfg_file.s) {
+	if(!tls_domains_cfg_file.s) {
 		rpc->fault(ctx, 500, "No TLS configuration file configured");
 		return;
 	}
@@ -62,20 +59,23 @@ static void tls_reload(rpc_t* rpc, void* ctx)
 
 	cfg = tls_load_config(&tls_domains_cfg_file);
 
-	if (!cfg) {
-		rpc->fault(ctx, 500, "Error while loading TLS configuration file"
-							" (consult server log)");
+	if(!cfg) {
+		rpc->fault(ctx, 500,
+				"Error while loading TLS configuration file"
+				" (consult server log)");
 		return;
 	}
 
-	if (tls_fix_domains_cfg(cfg, &srv_defaults, &cli_defaults) < 0) {
-		rpc->fault(ctx, 500, "Error while fixing TLS configuration"
-								" (consult server log)");
+	if(tls_fix_domains_cfg(cfg, &srv_defaults, &cli_defaults) < 0) {
+		rpc->fault(ctx, 500,
+				"Error while fixing TLS configuration"
+				" (consult server log)");
 		goto error;
 	}
-	if (tls_check_sockets(cfg) < 0) {
-		rpc->fault(ctx, 500, "No server listening socket found for one of"
-							" TLS domains (consult server log)");
+	if(tls_check_sockets(cfg) < 0) {
+		rpc->fault(ctx, 500,
+				"No server listening socket found for one of"
+				" TLS domains (consult server log)");
 		goto error;
 	}
 
@@ -90,124 +90,111 @@ static void tls_reload(rpc_t* rpc, void* ctx)
 	rpc->rpl_printf(ctx, "Ok. TLS configuration reloaded.");
 	return;
 
- error:
+error:
 	tls_free_cfg(cfg);
-
 }
 
 
-static const char* tls_list_doc[2] = {
-	"List currently open TLS connections",
-	0
-};
+static const char *tls_list_doc[2] = {"List currently open TLS connections", 0};
 
-extern gen_lock_t* tcpconn_lock;
-extern struct tcp_connection** tcpconn_id_hash;
+extern gen_lock_t *tcpconn_lock;
+extern struct tcp_connection **tcpconn_id_hash;
 
-static void tls_list(rpc_t* rpc, void* c)
+static void tls_list(rpc_t *rpc, void *c)
 {
 	char buf[128];
 	char src_ip[IP_ADDR_MAX_STR_SIZE];
 	char dst_ip[IP_ADDR_MAX_STR_SIZE];
-	void* handle;
-	char* tls_info;
-	char* state;
-	struct tls_extra_data* tls_d;
-	struct tcp_connection* con;
+	void *handle;
+	char *tls_info;
+	char *state;
+	struct tls_extra_data *tls_d;
+	struct tcp_connection *con;
 	int i, len, timeout;
 	struct tm timestamp;
 	char timestamp_s[128];
-	const char* sni;
+	const char *sni;
 
 	TCPCONN_LOCK;
 	for(i = 0; i < TCP_ID_HASH_SIZE; i++) {
-		for (con = tcpconn_id_hash[i]; con; con = con->id_next) {
-			if (con->rcv.proto != PROTO_TLS) continue;
+		for(con = tcpconn_id_hash[i]; con; con = con->id_next) {
+			if(con->rcv.proto != PROTO_TLS)
+				continue;
 			tls_d = con->extra_data;
 			rpc->add(c, "{", &handle);
 			/* tcp data */
-			if ((len = ip_addr2sbuf(&con->rcv.src_ip, src_ip, sizeof(src_ip)))
+			if((len = ip_addr2sbuf(&con->rcv.src_ip, src_ip, sizeof(src_ip)))
 					== 0)
 				BUG("failed to convert source ip");
 			src_ip[len] = 0;
-			if ((len = ip_addr2sbuf(&con->rcv.dst_ip, dst_ip, sizeof(dst_ip)))
+			if((len = ip_addr2sbuf(&con->rcv.dst_ip, dst_ip, sizeof(dst_ip)))
 					== 0)
 				BUG("failed to convert destination ip");
 			dst_ip[len] = 0;
 			timeout = TICKS_TO_S(con->timeout - get_ticks_raw());
 			timestamp = *localtime(&con->timestamp);
-			if (snprintf(timestamp_s, 128, "%d-%02d-%02d %02d:%02d:%02d", timestamp.tm_year + 1900,
-					timestamp.tm_mon + 1, timestamp.tm_mday, timestamp.tm_hour,
-					timestamp.tm_min, timestamp.tm_sec) < 0) {
+			if(snprintf(timestamp_s, 128, "%d-%02d-%02d %02d:%02d:%02d",
+					   timestamp.tm_year + 1900, timestamp.tm_mon + 1,
+					   timestamp.tm_mday, timestamp.tm_hour, timestamp.tm_min,
+					   timestamp.tm_sec)
+					< 0) {
 				timestamp_s[0] = 'N';
 				timestamp_s[1] = '/';
 				timestamp_s[2] = 'A';
 				timestamp_s[3] = '\0';
 			}
 
-			if (tls_d) {
+			if(tls_d) {
 				sni = SSL_get_servername(tls_d->ssl, TLSEXT_NAMETYPE_host_name);
-				if (sni == NULL) {
+				if(sni == NULL) {
 					sni = "N/A";
 				}
 			} else {
 				sni = "N/A";
 			}
 
-			rpc->struct_add(handle, "dssdsdsd",
-					"id", con->id,
-					"sni", sni,
-					"timestamp", timestamp_s,
-					"timeout", timeout,
-					"src_ip", src_ip,
-					"src_port", con->rcv.src_port,
-					"dst_ip", dst_ip,
+			rpc->struct_add(handle, "dssdsdsd", "id", con->id, "sni", sni,
+					"timestamp", timestamp_s, "timeout", timeout, "src_ip",
+					src_ip, "src_port", con->rcv.src_port, "dst_ip", dst_ip,
 					"dst_port", con->rcv.dst_port);
-			if (tls_d) {
+			if(tls_d) {
 				if(SSL_get_current_cipher(tls_d->ssl)) {
 					tls_info = SSL_CIPHER_description(
-									SSL_get_current_cipher(tls_d->ssl),
-									buf, sizeof(buf));
+							SSL_get_current_cipher(tls_d->ssl), buf,
+							sizeof(buf));
 					len = strlen(buf);
-					if (len && buf[len - 1] == '\n') buf[len - 1] = '\0';
+					if(len && buf[len - 1] == '\n')
+						buf[len - 1] = '\0';
 				} else {
 					tls_info = "unknown";
 				}
 				/* tls data */
 				state = "unknown/error";
 				lock_get(&con->write_lock);
-					switch(tls_d->state) {
-						case S_TLS_NONE:
-							state = "none/init";
-							break;
-						case S_TLS_ACCEPTING:
-							state = "tls_accept";
-							break;
-						case S_TLS_CONNECTING:
-							state = "tls_connect";
-							break;
-						case S_TLS_ESTABLISHED:
-							state = "established";
-							break;
-					}
-					rpc->struct_add(handle, "sddds",
-							"cipher", tls_info,
-							"ct_wq_size", tls_d->ct_wq?
-											tls_d->ct_wq->queued:0,
-							"enc_rd_buf", tls_d->enc_rd_buf?
-											tls_d->enc_rd_buf->size:0,
-							"flags", tls_d->flags,
-							"state", state
-							);
+				switch(tls_d->state) {
+					case S_TLS_NONE:
+						state = "none/init";
+						break;
+					case S_TLS_ACCEPTING:
+						state = "tls_accept";
+						break;
+					case S_TLS_CONNECTING:
+						state = "tls_connect";
+						break;
+					case S_TLS_ESTABLISHED:
+						state = "established";
+						break;
+				}
+				rpc->struct_add(handle, "sddds", "cipher", tls_info,
+						"ct_wq_size", tls_d->ct_wq ? tls_d->ct_wq->queued : 0,
+						"enc_rd_buf",
+						tls_d->enc_rd_buf ? tls_d->enc_rd_buf->size : 0,
+						"flags", tls_d->flags, "state", state);
 				lock_release(&con->write_lock);
 			} else {
-				rpc->struct_add(handle, "sddds",
-						"cipher", "unknown",
-						"ct_wq_size", 0,
-						"enc_rd_buf", 0,
-						"flags", 0,
-						"state", "pre-init"
-						);
+				rpc->struct_add(handle, "sddds", "cipher", "unknown",
+						"ct_wq_size", 0, "enc_rd_buf", 0, "flags", 0, "state",
+						"pre-init");
 			}
 		}
 	}
@@ -215,76 +202,69 @@ static void tls_list(rpc_t* rpc, void* c)
 }
 
 
+static const char *tls_info_doc[2] = {"Returns internal tls related info.", 0};
 
-static const char* tls_info_doc[2] = {
-	"Returns internal tls related info.",
-	0 };
-
-static void tls_info(rpc_t* rpc, void* c)
+static void tls_info(rpc_t *rpc, void *c)
 {
 	struct tcp_gen_info ti;
-	void* handle;
+	void *handle;
 
 	tcp_get_info(&ti);
 	rpc->add(c, "{", &handle);
-	rpc->struct_add(handle, "ddd",
-			"max_connections", ti.tls_max_connections,
+	rpc->struct_add(handle, "ddd", "max_connections", ti.tls_max_connections,
 			"opened_connections", ti.tls_connections_no,
 			"clear_text_write_queued_bytes", tls_ct_wq_total_bytes());
 }
 
 
+static const char *tls_options_doc[2] = {
+		"Dumps all the tls config options.", 0};
 
-static const char* tls_options_doc[2] = {
-	"Dumps all the tls config options.",
-	0 };
-
-static void tls_options(rpc_t* rpc, void* c)
+static void tls_options(rpc_t *rpc, void *c)
 {
-	void* handle;
+	void *handle;
 	rpc->add(c, "{", &handle);
-	rpc->struct_add(handle, "dSdddSSSSSdSSdddddddddddddd",
-		"force_run",	cfg_get(tls, tls_cfg, force_run),
-		"method",		&cfg_get(tls, tls_cfg, method),
-		"verify_certificate", cfg_get(tls, tls_cfg, verify_cert),
-
-		"verify_depth",		cfg_get(tls, tls_cfg, verify_depth),
-		"require_certificate",	cfg_get(tls, tls_cfg, require_cert),
-		"verify_client",	&cfg_get(tls, tls_cfg, verify_client),
-		"private_key",		&cfg_get(tls, tls_cfg, private_key),
-		"ca_list",			&cfg_get(tls, tls_cfg, ca_list),
-		"certificate",		&cfg_get(tls, tls_cfg, certificate),
-		"cipher_list",		&cfg_get(tls, tls_cfg, cipher_list),
-		"session_cache",	cfg_get(tls, tls_cfg, session_cache),
-		"session_id",		&cfg_get(tls, tls_cfg, session_id),
-		"config",			&cfg_get(tls, tls_cfg, config_file),
-		"log",				cfg_get(tls, tls_cfg, log),
-		"debug",			cfg_get(tls, tls_cfg, debug),
-		"connection_timeout", TICKS_TO_S(cfg_get(tls, tls_cfg, con_lifetime)),
-		"disable_compression",	cfg_get(tls, tls_cfg, disable_compression),
-		"ssl_release_buffers",	cfg_get(tls, tls_cfg, ssl_release_buffers),
-		"ssl_freelist_max",		cfg_get(tls, tls_cfg, ssl_freelist_max),
-		"ssl_max_send_fragment", cfg_get(tls, tls_cfg, ssl_max_send_fragment),
-		"ssl_read_ahead",		cfg_get(tls, tls_cfg, ssl_read_ahead),
-		"send_close_notify",	cfg_get(tls, tls_cfg, send_close_notify),
-		"low_mem_threshold1",	cfg_get(tls, tls_cfg, low_mem_threshold1),
-		"low_mem_threshold2",	cfg_get(tls, tls_cfg, low_mem_threshold2),
-		"ct_wq_max",			cfg_get(tls, tls_cfg, ct_wq_max),
-		"con_ct_wq_max",		cfg_get(tls, tls_cfg, con_ct_wq_max),
-		"ct_wq_blk_size",		cfg_get(tls, tls_cfg, ct_wq_blk_size)
-		);
+	rpc->struct_add(handle, "dSdddSSSSSdSSdddddddddddddd", "force_run",
+			cfg_get(tls, tls_cfg, force_run), "method",
+			&cfg_get(tls, tls_cfg, method), "verify_certificate",
+			cfg_get(tls, tls_cfg, verify_cert),
+
+			"verify_depth", cfg_get(tls, tls_cfg, verify_depth),
+			"require_certificate", cfg_get(tls, tls_cfg, require_cert),
+			"verify_client", &cfg_get(tls, tls_cfg, verify_client),
+			"private_key", &cfg_get(tls, tls_cfg, private_key), "ca_list",
+			&cfg_get(tls, tls_cfg, ca_list), "certificate",
+			&cfg_get(tls, tls_cfg, certificate), "cipher_list",
+			&cfg_get(tls, tls_cfg, cipher_list), "session_cache",
+			cfg_get(tls, tls_cfg, session_cache), "session_id",
+			&cfg_get(tls, tls_cfg, session_id), "config",
+			&cfg_get(tls, tls_cfg, config_file), "log",
+			cfg_get(tls, tls_cfg, log), "debug", cfg_get(tls, tls_cfg, debug),
+			"connection_timeout",
+			TICKS_TO_S(cfg_get(tls, tls_cfg, con_lifetime)),
+			"disable_compression", cfg_get(tls, tls_cfg, disable_compression),
+			"ssl_release_buffers", cfg_get(tls, tls_cfg, ssl_release_buffers),
+			"ssl_freelist_max", cfg_get(tls, tls_cfg, ssl_freelist_max),
+			"ssl_max_send_fragment",
+			cfg_get(tls, tls_cfg, ssl_max_send_fragment), "ssl_read_ahead",
+			cfg_get(tls, tls_cfg, ssl_read_ahead), "send_close_notify",
+			cfg_get(tls, tls_cfg, send_close_notify), "low_mem_threshold1",
+			cfg_get(tls, tls_cfg, low_mem_threshold1), "low_mem_threshold2",
+			cfg_get(tls, tls_cfg, low_mem_threshold2), "ct_wq_max",
+			cfg_get(tls, tls_cfg, ct_wq_max), "con_ct_wq_max",
+			cfg_get(tls, tls_cfg, con_ct_wq_max), "ct_wq_blk_size",
+			cfg_get(tls, tls_cfg, ct_wq_blk_size));
 }
 
-static const char* tls_kill_doc[2] = {
-	"Kills a tls session, identified via id.",
-	0 };
+static const char *tls_kill_doc[2] = {
+		"Kills a tls session, identified via id.", 0};
 
-static void tls_kill(rpc_t* rpc, void* c)
+static void tls_kill(rpc_t *rpc, void *c)
 {
-	struct tcp_connection* con;
+	struct tcp_connection *con;
 	int i, kill_id = 0;
 
-	if (rpc->scan(c, "d", &kill_id) < 0) {
+	if(rpc->scan(c, "d", &kill_id) < 0) {
 		/* Reply is set automatically by scan upon failure,
 		* no need to do anything here
 		*/
@@ -293,9 +273,10 @@ static void tls_kill(rpc_t* rpc, void* c)
 
 	TCPCONN_LOCK;
 	for(i = 0; i < TCP_ID_HASH_SIZE; i++) {
-		for (con = tcpconn_id_hash[i]; con; con = con->id_next) {
-			if (con->rcv.proto != PROTO_TLS) continue;
-			if (con->id == kill_id) {
+		for(con = tcpconn_id_hash[i]; con; con = con->id_next) {
+			if(con->rcv.proto != PROTO_TLS)
+				continue;
+			if(con->id == kill_id) {
 				con->state = -2;
 				con->timeout = get_ticks_raw();
 
@@ -313,10 +294,8 @@ static void tls_kill(rpc_t* rpc, void* c)
 
 
 rpc_export_t tls_rpc[] = {
-	{"tls.reload", tls_reload, tls_reload_doc, RPC_EXEC_DELTA},
-	{"tls.list",   tls_list,   tls_list_doc,   RET_ARRAY},
-	{"tls.info",   tls_info,   tls_info_doc, 0},
-	{"tls.options",tls_options, tls_options_doc, 0},
-	{"tls.kill",   tls_kill, tls_kill_doc, 0},
-	{0, 0, 0, 0}
-};
+		{"tls.reload", tls_reload, tls_reload_doc, RPC_EXEC_DELTA},
+		{"tls.list", tls_list, tls_list_doc, RET_ARRAY},
+		{"tls.info", tls_info, tls_info_doc, 0},
+		{"tls.options", tls_options, tls_options_doc, 0},
+		{"tls.kill", tls_kill, tls_kill_doc, 0}, {0, 0, 0, 0}};

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 358 - 275
src/modules/tls/tls_select.c


+ 1 - 1
src/modules/tls/tls_select.h

@@ -47,6 +47,6 @@ extern pv_export_t tls_pv[];
 
 void tls_set_pv_con(struct tcp_connection *c);
 
-sr_kemi_xval_t* ki_tls_cget_attr(sip_msg_t* msg, str *aname);
+sr_kemi_xval_t *ki_tls_cget_attr(sip_msg_t *msg, str *aname);
 
 #endif /* _TLS_SELECT_H */

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 262 - 271
src/modules/tls/tls_server.c


+ 29 - 26
src/modules/tls/tls_server.h

@@ -34,34 +34,37 @@
 #include "tls_domain.h"
 #include "tls_ct_wrq.h"
 
-typedef enum tls_conn_states {
-						S_TLS_NONE = 0,
-						S_TLS_ACCEPTING,
-						S_TLS_CONNECTING,
-						S_TLS_ESTABLISHED
-					} tls_conn_states_t;
-
-typedef struct tls_rd_buf {
-	unsigned int pos; /* current position */
+typedef enum tls_conn_states
+{
+	S_TLS_NONE = 0,
+	S_TLS_ACCEPTING,
+	S_TLS_CONNECTING,
+	S_TLS_ESTABLISHED
+} tls_conn_states_t;
+
+typedef struct tls_rd_buf
+{
+	unsigned int pos;  /* current position */
 	unsigned int size; /* total size (buf) */
 	unsigned char buf[1];
 } tls_rd_buf_t;
 
 /* tls conn flags */
-#define F_TLS_CON_WR_WANTS_RD    1 /* write wants read */
-#define F_TLS_CON_HANDSHAKED     2 /* connection is handshaked */
-#define F_TLS_CON_RENEGOTIATION  4 /* renegotiation by clinet */
-
-typedef struct tls_extra_data {
-	tls_domains_cfg_t* cfg; /* Configuration used for this connection */
-	SSL* ssl;               /* SSL context used for the connection */
-	BIO* rwbio;             /* bio used for read/write
+#define F_TLS_CON_WR_WANTS_RD 1	  /* write wants read */
+#define F_TLS_CON_HANDSHAKED 2	  /* connection is handshaked */
+#define F_TLS_CON_RENEGOTIATION 4 /* renegotiation by clinet */
+
+typedef struct tls_extra_data
+{
+	tls_domains_cfg_t *cfg; /* Configuration used for this connection */
+	SSL *ssl;				/* SSL context used for the connection */
+	BIO *rwbio;				/* bio used for read/write
 							 * (openssl code might add buffering BIOs so
 							 * it's better to remember our original BIO) */
-	tls_ct_q* ct_wq;
-	struct tls_rd_buf* enc_rd_buf;
+	tls_ct_q *ct_wq;
+	struct tls_rd_buf *enc_rd_buf;
 	unsigned int flags;
-	enum  tls_conn_states state;
+	enum tls_conn_states state;
 } tls_extra_data_t;
 
 
@@ -84,16 +87,16 @@ void tls_h_tcpconn_clean_f(struct tcp_connection *c);
  */
 void tls_h_tcpconn_close_f(struct tcp_connection *c, int fd);
 
-int tls_h_encode_f(struct tcp_connection *c, const char ** pbuf,
-		unsigned int* plen, const char** rest_buf, unsigned int* rest_len,
-		snd_flags_t* send_flags) ;
+int tls_h_encode_f(struct tcp_connection *c, const char **pbuf,
+		unsigned int *plen, const char **rest_buf, unsigned int *rest_len,
+		snd_flags_t *send_flags);
 
-int tls_h_read_f(struct tcp_connection *c, rd_conn_flags_t* flags);
+int tls_h_read_f(struct tcp_connection *c, rd_conn_flags_t *flags);
 
 int tls_h_fix_read_conn(struct tcp_connection *c);
 
-int tls_connect(struct tcp_connection *c, int* error);
-int tls_accept(struct tcp_connection *c, int* error);
+int tls_connect(struct tcp_connection *c, int *error);
+int tls_accept(struct tcp_connection *c, int *error);
 
 void tls_lookup_event_routes(void);
 int ksr_tls_set_connect_server_id(str *srvid);

+ 8 - 9
src/modules/tls/tls_util.c

@@ -41,25 +41,25 @@
  * Return value: -1 on error
  *                0 on success
  */
-int shm_asciiz_dup(char** dest, char* val)
+int shm_asciiz_dup(char **dest, char *val)
 {
-	char* ret;
+	char *ret;
 	int len;
 
-	if (!val) {
+	if(!val) {
 		*dest = NULL;
 		return 0;
 	}
 
 	len = strlen(val);
 	ret = shm_malloc(len + 1);
-	if (!ret) {
+	if(!ret) {
 		ERR("No memory left\n");
 		return -1;
 	}
 	memcpy(ret, val, len + 1);
 	*dest = ret;
-        return 0;
+	return 0;
 }
 
 
@@ -70,12 +70,12 @@ void collect_garbage(void)
 {
 	tls_domains_cfg_t *prev, *cur, *next;
 
-	     /* Make sure we do not run two garbage collectors
+	/* Make sure we do not run two garbage collectors
 	      * at the same time
 	      */
 	lock_get(tls_domains_cfg_lock);
 
-	     /* Skip the current configuration, garbage starts
+	/* Skip the current configuration, garbage starts
 	      * with the 2nd element on the list
 	      */
 	prev = *tls_domains_cfg;
@@ -83,7 +83,7 @@ void collect_garbage(void)
 
 	while(cur) {
 		next = cur->next;
-		if (atomic_get(&cur->ref_count) == 0) {
+		if(atomic_get(&cur->ref_count) == 0) {
 			/* Not referenced by any existing connection */
 			prev->next = cur->next;
 			tls_free_cfg(cur);
@@ -96,4 +96,3 @@ void collect_garbage(void)
 
 	lock_release(tls_domains_cfg_lock);
 }
-

+ 17 - 18
src/modules/tls/tls_util.h

@@ -32,16 +32,15 @@
 #include "../../core/str.h"
 #include "tls_domain.h"
 
-static inline int tls_err_ret(char *s, SSL* ssl,
-		tls_domains_cfg_t **tls_domains_cfg)
+static inline int tls_err_ret(
+		char *s, SSL *ssl, tls_domains_cfg_t **tls_domains_cfg)
 {
 	long err;
 	int ret = 0;
 	const char *sn = NULL;
 
-	if ((*tls_domains_cfg)->srv_default->ctx &&
-		(*tls_domains_cfg)->srv_default->ctx[0])
-	{
+	if((*tls_domains_cfg)->srv_default->ctx
+			&& (*tls_domains_cfg)->srv_default->ctx[0]) {
 		if(ssl) {
 			sn = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
 		}
@@ -54,28 +53,28 @@ static inline int tls_err_ret(char *s, SSL* ssl,
 	return ret;
 }
 
-#define TLS_ERR_RET(r, s) \
-do { \
-	(r) = tls_err_ret((s), NULL, tls_domains_cfg); \
-} while(0)
+#define TLS_ERR_RET(r, s)                              \
+	do {                                               \
+		(r) = tls_err_ret((s), NULL, tls_domains_cfg); \
+	} while(0)
 
 
-#define TLS_ERR(s) \
-do { \
-	tls_err_ret((s), NULL, tls_domains_cfg); \
-} while(0)
+#define TLS_ERR(s)                               \
+	do {                                         \
+		tls_err_ret((s), NULL, tls_domains_cfg); \
+	} while(0)
 
-#define TLS_ERR_SSL(s, ssl) \
-do { \
-	tls_err_ret((s), (ssl), tls_domains_cfg); \
-} while(0)
+#define TLS_ERR_SSL(s, ssl)                       \
+	do {                                          \
+		tls_err_ret((s), (ssl), tls_domains_cfg); \
+	} while(0)
 
 /*
  * Make a shared memory copy of ASCII zero terminated string
  * Return value: -1 on error
  *                0 on success
  */
-int shm_asciiz_dup(char** dest, char* val);
+int shm_asciiz_dup(char **dest, char *val);
 
 
 /*

+ 16 - 14
src/modules/tls/tls_verify.c

@@ -33,19 +33,20 @@
 /* This callback is called during each verification process,
    at each step during the chain of certificates (this function
    is not the certificate_verification one!). */
-int verify_callback(int pre_verify_ok, X509_STORE_CTX *ctx) {
+int verify_callback(int pre_verify_ok, X509_STORE_CTX *ctx)
+{
 	char buf[256];
 	X509 *err_cert;
 	int err, depth;
 
 	depth = X509_STORE_CTX_get_error_depth(ctx);
-	LM_DBG("tls init - depth = %d\n",depth);
-	if ( depth > VERIFY_DEPTH_S ) {
+	LM_DBG("tls init - depth = %d\n", depth);
+	if(depth > VERIFY_DEPTH_S) {
 		LM_NOTICE("tls init - cert chain too long ( depth > VERIFY_DEPTH_S)\n");
-		pre_verify_ok=0;
+		pre_verify_ok = 0;
 	}
 
-	if( pre_verify_ok ) {
+	if(pre_verify_ok) {
 		LM_NOTICE("tls init - preverify is good: verify return: %d\n",
 				pre_verify_ok);
 		return pre_verify_ok;
@@ -53,21 +54,20 @@ int verify_callback(int pre_verify_ok, X509_STORE_CTX *ctx) {
 
 	err_cert = X509_STORE_CTX_get_current_cert(ctx);
 	err = X509_STORE_CTX_get_error(ctx);
-	X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof buf);
+	X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof buf);
 
 	LM_NOTICE("tls init - subject = %s\n", buf);
 	LM_NOTICE("tls init - verify error - num=%d:%s\n", err,
 			X509_verify_cert_error_string(err));
-	LM_NOTICE("tls init - error code is %d (depth: %d)\n",
-			err, depth);
+	LM_NOTICE("tls init - error code is %d (depth: %d)\n", err, depth);
 
-	switch (err) {
+	switch(err) {
 		case X509_V_OK:
 			LM_NOTICE("tls init - all ok\n");
 			break;
 		case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
-			X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof buf);
-			LM_NOTICE("tls init - issuer= %s\n",buf);
+			X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, sizeof buf);
+			LM_NOTICE("tls init - issuer= %s\n", buf);
 			break;
 
 		case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
@@ -119,17 +119,19 @@ int verify_callback(int pre_verify_ok, X509_STORE_CTX *ctx) {
 
 		default:
 			LM_NOTICE("tls init - something wrong with the"
-					" cert ... error code is %d (check x509_vfy.h)\n",
+					  " cert ... error code is %d (check x509_vfy.h)\n",
 					err);
 			break;
 	}
 
 	LM_NOTICE("tls init - verify return: %d\n", pre_verify_ok);
-	return(pre_verify_ok);
+	return (pre_verify_ok);
 }
 
 
-int verify_callback_unconditional_success(int pre_verify_ok, X509_STORE_CTX *ctx) {
+int verify_callback_unconditional_success(
+		int pre_verify_ok, X509_STORE_CTX *ctx)
+{
 	LM_NOTICE("Post-verification callback: unconditional success\n");
 	return 1;
 }

+ 2 - 1
src/modules/tls/tls_verify.h

@@ -36,6 +36,7 @@ int verify_callback(int pre_verify_ok, X509_STORE_CTX *ctx);
 /* Post-verification callback handler which unconditionally returns 1 (success)
    Note that actual verification result can be retrieved through TLS PVs after-the-fact
  */
-int verify_callback_unconditional_success(int pre_verify_ok, X509_STORE_CTX *ctx);
+int verify_callback_unconditional_success(
+		int pre_verify_ok, X509_STORE_CTX *ctx);
 
 #endif /* _TLS_VERIFY_H */

+ 13 - 10
src/modules/tls/utils/openssl_mutex_shared/openssl_mutex_shared.c

@@ -3,13 +3,15 @@
 
 #define SYMBOL_EXPORT __attribute__((visibility("default")))
 
-int SYMBOL_EXPORT pthread_mutex_init (pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr)
+int SYMBOL_EXPORT pthread_mutex_init(
+		pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr)
 {
-	static int (*real_pthread_mutex_init)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr);
-	if (!real_pthread_mutex_init)
+	static int (*real_pthread_mutex_init)(
+			pthread_mutex_t * __mutex, const pthread_mutexattr_t *__mutexattr);
+	if(!real_pthread_mutex_init)
 		real_pthread_mutex_init = dlsym(RTLD_NEXT, "pthread_mutex_init");
 
-	if (__mutexattr) {
+	if(__mutexattr) {
 		pthread_mutexattr_t attr = *__mutexattr;
 		pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
 		return real_pthread_mutex_init(__mutex, &attr);
@@ -23,15 +25,16 @@ int SYMBOL_EXPORT pthread_mutex_init (pthread_mutex_t *__mutex, const pthread_mu
 	return ret;
 }
 
-int SYMBOL_EXPORT pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,
-				const pthread_rwlockattr_t *__restrict __attr)
+int SYMBOL_EXPORT pthread_rwlock_init(pthread_rwlock_t *__restrict __rwlock,
+		const pthread_rwlockattr_t *__restrict __attr)
 {
-	static int (*real_pthread_rwlock_init)(pthread_rwlock_t *__restrict __rwlock,
-				const pthread_rwlockattr_t *__restrict __attr);
-	if (!real_pthread_rwlock_init)
+	static int (*real_pthread_rwlock_init)(
+			pthread_rwlock_t *__restrict __rwlock,
+			const pthread_rwlockattr_t *__restrict __attr);
+	if(!real_pthread_rwlock_init)
 		real_pthread_rwlock_init = dlsym(RTLD_NEXT, "pthread_rwlock_init");
 
-	if (__attr) {
+	if(__attr) {
 		pthread_rwlockattr_t attr = *__attr;
 		pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
 		return real_pthread_rwlock_init(__rwlock, &attr);

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio