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