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