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