2d245da3883ba555790f420f523faffb537133f2
[guacd.git] / src / daemon.c
1
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
5  * The contents of this file are subject to the Mozilla Public License Version
6  * 1.1 (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  * http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the
13  * License.
14  *
15  * The Original Code is guacd.
16  *
17  * The Initial Developer of the Original Code is
18  * Michael Jumper.
19  * Portions created by the Initial Developer are Copyright (C) 2010
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *
24  * Alternatively, the contents of this file may be used under the terms of
25  * either the GNU General Public License Version 2 or later (the "GPL"), or
26  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27  * in which case the provisions of the GPL or the LGPL are applicable instead
28  * of those above. If you wish to allow use of your version of this file only
29  * under the terms of either the GPL or the LGPL, and not to allow others to
30  * use your version of this file under the terms of the MPL, indicate your
31  * decision by deleting the provisions above and replace them with the notice
32  * and other provisions required by the GPL or the LGPL. If you do not delete
33  * the provisions above, a recipient may use your version of this file under
34  * the terms of any one of the MPL, the GPL or the LGPL.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 #include <unistd.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <sys/types.h>
44
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47
48 #include <errno.h>
49 #include <syslog.h>
50
51 #include <guacamole/client.h>
52 #include <guacamole/error.h>
53
54 #include "client.h"
55
56 typedef struct client_thread_data {
57
58     int fd;
59
60 } client_thread_data;
61
62
63 void* start_client_thread(void* data) {
64
65     guac_client* client;
66     guac_client_plugin* plugin;
67     client_thread_data* thread_data = (client_thread_data*) data;
68     guac_socket* socket;
69     guac_instruction* select;
70     guac_instruction* connect;
71
72     /* Open guac_socket */
73     socket = guac_socket_open(thread_data->fd);
74
75     /* Get protocol from select instruction */
76     select = guac_protocol_expect_instruction(
77             socket, GUAC_USEC_TIMEOUT, "select");
78     if (select == NULL) {
79
80         /* Log error */
81         syslog(LOG_ERR, "Error reading \"select\": %s",
82                 guac_status_string(guac_error));
83
84         /* Free resources */
85         guac_socket_close(socket);
86         free(data);
87         return NULL;
88     }
89
90     /* Validate args to select */
91     if (select->argc != 1) {
92
93         /* Log error */
94         syslog(LOG_ERR, "Bad number of arguments to \"select\" (%i)",
95                 select->argc);
96
97         /* Free resources */
98         guac_socket_close(socket);
99         free(data);
100         return NULL;
101     }
102
103     syslog(LOG_INFO, "Protocol \"%s\" selected", select->argv[0]);
104
105     /* Get plugin from protocol in select */
106     plugin = guac_client_plugin_open(select->argv[0]);
107     guac_instruction_free(select);
108
109     if (plugin == NULL) {
110
111         /* Log error */
112         syslog(LOG_ERR, "Error loading client plugin: %s",
113                 guac_status_string(guac_error));
114
115         /* Free resources */
116         guac_socket_close(socket);
117         free(data);
118         return NULL;
119     }
120
121     /* Send args response */
122     if (guac_protocol_send_args(socket, plugin->args)
123             || guac_socket_flush(socket)) {
124
125         /* Log error */
126         syslog(LOG_ERR, "Error sending \"args\": %s",
127                 guac_status_string(guac_error));
128
129         if (guac_client_plugin_close(plugin))
130             syslog(LOG_ERR, "Error closing client plugin");
131
132         guac_socket_close(socket);
133         free(data);
134         return NULL;
135     }
136
137     /* Get args from connect instruction */
138     connect = guac_protocol_expect_instruction(
139             socket, GUAC_USEC_TIMEOUT, "connect");
140     if (connect == NULL) {
141
142         /* Log error */
143         syslog(LOG_ERR, "Error reading \"connect\": %s",
144                 guac_status_string(guac_error));
145
146         if (guac_client_plugin_close(plugin))
147             syslog(LOG_ERR, "Error closing client plugin");
148
149         guac_socket_close(socket);
150         free(data);
151         return NULL;
152     }
153
154     /* Load and init client */
155     client = guac_client_plugin_get_client(plugin, socket,
156             connect->argc, connect->argv); 
157     guac_instruction_free(connect);
158
159     if (client == NULL) {
160
161         syslog(LOG_ERR, "Error instantiating client: %s",
162                 guac_status_string(guac_error));
163
164         if (guac_client_plugin_close(plugin))
165             syslog(LOG_ERR, "Error closing client plugin");
166
167         guac_socket_close(socket);
168         free(data);
169         return NULL;
170     }
171
172     /* Start client threads */
173     syslog(LOG_INFO, "Starting client");
174     guac_start_client(client);
175
176     /* Clean up */
177     syslog(LOG_INFO, "Client finished");
178     guac_client_free(client);
179     if (guac_client_plugin_close(plugin))
180         syslog(LOG_ERR, "Error closing client plugin");
181
182     /* Close socket */
183     guac_socket_close(socket);
184     close(thread_data->fd);
185
186     free(data);
187     return NULL;
188
189 }
190
191 int main(int argc, char* argv[]) {
192
193     /* Server */
194     int socket_fd;
195     struct sockaddr_in server_addr;
196     int opt_on = 1;
197
198     /* Client */
199     struct sockaddr_in client_addr;
200     socklen_t client_addr_len;
201     int connected_socket_fd;
202
203     /* Arguments */
204     int listen_port = 4822; /* Default port */
205     int opt;
206
207     char* pidfile = NULL;
208
209     /* Daemon Process */
210     pid_t daemon_pid;
211
212     /* Parse arguments */
213     while ((opt = getopt(argc, argv, "l:p:")) != -1) {
214         if (opt == 'l') {
215             listen_port = atoi(optarg);
216             if (listen_port <= 0) {
217                 fprintf(stderr, "Invalid port: %s\n", optarg);
218                 exit(EXIT_FAILURE);
219             }
220         }
221         else if (opt == 'p') {
222             pidfile = strdup(optarg);
223         }
224         else {
225             fprintf(stderr, "USAGE: %s [-l LISTENPORT] [-p PIDFILE]\n", argv[0]);
226             exit(EXIT_FAILURE);
227         }
228     }
229
230     /* Get binding address */
231     memset(&server_addr, 0, sizeof(server_addr)); /* Zero struct */
232     server_addr.sin_family = AF_INET;
233     server_addr.sin_addr.s_addr = INADDR_ANY;
234     server_addr.sin_port = htons(listen_port);
235
236     /* Get socket */
237     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
238     if (socket_fd < 0) {
239         fprintf(stderr, "Error opening socket: %s\n", strerror(errno));
240         exit(EXIT_FAILURE);
241     }
242
243     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
244         fprintf(stderr, "Warning: Unable to set socket options for reuse: %s\n", strerror(errno));
245     }
246
247     /* Bind socket to address */
248     if (bind(socket_fd, (struct sockaddr*) &server_addr,
249                 sizeof(server_addr)) < 0) {
250         fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
251         exit(EXIT_FAILURE);
252     } 
253
254     /* Fork into background */
255 #ifdef HAVE_FORK
256     daemon_pid = fork();
257
258     /* If error, fail */
259     if (daemon_pid == -1) {
260         fprintf(stderr, "Error forking daemon process: %s\n", strerror(errno));
261         exit(EXIT_FAILURE);
262     }
263
264     /* If parent, write PID file and exit */
265     else if (daemon_pid != 0) {
266
267         if (pidfile != NULL) {
268
269             /* Attempt to open pidfile and write PID */
270             FILE* pidf = fopen(pidfile, "w");
271             if (pidf) {
272                 fprintf(pidf, "%d\n", daemon_pid);
273                 fclose(pidf);
274             }
275
276             /* Warn on failure */
277             else {
278                 fprintf(stderr, "WARNING: Could not write PID file: %s\n", strerror(errno));
279                 exit(EXIT_FAILURE);
280             }
281
282         }
283
284         exit(EXIT_SUCCESS);
285     }
286 #else
287     daemon_pid = getpid();
288     syslog(LOG_INFO, "fork() not defined at compile time.");
289     syslog(LOG_INFO, "guacd running in foreground only.");
290 #endif
291
292     /* Otherwise, this is the daemon */
293     syslog(LOG_INFO, "Started, listening on port %i", listen_port);
294
295     /* Ignore SIGPIPE */
296     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
297         syslog(LOG_ERR, "Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
298     }
299
300     /* Ignore SIGCHLD (force automatic removal of children) */
301     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
302         syslog(LOG_ERR, "Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
303     }
304
305     /* Daemon loop */
306     for (;;) {
307
308 #ifdef HAVE_FORK
309         pid_t child_pid;
310 #else
311         guac_thread_t thread;
312 #endif
313         client_thread_data* data;
314
315         /* Listen for connections */
316         if (listen(socket_fd, 5) < 0) {
317             syslog(LOG_ERR, "Could not listen on socket: %s", strerror(errno));
318             return 3;
319         }
320
321         /* Accept connection */
322         client_addr_len = sizeof(client_addr);
323         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
324         if (connected_socket_fd < 0) {
325             syslog(LOG_ERR, "Could not accept client connection: %s", strerror(errno));
326             return 3;
327         }
328
329         data = malloc(sizeof(client_thread_data));
330         data->fd = connected_socket_fd;
331
332         /* 
333          * Once connection is accepted, send child into background, whether through
334          * fork() or through creating a thread. If thead support is not present on
335          * the platform, guacd will still work, but will only be able to handle one
336          * connection at a time.
337          */
338
339 #ifdef HAVE_FORK
340
341         /*** FORK ***/
342
343         /*
344          * Note that we prefer fork() over threads for connection-handling
345          * processes as they give each connection its own memory area, and
346          * isolate the main daemon and other connections from errors in any
347          * particular client plugin.
348          */
349
350         child_pid = fork();
351
352         /* If error, log */
353         if (child_pid == -1)
354             syslog(LOG_ERR, "Error forking child process: %s\n", strerror(errno));
355
356         /* If child, start client, and exit when finished */
357         else if (child_pid == 0) {
358             start_client_thread(data);
359             return 0;
360         }
361
362         /* If parent, close reference to child's descriptor */
363         else if (close(connected_socket_fd) < 0) {
364             syslog(LOG_ERR, "Error closing daemon reference to child descriptor: %s", strerror(errno));
365         }
366
367 #else
368
369         if (guac_thread_create(&thread, start_client_thread, (void*) data))
370             syslog(LOG_ERR, "Could not create client thread: %s", strerror(errno));
371
372 #endif
373
374     }
375
376     /* Close socket */
377     if (close(socket_fd) < 0) {
378         syslog(LOG_ERR, "Could not close socket: %s", strerror(errno));
379         return 3;
380     }
381
382     return 0;
383
384 }
385