int main(int argc, char **argv)	
{
	argcheck(argc, argv);

	// Setup connection
	char nPORT[7];	// port to connect to
	char * HOST = new char[DEFAULT_BUFLEN];	// host to connect to
	SOCKET serverSocket = INVALID_SOCKET;
	bool success = setupConnection(argc, argv, nPORT, HOST);

	// if connection setup was successful, continue with socket setup
	if (success) {
		//initialize socket 
		SOCKET listenSocket = setupListenSocket(nPORT, argv);
		if (listenSocket == INVALID_SOCKET) {
			fprintf(stderr, "error: INVALID_SOCKET, quitting.");
			//LogF.writetolog("error: INVALID_SOCKET, quitting.");
			exit(0);
		}

		// if the socket setup was successful, continue with testing interface
		else {
			// Create server object
			server = new Client(listenSocket);

			// testing interface with server
			try {
				connectToServerSubsystem();
			} catch (ServerException& e) {
				printf(e.sendEr());
			}
		}
	}

	// if connection setup failed, exit
	else {
		printf("connection setup failed, exiting");
		//LogF.writetolog("connection setup failed.");
		exit(0);
	}
	return 0;	// exit
}
Ejemplo n.º 2
0
int main( int argc, char *argv[] )
{
  /* for parsing args */
  extern char *optarg;
  extern int optind;
  int ch;

  /* vars */
  int i,j;
  int listenfd;

  /* select vars */
  fd_set read_set;
  int fdmax;

  /* client arr */
  Arraylist clientList;
  /* channel arr */
  Arraylist channelList;

  /* servername */
  char servername[MAX_SERVERNAME+1];

  while ((ch = getopt(argc, argv, "hD:")) != -1)
  switch (ch) {
  case 'D':
    if (set_debug(optarg)) {
      exit(0);
    }
    break;
  case 'h':
  default: /* FALLTHROUGH */
    usage();
  }
  argc -= optind;
  argv += optind;

  if (argc < 2) {
    usage();
  }
  signal(SIGPIPE, SIG_IGN);
  init_node(argv[0], argv[1]);

  printf( "I am node %lu and I listen on port %d for new users\n", curr_nodeID, curr_node_config_entry->irc_port );

  /* Start your engines here! */
  if (gethostname(servername,MAX_SERVERNAME) < 0){
    perror("gethostname");
    return EXIT_FAILURE;
  }
  servername[MAX_SERVERNAME] = '\0';

  /* delegate all function calling to setupListenSocket.
        It should print out relevant err messages. */
  listenfd = setupListenSocket(curr_node_config_entry->irc_port);
  if (listenfd < 0){
    return EXIT_FAILURE;
  }

  /* initialize client array */
  clientList = arraylist_create();

  /* initialize channel array */
  channelList = arraylist_create();

  /* prepare for select */
  fdmax = listenfd;
  FD_ZERO(&master_set);
  FD_ZERO(&write_set);
  FD_SET(listenfd,&master_set);

  /* FD_ZERO(&write_set);  initially no data to write */

  /* main loop!! */
  for (;;){
    int retval;
    read_set = master_set;

    /* wait until any sockets become available */
    retval = select(fdmax+1,&read_set,&write_set,NULL,NULL);

    if (retval <= 0){
      if (retval < 0)
      DEBUG_PERROR("select");
      continue; /* handle errors gracefully and wait again if timed out (it shouldn't)*/
    }
    /* at least one socket ready*/
    for (i = 0; i <= fdmax; i++){
      if (FD_ISSET(i, &write_set)) {
        int listIndex = findClientIndexBySockFD(clientList,i);
        client_t *thisClient = (client_t *) CLIENT_GET(clientList,listIndex);
        /*client data ready to be written */
        int nbytes;
        /* iterate through item to be sent, until it will block */
        Arraylist outbuf = thisClient->outbuf;

        while (!arraylist_is_empty(outbuf))
        {
          /* write */
          char *dataToSend = (char *) (arraylist_get(outbuf,0)) + thisClient->outbuf_offset;
          size_t sizeToSend = strlen(dataToSend);
          nbytes = send(thisClient->sock, dataToSend, sizeToSend, 0);
          if (nbytes <0){
            /* error */
            if (errno == EPIPE || errno == ECONNRESET){
              /* connection lost or closed by the peer */

              DPRINTF(DEBUG_SOCKETS,"send: client %d hungup\n",i);
              remove_client(clientList,listIndex);
              continue;
            }
          }
          else if (nbytes == sizeToSend){
            /* current line completely sent */
            char *toRemove = (char *) (arraylist_get(outbuf,0));
            arraylist_removeIndex(outbuf,0);
            free(toRemove);
          }
          else{
            /* partial send */
            thisClient->outbuf_offset += nbytes;
            break;
          }
        }
        if (arraylist_is_empty(outbuf))
          FD_CLR(i, &write_set);
      }
      if (FD_ISSET(i, &read_set)) {
        if (i == listenfd){
          /* incoming connection */
          int newindex = handle_incoming_conn(clientList,servername,listenfd);
          if (newindex < 0){
            continue;
          }
          client_t *newClient = CLIENT_GET(clientList,newindex);
          int newfd = newClient->sock;
          FD_SET(newfd,&master_set);
          if (newfd > fdmax){
            fdmax = newfd;
          }
        }
        else{
          /* client data ready */
          char *tempPtr;
          int listIndex = findClientIndexBySockFD(clientList,i);

          /* for split function */
          char** tokenArr;
          int numToken;
          int lastTokenTerminated;

          if (listIndex < 0){
            close(i);
            FD_CLR(i,&master_set);
            continue;
          }

          int nbytes = recv(i, CLIENT_GET(clientList,listIndex)->inbuf + CLIENT_GET(clientList,listIndex)->inbuf_size,
          MAX_MSG_LEN - CLIENT_GET(clientList,listIndex)->inbuf_size, 0);

          /* recv failed. Either client left or error */
          if (nbytes <= 0){
            if (nbytes == 0){
              DPRINTF(DEBUG_SOCKETS,"recv: client %d hungup\n",i);
              remove_client(clientList, listIndex);

            }
            else if (errno == ECONNRESET || errno == EPIPE){
              DPRINTF(DEBUG_SOCKETS,"recv: client %d connection reset \n",i);
              remove_client(clientList, listIndex);

            }
            else{
              perror("recv");
            }
            continue;
          }

          /* NULL terminate to use strpbrk */
          CLIENT_GET(clientList,listIndex)->inbuf_size += nbytes;
          CLIENT_GET(clientList,listIndex)->inbuf[CLIENT_GET(clientList,listIndex)->inbuf_size] = '\0';
          tempPtr = strpbrk(CLIENT_GET(clientList,listIndex)->inbuf,"\r\n");
          if (!tempPtr){
            if (CLIENT_GET(clientList,listIndex)->inbuf_size == MAX_MSG_LEN){
              /* Message too long. Dump the content */
              DPRINTF(DEBUG_INPUT,"recv: message longer than MAX_MESSAGE detected. The message will be discarded\n");
              CLIENT_GET(clientList,listIndex)->inbuf_size = 0;
            }
            continue;
          }

          tokenArr = splitByDelimStr(CLIENT_GET(clientList,listIndex)->inbuf,"\r\n",&numToken,&lastTokenTerminated);
          /* since we have checked if there's delimeter beforehand, there should be at least one terminated token available*/
          if (!tokenArr){
            DPRINTF(DEBUG_INPUT,"splitByDelimStr: failed to split inputToken\n");
            CLIENT_GET(clientList,listIndex)->inbuf_size = 0;
            continue;
          }
          if (!lastTokenTerminated){
            CLIENT_GET(clientList,listIndex)->inbuf_size = strlen(tokenArr[numToken-1]);
            memcpy(CLIENT_GET(clientList,listIndex)->inbuf,tokenArr[numToken-1],CLIENT_GET(clientList,listIndex)->inbuf_size);
            numToken--;
          }

          for (j=0;j<numToken;j++){
            handle_line(clientList,listIndex,channelList,servername,tokenArr[j]);
          }

          for (j = 0; j < arraylist_size(clientList); j++){
            client_t *client = CLIENT_GET(clientList,j);
            if (arraylist_size(client->outbuf)){
                FD_SET(client->sock,&write_set);
            }
          }
          freeTokens(&tokenArr,numToken);
        }
      }
    }
  }

  return 0;
}