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