6257947644987840f9d4f58bc9a2624493909d4e
[citadel.git] / appimage / ctdlvisor.c
1 //
2 // This is a supervisor program that handles start/stop/restart of
3 // the various Citadel System components, when we are running on
4 // an AppImage instance.
5 //
6 // Copyright (c) 2021 by the citadel.org team
7 //
8 // This program is open source software.  It runs great on the
9 // Linux operating system (and probably elsewhere).  You can use,
10 // copy, and run it under the terms of the GNU General Public
11 // License version 3.  Richard Stallman is an asshole communist.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <sys/wait.h>
23 #include <errno.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <limits.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 char *data_directory = "/usr/local/citadel";
31 char *http_port = "80";
32 char *https_port = "443";
33 pid_t citserver_pid;
34 pid_t webcit_pid;
35 pid_t webcits_pid;
36 int shutting_down = 0;
37
38 // Call this instead of exit() just for common diagnostics etc.
39 void ctdlvisor_exit(int code) {
40         printf("ctdlvisor: exit code %d\n", code);
41         exit(code);
42 }
43
44
45 // Interrupting this program with a signal will begin an orderly shutdown.
46 void signal_handler(int signal) {
47         fprintf(stderr, "ctdlvisor: caught signal %d\n", signal);
48
49         while(shutting_down) {
50                 fprintf(stderr, "ctdlvisor: already shutting down\n");
51                 sleep(1);
52         }
53
54         int status;
55         pid_t who_exited;
56         char *what_exited = NULL;
57
58         shutting_down = 1;
59         kill(citserver_pid, SIGTERM);
60         kill(webcit_pid, SIGTERM);
61         kill(webcits_pid, SIGTERM);
62         do {
63                 fprintf(stderr, "ctdlvisor: waiting for all child process to exit...\n");
64                 who_exited = waitpid(-1, &status, 0);
65                 if (who_exited == citserver_pid) {
66                         what_exited = "Citadel Server";
67                 }
68                 else if (who_exited == webcit_pid) {
69                         what_exited = "WebCit HTTP";
70                 }
71                 else if (who_exited == webcits_pid) {
72                         what_exited = "WebCit HTTPS";
73                 }
74                 else {
75                         what_exited = "unknown";
76                 }
77                 fprintf(stderr, "ctdlvisor: pid=%d (%s) exited, status=%d, exitcode=%d\n", who_exited, what_exited, status, WEXITSTATUS(status));
78         } while (who_exited >= 0);
79
80         ctdlvisor_exit(0);
81 }
82
83
84 void detach_from_tty(void) {
85         signal(SIGHUP, SIG_IGN);
86         signal(SIGINT, SIG_IGN);
87         signal(SIGQUIT, SIG_IGN);
88
89         setsid();       // become our own process group leader
90         umask(0);
91         if (    (freopen("/dev/null", "r", stdin) != stdin) ||
92                 (freopen("/dev/null", "w", stdout) != stdout) ||
93                 (freopen("/dev/null", "w", stderr) != stderr)
94         ) {
95                 fprintf(stderr, "sysdep: unable to reopen stdio: %s\n", strerror(errno));
96         }
97 }
98
99
100 pid_t start_citadel() {
101         char bin[1024];
102         sprintf(bin, "%s/usr/local/citadel/citserver", getenv("APPDIR"));
103         pid_t pid = fork();
104         if (pid == 0) {
105                 fprintf(stderr, "ctdlvisor: executing %s\n", bin);
106                 detach_from_tty();
107                 execlp(bin, "citserver", "-x9", "-h", data_directory, NULL);
108                 exit(errno);
109         }
110         else {
111                 return(pid);
112         }
113 }
114
115
116 pid_t start_webcit() {
117         char bin[1024];
118         sprintf(bin, "%s/usr/local/webcit/webcit", getenv("APPDIR"));
119         char wchome[1024];
120         sprintf(wchome, "-h%s/usr/local/webcit", getenv("APPDIR"));
121         pid_t pid = fork();
122         if (pid == 0) {
123                 fprintf(stderr, "ctdlvisor: executing %s\n", bin);
124                 detach_from_tty();
125                 execlp(bin, "webcit", "-x9", wchome, "-p", http_port, "uds", data_directory, NULL);
126                 exit(errno);
127         }
128         else {
129                 return(pid);
130         }
131 }
132
133
134 pid_t start_webcits() {
135         char bin[1024];
136         sprintf(bin, "%s/usr/local/webcit/webcit", getenv("APPDIR"));
137         char wchome[1024];
138         sprintf(wchome, "-h%s/usr/local/webcit", getenv("APPDIR"));
139         pid_t pid = fork();
140         if (pid == 0) {
141                 fprintf(stderr, "ctdlvisor: executing %s\n", bin);
142                 detach_from_tty();
143                 execlp(bin, "webcit", "-x9", wchome, "-s", "-p", https_port, "uds", data_directory, NULL);
144                 exit(errno);
145         }
146         else {
147                 return(pid);
148         }
149 }
150
151
152 void test_binary_compatibility(void) {
153         char cmd[1024];
154         int ret;
155         fprintf(stderr, "ctdlvisor: testing compatibility...\n");
156         sprintf(cmd, "%s/usr/local/citadel/citserver -c", getenv("APPDIR"));
157         ret = system(cmd);
158         if (ret) {
159                 fprintf(stderr, "ctdlvisor: this appimage cannot run on your system.\n"
160                                 "           The reason may be indicated by any error messages appearing above.\n");
161         }
162         else {
163                 fprintf(stderr, "ctdlvisor: this appimage appears to be compatible with your system.\n");
164         }
165         exit(ret);
166 }
167
168
169 void main_loop(void) {
170         int status;
171         pid_t who_exited;
172         int citserver_exit_code = 0;
173
174         do {
175                 fprintf(stderr, "ctdlvisor: waiting for any child process to exit...\n");
176                 who_exited = waitpid(-1, &status, 0);
177                 fprintf(stderr, "ctdlvisor: pid=%d exited, status=%d, exitcode=%d\n", who_exited, status, WEXITSTATUS(status));
178
179                 // A *deliberate* exit of citserver will cause ctdlvisor to shut the whole AppImage down.
180                 // If it crashes, however, we will start it back up.
181                 if (who_exited == citserver_pid) {
182                         citserver_exit_code = WEXITSTATUS(status);
183                         if (citserver_exit_code == 0) {
184                                 fprintf(stderr, "ctdlvisor: citserver exited normally - ending AppImage session\n");
185                                 shutting_down = 1;
186                                 kill(webcit_pid, SIGTERM);
187                                 kill(webcits_pid, SIGTERM);
188                         }
189                         else if ((citserver_exit_code >= 101) && (citserver_exit_code <= 109)) {
190                                 fprintf(stderr, "ctdlvisor: citserver exited intentionally - ending AppImage session\n");
191                                 shutting_down = 1;
192                                 kill(webcit_pid, SIGTERM);
193                                 kill(webcits_pid, SIGTERM);
194                         }
195                         else {
196                                 citserver_pid = start_citadel();
197                         }
198                 }
199
200                 // WebCit processes are restarted if they exit for any reason.
201                 if ((who_exited == webcit_pid) && (!shutting_down))     webcit_pid = start_webcit();
202                 if ((who_exited == webcits_pid) && (!shutting_down))    webcits_pid = start_webcits();
203
204                 // If we somehow end up in an endless loop, at least slow it down.
205                 sleep(1);
206
207         } while (who_exited >= 0);
208         ctdlvisor_exit(citserver_exit_code);
209 }
210
211
212 void run_in_foreground(void) {
213         fprintf(stderr, "ctdlvisor: Welcome to the Citadel System, brought to you using AppImage.\n");
214         fprintf(stderr, "ctdlvisor: LD_LIBRARY_PATH = %s\n", getenv("LD_LIBRARY_PATH"));
215         fprintf(stderr, "ctdlvisor:            PATH = %s\n", getenv("PATH"));
216         fprintf(stderr, "ctdlvisor:          APPDIR = %s\n", getenv("APPDIR"));
217         fprintf(stderr, "ctdlvisor:  data directory = %s\n", data_directory);
218         fprintf(stderr, "ctdlvisor:       HTTP port = %s\n", http_port);
219         fprintf(stderr, "ctdlvisor:      HTTPS port = %s\n", https_port);
220
221         if (access(data_directory, R_OK|W_OK|X_OK)) {
222                 fprintf(stderr, "ctdlvisor: %s: %s\n", data_directory, strerror(errno));
223                 ctdlvisor_exit(errno);
224         }
225
226         signal(SIGTERM, signal_handler);
227         signal(SIGHUP, signal_handler);
228         signal(SIGINT, signal_handler);
229         signal(SIGQUIT, signal_handler);
230
231         citserver_pid = start_citadel();
232         webcit_pid = start_webcit();
233         webcits_pid = start_webcits();
234
235         main_loop();
236         ctdlvisor_exit(0);
237 }
238
239
240 void install_as_service(void) {
241
242         // FIXME fail if some other citadel distribution is already there
243         // FIXME fail if any server processes are running
244         // FIXME interact with the user
245         // FIXME get port numbers and data directory
246         // FIXME create the data directory
247         // FIXME move the appimage into its permanent location
248
249         fprintf(stderr, "Installing as service\n");
250
251         FILE *fp = fopen("/etc/systemd/system/ctdl.service", "w");
252         fprintf(fp,     "# This unit file starts all Citadel services via the AppImage distribution.\n"
253                         "[Unit]\n"
254                         "Description=Citadel\n"
255                         "After=network.target\n"
256                         "[Service]\n"
257                         "ExecStart=/root/citadel/appimage/Citadel-x86_64.AppImage run -h %s -s %s -s %s\n"
258                         "ExecStop=/bin/kill $MAINPID\n"
259                         "KillMode=process\n"
260                         "Restart=on-failure\n"
261                         "LimitCORE=infinity\n"
262                         "[Install]\n"
263                         "WantedBy=multi-user.target\n"
264                 ,
265                         data_directory, http_port, https_port
266         );
267         fclose(fp);
268
269         fprintf(stderr, "systemd unit file is installed.  Type 'systemctl enable ctdl' to have it start at boot.\n");
270 }
271
272
273 static char *usage =
274         "\n"
275         "ctdlvisor: usage: ctdlvisor [-h data_directory] [-p http_port] [-s https_port] command\n"
276         "           'command' must be one of: run, install, remove, upgrade, test, help\n"
277         "\n"
278 ;
279
280 int main(int argc, char **argv) {
281         int c;
282
283         if (getenv("APPDIR") == NULL) {
284                 fprintf(stderr, "ctdlvisor: APPDIR is not set.  This program must be run from within an AppImage.\n");
285                 ctdlvisor_exit(1);
286         }
287
288         while ((c = getopt (argc, argv, "h:p:s:")) != -1)  switch(c) {
289                 case 'h':
290                         data_directory = optarg;
291                         break;
292                 case 'p':
293                         http_port = optarg;
294                         break;
295                 case 's':
296                         https_port = optarg;
297                         break;
298                 default:
299                         fprintf(stderr, "%s", usage);
300                         ctdlvisor_exit(1);
301         }
302
303
304         if (argc != optind+1) {
305                 fprintf(stderr, "%s", usage);
306                 ctdlvisor_exit(1);
307         }
308
309         if (!strcasecmp(argv[optind], "run")) {
310                 run_in_foreground();
311         }
312         else if (!strcasecmp(argv[optind], "install")) {
313                 install_as_service();
314         }
315         else if (!strcasecmp(argv[optind], "remove")) {
316                 fprintf(stderr, "oops, this is not implemented yet\n");
317         }
318         else if (!strcasecmp(argv[optind], "upgrade")) {
319                 fprintf(stderr, "oops, this is not implemented yet\n");
320         }
321         else if (!strcasecmp(argv[optind], "test")) {
322                 test_binary_compatibility();
323         }
324         else if (!strcasecmp(argv[optind], "help")) {
325                 fprintf(stderr, "%s", usage);
326                 fprintf(stderr, "[-h dir]  Use 'dir' as the Citadel data directory (this directory must exist)\n"
327                                 "[-p port] Listen for HTTP connections on 'port'\n"
328                                 "[-s port] Listen for HTTPS connections on 'port'\n"
329                                 "'command' must be one of:\n"
330                                 "       run     - launch Citadel services (does not detach from terminal)\n"
331                                 "       install - create systemd unit files for automatic startup at boot\n"
332                                 "       remove  - delete systemd unit files to end automatic startup\n"
333                                 "       upgrade - download and install a new version of this appimage\n"
334                                 "       test    - test the appimage for binary compatibility with this host\n"
335                                 "       help    - display this message\n"
336                                 "\n"
337                 );
338         }
339         else {
340                 fprintf(stderr, "%s", usage);
341                 ctdlvisor_exit(1);
342         }
343
344         ctdlvisor_exit(0);
345 }