示例#1
0
void receiveFiles(int sid)
{
    int countFiles=0;

    recv(sid, &countFiles, 1, 0);

    printf("\nLiczba plików : %d\n",countFiles);

    printf("\n===== POBIERAM =====");
    int i;
    for(i=0; i<countFiles; i++)
    {
        infoFile *file = receiveFile(sid);
        showFile(file);
        writeFile(configstruct.rootPath, file);

        if (file == NULL)
        {
            fprintf(stderr, "Cannot receive file\n");
            return;
        }

//		dataFilesTmp[i] = *file;
    }

//	dataFiles=dataFilesTmp;
}
示例#2
0
void handler(int client) {
  Message writeMsg;

  writeMsg = *receiveMessage(client, MSG_WRQ, "receive write request", &server_error);

  printf("\n========================================\n\n");
  printf("Received write request of file %s\n", writeMsg.writeRequest.fileName);
  printf("File size: %d bytes\n", writeMsg.writeRequest.fileSize);
  printf("MD5: ");
  printMD5Checksum(writeMsg.writeRequest.md5);
  printf("\n");

  char choice;
  printf("Accept?(y\\n): "); scanf("%c", &choice); getchar();

  if (choice == 'y')
  {
    receiveFile(client, writeMsg);
  }
  else
  {
    sendAckMessage(client, 0, &server_error);   // deny
    printf("Deny message sent\n");
  }
}
bool SendFileHandler(int socket, int commandLength)
{
	qDebug()<<"Recieved send file command";

	const int bufferSize = 500 * 1024;
	char* buffer = new char[bufferSize];
	boost::scoped_array<char> bufferContainer(buffer);

	unsigned long transferId;
	if(!getFourByte(socket, transferId))
	{
		qDebug()<<"Get transfer id error";
		return false;
	}

	commandLength -= 4;
	if(!receiveData(socket, buffer, commandLength))
	{
		qDebug()<<"Receive file name error";
		return false;
	}
	buffer[commandLength] = 0;
	ReceiveFile receiveFile(buffer, transferId);
	receiveFile.doCommand();

	return true;
}
示例#4
0
int main(int argc, char* argv[])
{
    int s = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    
    if (s <= 0) {
        cerr << "server: Socket creation failed." << endl;
        exit(-1);
    }

    sockaddr_in address;
    int addressSize = sizeof(address);
    bzero(&address,addressSize);
    address.sin_family=AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port  = htons(15000);
    
    int status=0;
    status = ::bind(s,(struct sockaddr*) &address, sizeof(address));
    
    if (status != 0) {
        cerr << "server: Bind failed, unable to create port." << endl;
        exit(-1);
    }
    
    receiveFile(s ,address);

    close(s);
  
    return 0;
}
示例#5
0
int main(int argc,char *argv[]){
	int sock,newsock;
	int portNum,pid;
	socklen_t clientLen;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	char buffer[1000];

	if(argc != 2){
		printf("ERROR, wrong number of arguments!\n");
		printf("./ftps portNumber");
		exit(0);
	}
	sock = SOCKET(AF_INET,SOCK_STREAM,0);
	if(sock < 0){
		printf("ERROR OPENING SOCKET!");
		exit(0);
	}
	/*Sets up connection for the server */
	//portNum = atoi(argv[1]);
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = 0;
	server_addr.sin_port = htons(SERVERPORT);
	
	if(BIND(sock,(struct sockaddr *)&server_addr,sizeof(server_addr)) < 0){
		perror("ERROR binding to socket!");
		exit(0);
	}
	
	receiveFile(sock);
		
	return 0;	
}
示例#6
0
void FileReceiver::init(QTcpSocket* socket) {
	this->socket = socket;
	connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
	connect(this->socket, SIGNAL(readyRead()), this, SLOT(readyRead()));

	receiveFile();
	//	now send a START message to sender
	socket->write("START");
}
示例#7
0
int main(int argc, char *argv[]) {
    int sockfd;
    struct addrinfo hints, *servinfo;
    int status;
    
    if (argc != 2) {
        printf("Usage: %s <port>\n", argv[0]);
        return 1;
    }
    printf("ftps: Starting server on port %s...\n", argv[1]);
    
    // Create output folder
    if (mkdir(OUTPUT_DIR, S_IRWXU) == -1) {
        int err = errno;
        if (err != EEXIST) {
            fprintf(stderr, "ftps: Error creating output directory: %s\n",
                    strerror(err));
            exit(1);
        }
    }
    
    // Setup structures
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ((status = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) {
        fprintf(stderr, "ftps: getaddrinfo: %s\n", gai_strerror(status));
        return 1;
    }
    
    // Get socket
    if ((sockfd = SOCKET(servinfo->ai_family, servinfo->ai_socktype,
                         servinfo->ai_protocol)) == -1) {
        perror("ftps: socket");
        exit(1);
    }
    // Bind
    if (BIND(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) == -1) {
        perror("ftps: bind");
        CLOSE(sockfd);
        exit(1);
    }
    
    // Accept - Block until connection
    while (ACCEPT(sockfd, servinfo->ai_addr, &(servinfo->ai_addrlen)) != 0);
    
    // Clean up
    freeaddrinfo(servinfo);
    
    // Wait for file then exit
    receiveFile(sockfd);
    CLOSE(sockfd);
    exit(0);
    
    return 0;
}
示例#8
0
/* client function that performs the pull method */
int clientPull(int sock)
{
	int numSongs=numSongsInDir();

	if(numSongs)
	{

		if(!sendHeader(2, numSongs*sizeof(song), numSongs, sock))
			fatal_error("send header has failed\n");

		song *songs=createSongArray(numSongs);
		if(!songs)
			fatal_error("creating song array failed\n");

		if(sendSongArray(songs,numSongs,sock)!=sizeof(song)*numSongs)
			fatal_error("sending song array failed\n"); 

		free(songs);
	}
	else
	{
		if(!sendHeader(2, 0, 0, sock))
			fatal_error("send header has failed\n");
	}
		
	header *rcvHead= receiveHeader(sock);
	if(!rcvHead)
		fatal_error("error receiving rcv header\n");
		
	if(!rcvHead->indexes)
	{
		fprintf(stderr,"You have all the songs that are on the server.\n\n");
	}	
	else
	{
		song *rcvSongs=recvSongArray(rcvHead->indexes,sock);
		if(!rcvSongs)
			fatal_error("error receiving song array\n");
			
		fprintf(stderr, "The following songs have been added to your directory:\n");
		int i;
		for(i=0;i<rcvHead->indexes;i++)
		{
			FILE *file = fopen(rcvSongs[i].title,"w+");
			if(!receiveFile(file, rcvSongs[i].lenOfSong, sock))
				fatal_error("receive file failed\n");
			fclose(file);
			fprintf(stderr, "%s\n",rcvSongs[i].title);
		}
		fprintf(stderr,"\n");
		free(rcvSongs);
	}
	free(rcvHead);
	return 1;
		
}
示例#9
0
/*
-- FUNCTION: processCommand
--
-- DATE: September 23, 2011
--
-- REVISIONS: 
-- September 25, 2011 - removed socket as part of the arguments and moved the 
-- creation of the socket inside.
-- September 27, 2011 - moved the creation of the socket to a helper function
-- September 27, 2011 - changed arguments to controlSocket and transferSocket
--
-- DESIGNER: Karl Castillo
--
-- PROGRAMMER: Karl Castillo
--
-- INTERFACE: void processCommand(int* controlSocket, int* transferSocket);
--				controlSocket - pointer to the controlSocket
--				transferSocket - pointer to the transferSocket
--
-- RETURNS: void
--
-- NOTES:
-- This function sets up the required client connections to connect to the
-- transfer server, such as creating a socket, setting the socket to reuse mode,
-- binding it to an address, and setting it to listen. If an error occurs, the
-- function calls "systemFatal" with an error message.
--
-- A menu will be printed with the available commands. Each command will produce
-- a different effect on the server.
--
-- Commands:
-- e - exit the program
-- r - receive a file from the server
-- s - send a file to the server
-- f - show local files
-- h - show a list of available commands
*/
void processCommand(int* controlSocket)
{
	FILE* temp = NULL;
	char* cmd = (char*)malloc(sizeof(char) * BUFFER_LENGTH);
	int port = getPort(controlSocket);
	
	// Print help
	printHelp();
	printf("$ ");
	
	while(TRUE) {		
		cmd[0] = getc(stdin);
		
		switch(cmd[0]) {
		case 'e': // exit
			closeSocket(controlSocket);
			exit(EXIT_SUCCESS);
		case 'r': // receive file
			cmd[0] = (char)0;
			printf("Enter Filename: ");
			scanf("%s", cmd + 1);
			// Send Command and file name
			if(sendData(controlSocket, cmd, BUFFER_LENGTH) == -1) {
				systemFatal("Error sending receive command");
			}
			closeSocket(controlSocket);
			receiveFile(port, cmd + 1);
			exit(EXIT_SUCCESS);
		case 's': // send file
			cmd[0] = (char)1;
			printf("Enter Filename: ");
			scanf("%s", cmd + 1);
			// Send Command and file name
			if(sendData(controlSocket, cmd, BUFFER_LENGTH) == -1) {
				systemFatal("Error sending send command.");
			}
			if((temp = fopen(cmd + 1, "r"))== NULL) {
				fprintf(stderr, "%s does not exist\n", cmd + 1);
				continue;
			}
			fclose(temp);
			closeSocket(controlSocket);
			sendFile(port, cmd + 1);
			exit(EXIT_SUCCESS);
		case 'h': // show commands
			printHelp();
			printf("$ ");
			break;
		case 'f':
			system("ls");
			printf("$ ");
			break;
		}
	}
	
}
示例#10
0
void Logic::receive() {
    std::string msg = security.receive();
    int type = msg[0];
    std::string content(msg.data()+1, msg.size()-1);
    switch(type) {
        case 9: receiveFile(content); break;
        case 6: receiveFileRequest(content); break;
        case 12: logOut(); break;
        default: break;
    }
}
示例#11
0
文件: client.cpp 项目: malimome/LoSt
int FileRet(int sock, uint64_t *elapsed)
{
  int res;
  sendFile(TEMPFILE, sock);
  getTimeElapsed();

  res=receiveFile(TEMPFILE, sock);
  *elapsed = getTimeElapsed();
  cout<<"Time elapsed:  "<< *elapsed << "\t res: " << res <<endl;

  return res;
}
示例#12
0
int main(int argc, char** argv){
//define the files to be used
    char *fileName, *inputFile, *outFile;  
    int port;
    long fileLength=0;
    int opt, err;
    //add salt according to taste
    char *password, *salt = "NaCl";
    int keyLength = 32, macLength = 32, blockLength = 16;
    int numberOfIterations = 4096;
    char *initCounter;  
    char *key;

//parse the arguments and let the program decide the mode to be followed
    opt = parseArgs(argc, argv, &fileName, NULL, &port);
    checkErr(opt, USAGE_STR);

    if(D_DAEMON == opt){
	err = receiveFile(port, &inputFile, &fileLength);
	checkErr(err, "File receive error");
    
    } else if(L_LOCAL == opt){
	err = readFile(fileName, &fileLength, &inputFile );
	checkErr(err, "File read error");
    }
    password = getpass("Password:"******"Key derivation error");
    printKey(key, keyLength);

    err = verifyMac(key, keyLength, inputFile, fileLength, macLength);
    checkErr(err, "HMAC verification error");

    initCounter = (char*)(malloc(blockLength * sizeof(char)));

    memset((void *)initCounter, 0, (size_t)(blockLength * sizeof(char))); 

    err = aesCounter(key, keyLength, inputFile, fileLength - macLength, initCounter,
	    blockLength, &outFile);
    checkErr(err, "Decryption error");

    err = writeFile(fileName, outFile, fileLength - macLength, NULL, 1, opt);
    checkErr(err, "Error in output file operation");
    printf("%ld bytes written.\n", fileLength - macLength);

    return 0;
}
示例#13
0
void RemotePicberry::run()
{
    char response[6];
    int percentage = 0;
    bool multi_round = false;
    int round = 0;

    if(mode == SRV_WRITE) {
        multi_round = true;
        sendFile();
        sendFinishFileSend();
    }

    while(working) {
        if(picberry_socket.bytesAvailable() ||
                picberry_socket.waitForReadyRead()) {
            picberry_socket.readLine(response, 5);
            qDebug() << response;
            if(QString(response) == "@FIN") {
                if(!multi_round) {
                    working=false;
                }
                else if(multi_round && round==1) {
                    sendFinishFirstRun();
                }
                else if(multi_round && round==2) {
                    working = false;
                }
                round++;
            }
            else if(QString(response) == "@ERR") {
                sendError();
                working = false;
                return;
            }
            else {
                sscanf(response, "@%d", &percentage);
                sendProgress(percentage);
            }
        }
    }
    if(mode == SRV_READ) {
        sendStartFileReceive();
        receiveFile();
    }
    picberry_socket.readAll();
    sendFinish();
}
示例#14
0
文件: main.c 项目: 56Nexus/Lab4
int main(int argc, char *argv[])
{
    if (argc < 3 || argc > 4) {
        fprintf(stderr,
                "usage 1: main <host> <port>\nusage 2: main <host> <port> <filePath>\n");
        return 1;
    }
    // Change SIGINT action
    struct sigaction intSignal;
    intSignal.sa_handler = intHandler;
    sigaction(SIGINT, &intSignal, NULL);

    if (argc == 3)
        receiveFile(argv[1], atoi(argv[2]));
    else
        sendFile(argv[1], atoi(argv[2]), argv[3]);

    return 0;
}
示例#15
0
文件: App.c 项目: francisquinha/RCOM
//return 0 if ok, -1 if image was not received, -2 start faled, -3 if connection failed on disk
int receiveImage(bool reconnect) {

	//receive
	int ret = 0;
	if (reconnect == FALSE) image_already_bytes = 0;
	ret = receiveFile(app.fd, image_name, &image_bytes, &image_bytes_length, &image_already_bytes);

	if (ret == -1) can_reconect = YES;
	else can_reconect = NO;

	//receive disk(do this before saving image to avoid delays)
	char* packet; int llread_result = 0;
	llread_result = llread(app.fd, &packet);
	if (llread_result != -2)//read returns -2 when receives disk
	{
		if (llread_result > 0) free(packet);
		ret = -3;
	}

	return ret;
}
int main(int argc, char**argv){
	struct addrinfo hints, *result;
	int sock;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s port filename\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	file_path =  argv[2];
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_INET6;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_protocol = IPPROTO_UDP;
	
	if(getaddrinfo(NULL, argv[1], &hints, &result)==-1){
		perror("getaddrinfo");
		exit(EXIT_FAILURE);
	}
	
	sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
	if(sock == -1){
			perror("socket creation");
			exit(EXIT_FAILURE);
	}
	
	if(bind(sock,(struct sockaddr *) result->ai_addr, sin6len)==-1){
		perror("bind");
		exit(EXIT_FAILURE);
	}
	
	if(readsync(sock)==-1){
		perror("Sync error on reading sync");
		exit(EXIT_FAILURE);
	}
	
	if(sendMsg(sock, PTYPE_SYN, 0, 0) ==-1){
		perror("Sync error on first send");
		exit(EXIT_FAILURE);
	}
	
	if(sendMsg(sock, PTYPE_ACK, 0, 0) ==-1){
		perror("Sync error on first ack");
		exit(EXIT_FAILURE);
	}
	
	if(readAck(sock)== -1){
			perror("Acknoledgement reading");
			exit(EXIT_FAILURE);
	}
	if(receiveFile(sock)==-1){
		perror("Error while receiving file");
		exit(EXIT_FAILURE);	
	}
	
	freeaddrinfo(result);
	close(sock);
	exit(EXIT_SUCCESS);

	
		
}
示例#17
0
int main(int argc, char** argv) {

  printf("Group number 12\n");
  printf("Members: Kevin and Dorothy\n");

  // Create a UDP socket file descriptor. AF_INET is internet protocol and 
  // SOCK_DGRAM stands for UDP. If the return value is negative then something
  // is wrong.
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0); 
  if(sockfd < 0) {
    printf("Server: failed to open datagram socket, program will now exit");
    exit(1);
  }

  // Initialize the address structure to zero.
  struct sockaddr_in server_addr;
  bzero((char*)&server_addr, sizeof(server_addr));

  // This indicates what type of Internet protocol the socket address holds.
  // Also make the server accept calls on any server addresses, and convert them
  // into the network data representation.
  server_addr.sin_family = AF_INET; // what type of internet protocol.
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // accept any calls.

  // Using default port number if argc == 1.
  if(argc == 1) {
    printf("Server: port number is %d\n.", SERVER_PORT_NUMBER);
    server_addr.sin_port = htons(SERVER_PORT_NUMBER);
  }

  // Using the specified port number if argc == 3.
  else if(argc == 3 && strcmp(argv[1], "-p") == 0) {
    // 65535 is the largest TCP/IP network port number.
    if(atoi(argv[2]) > 65535) {
      printf("Server: port number is too big. Please make it less than 65536.\n");
      exit(1);
    }
    printf("Server: changing port number to %s\n", argv[2]);
    server_addr.sin_port = htons(atoi(argv[2]));
  }

  // Someone has typed an invalid command.
  else {
    printf("Invalid command!\n"); 
    exit(1);
  }

  // Bind the socket to the address and port from server address. This will
  // likely to happen if there's a zombie process that hasn't been killed.
  if(bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
    printf("Server: failed to bind local address.");
    printf("Program will now exit.\n");
    exit(1);
  }

  // Make a memory allocation for client address.
  struct sockaddr client_addr; int clilen = sizeof(struct sockaddr);

  signal(SIGCHLD, SIG_IGN); // prevent zombie process.

  while(1) {

    sigsetjmp(beginning, 1); // get back here when 10 timeouts reached.

    // receive requests from client here.
    struct REQUEST* request = malloc(sizeof(struct REQUEST));
    bzero(request, sizeof(request));
    struct ACKNOWLEDGE* ack = malloc(sizeof(struct ACKNOWLEDGE));
    bzero(ack, sizeof(ack));

    // Start receiving request from client.
    int n = recvfrom(sockfd, request, sizeof(struct REQUEST), 0, &client_addr, &clilen);

    if(n < 0) {
      printf("%s: something is wrong when receiving requests from client...\n");
      free(request); request = 0; free(ack); ack = 0;
      continue; // don't do anything. Just go back to the beginning of loop.
    }

    // Grab the name of the requested file to some variable.
    char filename[MAX_FILENAME]; strcpy(filename, request->filename);

    // Let the child process handle client requests.
    if(fork() == 0) {
      
      close(sockfd);

      // Here, do the same thing as how one initializes the parent address.
      int child = socket(AF_INET, SOCK_DGRAM, 0);
      struct sockaddr_in child_addr; 
      bzero((char*)&child_addr, sizeof(child_addr));
      child_addr.sin_family = AF_INET;
      child_addr.sin_addr.s_addr = htonl(INADDR_ANY);
      child_addr.sin_port = htons(0); // Arbitrary port number.
      bind(child, (struct sockaddr*)&child_addr, sizeof(child_addr));

      switch(ntohs(request->opcode)) {

	case WRQ: // Write request sent to the server.
	  printf("Server: received [Write Request]\n");

	  // Server approves the request. Now it can start receiving the file.
	  ack->opcode = htons(ACK); ack->block = htons(0);

	  // Check whether the file already exists. Don't do anything if it 
	  // already exists.
	  FILE* check = fopen(filename, "rb");
	  if(check != 0) {
	    printf("Server: file \"%s\" exists. Don't do anything.\n", filename);
	    fclose(check); ack->opcode = htons(ERROR);
	    sendto(sockfd, ack, sizeof(struct ACKNOWLEDGE), 0, &client_addr, clilen);
	    free(request); request = 0; free(ack); ack = 0;
	    close(child); exit(1);
	    continue;
	  }

	  // Otherwise, send the acknowledgement to the client, and start receiving
	  // the request file.
	  sendto(sockfd, ack, sizeof(struct ACKNOWLEDGE), 0, &client_addr, clilen);
	  receiveFile(sockfd, filename);

	  // Close the child process and go back to the beginning.
	  free(request); request = 0; free(ack); ack = 0;
	  close(child); exit(0);
	  break;

	case RRQ: // Read request sent to the server.
	  printf("Server: received [Read Request]\n");

	  // Check whether the file exists in the server, or the permission.
	  FILE* checking = fopen(filename, "rb");

	  // Can't open the file means either file doesn't exist, or permission
	  // denied. In this case, just go back to the beginning.
	  if(checking == 0) {
	    printf("Server: file \"%s\" doesn't exist or no permission.\n", filename);
	    ack->opcode = htons(ERROR);
	    sendto(sockfd, ack, sizeof(struct ACKNOWLEDGE), 0, &client_addr, clilen);
	    close(child); exit(0);
	    break;
	  }

	  // Otherwise, send the acknowledgement to the client.
	  else ack->opcode = htons(ACK);
	  ack->block = htons(0);
	  sendto(sockfd, ack, sizeof(struct ACKNOWLEDGE), 0, &client_addr, clilen);

	  // Here, start sending the requested file to the client.
	  sendFile(sockfd, &client_addr, clilen, filename);

	  // Close the child process, and go back to the beginning.
	  close(child); exit(0);
	  break;

      }
    }


  }

  return 0;
}
示例#18
0
int main(int argc, char *argv[])
{
    if(argc == 1) {
    	fprintf(stderr,"Error no arguments type -? for usage.\n");
	exit(EXIT_FAILURE);
    }
    int sockfd;
    SSL_CTX *ctx;

    //setup variables that define what the client does
    char request[LENGTH];
    memset(request, '\0', LENGTH);

    enum { SEND_MODE, FETCH_MODE, VOUCH_MODE, LIST_MODE, DEFAULT_MODE } mode = DEFAULT_MODE;
    int option = 0;
    int circumference = 0, port = 0;
    char *fileName, *hostname, *trustedname, *certificate, *certname, *msg;

    //Specifying the expected options
    while ((option = getopt(argc, argv,"a:c:f:h:ln:u:v:?")) != -1) {
        switch (option) {
            case 'a' : //upload a file
		fileName = optarg;
		//print the request to a variable that will be send later
		snprintf(request, sizeof(request), "add file %s", basename(fileName));
		//set the mode of the client
		mode = SEND_MODE;
                break;
            case 'c' : //provide circumference
                circumference = atoi(optarg);
                break;
            case 'f' : //fetch a file
                snprintf(request, sizeof(request), "fetch %s",optarg);
      		fileName = optarg;
		mode = FETCH_MODE;
                break;
            case 'h' : //specify server address
		//get the hostname and port
                hostname = strtok(optarg, ":");
                char *temp = strtok(NULL, ":");
		if(temp != NULL) port = atoi(temp);
                break;
            case 'l' : //list all files on server
		snprintf(request, sizeof(request), "list");
		mode = LIST_MODE;
		break;
            case 'n' : //require name in circle
                trustedname = optarg;
		break;
            case 'u' : //upload a cert
                fileName = optarg;
		certname = basename(fileName);
		snprintf(request, sizeof(request), "add cert %s",certname);		
		mode = SEND_MODE;
                break;
            case 'v' : //vouch
		if(argv[optind] == NULL || argv[optind][0] == '-') { //check whether certificate arg is given
			fprintf(stderr,"Please specify a certicate. Type -? for usage.\n");
			exit(EXIT_FAILURE);
		}
		fileName = argv[optind];
		certname = basename(fileName);
		snprintf(request, sizeof(request), "vouch %s %s",optarg, certname);
		mode = VOUCH_MODE;
		optind = optind+1;
		break;
	    case '?' : //print usage
		print_usage();
		exit(EXIT_SUCCESS);
		break;
            default: print_usage();
                exit(EXIT_FAILURE);
        }
}

    //no hostname specified
    if(hostname == NULL || port == 0) {
    	fprintf(stderr, "[Client] Please specify a hostname and port, type -? for usage\n");
	exit(EXIT_FAILURE);
    }
    //try and connect to the server
    if((sockfd = connectServer(hostname, port)) == -1) {
    	fprintf(stderr, "[Client] Unable to connect to the server.\n");
	exit(EXIT_FAILURE);
    }
    //SSL handshake		
    SSL *ssl = createSSL(sockfd, ctx);
    
    //ask the server to server us
    sendRequest(ssl, request); 
    int getMsg = 1; //whether or not we want to get a message from the server after all is said and done

    int result;
    //execute the requested client options
    switch (mode) {
            case SEND_MODE : 
		result = sendFile(ssl, fileName); 
		if(result == EXIT_FAILURE) {
			exit(EXIT_FAILURE);
		}
		break;

            case FETCH_MODE :
		//first send circumference then send trustedname
		sendCircumference(ssl, circumference);
		memset(request, '\0', LENGTH); //empty the request buffer, ready to send trustedname
		snprintf(request, sizeof(request), "%s",trustedname);	
		sendRequest(ssl, request); //send the trustedname as a request (only doing this because I cant be bothered writing a new method and this one works fine.
		if(getServerMessage(ssl) == EXIT_FAILURE) {
			exit(EXIT_FAILURE);
		}		
		result = receiveFile(ssl);
                break;

            case LIST_MODE : 
		result = receiveFile(ssl);
		break;

            case VOUCH_MODE : 		
		if(getServerMessage(ssl) == EXIT_FAILURE) {
			getMsg = 0; 
			break;
		}
		result = sendFile(ssl, fileName);//send the vouching cert to the server
		if(result == EXIT_FAILURE) exit(EXIT_FAILURE);
		break;
            case DEFAULT_MODE: fprintf(stderr, "[Client] Please specify a send or receive argument, type -? for usage.\n");
    		exit(EXIT_FAILURE);
    }
    //get the result of our request back from the server
    if(getMsg) getServerMessage(ssl);
    
       
    close(sockfd);
    SSL_CTX_free(ctx);        /* release context */
    fprintf(stderr,"[Client] Connection lost.\n");
    
    exit(EXIT_SUCCESS);
}
示例#19
0
//HANDLE SIGNALS SENT THROUGH THE CONNECTION.
int processReceived(char mode, char * fname, int fd, int id, int user){
	FILE * fp;
	int master_fd[1];
	switch(mode){
		case OPEN:		fp = fopen(fname,"r");
					if(fp == NULL){
						printf("ERROR: %s not found in the shared directories",fname);
						//exit(1);
					}//TODO
					//sendFile(fd,fname,fp);
					break;

		case SAVE:		receiveFile(fd, fname);
					break;
	
	}

	if(user == MASTER){
		switch(mode){
/**			case QUIT:		close(fd);
						workers.worker_fd[id] = -1;
						workers.workerCount--;
						printf("Worker %d has quit\n",id+1);
						break;

			case FAIL:		printf("Worker %d has failed\n",id+1);
						reassign();
						printf("Map task reassigned to worker %d\n",*workers.idle);
						break;

			case SUCCESS:		printf("Worker %d has completed the map task\n",id+1);
						*workers.idle = id;
						workers.idle--;
						mode = SIGNAL;
						break;**/
			case NOTIFY:		printf("Worker %d: %s\n", id, fname);
						break;
		}
	}
	else if(user == WORKER){
		master_fd[0] = fd;
		switch(mode){
			case START_MAP:		printf("Starting Map task for %s\n",fname);
						fname = concat(2,CACHE,fname);
						printf("%s\n",fname);
						run(fname, MAP, master_fd, 1);
						printf("Completed Map task\n");
						cmd(fd, NOTIFY, "Completed Map task");
						break;

			case START_REDUCE:	printf("Starting Reduce task for %s\n", fname);
						fname = concat(2,CACHE,fname);
						run(fname, REDUCE, master_fd, 1);
						printf("Completed Reduce task\n");
						cmd(fd, NOTIFY, "Completed the Reduce task");
						break;

			case KILL:		//TODO:
						break;
		}
	}

}
示例#20
0
int handle_command(int socket)
{
	char message[MESSAGE];
	int result;
	int code;

	//receive message
	if((result = recvall(socket, message, sizeof(message))) == -1){
		printf("handle_command recvall failed\n");
		return -1;
	}

	//if result 0, close connection
	if(result == CLOSED){
		struct peer *closedSocket = findConnection(socket);
		printf("%s closed the connection\n", closedSocket->hostname);
		updateSelect(DELETE, socket, &master_set, &fdmax);
		removeFromConnections(socket);
		if(localInfo.isServer){
		//broadcast new IP list
			sendIPLIST();
		}
		return 0;
	}

	//printf("NEW MESSAGE: %s\n", message);
	
	//EXTRACTING MESSAGE 
	char* newptr = message;
	int nbytes;

	char hostName[200];
	char port[50];
	char ipaddr[INET6_ADDRSTRLEN];

	//extract header
	sscanf(newptr, "%d %n", &code, &nbytes);
	newptr += nbytes;

	//SERVER IP UPDATE
	switch(code) {

		case ADD_IP_LIST :
		{
			DESTROY_IPLIST();
			printf("\n%s UPDATED SERVER IP LIST:\n", getTime());
			while(true){
				//parse out the IP LIST
				sscanf(newptr, "%s %s %s %n", hostName, ipaddr, port, &nbytes);
				if(strcmp(hostName, "EOF") == 0) {break;}
				//printf("%s %s %s\n",hostName, ipaddr, port);
				SAVE_IPLIST(hostName, port, ipaddr);
				newptr += nbytes;
			}
			PRINT_IPLIST();
			printf("\n");
			break;
		}
		case SEND_FILE :
		{
			char filename[50];
			char file_len[50];
			char chunks_num[50];
			sscanf(newptr, "%s %s %s", filename, file_len, chunks_num);
			struct peer *sender = findConnection(socket);
			printf("DOWNLOADING FILE: %s FROM: %s\n", filename, sender->hostname);
			if ((result = receiveFile(socket, filename, file_len, chunks_num)) != 0){
				return result;
			}
			break;
		}
		case REQUEST_FILE : 
		{
			char filename[50];
			int connectionID;
			sscanf(newptr, "%s", filename);

			if((connectionID = findID(socket)) == -1){
				printf("REQUEST_FILE: connection does not exist\n");
				return EHOSTUNREACH;
			}

			char ID[20];
			sprintf(ID, "%d", connectionID);
			int argCount = 3;
			char *arguments[] = {"UPLOAD", ID, filename};

			if((result = cmd_upload(argCount, arguments)) != 0){
				printf("ERROR: Could not upload file.\n");
				char message[MESSAGE];
				sprintf(message, "%d %s\n",NOTIFICATION, "REQUEST FAILED: COULD NOT UPLOAD FILE!");
				sendall(socket, message, sizeof(message));
				return EHOSTUNREACH;
			}
			break;
		}
		case NOTIFICATION :
		{	
			struct peer *sender = findConnection(socket);
			printf("\n**** NOTIFICATION FROM: %s ****\n", sender->hostname);
			printf(">> %s\n", newptr);
			break;
		}
		default :
			printf("Invalid Message Code, cannot understand\n");
			return -1;
	}

	return 0;	
}
int main(int argc, char **argv)
{
    int         socketDescriptor, new_socketDescriptor, client_len, port;
    struct	    sockaddr_in server, client;
    char	    *bufferPointer, buf[BUFFER_LENGTH], messageType;
    bool        notEndOfMessage;
    std::string fileName;
    std::ostringstream messageBuffer;

    switch(argc)
    {
        case 1:
            port = SERVER_TCP_PORT;	// Use the default port
            break;
        case 2:
            port = atoi(argv[1]);	// Get user specified port
            break;
        default:
            fprintf(stderr, "Usage: %s [port]\n", argv[0]);
            exit(1);
    }

    // Create a stream socket
    if ((socketDescriptor = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror ("Can't create a socket");
        exit(1);
    }

    // Bind an address to the socket
    bzero((char *)&server, sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = htonl(INADDR_ANY); // Accept connections from any client

    if (bind(socketDescriptor, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
        perror("Can't bind name to socket");
        exit(1);
    }

    // Listen for connections
    // queue up to 5 connect requests
    listen(socketDescriptor, 5);

    notEndOfMessage = true;
    client_len= sizeof(client);
    new_socketDescriptor = accept(socketDescriptor, (struct sockaddr *)&client, (socklen_t*)&client_len);

    if (new_socketDescriptor == -1) //If fails to connect to client
    {
        fprintf(stderr, "Can't accept client\n");
        exit(1);
    }

    printf("Remote Address:  %s\n", inet_ntoa(client.sin_addr));

    while(notEndOfMessage) //Receives data from client and puts into buffer
    {
        bufferPointer = buf;
        recv(new_socketDescriptor, bufferPointer, BUFFER_LENGTH - 1, 0);
        messageBuffer << std::string(bufferPointer);

        if(checkIfEndOfMessage(messageBuffer)) //Breaks if hits end of file character
        {
            notEndOfMessage = false;
        }
    }

    messageType = getMessageType(messageBuffer);
    fileName = getFileName(messageBuffer);

    if(messageType == 'S')//SEND request
    {
        receiveFile(fileName, messageBuffer);
    }
    else if(messageType == 'G')//GET request
    {
        sendFile(fileName, new_socketDescriptor);
    }
    else //Not SEND or GET request, fail condition
    {
        std::cout << "Error on message type";
    }

    close(socketDescriptor);
    return(0);
}
示例#22
0
DWORD WINAPI inputThread(LPVOID _param)
{
	HANDLE hFile = (HANDLE)_param;
	HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
	OVERLAPPED writeOverlapped = {0};
	if(hFile == INVALID_HANDLE_VALUE || hIn == INVALID_HANDLE_VALUE)
	{
		fprintf(stderr, "Failed to get stdin or OpeniBoot handle.\n");
		gbRunning = false;
		return 1;
	}

	writeOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	if(!writeOverlapped.hEvent)
	{
		fprintf(stderr, "Failed to allocate event for writing.\n");
		return 3;
	}

	while(gbRunning)
	{
		char conInput[1024];
		DWORD amtRead;
		if(ReadFile(hIn, conInput, sizeof(conInput)-2, &amtRead, NULL))
		{
			if(amtRead > 0)
			{
				if(conInput[amtRead-1] != '\n')
				{
					conInput[amtRead] = '\n';
					conInput[amtRead+1] = '\0';
				}
				else
					conInput[amtRead] = '\0';

				switch(conInput[0])
				{
				case '!': // Send File
					{
						conInput[amtRead-2] = '\0'; // No trailing \r\n.
						char *cmd = conInput+1;

						int iLocation = -1;
						char *szLocation = strchr(cmd, '@');
						if(szLocation)
						{
							*szLocation = 0;
							szLocation++;

							sscanf(szLocation, "%d", &iLocation);
						}

						sendFile(hFile, cmd, iLocation);
					}
					break;

				case '~': // Receive File
					{
						conInput[amtRead-2] = '\0'; // No trailing \r\n.
						char *cmd = conInput+1;

						int iLocation = -1;
						char *szLocation = strchr(cmd, '@');
						if(szLocation)
						{
							*szLocation = 0;
							szLocation++;

							sscanf(szLocation, "%d", &iLocation);
						}

						size_t iSize = 0;
						char *szSize = strchr(cmd, ':');
						if(szSize)
						{
							*szSize = 0;
							szSize++;

							sscanf(szSize, "%ul", &iSize);
						}

						receiveFile(hFile, cmd, iSize, iLocation);
					}
					break;

				case ':': // Local Command
					{
						conInput[amtRead-2] = '\0'; // No trailing \r\n.
						parseCommand(hFile, conInput+1);
					}
					break;

				default: // Remote Command
					{
						DWORD written;
						if(!WriteFile(hFile, conInput, amtRead, &written, &writeOverlapped)
							&& GetLastError() == ERROR_IO_PENDING)
							WaitForSingleObject(writeOverlapped.hEvent, INFINITE);
					}
					break;
				}
			}
		}
		else
		{
			fprintf(stderr, "Failed to read from stdin.\n");
			gbRunning = false;
			CloseHandle(writeOverlapped.hEvent);
			return 2;
		}
	}

	CloseHandle(writeOverlapped.hEvent);
	return 0;
}
示例#23
0
void nameFilesFolder(int sid)
{
    infoFile **files;
    int i=0, numberFile=0;
    DIR *d;
    struct dirent *dir;

    d = opendir(configstruct.rootPath);
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            if( strcmp(dir->d_name, ".")!=0 &&
                    strcmp(dir->d_name, "..")!=0 )
                i++;
        }
    }
    closedir(d);

    d = opendir(configstruct.rootPath);
    if (d)
    {
        files = (infoFile**) malloc( i*sizeof(infoFile*) );
        i=0;
        while ((dir = readdir(d)) != NULL)
        {
            if( strcmp(dir->d_name, ".")!=0 &&
                    strcmp(dir->d_name, "..")!=0 )
            {
                files[i] = readFile(configstruct.rootPath, dir->d_name);
                printf("%2d. %s %lu\n", i, files[i]->name, files[i]->size);
                i++;
            }
        }
    }
    closedir(d);

    printf("\nNumer pliku do wysłania : ");
    scanf("%d", &numberFile);

    printf("===== WYSYŁAM =====");
    showFile( files[numberFile] );
    sendFile(sid, files[numberFile] );


    enum odp o;
    recv(sid, &o, sizeof(enum odp), 0);
    if (o==NOWY)
    {
        printf("%s : Utworzono nowy plik na serwerze\n\n", files[numberFile]->name);
    }
    else if (o==NIEZNANY)
    {
        printf("%s : Nieznana wersja pliku\n\n", files[numberFile]->name);
        printf("===== CO CHCZESC ZROBIĆ =====\n");
        printf("0 - Anuluj\n");
        printf("1 - Zapisz jako najnowszą wersję\n");
        printf("2 - Zapisz pod nową nazwą\n");
        printf("3 - Pobierz najnowsza wersje (zastąp aktualną)\n");
        printf("4 - Pobierz najnowsza wersje pod nową nazwą\n");
        while (1==1)
        {
            char wybor;
            scanf("%c", &wybor);
            if (wybor=='0')
            {
                enum odp o2 = NONE;
                send(sid, &o2, sizeof(enum odp), 0);
                break;
            }
            else if (wybor=='1')
            {
                enum odp o2 = NOWA_WERSJA;
                send(sid, &o2, sizeof(enum odp), 0);
                break;
            }
            else if (wybor=='2')
            {
                printf("Nowa nazwa plik : ");
                scanf("%s", files[numberFile]->name);
                enum odp o2 = NOWY_PLIK;
                send(sid, &o2, sizeof(enum odp), 0);
                sendFile(sid, files[numberFile]);
                break;
            }
            else if (wybor=='3')
            {
                enum odp o2 = POBIERZ_PLIK;
                send(sid, &o2, sizeof(enum odp), 0);
                infoFile *file2 = receiveFile(sid);
                showFile(file2);
                writeFile(configstruct.rootPath, file2);
                freeFile(file2);
                break;
            }
            else if (wybor=='4')
            {
                enum odp o2 = POBIERZ_PLIK_NAZWA;
                send(sid, &o2, sizeof(enum odp), 0);
                infoFile *file = receiveFile(sid);
                printf("Podaj nową nazwę pliku : ");
                scanf("%s", file->name);
                writeFile(configstruct.rootPath, file);
                freeFile(file);
                break;
            }
        }
    }
    else if (o==AKTUALNY)
    {
        printf("%s : To jest najnowsza wersja pliku\n\n", files[numberFile]->name);

    }
    else if (o==STARY)
    {
        printf("%s : To jest stara wersja pliku\n\n", files[numberFile]->name);

    }
}
示例#24
0
文件: client.cpp 项目: malimome/LoSt
bool challengeResponse(int sock, unsigned long l, uint64_t *diffNano)
{
  verifier(l);

  FILE* fp = fopen("ctmp","wb");

	fprintf(fp, "%lu\n", (unsigned long)l);
	for (int i = 0; i<l; i++)
		fprintf(fp, "%lu\n", indices[i]);

  char strCff[1024] = {0};
  for(int i=0; i<l; i++)
  {
   	mpz_get_str(strCff, 62, coeff[i]);
   	fprintf(fp, "%s\n", strCff);
  	bzero(strCff, 1024);
  }
  fclose(fp);

	sendFile("ctmp", sock);
  getTimeElapsed();
    /* Buffers for response generated by server (prover) */
	receiveFile("ctmpr", sock);

	*diffNano = getTimeElapsed();
  cout<<"Time elapsed:  "<< *diffNano <<endl;

  mpz_t servSigma,meu[s];
  fp = fopen("ctmpr","rb");
  for(int i=0; i<s; i++)
  {
  	mpz_init(meu[i]);
   	fgets(strCff, sizeof(strCff), fp);
   	mpz_set_str(meu[i], strCff, 62);
   	bzero(strCff, 1024);
  }

	mpz_init(servSigma);
	fgets(strCff, sizeof(strCff), fp);
	mpz_set_str(servSigma, strCff, 62);
	fclose(fp);

  mpz_t cliSigma;
  mpz_init(cliSigma);

  verify(meu, l, &cliSigma);

  bzero(strCff, 1024);
  mpz_get_str(strCff, 10, cliSigma);
	cout << "Sigma at client: " << strCff<< endl;

	free(indices);

  if(mpz_cmp(cliSigma, servSigma)==0)
  {
    cout<<"@@@@@@@@@@@ Data verified........................"<< endl << endl;
    return true;
  }
  else
  {
    cout<<"########### Data lost............................"<< endl << endl;
    return false;
  }
}