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