#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include "../util/pool.h"
#include "../public/nsapi.h"
#include "../util/plist.h"
#include "../util/date.h"
#include "../../ucx/string.h"
#include "webserver.h"
#include "log.h"
#include "httprequest.h"
#include "httplistener.h"
#include "srvctrl.h"
#include "configmanager.h"
static int std_pipe_fds[
2];
static WSBool is_daemon;
void test() {
time_t t = time(
NULL);
pool_handle_t *pool = pool_create();
sstr_t date = date_format_http(t, pool);
printf(
"%s\n", date.ptr);
}
WSBool main_is_daemon(
void) {
return is_daemon;
}
void sig_usr1_reload(
int sig) {
log_ereport(
LOG_INFORM,
"sig reload");
if(cfgmgr_load_config(
NULL) !=
0) {
log_ereport(
LOG_FAILURE,
"cannot reload config");
}
start_all_listener();
signal(
SIGUSR1, sig_usr1_reload);
}
void sig_term(
int sig) {
webserver_shutdown();
}
void* log_pipe_thread(
void *data) {
char buf[
1024];
ssize_t r;
while((r = read(std_pipe_fds[
0], buf,
1024)) >
0) {
}
return NULL;
}
int main(
int argc,
char **argv) {
is_daemon =
1;
for(
int i=
0;i<argc;i++) {
char *p = argv[i];
if(p[
0] ==
'-' && p[
1] ==
'c') {
is_daemon =
0;
break;
}
}
if(is_daemon) {
pid_t pid = fork();
if(pid <
0) {
return EXIT_FAILURE;
}
else if(pid >
0) {
return EXIT_SUCCESS;
}
if(setsid() <
0) {
fprintf(stderr,
"setsid failed\n");
return EXIT_FAILURE;
}
printf(
"start daemon\n");
for(
int i=
0;i<
3;i++) {
close(i);
}
if(pipe(std_pipe_fds) !=
0) {
perror(
"pipe");
return EXIT_FAILURE;
}
pthread_t tid;
pthread_create(&tid,
NULL, log_pipe_thread,
NULL);
}
pool_init(
NULL,
NULL,
NULL);
signal(
SIGUSR1, sig_usr1_reload);
signal(
SIGTERM, sig_term);
signal(
SIGINT, sig_term);
struct sigaction act;
ZERO(&act,
sizeof(
struct sigaction));
act.sa_handler =
SIG_IGN;
sigaction(
SIGPIPE, &act,
NULL);
log_ereport(
LOG_INFORM,
"startup");
int status;
status = webserver_init();
if(status !=
0) {
log_ereport(
LOG_FAILURE,
"cannot initialize server.");
return EXIT_FAILURE;
}
status = webserver_run();
if(status !=
0) {
log_ereport(
LOG_FAILURE,
"cannot run server.");
return EXIT_FAILURE;
}
if(srvctrl_wait()) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}