void FTPClient::writeDataSock(std::string data)
{
    const char* tptr;
    tptr = data.c_str();

    bzero(this->sbuffer,S_BUFFER_SIZE);
    strcpy((char *)this->sbuffer, tptr);

    writeSock(this->datafd,data.length());
}
// Here the argument 'command' contains "the FTP command + it's assoc. param"
enum protocolStatus FTPClient::writeCtrlSock(std::string command)
{
    const char* tptr;
    tptr = command.c_str();

    bzero(this->sbuffer,S_BUFFER_SIZE);
    strcpy((char *)this->sbuffer, tptr);

    writeSock(this->ctrlfd,command.length());

    ssize_t numBytes = receiveReply(this->ctrlfd);
    std::cerr << interpretResponse(this->rbuffer, numBytes) << std::endl;
    return checkCommandStatus();
}
Beispiel #3
0
int writeFd(LOG_OPT* pLogOpt, const char* data)
{
	int fd = 0;
	time_t tnow;
	struct tm tm;
	struct tm* ptm;
    struct stat l_stat;
	char time_buf[MAX_TIME_MSG_LEN] = {0};
	char* pFileName = NULL;
	char msg[MAX_SINGLE_MSG_LEN] = {0};
	
	if (NULL == data|| strlen(data) <= 0)
		return 0;
	
	tnow = time(NULL);
	ptm = localtime_r(&tnow, &tm);

	strftime(time_buf, sizeof(time_buf), TIME_FORMAT, ptm);
	snprintf(msg, sizeof(msg), "%s%s%s", time_buf, data, LOG_EOL);

	if (pLogOpt->sem_flag)
		lockSem(pLogOpt->sem_id);
	
	if (0 == pLogOpt->is_daemon){
		printf("%s", msg);
	}

	if (-1 == write(pLogOpt->file_fd, msg, strlen(msg))){
		if (pLogOpt->file_name){
			fd = open(pLogOpt->file_name, O_WRONLY|O_APPEND|O_CREAT, 0666);
			if (fd > 0){
				write(pLogOpt->file_fd, msg, strlen(msg));
				pLogOpt->file_fd = fd;
			}
		}
	}

	if (pLogOpt->sem_flag)
		unlockSem(pLogOpt->sem_id);

	if (NULL != pLogOpt->file_name && pLogOpt->max_size > 0){
		stat(pLogOpt->file_name, &l_stat);
		if (l_stat.st_size > pLogOpt->max_size){
			close(pLogOpt->file_fd);
			free(pLogOpt->file_name);
			if (NULL == (pFileName = (char*)calloc(1, MAX_LOG_PATH_LEN * sizeof(char)))){
				pLogOpt->err_code = LOG_ERR_MALLOC_NULL;
				return -1;
			}
			getFileName(pFileName);
			if ((fd = open(pLogOpt->file_name, O_WRONLY|O_APPEND|O_CREAT, 0666)) < 0){
				pLogOpt->err_code = LOG_ERR_FD_WRONG;
				return -1;
			}
			pLogOpt->file_fd = fd;
			pLogOpt->file_name = pFileName;
		}
	}

	if (pLogOpt->sock_type == LOG_TYPE_TCP || pLogOpt->sock_type == LOG_TYPE_UDP || pLogOpt->sock_type == LOG_TYPE_FUN)
		return writeSock(pLogOpt, msg);
	
	return 0;
}
Beispiel #4
0
int main(int argc, char *argv[])
{
  int sockfd,
      portno,
      n,
      receivedNum = 0, // int representing the data size sent
      returnStatus,    // value returned from read or write
      dataSizeNum,
      convertedNum,
      connectStatus;
  struct sockaddr_in serv_addr;
  struct hostent *server;        // Defines a host computer
  char txtBuffer[BUFF_SIZE],
       keyBuffer[BUFF_SIZE],
       ciphBuffer[BUFF_SIZE];
  FILE* filePtr;

  // Check for correct arguments
  if (argc < 4)
  {
    fprintf(stderr, "usage: %s plaintext key port\n", argv[0]);
    exit(1);
  }

  // Read the plaintext file
  filePtr = fopen(argv[1], "r");
  if (filePtr == NULL)
  {
    fprintf(stderr, "could not open plaintext file\n");
    exit(1);
  }
  bzero(txtBuffer, BUFF_SIZE);
  fgets(txtBuffer, BUFF_SIZE, filePtr);
  fclose(filePtr);

  // Read the key file
  filePtr = fopen(argv[2], "r");
  if (filePtr == NULL)
  {
    fprintf(stderr, "could not open key file\n");
    exit(1);
  }
  bzero(keyBuffer, BUFF_SIZE);
  fgets(keyBuffer, BUFF_SIZE, filePtr);
  fclose(filePtr);

  // Check for bad characters or if key file is too short
  if (strlen(keyBuffer) < strlen(txtBuffer))
  {
    fprintf(stderr, "ERROR: key %s is too short\n", argv[2]);
    exit(1);
  }

  if (!validChars(txtBuffer))
  {
    fprintf(stderr, "ERROR: bad characters in %s\n", argv[1]);
    exit(1);
  }
  if (!validChars(keyBuffer))
  {
    fprintf(stderr, "ERROR: bad characters in %s\n", argv[2]);
    exit(1);
  }

  /******** Connect to server ********/

  // Set port number and host name
  portno = atoi(argv[3]);
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0)
    error("ERROR opening socket");
  server = gethostbyname("localhost");
  if (server == NULL)
  {
    fprintf(stderr,"ERROR, no such host\n");
    exit(0);
  }

  // Set server address
  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy((char *)server->h_addr,
        (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
  serv_addr.sin_port = htons(portno);

  // Connect to the server
  if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
    error("ERROR on initial connect");

  // Check if trying to connect to otp_dec_d; if so, reject
  returnStatus = read(sockfd, &receivedNum, sizeof(receivedNum));
  if (returnStatus > 0)
  {
    receivedNum = ntohl(receivedNum);
    if (receivedNum == 2)
    {
      fprintf(stderr, "ERROR: could not contact otp_dec_d on port %s\n",
              argv[3]);
      exit(2);
    }
  }

  // Receive the new port number from server after initial connect
  returnStatus = read(sockfd, &receivedNum, sizeof(receivedNum));
  if (returnStatus > 0)
    receivedNum = ntohl(receivedNum);
  else
    fprintf(stderr, "ERROR receiving port number: %d\n", returnStatus);

  // Restart socket on new port number

  close(sockfd);
  // Set port number and host name
  portno = receivedNum; // set to new port number
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0)
    error("ERROR opening socket");
  server = gethostbyname("localhost");
  if (server == NULL)
  {
    fprintf(stderr,"ERROR, no such host\n");
    exit(1);
  }
  // Set server address
  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy((char *)server->h_addr,
        (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
  serv_addr.sin_port = htons(portno);
  // Connect to the server
  do
  {
  connectStatus =
    connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
  if (connectStatus < 0)
    perror("ERROR on secondary connect");
  } while (connectStatus < 0);

  /******** Begin data exchange with server *********/

  // Write the data size of plaintext to the socket
  dataSizeNum = strlen(txtBuffer);
  convertedNum = htonl(dataSizeNum);
  returnStatus = write(sockfd, &convertedNum, sizeof(convertedNum));
  if (returnStatus < 0)
    error("ERROR writing data size");
  // Write plaintext to the socket
  writeSock(sockfd, txtBuffer);

  // Write the data size of the key to the socket
  dataSizeNum = strlen(keyBuffer);
  convertedNum = htonl(dataSizeNum);
  returnStatus = write(sockfd, &convertedNum, sizeof(convertedNum));
  if (returnStatus < 0)
    error("ERROR writing data size");
  // Write key to the socket
  writeSock(sockfd, keyBuffer);

  // Read the data size of ciphertext
  returnStatus = read(sockfd, &receivedNum, sizeof(receivedNum));
  if (returnStatus > 0)
    receivedNum = ntohl(receivedNum);
  else
    fprintf(stderr, "ERROR receiving data size: %d\n", returnStatus);
  // Read ciphertext from the socket
  readSock(sockfd, ciphBuffer, receivedNum);

  printf("%s", ciphBuffer);

  close(sockfd);
  return 0;
}
void FTPClient::writeChar(int32_t sockfd, char ch)
{
    bzero(this->sbuffer,S_BUFFER_SIZE);
    *sbuffer = ch;
    writeSock(this->datafd,1);
}
Beispiel #6
0
void Dijkstra(int **graph, int source, int vert, int destination,int sock)
{
	int *dist = (int*)malloc(vert * sizeof(int*));
	int *prev = (int*)malloc(vert * sizeof(int*));
	int *visited = (int*)malloc(vert * sizeof(int*));
	int curr = source;
	int i = 0;
	while( i < vert)
	{
		dist[i] = 99999;
		prev[i] = -1;
		visited[i] = 0;
		i++;

	}
	dist[source] = 0;
	i = 0;
	while(i < vert)
	{
		visited[curr] = 1;
		int w = 0;
		while(w < vert)
		{
			if((graph[curr][w] != 0) && (graph[curr][w] != 99999) && (graph[curr][w] + dist[curr] < dist[w]) && (visited[w] != 1))
			{
				dist[w] = dist[curr] + graph[curr][w];
				prev[w] = curr;
			}
			w++;
		}
		curr = lowestIndex(dist,visited,vert);
		i++;
	}
	int buffer[vert];
	int tbuffer[vert];
	int count = 0;
	int dest = 0;
	int temp = destination;
	i = 0;
	if(dist[destination] != 99999)
	{
		writeSock(sock,-1);
		printf("%d to %d: ",source,destination);
		while(dest != -1)
		{
			buffer[count] = temp;
			dest = prev[temp];
			temp = dest;
			count++;
		}
		i = count-1;
		while( i >= 0)
		{
			printf("%d... ", buffer[i]);
			i--;
		}
		printf("->%d\n",dist[destination]);
		exit(0);
	}
	else
	{
		sleep(2);
		writeSock(sock,destination);
		temp = 8;
		while(dest != -1)
		{
			buffer[count] = temp;
			dest = prev[temp];
			temp = dest;
			count++;
		}
		i = 0;
		dist[destination] = readSock(sock);
		int t = readSock(sock);
		while(i < t)
		{
			tbuffer[i] = readSock(sock);
			i++;
		}
		i = t;
		temp = 0;
		while(i < (count +t))
		{
			tbuffer[i] = buffer[temp];
			temp++;
			i++;
		}
		i = (count + t) - 1;
		while(i >= 0)
		{
			printf("%d..", tbuffer[i]);
			i--;
		}
		printf("->%d\n",dist[8] + dist[destination]);
	}
}
int web()
{
    sendLog("Web Server Started");
    //Load the config for our server
    srvRun = 0; //set the server run vallue to zero
    //inital setup
    int websockfs, newsockfd, portno, sockdead;
    uint clilen;
    char buffer[CHAR_MAX];
    struct sockaddr_in serv_addr, cli_addr;
    int  n;

    //Make a new socket called websockfs
    websockfs = socket(AF_INET, SOCK_STREAM, 0);

    if (websockfs < 0)
    {
        perror("Error creating socket \n ");
        kill(g_mainpid,SIGTERM);
    }

    //Create socket strcuture
    memset(&serv_addr, 0, sizeof(serv_addr));
    portno = atoi(g_configstruct.port);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(g_configstruct.interface);
    serv_addr.sin_port = htons(portno);
    //This option will let us reuse the port even if it is already in use
    //This allows us to restart the program with out running into issues
    int optval = 1;
    setsockopt(websockfs, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
    //Create a new binding address
    if (bind(websockfs, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
    {
		 perror("Error binding socket shutting down!");
        kill(g_mainpid,SIGTERM);
    }
	
    //STOP THE ZOMBIES, this causes the children to die and stay dead.
    struct sigaction sigchld_action = {
        .sa_handler = SIG_DFL,
        .sa_flags = SA_NOCLDWAIT
    };
    sigaction(SIGCHLD, &sigchld_action, NULL);

    // The listener will now fork off into a child procces
    pid_t listenpid;
    if(srvRun==0)
    {
        srvRun=1;
        //Begin fork
        fflush(stdout);
        listenpid = fork();
        if(listenpid < 0)
        {
            sendLog("Error forking listen child");
            exit(1);
        }

        else if (listenpid==0)
        {
            //Wait and listen for incoming socket connections
            sendLog("Listen");
            listen(websockfs,5);
            clilen = sizeof(cli_addr);

            while(1)
            {
                newsockfd = accept(websockfs, (struct sockaddr *)&cli_addr, &clilen);
				  //After we close the socket and we are sending this child a sigterm shutdown
				  if(g_killflag==1)
				  {
					wait(NULL);
					close(newsockfd);
					close(websockfs);
					sendLog("Web server shutdown");
					exit(0);
				  }
                if (newsockfd < 0)
                {
					  sendLog("Error reading from sock");
                    exit(0);
                }
                //Another fork, after the server forms a socket connection with the
                //client it will fork off into another child proccess
                pid_t clientpid;
                clientpid = fork();
                if(clientpid < 0)
                {
                    printf("Error");
                }

                else if (clientpid==0)
                {
                  prctl(PR_SET_PDEATHSIG, SIGKILL);
					memset(buffer,0,sizeof(buffer));
					n = read( newsockfd,buffer,sizeof(buffer));
					if (n < 0)
					{
						sendLog("Error reading from socket");
					}
					FILE *requestfile = NULL;
					char header[CHAR_MAX];
					//Parse the users request and return a FILE to send
					//and a HTTP response header
					parser(&header,&requestfile,&buffer);
					//We will write to the socket our header, and file
					writeSock(header,requestfile,&newsockfd);
					//shutdown(websockfs,0);
					//Clean up time
					shutdown(newsockfd,2);
					close(newsockfd);
					fclose(requestfile);
					//printf("socket closed\n");
					fflush(stdout);
					sendLog("Close Socket");
					exit(0);
                }
				
                else
                {	  //Close the parents copy of the newsockfd
                    close(newsockfd);
                }
            }
            //shutdown(websockfs,2);
        }
        printf("Going to main loop\n");
        fflush(stdout);
        //Parent Loop continues untill the sighup or sigkill
        while(1)
        {
            if(g_hupflag==1)
            {
                sendLog("Reloading Config");
                sendLog("Server stoping for reload");
				  g_deathklock = listenpid;
				  alarm(5);
				  kill(listenpid,SIGTERM);
				  shutdown(websockfs,2);
				  waitpid(listenpid,NULL,0);
				  alarm(0);
				  sendLog("reload_config");
				  g_configstruct = loadConf();
                 g_hupflag = 0;
                return 0;
            }
            sleep(1);
            if(g_killflag==1)
            {
				//Going through the steps to kill child
				  printf("Got a shutdown signal!\n");
				  sendLog("Shutting down server");
				  g_deathklock = listenpid;
				  alarm(5);
				  kill(listenpid,SIGTERM);
				  shutdown(websockfs,2);
				  waitpid(listenpid,NULL,0);
				  alarm(0);
                return 0;
            }

        }
        
    }
return 0;
}
Beispiel #8
0
void Dijkstra(int **graph, int source, int vert,int sock)
{
	int destination;
	int *dist = (int*)malloc(vert * sizeof(int*));
	int *prev =(int*)malloc(vert * sizeof(int*));
	int *visited =(int*)malloc(vert * sizeof(int*));
	int curr = source;
	int i = 0;
	while( i < vert)
	{
		dist[i] =99999;
		prev[i] = -1;
		visited[i] = 0;
		i++;
	}
	dist[source] = 0;
	i = 0;
	while(i < vert)
	{
		
		visited[curr] = 1;
		int w = 0;
		while(w < vert)
		{
			if((graph[curr][w] != 0) && (graph[curr][w] != 99999) && (graph[curr][w] + dist[curr] < dist[w]) && (visited[w] != 1))
			{
				dist[w] = dist[curr] + graph[curr][w];
				prev[w] = curr;
		
			}
			w++;
		}
		curr = lowestIndex(dist,visited,vert);
		i++;
	}
	destination = readSock(sock);
	if(destination < 0)
	{
		exit(0);
	}
	else
	{
		int buffer[vert];
		int count = 0;
		int dest = 0;
		int temp = destination;
		while(dest != -1)
		{
			buffer[count] = temp;
			dest = prev[temp];
			temp = dest;
			count++;
		}
		readSock(sock);
		sleep(1);
		writeSock(sock,dist[destination]);
		writeSock(sock,count);
		sleep(1);
		i = 0;
		sleep(1);
		while(i < count)
		{
			writeSock(sock,buffer[i]);
			i++;
		}
	}
}