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