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