-
Notifications
You must be signed in to change notification settings - Fork 0
/
phoenix.cc
315 lines (278 loc) · 8.57 KB
/
phoenix.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// -*- C++ -*-
//
// Main program.
//
// Copyright 1992-2021 Deven T. Corzine <[email protected]>
//
// SPDX-License-Identifier: MIT
//
#include "phoenix.h"
#ifndef HAVE_STRERROR
extern int sys_nerr;
extern char *str_errlist[];
char *strerror(int n)
{
static String msg;
if (n >= 0 && n < sys_nerr) {
return (char *) sys_errlist[n];
} else {
msg.sprintf("Unknown error %d", n);
return ~msg;
}
}
#endif
// Global variables.
EventQueue events; // Server event queue.
Pointer<Event> Shutdown; // Pointer to Shutdown event, if any.
FILE *logfile = NULL; // log file
Timestamp ServerStartTime; // time server started
int ServerStartUptime; // system uptime when server started
// XXX Should logfile use non-blocking code instead?
// Provide basic new and delete operators.
void *operator new (size_t s) { return malloc(s); }
void *operator new[] (size_t s) { return malloc(s); }
void operator delete (void *p) { free(p); }
void operator delete[](void *p) { free(p); }
void operator delete (void *p, size_t s) { free(p); }
void operator delete[](void *p, size_t s) { free(p); }
// XXX class Log?
void OpenLog() // Open log file.
{
String filename;
Timestamp t;
struct tm *tm;
if (!(tm = t.localtime())) error("OpenLog(): localtime");
filename.sprintf("logs/%04d%02d%02d-%02d%02d%02d", tm->tm_year + 1900,
tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min,
tm->tm_sec);
if (!(logfile = fopen(~filename, "a"))) error("OpenLog(): %s", ~filename);
setvbuf(logfile, NULL, _IOLBF, 0);
unlink("log");
if (symlink(~filename, "log") == -1) error("OpenLog(): log -> %s", ~filename);
fprintf(stderr, "Logging on \"%s\".\n", ~filename);
}
// XXX Use << operator instead of printf() formats?
void Log(const char *format, ...) // XXX log message
{
String msg;
va_list ap;
Timestamp t;
if (!logfile) return;
va_start(ap, format);
msg.vsprintf(format, ap);
va_end(ap);
(void) fprintf(logfile, "[%s] %s\n", t.date(4, 15), ~msg);
}
void warn(const char *format, ...) // XXX print error message
{
String msg;
va_list ap;
Timestamp t;
va_start(ap, format);
msg.vsprintf(format, ap);
va_end(ap);
if (errno) msg.sprintf("%s: %s", ~msg, strerror(errno));
(void) fprintf(stderr, "\n%s\n", ~msg);
if (logfile) (void) fprintf(logfile, "[%s] %s\n", t.date(4, 15), ~msg);
}
void error(const char *format, ...) // XXX print error message and exit
{
String msg;
va_list ap;
Timestamp t;
va_start(ap, format);
msg.vsprintf(format, ap);
va_end(ap);
if (errno) msg.sprintf("%s: %s", ~msg, strerror(errno));
(void) fprintf(stderr, "\n%s\n", ~msg);
if (logfile) {
(void) fprintf(logfile, "[%s] %s\n", t.date(4, 15), ~msg);
fclose(logfile);
}
exit(1);
}
void crash(const char *format, ...) // XXX print error message and crash
{
String msg;
va_list ap;
Timestamp t;
va_start(ap, format);
msg.vsprintf(format, ap);
va_end(ap);
(void) fprintf(stderr, "\n%s\n", ~msg);
if (logfile) {
(void) fprintf(logfile, "[%s] %s\n", t.date(4, 15), ~msg);
fclose(logfile);
}
abort();
exit(-1);
}
void quit(int sig) // received SIGQUIT or SIGTERM
{
if (Shutdown) {
Log("Additional shutdown signal %d received.", sig);
} else {
String signal;
signal.sprintf("signal %d", sig);
events.Enqueue(Shutdown = new ShutdownEvent(~signal, 5));
}
}
int SystemUptime() // Get system uptime, if available.
{
int uptime = 0;
FILE *fp = fopen("/proc/uptime", "r");
if (fp) {
if (fscanf(fp, "%d", &uptime) != 1) uptime = 0;
fclose(fp);
}
return uptime;
}
void trim(char *&input)
{
while (*input && isspace(*input)) input++;
char *p = input;
while (*p) p++;
while (p > input && isspace(p[-1])) p--;
*p = 0;
}
char *getword(char *&input, char separator)
{
while (*input && isspace(*input)) input++;
char *p = input;
while (*input && !isspace(*input) && *input != separator) input++;
if (*input) {
while (*input && isspace(*input)) *input++ = 0;
if (*input == separator) *input++ = 0;
while (*input && isspace(*input)) *input++ = 0;
}
return *p ? p : NULL;
}
char *match(char *&input, const char *keyword, int min) {
char *p = input;
const char *q = keyword;
int i;
if (!min) min = strlen(keyword);
for (i = 0; *q; p++, q++, i++) {
if (isspace(*p) || !*p) break;
if ((isupper(*p) ? tolower(*p) : *p) !=
(isupper(*q) ? tolower(*q) : *q)) return NULL;
}
if ((*p && !isspace(*p) && !*q) || i < min) return NULL;
while (isspace(*p)) p++;
return input = p;
}
static char usage[] = "Usage: %s [--cron] [--debug] [--port %d]\n";
int main(int argc, char **argv) // main program
{
int pid; // server process number
int port = 0; // TCP port to use
int opts = 1; // option parsing flag
int arg; // current argument
boolean cron = false; // --cron option
boolean debug = false; // --debug option
// Check for command-line options.
for (arg = 1; arg < argc && argv[arg]; arg++) {
if (opts && !strcmp(argv[arg], "--")) {
opts = 0;
} else if (opts && !strcmp(argv[arg], "--help")) {
fprintf(stdout, usage, argv[0], PORT);
exit(0);
} else if (opts && !strcmp(argv[arg], "--version")) {
fprintf(stdout, "Phoenix %s (C++ version)\n", VERSION);
exit(0);
} else if (opts && !strcmp(argv[arg], "--cron")) {
cron = true;
} else if (opts && !strcmp(argv[arg], "--debug")) {
debug = true;
} else if (opts && !strcmp(argv[arg], "--port")) {
if (++arg < argc && argv[arg]) {
port = atoi(argv[arg]);
} else {
fprintf(stderr, usage, argv[0], PORT);
exit(1);
}
} else {
fprintf(stderr, usage, argv[0], PORT);
exit(1);
}
}
// Use configured default port if not specified.
if (!port) port = PORT;
// If --cron option was given, check if the listening port is busy.
if (cron && Listen::PortBusy(port)) exit(0);
// Mark server start with current time and system uptime if available.
ServerStartTime = 0;
ServerStartUptime = SystemUptime();
// Change to LIBDIR (create if necessary).
if (chdir(LIBDIR) && errno == ENOENT && mkdir(LIBDIR, 0700)) {
error("mkdir(\"%s\", 0700)", LIBDIR);
}
if (chdir(LIBDIR)) error("chdir(\"%s\")", LIBDIR);
// Create logs subdirectory (ignore errors since it may exist), open log.
mkdir("logs", 0700); // ignore errors
OpenLog();
// Open listening port.
Listen::Open(port);
#if defined(HAVE_FORK) && defined(HAVE_WORKING_FORK)
// Fork subprocess and exit parent.
if (debug) {
Log("Started Phoenix server, version %s.", VERSION);
Log("Listening for connections on TCP port %d. (pid %d)", port, getpid());
} else {
switch (pid = fork()) {
case 0:
switch (pid = fork()) {
case 0:
setsid();
close(0);
close(1);
close(2);
Log("Started Phoenix server, version %s.", VERSION);
Log("Listening for connections on TCP port %d. (pid %d)", port,
getpid());
break;
case -1:
error("main(): fork()");
break;
default:
fprintf(stderr, "Started Phoenix server, version %s.\n"
"Listening for connections on TCP port %d. (pid %d)\n",
VERSION, port, pid);
exit(0);
break;
}
break;
case -1:
error("main(): fork()");
break;
default:
int status;
wait(&status);
exit(!WIFEXITED(status) || WEXITSTATUS(status));
break;
}
}
#else
Log("Started Phoenix server, version %s. (pid %d)"), VERSION, getpid());
Log("Listening for connections on TCP port %d.", port);
#endif
// Setup signal handlers.
#ifdef USE_SIGIGNORE
sigignore(SIGHUP);
sigignore(SIGINT);
sigignore(SIGPIPE);
sigignore(SIGALRM);
#else
signal(SIGHUP, SIG_IGN);
signal(SIGINT, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGALRM, SIG_IGN);
#endif
signal(SIGQUIT, quit);
signal(SIGTERM, quit);
// Main loop.
while(1) {
Session::CheckShutdown();
FD::Select(events.Execute());
}
}