Init logging handlers in client.
[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 __guacd_log_info(guac_client* client, const char* format, va_list args) {
64     vsyslog(LOG_INFO, format, args);
65 }
66
67 void __guacd_log_error(guac_client* client, const char* format, va_list args) {
68     vsyslog(LOG_ERR, format, args);
69 }
70
71 void* start_client_thread(void* data) {
72
73     guac_client* client;
74     guac_client_plugin* plugin;
75     guac_instruction* select;
76     guac_instruction* connect;
77
78     /* Get thread data */
79     client_thread_data* thread_data = (client_thread_data*) data;
80
81     /* Open guac_socket */
82     guac_socket* socket = guac_socket_open(thread_data->fd);
83
84     /* Get protocol from select instruction */
85     select = guac_protocol_expect_instruction(
86             socket, GUAC_USEC_TIMEOUT, "select");
87     if (select == NULL) {
88
89         /* Log error */
90         syslog(LOG_ERR, "Error reading \"select\": %s",
91                 guac_status_string(guac_error));
92
93         /* Free resources */
94         guac_socket_close(socket);
95         free(data);
96         return NULL;
97     }
98
99     /* Validate args to select */
100     if (select->argc != 1) {
101
102         /* Log error */
103         syslog(LOG_ERR, "Bad number of arguments to \"select\" (%i)",
104                 select->argc);
105
106         /* Free resources */
107         guac_socket_close(socket);
108         free(data);
109         return NULL;
110     }
111
112     syslog(LOG_INFO, "Protocol \"%s\" selected", select->argv[0]);
113
114     /* Get plugin from protocol in select */
115     plugin = guac_client_plugin_open(select->argv[0]);
116     guac_instruction_free(select);
117
118     if (plugin == NULL) {
119
120         /* Log error */
121         syslog(LOG_ERR, "Error loading client plugin: %s",
122                 guac_status_string(guac_error));
123
124         /* Free resources */
125         guac_socket_close(socket);
126         free(data);
127         return NULL;
128     }
129
130     /* Send args response */
131     if (guac_protocol_send_args(socket, plugin->args)
132             || guac_socket_flush(socket)) {
133
134         /* Log error */
135         syslog(LOG_ERR, "Error sending \"args\": %s",
136                 guac_status_string(guac_error));
137
138         if (guac_client_plugin_close(plugin))
139             syslog(LOG_ERR, "Error closing client plugin");
140
141         guac_socket_close(socket);
142         free(data);
143         return NULL;
144     }
145
146     /* Get args from connect instruction */
147     connect = guac_protocol_expect_instruction(
148             socket, GUAC_USEC_TIMEOUT, "connect");
149     if (connect == NULL) {
150
151         /* Log error */
152         syslog(LOG_ERR, "Error reading \"connect\": %s",
153                 guac_status_string(guac_error));
154
155         if (guac_client_plugin_close(plugin))
156             syslog(LOG_ERR, "Error closing client plugin");
157
158         guac_socket_close(socket);
159         free(data);
160         return NULL;
161     }
162
163     /* Load and init client */
164     client = guac_client_plugin_get_client(plugin, socket,
165             connect->argc, connect->argv); 
166     guac_instruction_free(connect);
167
168     if (client == NULL) {
169
170         syslog(LOG_ERR, "Error instantiating client: %s",
171                 guac_status_string(guac_error));
172
173         if (guac_client_plugin_close(plugin))
174             syslog(LOG_ERR, "Error closing client plugin");
175
176         guac_socket_close(socket);
177         free(data);
178         return NULL;
179     }
180
181     /* Set up logging in client */
182     client->log_info_handler  = __guacd_log_info;
183     client->log_error_handler = __guacd_log_error;
184
185     /* Start client threads */
186     syslog(LOG_INFO, "Starting client");
187     if (guac_start_client(client))
188         syslog(LOG_ERR, "Client finished abnormally");
189     else
190         syslog(LOG_INFO, "Client finished normally");
191
192     /* Clean up */
193     guac_client_free(client);
194     if (guac_client_plugin_close(plugin))
195         syslog(LOG_ERR, "Error closing client plugin");
196
197     /* Close socket */
198     guac_socket_close(socket);
199     close(thread_data->fd);
200
201     free(data);
202     return NULL;
203
204 }
205
206 int main(int argc, char* argv[]) {
207
208     /* Server */
209     int socket_fd;
210     struct sockaddr_in server_addr;
211     int opt_on = 1;
212
213     /* Client */
214     struct sockaddr_in client_addr;
215     socklen_t client_addr_len;
216     int connected_socket_fd;
217
218     /* Arguments */
219     int listen_port = 4822; /* Default port */
220     int opt;
221
222     char* pidfile = NULL;
223
224     /* Daemon Process */
225     pid_t daemon_pid;
226
227     /* Parse arguments */
228     while ((opt = getopt(argc, argv, "l:p:")) != -1) {
229         if (opt == 'l') {
230             listen_port = atoi(optarg);
231             if (listen_port <= 0) {
232                 fprintf(stderr, "Invalid port: %s\n", optarg);
233                 exit(EXIT_FAILURE);
234             }
235         }
236         else if (opt == 'p') {
237             pidfile = strdup(optarg);
238         }
239         else {
240             fprintf(stderr, "USAGE: %s [-l LISTENPORT] [-p PIDFILE]\n", argv[0]);
241             exit(EXIT_FAILURE);
242         }
243     }
244
245     /* Get binding address */
246     memset(&server_addr, 0, sizeof(server_addr)); /* Zero struct */
247     server_addr.sin_family = AF_INET;
248     server_addr.sin_addr.s_addr = INADDR_ANY;
249     server_addr.sin_port = htons(listen_port);
250
251     /* Get socket */
252     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
253     if (socket_fd < 0) {
254         fprintf(stderr, "Error opening socket: %s\n", strerror(errno));
255         exit(EXIT_FAILURE);
256     }
257
258     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
259         fprintf(stderr, "Warning: Unable to set socket options for reuse: %s\n", strerror(errno));
260     }
261
262     /* Bind socket to address */
263     if (bind(socket_fd, (struct sockaddr*) &server_addr,
264                 sizeof(server_addr)) < 0) {
265         fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
266         exit(EXIT_FAILURE);
267     } 
268
269     /* Fork into background */
270 #ifdef HAVE_FORK
271     daemon_pid = fork();
272
273     /* If error, fail */
274     if (daemon_pid == -1) {
275         fprintf(stderr, "Error forking daemon process: %s\n", strerror(errno));
276         exit(EXIT_FAILURE);
277     }
278
279     /* If parent, write PID file and exit */
280     else if (daemon_pid != 0) {
281
282         if (pidfile != NULL) {
283
284             /* Attempt to open pidfile and write PID */
285             FILE* pidf = fopen(pidfile, "w");
286             if (pidf) {
287                 fprintf(pidf, "%d\n", daemon_pid);
288                 fclose(pidf);
289             }
290
291             /* Warn on failure */
292             else {
293                 fprintf(stderr, "WARNING: Could not write PID file: %s\n", strerror(errno));
294                 exit(EXIT_FAILURE);
295             }
296
297         }
298
299         exit(EXIT_SUCCESS);
300     }
301 #else
302     daemon_pid = getpid();
303     syslog(LOG_INFO, "fork() not defined at compile time.");
304     syslog(LOG_INFO, "guacd running in foreground only.");
305 #endif
306
307     /* Otherwise, this is the daemon */
308     syslog(LOG_INFO, "Listening on port %i", listen_port);
309
310     /* Ignore SIGPIPE */
311     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
312         syslog(LOG_ERR, "Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
313     }
314
315     /* Ignore SIGCHLD (force automatic removal of children) */
316     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
317         syslog(LOG_ERR, "Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
318     }
319
320     /* Daemon loop */
321     for (;;) {
322
323 #ifdef HAVE_FORK
324         pid_t child_pid;
325 #else
326         guac_thread_t thread;
327 #endif
328         client_thread_data* data;
329
330         /* Listen for connections */
331         if (listen(socket_fd, 5) < 0) {
332             syslog(LOG_ERR, "Could not listen on socket: %s", strerror(errno));
333             return 3;
334         }
335
336         /* Accept connection */
337         client_addr_len = sizeof(client_addr);
338         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
339         if (connected_socket_fd < 0) {
340             syslog(LOG_ERR, "Could not accept client connection: %s", strerror(errno));
341             return 3;
342         }
343
344         data = malloc(sizeof(client_thread_data));
345         data->fd = connected_socket_fd;
346
347         /* 
348          * Once connection is accepted, send child into background, whether through
349          * fork() or through creating a thread. If thead support is not present on
350          * the platform, guacd will still work, but will only be able to handle one
351          * connection at a time.
352          */
353
354 #ifdef HAVE_FORK
355
356         /*** FORK ***/
357
358         /*
359          * Note that we prefer fork() over threads for connection-handling
360          * processes as they give each connection its own memory area, and
361          * isolate the main daemon and other connections from errors in any
362          * particular client plugin.
363          */
364
365         child_pid = fork();
366
367         /* If error, log */
368         if (child_pid == -1)
369             syslog(LOG_ERR, "Error forking child process: %s\n", strerror(errno));
370
371         /* If child, start client, and exit when finished */
372         else if (child_pid == 0) {
373             start_client_thread(data);
374             return 0;
375         }
376
377         /* If parent, close reference to child's descriptor */
378         else if (close(connected_socket_fd) < 0) {
379             syslog(LOG_ERR, "Error closing daemon reference to child descriptor: %s", strerror(errno));
380         }
381
382 #else
383
384         if (guac_thread_create(&thread, start_client_thread, (void*) data))
385             syslog(LOG_ERR, "Could not create client thread: %s", strerror(errno));
386
387 #endif
388
389     }
390
391     /* Close socket */
392     if (close(socket_fd) < 0) {
393         syslog(LOG_ERR, "Could not close socket: %s", strerror(errno));
394         return 3;
395     }
396
397     return 0;
398
399 }
400