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