Project

General

Profile

Statistics
| Revision:

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

History | View | Annotate | Download (8.57 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
    logger.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
/**
86
 * @brief Starts the server running (starts an infinite loop)
87
 */
88
int ColonetServer::run_server() {
89
  connection_pool.set_listen_socket_in_ready_set(listen_socket);
90

    
91
  //TODO: why is all of this in that if statement and not just conn_pool.maxfd = listen_socket ?
92
  if (listen_socket > connection_pool.get_max_file_descriptor()) {
93
    connection_pool.set_max_file_descriptor(listen_socket);
94

    
95
    int accept_socket = 0;
96
    struct sockaddr_in client_addr;
97
    socklen_t client_addr_size = sizeof(client_addr);
98

    
99
    logger.log_message("Server initialized.  About to start listening for connections");
100

    
101
    while(1) {
102
      connection_pool.perform_select(listen_socket);
103

    
104
      //either no descriptors are ready or there was an error
105
      if (connection_pool.get_number_clients_ready() <= 0) {
106
        continue;
107
      }
108

    
109
      if (connection_pool.is_socket_ready_to_read(listen_socket)) {
110
        printf("Something is trying to connect...\n");
111
        if ((accept_socket = accept(listen_socket, (struct sockaddr*) &client_addr, &client_addr_size)) < 0) {
112
          if (errno == EMFILE) {
113
            printf("\tWhen attempting to accept a connection, "
114
                   "reached the per process limit of file descriptors."
115
                   "  Dropping the new connection.\n");
116
            continue;
117
          } else {
118
            printf("\tThere was an error when attempting to accept a connection");
119
          }
120
          continue;
121
        }
122

    
123
        char log_buffer[LOG_BUFFER_LENGTH];
124
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s attempting to connect.", 
125
                 inet_ntoa(client_addr.sin_addr));
126
        logger.log_string(LOG_TYPE_CONNECT, log_buffer);
127

    
128
        if (connection_pool.add_client(accept_socket) < 0) {
129
          printf("\tThere was an error when trying to add a client to the connection pool.");
130
          continue;
131
        }
132

    
133
        snprintf(log_buffer, LOG_BUFFER_LENGTH, "Client at address %s successfully added to connection pool.", 
134
                 inet_ntoa(client_addr.sin_addr));
135
        logger.log_string(LOG_TYPE_CONNECT, log_buffer);
136
      }
137

    
138
      if (connection_pool.check_clients() < 0) {
139
        printf("\tThere was an error trying to update the clients.");
140
        continue;
141
      }
142
    }
143
  }
144

    
145
  return 0;
146
}
147

    
148
/**
149
 * @todo This method is here because the wireless message handler has a dependency on the connection_pool
150
 *  This should be removed when that dependency is broken
151
 *
152
 * @return A pointer to the connection pool
153
 */
154
ConnectionPool * ColonetServer::get_connection_pool_pointer() {
155
  return &connection_pool;
156
}
157

    
158
/**
159
 * @brief Initializes the wireless
160
 *
161
 * @return 0 on success, negative error code on error
162
 */
163
int ColonetServer::initialize_wireless() {
164
  char* log_filename = NULL;
165

    
166
  if (optionsG.logging_enabled) {
167
    log_filename = optionsG.log_filename;
168
  }
169

    
170
  /*
171
    colonet_wl_init(optionsG.wireless_port, wirelessMessageHandler,
172
                log_filename);
173

174
  if (!colonet_wl_run_listener_thread()) {
175
    fprintf(stderr, "%s: colonet_wl_run_listener_thread failed.\n",
176
            __FUNCTION__);
177
    return -1;
178
  }
179
  */
180

    
181
  return 0;
182
}
183

    
184
/**
185
 * @brief Initialize a connection to listen on
186
 *
187
 * @port The port to try to open to listen on
188
 *
189
 * @return 0 on success, negative error code on error
190
 */
191
int ColonetServer::initialize_connection(int port) {
192
  printf("Initializing connection that will be used to listen for " 
193
         "clients...\n");
194
  int options = 1;
195
  struct sockaddr_in my_address;
196

    
197
  //get a socket fd
198
  if ((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
199
    printf("\tThere was an error creating a socket\n");
200
    return -1;
201
  }
202

    
203
  //set up the address struct
204
  memset(&my_address,'\0',sizeof(my_address));
205
  my_address.sin_family = AF_INET;
206
  my_address.sin_addr.s_addr = htonl(INADDR_ANY);
207
  my_address.sin_port = htons(port);
208
  
209
  setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &options, sizeof(options));
210

    
211
  //get the current socket options
212
  if ((options = fcntl(listen_socket, F_GETFL)) < 0) {
213
    printf("\tThere was an error getting the socket options.\n");
214
    return -1;
215
  }
216

    
217
  //set the socket to non blocking
218
  options = (options | O_NONBLOCK);
219
  if (fcntl(listen_socket, F_SETFL, options) < 0) {
220
    printf("\tThere was an error setting the socket to be non blocking.\n");
221
    return -1;
222
  }
223
  
224
  //bind the socket to listen on the specified port
225
  if (bind(listen_socket, (struct sockaddr *) &my_address, sizeof(my_address)) < 0) {
226
    printf("\tThere was an error binding the socket\n");
227
    return -1;
228
  }
229
  
230
  return 0;
231
}
232

    
233
/**
234
 * @brief The main function of the server
235
 *
236
 * @param argc The number of command line arguments passed to the program
237
 * @param argv The command line arguments passed to the program
238
 *
239
 * @return 0 on success, negative error code on error
240
 */
241
int main(int argc, char** argv) {
242
  ColonetServer colonet_server;
243

    
244
  connection_pool = colonet_server.get_connection_pool_pointer();
245

    
246
  if (colonet_server.initialize_server(argc, argv) < 0) {
247
    printf("\t\nThere was an error initializing the server. "
248
                             "Terminating server...\n");
249
    return -1;
250
  }
251

    
252
  if (colonet_server.start_listening() < 0) {
253
    return -1;
254
  }
255
  
256
  colonet_server.run_server();
257

    
258
  return 0;
259
}
260

    
261
//this is old code that was commented out that I didn't want to delete yet
262
/*
263
int parseCommandLine(int argc, char * argv[], commandParams_t * params)
264
{
265
  printf("Parsing Command Line...\n");
266
  if (!params)
267
    return -1;
268

269
  //if no command line parameters were specified, set to defaults
270
  if (argc == 1) {
271
    printf("No port was specified for listening for client connections."
272
           "  Defaulting to %d\n", DEFAULTPORT);
273
    params->listenPort = DEFAULTPORT;
274
  }
275

276
  if (!argv)
277
    return -1;
278

279
  int i;
280
  for (i = 1; i < argc; i++) {
281
    char * temp = argv[i];
282
    if (temp[0] != '-')
283
      {
284
        printUsage(argv[0]);
285
        return -1;
286
      }
287

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

324
  return 0;
325
}
326
*/
327