2e7b9f59c00a0298d8382a01083f5a34deef9f83
[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 <sys/types.h>
43
44 #ifdef __MINGW32__
45 #include <winsock2.h>
46 #else
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #endif
50
51 #ifdef HAVE_LIBPTHREAD
52 #include <pthread.h>
53 #elif defined(__MINGW32__)
54 #include <windows.h>
55 #include <process.h>
56 #endif
57
58 #include <errno.h>
59
60 #include <guacamole/client.h>
61 #include <guacamole/log.h>
62
63 /* Windows / MINGW32 handles closing sockets differently */ 
64 #ifdef __MINGW32__
65 #define CLOSE_SOCKET(socket) closesocket(socket)
66 #else
67 #define CLOSE_SOCKET(socket) close(socket)
68 #endif
69
70
71 /* Cross-platform strerror()/errno clone */
72 char error[65536];
73 char* lasterror() {
74 #ifdef __MINGW32__
75     snprintf(error, sizeof(error)-1, "ERROR #%i", GetLastError());
76     return error;
77 #else
78     return strerror(errno);
79 #endif
80 }
81
82
83 typedef struct client_thread_data {
84
85     int fd;
86
87 } client_thread_data;
88
89
90 void* start_client_thread(void* data) {
91
92     guac_client* client;
93     client_thread_data* thread_data = (client_thread_data*) data;
94
95     GUAC_LOG_INFO("Spawning client");
96
97     /* Load and start client */
98     client = guac_get_client(thread_data->fd); 
99
100     if (client == NULL) {
101         GUAC_LOG_ERROR("Client retrieval failed");
102         return NULL;
103     }
104
105     guac_start_client(client);
106
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     /* Daemon Process */
139     pid_t daemon_pid;
140
141 #ifdef __MINGW32__
142     /* Structure for holding winsock version info */
143     WSADATA wsadata;
144 #endif
145
146     /* Parse arguments */
147     while ((opt = getopt(argc, argv, "l:")) != -1) {
148         if (opt == 'l') {
149             listen_port = atoi(optarg);
150             if (listen_port <= 0) {
151                 fprintf(stderr, "Invalid port: %s\n", optarg);
152                 exit(EXIT_FAILURE);
153             }
154         }
155         else {
156             fprintf(stderr, "USAGE: %s [-l LISTENPORT]\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, exit */
204     else if (daemon_pid != 0) {
205         exit(EXIT_SUCCESS);
206     }
207 #else
208     GUAC_LOG_INFO("fork() not defined at compile time.");
209     GUAC_LOG_INFO("guacd running in foreground only.");
210 #endif
211
212     /* Otherwise, this is the daemon */
213     GUAC_LOG_INFO("Started, listening on port %i", listen_port);
214
215     /* Daemon loop */
216     for (;;) {
217
218 #ifdef HAVE_LIBPTHREAD
219         pthread_t thread;
220 #endif
221         client_thread_data* data;
222
223         /* Listen for connections */
224         if (listen(socket_fd, 5) < 0) {
225             GUAC_LOG_ERROR("Could not listen on socket: %s", lasterror());
226             return 3;
227         }
228
229         /* Accept connection */
230         client_addr_len = sizeof(client_addr);
231         connected_socket_fd = accept(socket_fd, (struct sockaddr*) &client_addr, &client_addr_len);
232         if (connected_socket_fd < 0) {
233             GUAC_LOG_ERROR("Could not accept client connection: %s", lasterror());
234             return 3;
235         }
236
237         data = malloc(sizeof(client_thread_data));
238         data->fd = connected_socket_fd;
239
240 #ifdef HAVE_LIBPTHREAD
241         if (pthread_create(&thread, NULL, start_client_thread, (void*) data)) {
242             GUAC_LOG_ERROR("Could not create client thread: %s", lasterror());
243             return 3;
244         }
245 #elif __MINGW32__
246         if (_beginthread(start_client_thread, 0, (void*) data) == -1L) { 
247             GUAC_LOG_ERROR("Could not create client thread: %s", lasterror());
248             return 3;
249         }
250 #else
251 #warning THREAD SUPPORT NOT FOUND! guacd will only be able to handle one connection at a time.
252         GUAC_LOG_INFO("Thread support not present at compile time.");
253         GUAC_LOG_INFO("guacd handling one connection at a time.");
254         start_client_thread(data);
255 #endif
256
257     }
258
259     /* Close socket */
260     if (CLOSE_SOCKET(socket_fd) < 0) {
261         GUAC_LOG_ERROR("Could not close socket: %s", lasterror());
262         return 3;
263     }
264
265     return 0;
266
267 }
268