Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (9.21 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 <colonet_wireless.h>
12
#include <sys/select.h>
13
#include <sys/socket.h>
14
#include <netinet/in.h>
15
#include <errno.h>
16
#include <arpa/inet.h>
17

    
18
#include <fcntl.h>
19

    
20
#include <colonet_wireless.h>
21

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

    
28
#define LISTEN_BACKLOG 5
29
#define LOG_BUFFER_LENGTH 128
30

    
31
ConnectionPool * connection_pool;
32

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

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

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

    
57
  parseCmdLine(argc, argv);
58

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

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

    
68
  return 0;
69
}
70

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

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

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

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

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

    
109
    int accept_socket = 0;
110
    struct sockaddr_in client_addr;
111
    socklen_t client_addr_size = sizeof(client_addr);
112
    struct timeval select_timeout;
113
    
114
    memset(&select_timeout, 0, sizeof(select_timeout));
115

    
116
    log_message("Server initialized.  About to start listening for connections");
117

    
118
    while(1) {
119
      connection_pool.perform_select(listen_socket, &select_timeout);
120

    
121
      //either no descriptors are ready or there was an error
122
      //TODO: check for specific errors
123
      if (connection_pool.get_number_clients_ready() <= 0) {
124
        continue;
125
      }
126

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

    
142
        char log_buffer[LOG_BUFFER_LENGTH];
143
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s attempting to connect.", 
144
                 inet_ntoa(client_addr.sin_addr));
145
        logger.logMessage(LOG_TYPE_CONNECT, log_buffer);
146

    
147
        if (connection_pool.add_client(accept_socket) < 0) {
148
          printf("\tThere was an error when trying to add a client to the connection pool.");
149
          continue;
150
        }
151

    
152
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s successfully added to connection pool.", 
153
                 inet_ntoa(client_addr.sin_addr));
154
        logger.logMessage(LOG_TYPE_CONNECT, log_buffer);
155
      }
156

    
157
      if (connection_pool.check_clients(wireless) < 0) {
158
        printf("\tThere was an error trying to update the clients.");
159
        continue;
160
      }
161
    }
162
  }
163

    
164
  return 0;
165
}
166

    
167
/**
168
 * @todo This method is here because the wireless message handler has a dependency on the connection_pool
169
 *  This should be removed when that dependency is broken
170
 *
171
 * @return A pointer to the connection pool
172
 */
173
ConnectionPool * ColonetServer::get_connection_pool_pointer() {
174
  return &connection_pool;
175
}
176

    
177
/**
178
 * @brief Initializes the wireless
179
 *
180
 * @return 0 on success, negative error code on error
181
 */
182
int ColonetServer::initialize_wireless() {
183
  char* log_filename = NULL;
184

    
185
  if (optionsG.logging_enabled) {
186
    log_filename = optionsG.log_filename;
187
  }
188

    
189
  wireless = new ColonetWireless(optionsG.wireless_port, 
190
                                 wirelessMessageHandler, log_filename, 
191
                                 /*!optionsG.listener_mode*/false, true);
192
  //Note: last arg set to true ignores token ring;  in general, this should
193
  //probably be false (changed for demo purposes)
194

    
195
  if (!wireless->run_listener_thread()) {
196
    return -1;
197
  }
198

    
199
  return 0;
200
}
201

    
202
/**
203
 * @brief Initialize a connection to listen on
204
 *
205
 * @port The port to try to open to listen on
206
 *
207
 * @return 0 on success, negative error code on error
208
 */
209
int ColonetServer::initialize_connection(int port) {
210
  printf("Initializing connection that will be used to listen for " 
211
         "clients...\n");
212
  int options = 1;
213
  struct sockaddr_in my_address;
214

    
215
  //get a socket fd
216
  if ((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
217
    printf("\tThere was an error creating a socket\n");
218
    return -1;
219
  }
220

    
221
  //set up the address struct
222
  memset(&my_address,'\0',sizeof(my_address));
223
  my_address.sin_family = AF_INET;
224
  my_address.sin_addr.s_addr = htonl(INADDR_ANY);
225
  my_address.sin_port = htons(port);
226
  
227
  setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &options, sizeof(options));
228

    
229
  //get the current socket options
230
  if ((options = fcntl(listen_socket, F_GETFL)) < 0) {
231
    printf("\tThere was an error getting the socket options.\n");
232
    return -1;
233
  }
234

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

    
251
/**
252
 * @brief The main function of the server
253
 *
254
 * @param argc The number of command line arguments passed to the program
255
 * @param argv The command line arguments passed to the program
256
 *
257
 * @return 0 on success, negative error code on error
258
 */
259
int main(int argc, char** argv) {
260
  ColonetServer colonet_server;
261

    
262
  connection_pool = colonet_server.get_connection_pool_pointer();
263

    
264
  if (colonet_server.initialize_server(argc, argv) < 0) {
265
    colonet_server.log_error("\t\nThere was an error initializing the server. "
266
                             "Terminating server...\n");
267
    return -1;
268
  }
269

    
270
  if (colonet_server.start_listening() < 0) {
271
    return -1;
272
  }
273
  
274
  colonet_server.run_server();
275

    
276
  return 0;
277
}
278

    
279
//this is old code that was commented out that I didn't want to delete yet
280
/*
281
int parseCommandLine(int argc, char * argv[], commandParams_t * params)
282
{
283
  printf("Parsing Command Line...\n");
284
  if (!params)
285
    return -1;
286

287
  //if no command line parameters were specified, set to defaults
288
  if (argc == 1) {
289
    printf("No port was specified for listening for client connections."
290
           "  Defaulting to %d\n", DEFAULTPORT);
291
    params->listenPort = DEFAULTPORT;
292
  }
293

294
  if (!argv)
295
    return -1;
296

297
  int i;
298
  for (i = 1; i < argc; i++) {
299
    char * temp = argv[i];
300
    if (temp[0] != '-')
301
      {
302
        printUsage(argv[0]);
303
        return -1;
304
      }
305

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

342
  return 0;
343
}
344
*/
345