261f51e0e971fe06d52f1209f3b8f0830ff28ed2
[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
50 #include <guacamole/client.h>
51 #include <guacamole/thread.h>
52 #include <guacamole/log.h>
53
54
55 typedef struct client_thread_data {
56
57     int fd;
58
59 } client_thread_data;
60
61
62 void* start_client_thread(void* data) {
63
64     guac_client* client;
65     client_thread_data* thread_data = (client_thread_data*) data;
66
67     guac_log_info("Spawning client");
68
69     /* Load and start client */
70     client = guac_get_client(thread_data->fd); 
71
72     if (client == NULL) {
73         guac_log_error("Client retrieval failed");
74         free(data);
75         return NULL;
76     }
77
78     guac_start_client(client);
79     guac_free_client(client);
80
81     /* Close socket */
82     if (close(thread_data->fd) < 0) {
83         guac_log_error("Error closing connection: %s", strerror(errno));
84         free(data);
85         return NULL;
86     }
87
88     guac_log_info("Client finished");
89     free(data);
90     return NULL;
91
92 }
93
94 int main(int argc, char* argv[]) {
95
96     /* Server */
97     int socket_fd;
98     struct sockaddr_in server_addr;
99     int opt_on = 1;
100
101     /* Client */
102     struct sockaddr_in client_addr;
103     socklen_t client_addr_len;
104     int connected_socket_fd;
105
106     /* Arguments */
107     int listen_port = 4822; /* Default port */
108     int opt;
109
110     char* pidfile = NULL;
111
112     /* Daemon Process */
113     pid_t daemon_pid;
114
115     /* Parse arguments */
116     while ((opt = getopt(argc, argv, "l:p:")) != -1) {
117         if (opt == 'l') {
118             listen_port = atoi(optarg);
119             if (listen_port <= 0) {
120                 fprintf(stderr, "Invalid port: %s\n", optarg);
121                 exit(EXIT_FAILURE);
122             }
123         }
124         else if (opt == 'p') {
125             pidfile = strdup(optarg);
126         }
127         else {
128             fprintf(stderr, "USAGE: %s [-l LISTENPORT] [-p PIDFILE]\n", argv[0]);
129             exit(EXIT_FAILURE);
130         }
131     }
132
133     /* Get binding address */
134     memset(&server_addr, 0, sizeof(server_addr)); /* Zero struct */
135     server_addr.sin_family = AF_INET;
136     server_addr.sin_addr.s_addr = INADDR_ANY;
137     server_addr.sin_port = htons(listen_port);
138
139     /* Get socket */
140     socket_fd = socket(AF_INET, SOCK_STREAM, 0);
141     if (socket_fd < 0) {
142         fprintf(stderr, "Error opening socket: %s\n", strerror(errno));
143         exit(EXIT_FAILURE);
144     }
145
146     if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &opt_on, sizeof(opt_on))) {
147         fprintf(stderr, "Warning: Unable to set socket options for reuse: %s\n", strerror(errno));
148     }
149
150     /* Bind socket to address */
151     if (bind(socket_fd, (struct sockaddr*) &server_addr,
152                 sizeof(server_addr)) < 0) {
153         fprintf(stderr, "Error binding socket: %s\n", strerror(errno));
154         exit(EXIT_FAILURE);
155     } 
156
157     /* Fork into background */
158 #ifdef HAVE_FORK
159     daemon_pid = fork();
160
161     /* If error, fail */
162     if (daemon_pid == -1) {
163         fprintf(stderr, "Error forking daemon process: %s\n", strerror(errno));
164         exit(EXIT_FAILURE);
165     }
166
167     /* If parent, write PID file and exit */
168     else if (daemon_pid != 0) {
169
170         if (pidfile != NULL) {
171
172             /* Attempt to open pidfile and write PID */
173             FILE* pidf = fopen(pidfile, "w");
174             if (pidf) {
175                 fprintf(pidf, "%d\n", daemon_pid);
176                 fclose(pidf);
177             }
178
179             /* Warn on failure */
180             else {
181                 fprintf(stderr, "WARNING: Could not write PID file: %s\n", strerror(errno));
182                 exit(EXIT_FAILURE);
183             }
184
185         }
186
187         exit(EXIT_SUCCESS);
188     }
189 #else
190     daemon_pid = getpid();
191     guac_log_info("fork() not defined at compile time.");
192     guac_log_info("guacd running in foreground only.");
193 #endif
194
195     /* Otherwise, this is the daemon */
196     guac_log_info("Started, listening on port %i", listen_port);
197
198     /* Ignore SIGPIPE */
199     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
200         guac_log_error("Could not set handler for SIGPIPE to ignore. SIGPIPE may cause termination of the daemon.");
201     }
202
203     /* Ignore SIGCHLD (force automatic removal of children) */
204     if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
205         guac_log_error("Could not set handler for SIGCHLD to ignore. Child processes may pile up in the process table.");
206     }
207
208     /* Daemon loop */
209     for (;;) {
210
211 #ifdef HAVE_FORK
212         pid_t child_pid;
213 #else
214         guac_thread_t thread;
215 #endif
216         client_thread_data* data;
217
218         /* Listen for connections */
219         if (listen(socket_fd, 5) < 0) {
220             guac_log_error("Could not listen on socket: %s", strerror(errno));
221             return 3;
222         }
223
224         /* Accept connection */
225         client_addr_len = sizeof(client_addr);
226         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
227         if (connected_socket_fd < 0) {
228             guac_log_error("Could not accept client connection: %s", strerror(errno));
229             return 3;
230         }
231
232         data = malloc(sizeof(client_thread_data));
233         data->fd = connected_socket_fd;
234
235         /* 
236          * Once connection is accepted, send child into background, whether through
237          * fork() or through creating a thread. If thead support is not present on
238          * the platform, guacd will still work, but will only be able to handle one
239          * connection at a time.
240          */
241
242 #ifdef HAVE_FORK
243
244         /*** FORK ***/
245
246         /*
247          * Note that we prefer fork() over threads for connection-handling
248          * processes as they give each connection its own memory area, and
249          * isolate the main daemon and other connections from errors in any
250          * particular client plugin.
251          */
252
253         child_pid = fork();
254
255         /* If error, log */
256         if (child_pid == -1)
257             guac_log_error("Error forking child process: %s\n", strerror(errno));
258
259         /* If child, start client, and exit when finished */
260         else if (child_pid == 0) {
261             start_client_thread(data);
262             return 0;
263         }
264
265         /* If parent, close reference to child's descriptor */
266         else if (close(connected_socket_fd) < 0) {
267             guac_log_error("Error closing daemon reference to child descriptor: %s", strerror(errno));
268         }
269
270 #else
271
272         if (guac_thread_create(&thread, start_client_thread, (void*) data))
273             guac_log_error("Could not create client thread: %s", strerror(errno));
274
275 #endif
276
277     }
278
279     /* Close socket */
280     if (close(socket_fd) < 0) {
281         guac_log_error("Could not close socket: %s", strerror(errno));
282         return 3;
283     }
284
285     return 0;
286
287 }
288