Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
ex_network_ssl.c
1
7#include "nilorea/n_list.h"
8#include "nilorea/n_str.h"
9#include "nilorea/n_log.h"
10#include "nilorea/n_network.h"
12#include "nilorea/n_signals.h"
13
14char* port = NULL;
15char* addr = NULL;
16char* key = NULL;
17char* cert = NULL;
18char* root_dir = NULL;
19LIST* routes = NULL;
20int ip_version = NETWORK_IPALL;
21int max_http_request_size = 16384;
22bool done = 0;
23
24NETWORK *server = NULL,
25 *netw = NULL;
27void usage(void) {
28 fprintf(stderr,
29 " -p 'port' : set the https server port\n"
30 " -k 'key file' : SSL key file path\n"
31 " -c 'cert file' : SSL certificate file path\n"
32 " -a 'address name/ip' : optional, specify where to bind interface\n"
33 " -i 'ipmode' : optional, force 'ipv4' or 'ipv6', default supports both\n"
34 " -s 'size' : optional, maximum http request size (default: %d)\n"
35 " -d 'html root' : optional, specify a different http root dir (default: ./DATAS/)\n"
36 " -v : version\n"
37 " -h : help\n"
38 " -V 'log level' : optional, set the log level (default: LOG_ERR)\n",
39 max_http_request_size);
40}
41
42void process_args(int argc_nb, char** argv_ptr, char** addr_ptr, char** port_ptr, char** key_ptr, char** cert_ptr, LIST* routes_ptr, int* ip_version_ptr, int* max_http_request_size_ptr, char** root_dir_ptr) {
43 int getoptret = 0,
44 log_level = LOG_ERR; /* default log level */
45
46 if (argc_nb == 1) {
47 fprintf(stderr, "No arguments given, help:\n");
48 usage();
49 exit(1);
50 }
51 while ((getoptret = getopt(argc_nb, argv_ptr, "hvs:V:p:i:a:r:k:c:s:d:")) != EOF) {
52 switch (getoptret) {
53 case 'i':
54 if (!strcmp("v4", optarg)) {
55 (*ip_version_ptr) = NETWORK_IPV4;
56 n_log(LOG_NOTICE, "IPV4 selected");
57 } else if (!strcmp("v6", optarg)) {
58 (*ip_version_ptr) = NETWORK_IPV6;
59 n_log(LOG_NOTICE, "IPV6 selected");
60 } else {
61 n_log(LOG_NOTICE, "IPV4/6 selected");
62 }
63 break;
64 case 'v':
65 fprintf(stderr, "Date de compilation : %s a %s.\n", __DATE__, __TIME__);
66 exit(1);
67 case 'V':
68 if (!strncmp("LOG_NULL", optarg, 8)) {
69 log_level = LOG_NULL;
70 } else {
71 if (!strncmp("LOG_NOTICE", optarg, 10)) {
72 log_level = LOG_NOTICE;
73 } else {
74 if (!strncmp("LOG_INFO", optarg, 8)) {
75 log_level = LOG_INFO;
76 } else {
77 if (!strncmp("LOG_ERR", optarg, 7)) {
78 log_level = LOG_ERR;
79 } else {
80 if (!strncmp("LOG_DEBUG", optarg, 9)) {
81 log_level = LOG_DEBUG;
82 } else {
83 fprintf(stderr, "%s n'est pas un niveau de log valide.\n", optarg);
84 exit(-1);
85 }
86 }
87 }
88 }
89 }
90 break;
91 case 'p':
92 (*port_ptr) = strdup(optarg);
93 break;
94 case 'r':
95 list_push(routes_ptr, strdup(optarg), &free);
96 break;
97 case 'a':
98 (*addr_ptr) = strdup(optarg);
99 break;
100 case 'k':
101 (*key_ptr) = strdup(optarg);
102 break;
103 case 'c':
104 (*cert_ptr) = strdup(optarg);
105 break;
106 case 's':
107 (*max_http_request_size_ptr) = atoi(optarg);
108 break;
109 case 'd':
110 (*root_dir_ptr) = strdup(optarg);
111 break;
112 default:
113 case '?': {
114 if (optopt == 'd') {
115 fprintf(stderr, "\n Missing html root directory\n");
116 }
117 if (optopt == 's') {
118 fprintf(stderr, "\n Missing max http size string\n");
119 }
120 if (optopt == 'k') {
121 fprintf(stderr, "\n Missing key file string\n");
122 }
123 if (optopt == 'c') {
124 fprintf(stderr, "\n Missing certificate file string\n");
125 }
126
127 if (optopt == 'r') {
128 fprintf(stderr, "\n Missing route string\n");
129 }
130 if (optopt == 'a') {
131 fprintf(stderr, "\n Missing binding host/addr string\n");
132 }
133 if (optopt == 'i') {
134 fprintf(stderr, "\n Missing ip version (v4 or v6) string \n");
135 } else if (optopt == 'V') {
136 fprintf(stderr, "\n Missing log level string\n");
137 } else if (optopt == 'p') {
138 fprintf(stderr, "\n Missing port\n");
139 } else if (optopt != 's') {
140 fprintf(stderr, "\n Unknow missing option %c\n", optopt);
141 }
142 usage();
143 exit(1);
144 }
145 case 'h': {
146 usage();
147 exit(1);
148 }
149 }
150 }
151 set_log_level(log_level);
152} /* void process_args( ... ) */
153
154/* Exit handling */
155void action_on_sig(int recvd_signal) {
156 (void)recvd_signal;
157#ifndef __windows__
158 static int nb_sigterm = 0;
159 switch (recvd_signal) {
160 /* We should not use these signals as they make the debugging going funky */
161 case (SIGABRT):
162 n_log(LOG_ERR, "Caught SIGABRT !");
163 break;
164 case (SIGINT):
165 n_log(LOG_ERR, "Caught SIGINT !");
166 break;
167 case (SIGBUS):
168 n_log(LOG_ERR, "Caught SIGBUS !");
169 break;
170 case (SIGFPE):
171 n_log(LOG_ERR, "Caught SIGFPE !");
172 break;
173 case (SIGSEGV):
174 n_log(LOG_ERR, "Caught SIGSEGV !");
175 break;
176 case (SIGSYS):
177 n_log(LOG_ERR, "Caught SIGSYS !");
178 break;
179 case (SIGTERM):
180 nb_sigterm++;
181 if (nb_sigterm >= 2) {
182 n_log(LOG_ERR, "Caught too much SIGTERM, trying _exit() !!");
183 _exit(-1);
184 }
185 n_log(LOG_ERR, "Caught %d SIGTERM, exiting now !!", nb_sigterm);
186 exit(-1);
187 case (SIGUSR1):
188 done = TRUE;
189 n_log(LOG_ERR, "Caught SIGUSR1 !");
190 break;
191 case (SIGUSR2):
192 done = TRUE;
193 n_log(LOG_ERR, "Caught SIGUSR1 !");
194 break;
195 case (SIGHUP):
196 n_log(LOG_NOTICE, "Caught SIGHUP !");
197 break;
198 default:
199 n_log(LOG_ERR, "Caught unknow signal %d", recvd_signal);
200 break;
201 }
202#endif
203} /* action_on_sig() */
204
205// Function to handle different URLs and return appropriate responses
206void handle_request(NETWORK* netw_ptr, LIST* routes_ptr) {
207 __n_assert(netw_ptr, return);
208 __n_assert(routes_ptr, return);
209
210 bool found = 0;
211 char** split_results = NULL;
212 char* http_url = NULL;
213 N_STR* dynamic_request_answer = NULL;
214
215 // Read request
216 char* http_buffer = NULL;
217 Alloca(http_buffer, max_http_request_size + 1);
218 __n_assert(http_buffer, netw_close(&netw_ptr); return);
219
220 SSL_read(netw_ptr->ssl, http_buffer, max_http_request_size);
221 // n_log( LOG_DEBUG , "http_request: %s" , http_buffer );
222
223 // Extract URL from the request
224 char url[4096] = "";
225 netw_get_url_from_http_request(http_buffer, url, sizeof(url));
226 n_log(LOG_DEBUG, "url: %s", url);
227
228 // Handle the request based on the URL
229 N_STR* origin = new_nstr(32);
230 nstrprintf(origin, "%s:" SOCKET_SIZE_FORMAT, _str(netw_ptr->link.ip), netw_ptr->link.sock);
231
232 NETWORK_HTTP_INFO http_request = netw_extract_http_info(http_buffer);
233 N_STR* http_body = NULL;
234
235 split_results = split(url, "?", 0);
236 if (!split_results || !split_results[0]) {
237 http_body = char_to_nstr("<html><body><h1>Bad Request</h1></body></html>");
238 if (netw_build_http_response(&dynamic_request_answer, 400, "ex_network_ssl server", netw_guess_http_content_type(url), "", http_body) == FALSE) {
239 n_log(LOG_ERR, "couldn't build a Bad Request answer for %s", url);
240 }
241 n_log(LOG_ERR, "%s: %s %s 400", _nstr(origin), http_request.type, url);
242 } else {
243 http_url = split_results[0];
244 n_log(LOG_INFO, "%s: %s %s request...", _nstr(origin), http_request.type, url);
245 if (strcmp("OPTIONS", http_request.type) == 0) {
246 if (netw_build_http_response(&dynamic_request_answer, 200, "ex_network_ssl server", netw_guess_http_content_type(url), "Allow: OPTIONS, GET, POST\r\n", NULL) == FALSE) {
247 n_log(LOG_ERR, "couldn't build an OPTION answer for %s", url);
248 }
249 n_log(LOG_INFO, "%s: %s %s 200", _nstr(origin), http_request.type, url);
250 } else if (strcmp("GET", http_request.type) == 0) {
251 char system_url[4096] = "";
252 // example assume a root dir at DATAS
253 if (!root_dir) {
254 snprintf(system_url, sizeof(system_url), "./DATAS%s", http_url);
255 } else {
256 snprintf(system_url, sizeof(system_url), "%s%s", root_dir, http_url);
257 }
258
259 n_log(LOG_DEBUG, "%s: searching for file %s...", _nstr(origin), system_url);
260
261 if (file_exist(system_url)) {
262 n_log(LOG_DEBUG, "%s: file %s found !", _nstr(origin), system_url);
263 http_body = file_to_nstr(system_url);
264 if (!http_body) {
265 http_body = char_to_nstr("<html><body><h1>Internal Server Error</h1></body></html>");
266 if (netw_build_http_response(&dynamic_request_answer, 500, "ex_network_ssl server", netw_guess_http_content_type(url), "", http_body) == FALSE) {
267 n_log(LOG_ERR, "couldn't build an Internal Server Error answer for %s", url);
268 }
269 n_log(LOG_ERR, "%s: %s %s 500", _nstr(origin), http_request.type, url);
270 } else {
271 if (netw_build_http_response(&dynamic_request_answer, 200, "ex_network_ssl server", netw_guess_http_content_type(url), "", http_body) == FALSE) {
272 n_log(LOG_ERR, "couldn't build an http answer for %s", url);
273 }
274 n_log(LOG_INFO, "%s: %s %s 200", _nstr(origin), http_request.type, url);
275 }
276 } else {
277 http_body = char_to_nstr("<html><body><h1>404 Not Found</h1></body></html>");
278 if (netw_build_http_response(&dynamic_request_answer, 404, "ex_network_ssl server", netw_guess_http_content_type(url), "", http_body) == FALSE) {
279 n_log(LOG_ERR, "couldn't build a NOT FOUND answer for %s", url);
280 }
281 n_log(LOG_ERR, "%s: %s %s 404", _nstr(origin), http_request.type, url);
282 }
283 } else if (strcmp("POST", http_request.type) == 0) {
284 // Parse virtual route
285 found = 0;
286 list_foreach(node, routes_ptr) {
287 if (strcmp(node->ptr, http_url) == 0) {
288 // Handle 200 OK from virtual route
289 HASH_TABLE* post_data = netw_parse_post_data(http_request.body);
290 if (post_data) {
291 HT_FOREACH(hnode, post_data,
292 {
293 n_log(LOG_DEBUG, "%s: POST DATA: %s=%s", _nstr(origin), hnode->key, (char*)hnode->data.ptr);
294 });
295 destroy_ht(&post_data);
296 }
297 http_body = char_to_nstr("{\"status\":\"ok\"}");
298 if (netw_build_http_response(&dynamic_request_answer, 200, "ex_network_ssl server", "application/json", "", http_body) == FALSE) {
299 n_log(LOG_ERR, "couldn't build a route 200 answer for %s", url);
300 }
301 found = 1;
302 n_log(LOG_INFO, "%s: %s virtual:%s 200", _nstr(origin), http_request.type, url);
303 break;
304 }
305 }
306 if (!found) {
307 http_body = char_to_nstr("<html><body><h1>404 Not Found</h1></body></html>");
308 if (netw_build_http_response(&dynamic_request_answer, 404, "ex_network_ssl server", netw_guess_http_content_type(url), "", http_body) == FALSE) {
309 n_log(LOG_ERR, "couldn't build a NOT FOUND answer for %s", url);
310 }
311 n_log(LOG_ERR, "%s: %s %s 404", _nstr(origin), http_request.type, url);
312 }
313 } else {
314 http_body = char_to_nstr("<html><body><h1>Bad Request</h1></body></html>");
315 if (netw_build_http_response(&dynamic_request_answer, 400, "ex_network_ssl server", netw_guess_http_content_type(url), "", http_body) == FALSE) {
316 n_log(LOG_ERR, "couldn't build a Bad Request answer for %s", url);
317 }
318 n_log(LOG_ERR, "%s: %s %s 400", _nstr(origin), http_request.type, url);
319 }
320 free_split_result(&split_results);
321 }
322 if (dynamic_request_answer) {
323 SSL_write(netw_ptr->ssl, _nstr(dynamic_request_answer), dynamic_request_answer->written);
324 free_nstr(&dynamic_request_answer);
325 } else {
326 n_log(LOG_ERR, "couldn't build an answer for %s: %s %s", _nstr(origin), http_request.type, url);
327 }
328 netw_info_destroy(http_request);
329 free_nstr(&origin);
330 free_nstr(&http_body);
331} /* handle_request */
332
340
341void* ssl_network_thread(void* params) {
342 __n_assert(params, return NULL);
344 handle_request(ssl_params->netw, ssl_params->routes);
345 netw_close(&ssl_params->netw);
346 Free(ssl_params);
347 return NULL;
348}
349
350int main(int argc, char* argv[]) {
351 int exit_code = 0;
352 THREAD_POOL* thread_pool = NULL;
353 routes = new_generic_list(MAX_LIST_ITEMS);
354 __n_assert(routes, n_log(LOG_ERR, "could not allocate list !"); exit(1));
355
356 /* processing args and set log_level */
357 process_args(argc, argv, &addr, &port, &key, &cert, routes, &ip_version, &max_http_request_size, &root_dir);
358
359 if (!port) {
360 n_log(LOG_ERR, "No port given. Exiting.");
361 exit_code = 1;
362 goto clean_and_exit;
363 }
364 if (!key) {
365 n_log(LOG_ERR, "No key given. Exiting.");
366 exit_code = 1;
367 goto clean_and_exit;
368 }
369 if (!cert) {
370 n_log(LOG_ERR, "No certificate given. Exiting.");
371 exit_code = 1;
372 goto clean_and_exit;
373 }
374 /*
375 if (routes->nb_items == 0) {
376 n_log(LOG_ERR, "No route given. Exiting.");
377 exit_code = 1;
378 goto clean_and_exit;
379 }
380 */
381
382#ifndef __windows__
383 errno = 0;
384 signal(SIGPIPE, SIG_IGN);
385 /* initializing signal catching */
386 struct sigaction signal_catcher;
387
388 /* quit on sig */
389 signal_catcher.sa_handler = action_on_sig;
390 sigemptyset(&signal_catcher.sa_mask);
391 signal_catcher.sa_flags = SA_SIGINFO;
392
393 sigaction(SIGTERM, &signal_catcher, NULL);
394 sigaction(SIGUSR1, &signal_catcher, NULL);
395#endif
396
397 int nb_active_threads = get_nb_cpu_cores();
398 int nb_waiting_threads = 10 * nb_active_threads;
399 n_log(LOG_INFO, "Creating a new thread pool of %d active and %d waiting threads", nb_active_threads, nb_waiting_threads);
400 thread_pool = new_thread_pool(nb_active_threads, nb_waiting_threads);
401
402 n_log(LOG_INFO, "Creating listening network for %s:%s %d", _str(addr), _str(port), ip_version);
403 /* create listening network */
404 if (netw_make_listening(&server, addr, port, SOMAXCONN, ip_version) == FALSE) {
405 n_log(LOG_ERR, "Fatal error with network initialization");
406 exit(-1);
407 }
408
409 netw_set_crypto(server, key, cert);
410 while (!done) {
411 n_log(LOG_DEBUG, "Blocking on accept...");
412 /* get any accepted client on a network */
413 int return_code = 0;
414 netw = netw_accept_from_ex(server, 0, 0, 0, &return_code);
415 if (!netw) {
416 if (return_code == EINTR) {
417 n_log(LOG_INFO, "accept exited after catching a signal");
418 goto clean_and_exit;
419 } else {
420 n_log(LOG_ERR, "error on accept, NULL netw returned !");
421 }
422 } else {
423 n_log(LOG_INFO, "accepted SSL connection on socket %d", netw->link.sock);
424 NETWORK_SSL_THREAD_PARAMS* netw_ssl_params = NULL;
425 Malloc(netw_ssl_params, NETWORK_SSL_THREAD_PARAMS, 1);
426 netw_ssl_params->netw = netw;
427 netw_ssl_params->routes = routes;
428 if (add_threaded_process(thread_pool, &ssl_network_thread, (void*)netw_ssl_params, DIRECT_PROC) == FALSE) {
429 n_log(LOG_ERR, "Error adding client management to thread pool");
430 }
431 }
432 }
433clean_and_exit:
434 if (thread_pool) {
435 wait_for_threaded_pool(thread_pool, 1000);
436 destroy_threaded_pool(&thread_pool, 1000);
437 }
438 netw_close(&server);
439 netw_unload();
440 list_destroy(&routes);
441 exit(exit_code);
442}
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
Definition n_common.h:187
#define __n_assert(__ptr, __ret)
macro to assert things
Definition n_common.h:258
#define _str(__PTR)
define true
Definition n_common.h:176
#define Alloca(__ptr, __size)
Malloca Handler to get errors and set to 0.
Definition n_common.h:199
int file_exist(const char *filename)
test if file exist and if it's readable
Definition n_common.c:82
#define Free(__ptr)
Free Handler to get errors.
Definition n_common.h:242
#define _nstr(__PTR)
N_STR or "NULL" string for logging purposes.
Definition n_common.h:182
int destroy_ht(HASH_TABLE **table)
empty a table and destroy it
Definition n_hash.c:2180
#define HT_FOREACH(__ITEM_, __HASH_,...)
ForEach macro helper.
Definition n_hash.h:192
structure of a hash table
Definition n_hash.h:114
int list_push(LIST *list, void *ptr, void(*destructor)(void *ptr))
Add a pointer to the end of the list.
Definition n_list.c:199
#define list_foreach(__ITEM_, __LIST_)
ForEach macro helper.
Definition n_list.h:65
int list_destroy(LIST **list)
Empty and Free a list container.
Definition n_list.c:518
#define MAX_LIST_ITEMS
flag to pass to new_generic_list for the maximum possible number of item in a list
Definition n_list.h:55
Structure of a generic LIST container.
Definition n_list.h:39
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:69
#define LOG_DEBUG
debug-level messages
Definition n_log.h:64
#define LOG_ERR
error conditions
Definition n_log.h:56
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL )
Definition n_log.c:91
#define LOG_NOTICE
normal but significant condition
Definition n_log.h:60
#define LOG_NULL
no log output
Definition n_log.h:26
#define LOG_INFO
informational
Definition n_log.h:62
size_t written
size of the written data inside the string
Definition n_str.h:45
#define free_nstr(__ptr)
free a N_STR structure and set the pointer to NULL
Definition n_str.h:176
N_STR * char_to_nstr(const char *src)
Convert a char into a N_STR, short version.
Definition n_str.c:228
N_STR * new_nstr(NSTRBYTE size)
create a new N_STR string
Definition n_str.c:180
#define nstrprintf(__nstr_var, __format,...)
Macro to quickly allocate and sprintf to N_STR.
Definition n_str.h:94
char ** split(const char *str, const char *delim, int empty)
split the strings into a an array of char *pointer , ended by a NULL one.
Definition n_str.c:874
N_STR * file_to_nstr(char *filename)
Load a whole file into a N_STR.
Definition n_str.c:260
int free_split_result(char ***tab)
Free a split result allocated array.
Definition n_str.c:970
A box including a string and his lenght.
Definition n_str.h:39
char * ip
ip of the connected socket
Definition n_network.h:222
N_SOCKET link
networking socket
Definition n_network.h:302
SOCKET sock
a normal socket
Definition n_network.h:220
SSL * ssl
SSL handle.
Definition n_network.h:294
int netw_get_url_from_http_request(const char *request, char *url, size_t size)
Helper function to extract the URL from the HTTP request line.
Definition n_network.c:3301
int netw_set_crypto(NETWORK *netw, char *key, char *certificate)
activate SSL encryption on selected network, using key and certificate
Definition n_network.c:1160
#define NETWORK_IPV6
Flag to force IPV6
Definition n_network.h:30
int netw_make_listening(NETWORK **netw, char *addr, char *port, int nbpending, int ip_version)
Make a NETWORK be a Listening network.
Definition n_network.c:1644
#define NETWORK_IPV4
Flag to force IPV4
Definition n_network.h:28
int netw_build_http_response(N_STR **http_response, int status_code, const char *server_name, const char *content_type, char *additional_headers, N_STR *body)
function to dynamically generate an HTTP response
Definition n_network.c:3542
#define SOCKET_SIZE_FORMAT
socket associated printf style
Definition n_network.h:63
NETWORK * netw_accept_from_ex(NETWORK *from, size_t send_list_limit, size_t recv_list_limit, int blocking, int *retval)
make a normal 'accept' .
Definition n_network.c:1753
#define NETWORK_IPALL
Flag for auto detection by OS of ip version to use.
Definition n_network.h:26
int netw_close(NETWORK **netw)
Closing a specified Network, destroy queues, free the structure.
Definition n_network.c:1503
NETWORK_HTTP_INFO netw_extract_http_info(char *request)
extract a lot of informations, mostly as pointers, and populate a NETWORK_HTTP_INFO structure
Definition n_network.c:3219
int netw_info_destroy(NETWORK_HTTP_INFO http_request)
destroy a NETWORK_HTTP_INFO loaded informations
Definition n_network.c:3288
HASH_TABLE * netw_parse_post_data(const char *post_data)
Function to parse POST data.
Definition n_network.c:3375
const char * netw_guess_http_content_type(const char *url)
function to guess the content type based on URL extension
Definition n_network.c:3422
Structure of a NETWORK.
Definition n_network.h:236
structure for splitting HTTP requests
Definition n_network.h:339
THREAD_POOL * new_thread_pool(size_t nbmaxthr, size_t nb_max_waiting)
Create a new pool of nbmaxthr threads.
int add_threaded_process(THREAD_POOL *thread_pool, void *(*func_ptr)(void *param), void *param, int mode)
add a function and params to a thread pool
int destroy_threaded_pool(THREAD_POOL **pool, unsigned int delay)
delete a thread_pool, exit the threads and free the structs
long int get_nb_cpu_cores()
get number of core of current system
#define DIRECT_PROC
processing mode for added func, direct start
int wait_for_threaded_pool(THREAD_POOL *thread_pool, unsigned int delay)
Wait for all the launched process in the thread pool to terminate.
Structure of a trhead pool.
List structures and definitions.
Generic log system.
Network Engine.
Signals general handling with stack printing, from https://gist.github.com/jvranish/4441299.
N_STR and string function declaration.
Thread pool declaration.
structure of a NETWORK_SSL_THREAD_PARAMS
LIST * routes
virtual routes for the server
NETWORK * netw
network to use for the receiving thread