Project

General

Profile

Statistics
| Revision:

root / trunk / code / projects / colonet / ColonetServer / ColonetServer.cpp @ 118

History | View | Annotate | Download (8.88 KB)

1
/** 
2
 * @file ColonetServer.cpp
3
 *
4
 * @brief colonet_server - primary server application for Colonet
5
 *
6
 * @author Jason Knichel
7
 * @author Eugene Marinelli
8
 * @date 10/31/06
9
 */
10

    
11
#include <arpa/inet.h>
12
#include <fcntl.h>
13
#include <errno.h>
14
#include <netinet/in.h>
15
#include <string.h>
16
#include <sys/select.h>
17
#include <sys/socket.h>
18

    
19
#include <colonet_wireless.h>
20

    
21
#include "includes/ColonetServer.h"
22
#include "includes/ConnectionPool.h"
23
#include "includes/client.h"
24
#include "includes/options.h"
25
#include "includes/Log.h"
26

    
27
#define LISTEN_BACKLOG 5
28
#define LOG_BUFFER_LENGTH 128
29

    
30
ConnectionPool * connection_pool;
31

    
32
/**
33
 * @brief Default constructor for ColonetServer
34
 */
35
ColonetServer::ColonetServer(): logger("logFile.txt") {
36
  listen_socket = 0;
37
}
38

    
39
/**
40
 * @brief Destructor for ColonetServer
41
 */
42
ColonetServer::~ColonetServer() {
43
}
44

    
45
/**
46
 * @brief Initializes the various elements needed for the server to run
47
 *
48
 * @param argc The number of command line arguments passed to the program
49
 * @param argv The command line arguments passed to the program
50
 *
51
 * @return 0 on success, negative error code on failure
52
 */
53
int ColonetServer::initialize_server(int argc, char * argv[]) {
54
  printf("Initializing Server...\n");
55

    
56
  parseCmdLine(argc, argv);
57

    
58
  if (initialize_connection(optionsG.listen_port) < 0) {
59
    return -1;
60
  }
61

    
62
  if (initialize_wireless() < 0) {
63
    fprintf(stderr, "%s: initWireless failed\n", __FUNCTION__);
64
    return -1;
65
  }
66

    
67
  return 0;
68
}
69

    
70
/**
71
 * @brief Starts the server listening on the socket that was opened for listening
72
 *
73
 * @return 0 on success, negative error code on failure
74
 */
75
int ColonetServer::start_listening() {
76
  if (listen(listen_socket, LISTEN_BACKLOG) < 0) {
77
    log_error("\t\nThere was an error telling the socket to "
78
              "listen for connections from clients.  Terminating Server...\n");
79
    return -1;
80
  }
81
  return 0;
82
}
83

    
84
/**
85
 * @brief Logs an error message to the log file
86
 */
87
int ColonetServer::log_error(char * error_message) {
88
  return logger.logMessage(LOG_TYPE_ERROR, error_message);
89
}
90

    
91
/**
92
 * @brief Logs a message to the log file
93
 */
94
int ColonetServer::log_message(char * message) {
95
  return logger.logMessage(LOG_TYPE_MESSAGE, message);
96
}
97

    
98
/**
99
 * @brief Starts the server running (starts an infinite loop)
100
 */
101
int ColonetServer::run_server() {
102
  connection_pool.set_listen_socket_in_ready_set(listen_socket);
103

    
104
  //TODO: why is all of this in that if statement and not just conn_pool.maxfd = listen_socket ?
105
  if (listen_socket > connection_pool.get_max_file_descriptor()) {
106
    connection_pool.set_max_file_descriptor(listen_socket);
107

    
108
    int accept_socket = 0;
109
    struct sockaddr_in client_addr;
110
    socklen_t client_addr_size = sizeof(client_addr);
111

    
112
    log_message("Server initialized.  About to start listening for connections");
113

    
114
    while(1) {
115
      connection_pool.perform_select(listen_socket);
116

    
117
      //either no descriptors are ready or there was an error
118
      if (connection_pool.get_number_clients_ready() <= 0) {
119
        continue;
120
      }
121

    
122
      if (connection_pool.is_socket_ready_to_read(listen_socket)) {
123
        printf("Something is trying to connect...\n");
124
        if ((accept_socket = accept(listen_socket, (struct sockaddr*) &client_addr, &client_addr_size)) < 0) {
125
          if (errno == EMFILE) {
126
            printf("\tWhen attempting to accept a connection, "
127
                   "reached the per process limit of file descriptors."
128
                   "  Dropping the new connection.\n");
129
            continue;
130
          } else {
131
            printf("\tThere was an error when attempting to accept a connection");
132
          }
133
          continue;
134
        }
135

    
136
        char log_buffer[LOG_BUFFER_LENGTH];
137
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s attempting to connect.", 
138
                 inet_ntoa(client_addr.sin_addr));
139
        logger.logMessage(LOG_TYPE_CONNECT, log_buffer);
140

    
141
        if (connection_pool.add_client(accept_socket) < 0) {
142
          printf("\tThere was an error when trying to add a client to the connection pool.");
143
          continue;
144
        }
145

    
146
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s successfully added to connection pool.", 
147
                 inet_ntoa(client_addr.sin_addr));
148
        logger.logMessage(LOG_TYPE_CONNECT, log_buffer);
149
      }
150

    
151
      if (connection_pool.check_clients() < 0) {
152
        printf("\tThere was an error trying to update the clients.");
153
        continue;
154
      }
155
    }
156
  }
157

    
158
  return 0;
159
}
160

    
161
/**
162
 * @todo This method is here because the wireless message handler has a dependency on the connection_pool
163
 *  This should be removed when that dependency is broken
164
 *
165
 * @return A pointer to the connection pool
166
 */
167
ConnectionPool * ColonetServer::get_connection_pool_pointer() {
168
  return &connection_pool;
169
}
170

    
171
/**
172
 * @brief Initializes the wireless
173
 *
174
 * @return 0 on success, negative error code on error
175
 */
176
int ColonetServer::initialize_wireless() {
177
  char* log_filename = NULL;
178

    
179
  if (optionsG.logging_enabled) {
180
    log_filename = optionsG.log_filename;
181
  }
182

    
183
  colonet_wl_init(optionsG.wireless_port, wirelessMessageHandler,
184
                  log_filename);
185

    
186
  if (!colonet_wl_run_listener_thread()) {
187
    fprintf(stderr, "%s: colonet_wl_run_listener_thread failed.\n",
188
            __FUNCTION__);
189
    return -1;
190
  }
191

    
192
  return 0;
193
}
194

    
195
/**
196
 * @brief Initialize a connection to listen on
197
 *
198
 * @port The port to try to open to listen on
199
 *
200
 * @return 0 on success, negative error code on error
201
 */
202
int ColonetServer::initialize_connection(int port) {
203
  printf("Initializing connection that will be used to listen for " 
204
         "clients...\n");
205
  int options = 1;
206
  struct sockaddr_in my_address;
207

    
208
  //get a socket fd
209
  if ((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
210
    printf("\tThere was an error creating a socket\n");
211
    return -1;
212
  }
213

    
214
  //set up the address struct
215
  memset(&my_address,'\0',sizeof(my_address));
216
  my_address.sin_family = AF_INET;
217
  my_address.sin_addr.s_addr = htonl(INADDR_ANY);
218
  my_address.sin_port = htons(port);
219
  
220
  setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &options, sizeof(options));
221

    
222
  //get the current socket options
223
  if ((options = fcntl(listen_socket, F_GETFL)) < 0) {
224
    printf("\tThere was an error getting the socket options.\n");
225
    return -1;
226
  }
227

    
228
  //set the socket to non blocking
229
  options = (options | O_NONBLOCK);
230
  if (fcntl(listen_socket, F_SETFL, options) < 0) {
231
    printf("\tThere was an error setting the socket to be non blocking.\n");
232
    return -1;
233
  }
234
  
235
  //bind the socket to listen on the specified port
236
  if (bind(listen_socket, (struct sockaddr *) &my_address, sizeof(my_address)) < 0) {
237
    printf("\tThere was an error binding the socket\n");
238
    return -1;
239
  }
240
  
241
  return 0;
242
}
243

    
244
/**
245
 * @brief The main function of the server
246
 *
247
 * @param argc The number of command line arguments passed to the program
248
 * @param argv The command line arguments passed to the program
249
 *
250
 * @return 0 on success, negative error code on error
251
 */
252
int main(int argc, char** argv) {
253
  ColonetServer colonet_server;
254

    
255
  connection_pool = colonet_server.get_connection_pool_pointer();
256

    
257
  if (colonet_server.initialize_server(argc, argv) < 0) {
258
    colonet_server.log_error("\t\nThere was an error initializing the server. "
259
                             "Terminating server...\n");
260
    return -1;
261
  }
262

    
263
  if (colonet_server.start_listening() < 0) {
264
    return -1;
265
  }
266
  
267
  colonet_server.run_server();
268

    
269
  return 0;
270
}
271

    
272
//this is old code that was commented out that I didn't want to delete yet
273
/*
274
int parseCommandLine(int argc, char * argv[], commandParams_t * params)
275
{
276
  printf("Parsing Command Line...\n");
277
  if (!params)
278
    return -1;
279

280
  //if no command line parameters were specified, set to defaults
281
  if (argc == 1) {
282
    printf("No port was specified for listening for client connections."
283
           "  Defaulting to %d\n", DEFAULTPORT);
284
    params->listenPort = DEFAULTPORT;
285
  }
286

287
  if (!argv)
288
    return -1;
289

290
  int i;
291
  for (i = 1; i < argc; i++) {
292
    char * temp = argv[i];
293
    if (temp[0] != '-')
294
      {
295
        printUsage(argv[0]);
296
        return -1;
297
      }
298

299
    switch(temp[1])
300
      {
301
      case 'h': printUsage(argv[0]);
302
        break;
303
      case 'p': 
304
        {
305
          if (i >= argc-1)
306
            {
307
              printUsage(argv[0]);
308
              return -1;
309
            }
310
          i++;
311
          char * portString = argv[i];
312
          char * endptr = NULL;
313
          int port = strtol(portString, &endptr, 10);
314
          if (*endptr != '\0')
315
            {
316
              printf("Invalid port specified...%s, %d\n", endptr, port);
317
              return -1;
318
            }
319
          if (port < SMALLEST_POSS_LISTEN_PORT)
320
            {
321
              printf("You cannot listen on a port less than %d.\n",
322
                     SMALLEST_POSS_LISTEN_PORT);
323
              return -1;
324
            }
325
          params->listenPort = port;
326
          printf("Setting port to listen on to %d.\n", params->listenPort);
327
        }
328
        break;
329
      default: printUsage(argv[0]);
330
        return -1;
331
        break;
332
      }
333
  }
334

335
  return 0;
336
}
337
*/
338