Beispiel #1
0
TEST_F(PutFileTest, VersionOutdated)
{
    std::string path = "/not_empty_dir_00/existed_file_10";
    std::string rpath = _dataRoot 
        + PATH_SEPARATOR_STRING
        + BUCKET_NAME(VALID_BUCKET_ID)
        + PATH_SEPARATOR_STRING
        + USER_NAME(VALID_USER_ID)
        + path;

    int rt = 0;

    FileAttr attr;

    rt = ::open(rpath.c_str(), O_RDWR);
    ASSERT_NE(-1, rt);

    int fd = rt;

    ASSERT_EQ(sizeof(FileAttr), ::read(fd, &attr, sizeof(FileAttr)));

    attr.m_Version = 5;

    ASSERT_NE(-1, ::lseek(fd, 0, SEEK_SET));

    ASSERT_EQ(sizeof(FileAttr), ::write(fd, &attr, sizeof(FileAttr)));

    ::close(fd);

    putFile(VALID_USER_ID, path,
            &PutFileTest::cbVersionOutdated, 3);
    putFile(VALID_USER_ID, path,
            &PutFileTest::cbVersionOutdated, 8);
}
Beispiel #2
0
TEST_F(PutFileTest, PathExist)
{
    putFile(VALID_USER_ID, "/existed_file_00",
            &PutFileTest::cbPathExist);
    putFile(VALID_USER_ID, "/not_empty_dir_00/existed_file_10",
            &PutFileTest::cbPathExist);
}
Beispiel #3
0
TEST_F(PutFileTest, IsDirectory)
{
    putFile(VALID_USER_ID, "/empty_dir_00", 
            &PutFileTest::cbIsDirectory);
    putFile(VALID_USER_ID, "/empty_dir_00", 
            &PutFileTest::cbIsDirectory, 3);
}
Beispiel #4
0
TEST_F(PutFileTest, PathNotExist)
{
    putFile(VALID_USER_ID, "/new_file_00", 
            &PutFileTest::cbPathNotExist, 1);
    putFile(VALID_USER_ID, "/empty_dir_00/new_file_10", 
            &PutFileTest::cbPathNotExist, 1);
}
Beispiel #5
0
TEST_F(PutFileTest, PathInvalid)
{
    putFile(VALID_USER_ID, "/no_such_dir/new_file_10", 
            &PutFileTest::cbPathInvalid);
    putFile(VALID_USER_ID, "/empty_dir_00/new_file_10/", 
            &PutFileTest::cbPathInvalid);
    putFile(VALID_USER_ID, "/", 
            &PutFileTest::cbPathInvalid);
}
int syncHostnameFiles()
{

    //open current directory and send all files to all the connected peers
    char *directory = "./";
    char *filename = stringConcat(myHostName, ".txt");

    //send file for all peers in connectionList
    struct list *listIterator = connectionList;
    struct host *destination;
    while (listIterator != NULL) {
        destination = (struct host *) listIterator->value;
        //if destination is the master server do not send
        if (masterServer != NULL && destination->sockfd == masterServer->sockfd) {
            listIterator = listIterator->next;
            continue;
        }
        filename = stringConcat(directory, filename);
        putFile(destination->id, filename);
        listIterator = listIterator->next;
    }
    //printf("Sent file: %s\n", filename);

    return 0;
}
Beispiel #7
0
int main(int argc, char **argv){
	char *disk_image, *from_filename, *to_filename;
	FILE *fp;
	SuperBlock super_block;

	if(argc < 4){
    printf("Run like: ./diskget diskimg.img local_filename /path/to/diskimg/filename\n");
    exit(EXIT_FAILURE);
  	}

  	disk_image = argv[1];
  	from_filename = argv[2];
  	to_filename = argv[3];
  	fp = fopen(disk_image, "rb+");

	if(fp == NULL){
		fprintf(stderr,"Unable to read disk image\n");
		return -1;
	}

	fread(&super_block, sizeof(super_block), 1, fp);
	putFile(&super_block, fp, from_filename, to_filename);

	fclose(fp);
	return 0;
}
Beispiel #8
0
//Process a Request
void processRequest(char * buf){

    char token[64] = "";

    // Check Command
    if (strncmp(buf, "GET", 3) == 0) {
        //Token File Name
        printf("GET CALLED!\n");
        //Call Get Function
        strtok(buf, " ");
        strcpy(token, strtok(NULL, "\n"));
        getFile(token);
    } else if(strncmp(buf, "LIST", 4) == 0) {
        //List Call
        listFiles();
    } else if((strncmp(buf, "PUT", 3) == 0)) {
        printf("PUT Called!\n");
        if (userVerified){
            strtok(buf, " ");
            strcpy(token, strtok(NULL, "\n"));
            putFile(token);
        } else {
            printf("User not Verified! Please Enter the Corret Credentials!\n");
        }

    } else {
        printf("Unsupported Command: %s\n", buf);
        return;
    }
}
int syncAll() {
    //open current directory and send all files to all the connected peers
    DIR *d;
    struct dirent *dir;
    char *directory = "./";
    char *filename = "";
    d = opendir(directory);
    if (d != NULL) {
        while ((dir = readdir(d)) != NULL) {
            //for each file
            if (dir->d_type == DT_REG) {
                //for all peers in connectionList
                struct list *listIterator = connectionList;
                struct host *destination;
                while (listIterator != NULL) {
                    destination = (struct host *) listIterator->value;
                    //if destination is the master server do not send
                    if (masterServer != NULL && destination->sockfd == masterServer->sockfd) {
                        listIterator = listIterator->next;
                        continue;
                    }
                    filename = stringConcat(directory, dir->d_name);
                    putFile(destination->id, filename);
                    listIterator = listIterator->next;
                }
                printf("Sent file: %s\n", filename);
            }
        }
        closedir(d);
    }
    else {
        printf("Unable to open directory.\n");
    }
    return 0;
}
Beispiel #10
0
static void proc_pkt(unsigned char *pPkt, int pktLen, void *pUser)
{
	//printf("pkt len: %d\n", pktLen); return;
	struct conn_data *_data = (struct conn_data*)pUser;
	struct cmd_header *pch = (struct cmd_header*)pPkt;
	_data->cmd = pch->cmd;
	_data->total_len = pch->len;
	switch(pch->cmd)
	{
		case 'e': 
			if(pch->cls == 0)
			{
				sendResp(_data->hconn, 'e', pPkt + sizeof(struct cmd_header), pktLen - sizeof(struct cmd_header));
				fprintf(stdout, "<<<");
			}
			else
				fprintf(stdout, ">>>");
#define min(x, y) ((x)>(y)?(y):(x))
			fwrite(pPkt + sizeof(struct cmd_header), 1, min(30, pktLen-sizeof(struct cmd_header)), stdout);
			fprintf(stdout, "\n");
			break;

		case 'g':
			if(pch->cls == 0)
			{
				putFile(_data->hconn, (const char*)(pPkt + sizeof(struct cmd_header)));

				_data->cmd = _data->total_len = 0;
			}
			break;

		case 'p':
			if(pch->cls == 0)
			{
				struct ft_header *fth = (struct ft_header*)pPkt;
				_data->fp = fopen(fth->fn, "wb");
				_data->total_len -= (pktLen - sizeof(struct ft_header));
				if(_data->fp)
				{
					fwrite(fth+1, 1, pktLen - sizeof(struct ft_header), _data->fp);
					if(_data->total_len == 0) fclose(_data->fp);
				}
			}
			else
			{
				_data->total_len -= pktLen;
				if(_data->fp)
				{
					fwrite(pPkt, 1, pktLen, _data->fp);
					if(_data->total_len == 0)
					{
						fclose(_data->fp);
						_data->fp = NULL;
					}
				}
			}
			break;
	}
}
Beispiel #11
0
bool QDropboxFile::flush()
{
#ifdef QTDROPBOX_DEBUG
    qDebug() << "QDropboxFile::flush()" << endl;
#endif

    return putFile();
}
Beispiel #12
0
void Report::reportput(std::string characteristic)
{
   std::string name = path + reportName + characteristic + txtExtension;
   if (!fileExists(name)) {
      putFile(name, getAllHead() + getFinal());
   }
   else {
      putFile(name, getFinal(), std::ios_base::app);
   }
   name = mainFolder + reportName + characteristic + txtExtension;
   if (!fileExists(name)) {
      putFile(name, getAllHead() + getFinal());
   }
   else {
      putFile(name, getFinal(), std::ios_base::app);
   }
}
Beispiel #13
0
void Report::pdbput(std::string charakteristic, bool all, bool zkrychlit)
{
   std::vector<std::string> PDBs = results.getPDBs(all, zkrychlit);
   int i = 1;

   for (auto it : PDBs) {
      putFile(path + pdbName + charakteristic + /*std::to_string(i++) +*/ pdbExtension, it);
   }
}
Beispiel #14
0
// Test the low level interface
int MarketDefaultTest::Tester::testLowLevel()
{
	mStatus.message(kInfoMessage, _T("Starting testLowLevel\r\n"));

	// If we haven't created the lowlevel test file do so now
	// We can only create it once for each MAX session, because
	// we can't delete the MarketDefaults object.
	if (!file2Initialized) {
		initFileValues(&file2);
		TSTR path = getDefaultFilePath(_T("testLowLevelRead.ini"));
		DeleteFile(path);
		if (!createFile(path, &file2))
			return 1;
		file2Initialized = true;
	}

	// Get the MarketDefaults object
	MarketDefaults* dflts = GetMarketDefaults(_T("testLowLevelRead"));
	if (dflts == NULL) {
		mStatus.message(kErrorMessage, _T("Unexpected Error: Market defaults is NULL\r\n"));
		return 1;
	}

	int errors = 0;

	// Verify the values in each section and key
	errors += verifyValues(dflts, &file2);

	// This one we can do multiple times, because we are using the API
	initFileValues(&file1);
	dflts = GetMarketDefaults(_T("testLowLevelWrite"));
	if (dflts == NULL) {
		mStatus.message(kErrorMessage, _T("Unexpected Error: Market defaults is NULL\r\n"));
		return 1;
	}

	// Write the value using the API
	errors += putFile(dflts, &file1);
	// Verify that they are correct
	errors += verifyValues(dflts, &file1);
	// Remove some of the values
	removeValues(dflts, &file1);
	// Verify that they are correct
	errors += verifyValues(dflts, &file1);

	// Cleanup
	deleteFileValues(&file1);
	DeleteFile(GetMarketDefaultsFileName(_T("testLowLevelWrite")));

	mStatus.message(kInfoMessage, _T("Finished testLowLevel - %d error(s)\r\n\r\n"), errors);

	return errors;
}
int sendFile(int connectionId, char *filename) // this is include the error message that need to be sent
{
    //get the filename removing the directory names
    int filenamePartLength;
    char **filenameParts = splitString(filename, '/', &filenamePartLength);
    char *justFilename = filenameParts[filenamePartLength - 1];

    //get the destination
    struct host *destination = getHostByID(connectionList, connectionId);
    if (destination == NULL) {
        printf("Count't find connection id to send file.\n");
        return -1;
    }

    //call putfile()
    int status = putFile(connectionId, filename);
    //incase of error sent error message to requestor
    if (status == -2) {
        //unable to open file send an error message to the requester.
        char *errorMessage;
        asprintf(&errorMessage, "%s", strerror(errno));
        //printf("%s:%s:%d\n", errorMessage, strerror(errno), strlen(errorMessage));
        struct packet *pckt = packetBuilder(error, justFilename, strlen(errorMessage), errorMessage);
        char *packetString = packetDecoder(pckt);
        //printf("Packet String: %s\n", packetString);
//        printPacket(pckt);
        int bytes_sent = send(destination->sockfd, packetString, strlen(packetString), 0);
        return -2;
    }
    else if (status == -3) {
        char *errorMessage;
        asprintf(&errorMessage, "Error reading file: %s", filename);
        struct packet *pckt = packetBuilder(error, filename, strlen(errorMessage), errorMessage);
        char *packetString = packetDecoder(pckt);
        //printf("Packet String: %s\n", packetString);
        //printPacket(pckt);
        int bytes_sent = send(destination->sockfd, packetString, strlen(packetString), 0);
        return -3;
    }
    return 0;
}
Beispiel #16
0
TEST_F(PutFileTest, LocateError)
{
    putFile(INVALID_USER_ID, "/new_file_00", &PutFileTest::cbLocateError);
    putFile(NO_SUCH_USER_ID, "/new_file_01", &PutFileTest::cbLocateError);
}
Beispiel #17
0
int main(int argc, char* argv[])
{

        // args should only be the port number and the name
        // of the program running
        if (argc != 2) {
            printf("Usage Error - provide port number\n");
            exit(1);
        }

	char *port = argv[1];

        // create the ./files dir
        createSubdir();


	// getaddrinfo(): network address and service translation:
	struct addrinfo *socketaddrinfo = example_getaddrinfo(NULL, port);

	// socket(): create an endpoint for communication
	int sock = example_socket(socketaddrinfo);

	example_setsockopt(sock);
	example_bind(sock, socketaddrinfo);
	example_listen(sock, 128);
	freeaddrinfo(socketaddrinfo); // done with socketaddrinfo

	//printf("Press Ctrl+C to exit server.\n");
	//printf("Run a web browser on the same computer as you run the server and point it to:\n");
	//printf("http://127.0.0.1:%s\n", port);

	while(1)
	{
                printf("Waiting for connections...\n");
		// Get a socket for a particular incoming connection.
		int newsock = accept(sock, NULL, NULL);
		if(newsock == -1)
		{
			perror("accept(): ");
			continue; // try again if accept failed.
		}
                printf("Client connected\n");

                // Check the password of the client
                if (checkPass(newsock) == -1) {
                    printf("Incorrect password - Connection aborted\n");
                    closeSock(newsock);
                    continue;
                } else {
                    printf("Password accepted - Continuing connection\n");
                }

	        sendBytes(newsock, "You connected!\n", strlen("You connected!\n"));

                char cmd[1024];
                memset(cmd, 0, 1024);
                recvBytes(newsock, cmd, 1024);

                printf("Received command: %s\n", cmd);

                if (strcmp(cmd, "list") == 0) {
                    sendBytes(newsock, "File listing:\n", strlen("File listing:\n"));

                    // Scan the dirextory and send the file list
                    sendList(newsock);
                    continue;
                }

                if (strcmp(cmd, "get") == 0) {
                    char retBuf[1024];
                    memset(retBuf, 0, 1024);

                    // Read the name of the file
                    recvBytes(newsock, retBuf, 1024);

                    // Check if the file exists and send it
                    getFile(newsock, retBuf);
                    continue;
                }

                if (strcmp(cmd, "put") == 0) {
                    char retBuf[1024];
                    memset(retBuf, 0, 1024);

                    // Read the name of the file
                    getLine(newsock, retBuf);

                    // Check if the file exists and send it
                    putFile(newsock, retBuf);
                    continue;
                }

//		char http_body[] = "hello world";
//		char http_headers[1024];
//		snprintf(http_headers, 1024,
//		         "HTTP/1.0 200 OK\r\n"
//		         "Content-Length: %zu\r\n"
//		         "Content-Type: text/html\r\n\r\n",
//		         strlen(http_body)); // should check return value


		/* Note: send() does not guarantee that it will send all of
		 * the data that we ask it too. To reliably send data, we
		 * should inspect the return value from send() and then call
		 * send() again on any bytes did not get sent. */

		// Send the HTTP headers
		//if(send(newsock, http_headers, strlen(http_headers), 0) == -1)
		//{
		//	perror("send");
		//	close(newsock);
		//	exit(EXIT_FAILURE);
		//}

		//// Send the HTTP body
		//if(send(newsock, http_body, strlen(http_body), 0) == -1)
		//{
		//	perror("send");
		//	close(newsock);
		//	exit(EXIT_FAILURE);
		//}

		/* shutdown() (see "man 2 shutdown") can be used before
		   close(). It allows you to partially close a socket (i.e.,
		   indicate that we are done sending data but still could
		   receive). This could allow us to signal to a peer that we
		   are done sending data while still allowing us to receive
		   data. SHUT_RD will disallow reads from the socket, SHUT_WR
		   will disallow writes, and SHUT_RDWR will disallow read and
		   write. Also, unlike close(), shutdown() will affect all
		   processes that are sharing the socket---while close() only
		   affects the process that calls it. */
#if 0
		if(shutdown(newsock, SHUT_RDWR) == -1)
		{
			perror("shutdown");
			close(newsock);
			exit(EXIT_FAILURE);
		}
#endif

		closeSock(newsock);
	}
}
Beispiel #18
0
int main(int argc, char **argv)
{	

	const char *name;
	int sock = -1;
	char fin[512], fout[512];
	char cmd[512], reply[512];
	int params = -1;
	
	say ("\n%s (%s): started\n", TITLE, VERSION);
	
	if( argc == 1){
		say ("No service name passed, using default: %s\n", NAME);
		sock = initializeClient(NAME);
	} else{
		name = argv[1];
		say ("Connecting to: %s\n", name);
		sock = initializeClient(name);
	}
	usage();
	int i = 0;
	while(i<2){
		say(">>");
		cmd[0] = '\n';
		fin[0] = '\n';
		fout[0] = '\n';
		params = -1;
		
		
  		fgets(cmd, 511, stdin);

//		This is for quick testing with a couple of commands
// 		if(i==0)
// 			strcpy(cmd, "get asd asdsf\n");
// 		else if(i==1)
// 			strcpy(cmd, "put a.txt ss.txt\n");
// 		i++;
		
		
		
		if (strncmp(cmd, "get", 3) == 0){
			params = sscanf(cmd,"get %s %s", fin, fout);
			
			if(params !=2 ){
				sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
				warn(reply);
				usage();
				continue;
			}
			
			if( strcmp(fin, fout) == 0){
				warn("Since both applications write to the same folder (local case) the names should be different.\n");
				continue;
			}
			
		  	getFile(sock, s_ad, s_hid, fin, fout);
			
		}
		else if (strncmp(cmd, "put", 3) == 0){
 			params = sscanf(cmd,"put %s %s", fin, fout);


			if(params !=2 ){
				sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
				warn(reply);
				usage();
				continue;
			}

			
			if(strcmp(fin, fout) == 0){
				warn("Since both applications write to the same folder (local case) the names should be different.\n");
				continue;
			}
			if(!file_exists(fin)){
				warn("Source file: %s doesn't exist\n", fin);
				continue;
			}
				
			
			putFile(sock, my_ad, my_hid, fin, fout);
			
		}
		else{
			sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
			warn(reply);
			usage();
		}
		
	}	
	return 1;
}
Beispiel #19
0
//Starts the server and listens for connections
void Server::start(){

	//check if directory exists
	//If it doesn't , try to create the directory

	char temp[1024];

	//Get address info purposes
	struct sockaddr_storage otherAddr, otherAddr2;		//Connectors address information
	socklen_t otherAddrLen, otherAddrLen2;
	int rv;
	int i;

	//Socket purposes
	int newfd;
	int newfd2;

	//port numbers
	unsigned short dataPort;

	//Handling child processes
	struct sigaction sa;

	//Char buffers
	char buffer[DATA_SIZE];

	//String vector
	vector<string> tokens;

	//extra string(s)
	string errMsg = INVCOM;


	//Copy the string into character array
	//since chdir() takes char * as argument
	strncpy( temp, rootDir.c_str() , sizeof(temp) );
	temp[ sizeof(temp) - 1 ] = 0;

	//Check if directory is valid
	//If no directory create one
	if( !validDir(temp) ){

		if( mkdir(temp, 0777) != 0 ){
			perror("mkdir");
			exit(1);
		}

	}

	//change directory
	//call chdir()
	if(chdir(temp) != 0){
		//If chdir fails
		perror("chdir");
		exit(1);
	}

	if ( !getPWD() ){
		cout << "Unable to get cwd" << endl;
		exit(1);
	}

	//We have now changed the program's pwd to root directory 
	//Now create a socket and bind to the control port and start listening
	//for connections

	cs = controlSock = createSocket( controlPort);
	if(verbose)
		cout << "Control socket created" << endl;

	ds = dataSock = createSocket("0");
	if(verbose)
		cout << "Data socket created" << endl;

	dataPort = getPort(dataSock);

	//Now we have successfully created the socket 
	//and bound it to the control port
	//Start listening for connections
	//Entering the listening loop

	if ( listen (controlSock , BACKLOG) != 0 ) {
		perror("listen");
		close(controlSock);
		exit(1);
	}

	if( listen(dataSock , BACKLOG) != 0 ){
		perror("listen");
		close(dataSock);
		exit(1);
	}

	//handle dead processes
	sa.sa_handler = sigchldHandler;		//read all dead processes
	sigemptyset( &sa.sa_mask );
	sa.sa_flags = SA_RESTART;
	if( sigaction( SIGCHLD, &sa , NULL ) == -1 ){
		perror("sigaction");
		exit(1);
	}

	//Handle user interrupts
	signal(SIGINT, userIntHandler);

	cout << "Waiting for connections ... " << endl;

	while(1){

		otherAddrLen = sizeof ( otherAddr) ;
		newfd = accept ( controlSock , (struct sockaddr *) &otherAddr , &otherAddrLen );
		cout << "Connection from " << getIPFromAddr(&otherAddr) << ":" << getPortFromAddr(&otherAddr) << endl;
		commsock = newfd;

		send(newfd, (unsigned short *)&dataPort, 2, 0);

		otherAddrLen2 = sizeof otherAddr2;
		newfd2 = accept(dataSock, (struct sockaddr *) &otherAddr2, &otherAddrLen2 );
		datacommsock = newfd2;
		cout << "Connection to data socket from client port " << getPortFromAddr(&otherAddr2) << endl;

		if( fork() == 0 ){
			//The code in this block is executed by the child process
			close(controlSock);  //Child doesn't require the control socket
			close(dataSock);

			if(verbose){
				cout << "Closing listener sockets" << endl;
				cout << "Child process created for communication with client" << endl;
			}

			if (dup2( newfd , 0 ) != 0 ){
				perror("dup2");
				exit(1);
			}

			do{
				
				if(fgets( buffer, DATA_SIZE, stdin ) == NULL){
					close(newfd);
					exit(1);
				}

				//Remove carriage return and new line characters
				for(rv = 0; rv < DATA_SIZE ; rv++){

					if(buffer[rv] == '\r'){
						buffer[rv] = 0;
						break;
					}

					if(buffer[rv] == '\n'){
						buffer[rv] = 0;
						break;
					}
				}
				
				//Read buffer and find what command it is
				//Call the corresponding method

				string s(buffer);		//convert the character array into string
				if(verbose){
					cout << "Received command " + s << endl;
				}

				istringstream iss(s);

				//copy the tokens into the string vector
				copy( istream_iterator<string>(iss),
				 istream_iterator<string>() ,
				 back_inserter<vector<string> >(tokens) );


				//Copied the tokens into tokens
				rv = tokens.size();
				if(rv > 0){
					//If there is atleast one word
					if(tokens[0].compare("ls") == 0){
						//The client requested a file listing
						ls(s, newfd2);
					}
					else if(tokens[0].compare("quit") == 0){
						//The client closed the connection
						break;
					}
					else if(tokens[0].compare("cd") == 0){
						//The client requested a directory change
						if(rv == 2){
							cd(tokens[1], newfd2);
						}
						else{
							sendMessage( errMsg.c_str() , errMsg.length() , ERROR, NF, dataSock );
						}
					}
					else if( tokens[0].compare("pwd") == 0 ){
						//Client requested a pwd
						PWD(newfd2);
					}
					else if(tokens[0].compare("get") == 0){
						string temp="";
						for(i=1; i < rv;i++){
							temp = temp + tokens[i] + " ";
						}
						temp = temp.substr(0, temp.length()-1 );
						getFile(temp, newfd2);
					}
					else if(tokens[0].compare("put") == 0){
						string temp="";
						for(i=1; i < rv;i++){
							temp = temp + tokens[i] + " ";
						}
						temp = temp.substr(0, temp.length()-1 );
						putFile(temp, newfd2);
					}
					else{
						sendMessage( errMsg.c_str() , errMsg.length() , ERROR, NF, newfd2 );
					}
				}

				tokens.clear();		//clear the tokens

			}while (1);

			//The client closed the connection
			//So, close the socket and quit the child process
			close(newfd);		
			close(newfd2);	
			cout << "Connection closed" << endl;
			exit(1);
		}
		close(newfd);

	}

	close(controlSock);
	

}
Beispiel #20
0
TEST_F(PutFileTest, Normally)
{
    putFile(VALID_USER_ID, "/new_file_00", &PutFileTest::cbNormally);
    putFile(VALID_USER_ID, "/empty_dir_00/new_file_10", 
            &PutFileTest::cbNormally);
}
Beispiel #21
0
int main(int argc, char **argv)
{
	if(argc < 4) printUsage(argv[0]);

	p2p_server = id_bound = id_connect = NULL;
#ifdef __LINUX__
	int opt;
	while((opt = getopt(argc, argv, "s:u:c:")) != -1)
	{
		switch(opt)
		{
		case 's':
			p2p_server = optarg;
			break;
		case 'u':
			id_bound = optarg;
			break;
		case 'c':
			id_connect = optarg;
			break;
		case 'n':
			break;
		default:
			printUsage(argv[0]);
		}
	}
#elif defined(WIN32)
	int i;
	for(i=1; i<argc; i++)
	{
		if(strcmp(argv[i], "-s") == 0)
			p2p_server = argv[++i];
		else if(strcmp(argv[i], "-u") == 0)
			id_bound = argv[++i];
		else if(strcmp(argv[i], "-c") == 0)
			id_connect = argv[++i];
		else
			printUsage(argv[0]);
	}
#endif

	if(!p2p_server || (!id_bound && !id_connect)) printUsage(argv[0]);

	const char *svrs[] = { p2p_server };

	PA_NetLibInit();

	P2pCoreInitialize(svrs, 1, id_bound, &cbs);
	printf("Waiting for initialization....\n");
	PA_Sleep(2000);

	if(id_connect) connectTo(p2p_server, id_connect);

	char line[512];
	int err;
	printHelp();
	while(1)
	{
		err = 0;
		printf("Select: "); fflush(stdout);
		if(fgets(line, sizeof(line), stdin) == NULL) 
		{
			printf("EOF of stdin\n");
			break;
		}
		if(line[0] == 'q') break;
		else
		switch(line[0])
		{
		case 'h': printHelp(); break;
		case 'c': err = connectTo(p2p_server, sstrip(line+1)); break;
		case 'r': err = relayTo(p2p_server, sstrip(line+1)); break;
		case 's': printConnectionsState(); break;
		case 'g': err = getFile(g_hconn, sstrip(line+1)); break;
		case 'p': err = putFile(g_hconn, sstrip(line+1)); break;
		case 'e': echo(g_hconn, lstrip(line+1)); break;
		case 'f': flood(g_hconn, lstrip(line+1)); break;
		case 'F': flood2(g_hconn, lstrip(line+1)); break;
		default:
			if(!isspace(line[0]))
				printHelp();
			break;
		}

		if(err)
		{
			printErr(err);
		}
	}

	if(g_hconn) 
	{
		void *ptr;
		P2pConnGetUserData(g_hconn, &ptr);
		free(ptr);
		P2pConnClose(g_hconn);
	}
	P2pCoreTerminate();
	P2pCoreCleanup();

	return 0;
}
Beispiel #22
0
int main(int argc, char **argv)
{	

	const char *name;
	int sock = -1;
	char fin[512], fout[512];
	char cmd[512], reply[512];
	int params = -1;
	
	say ("\n%s (%s): started\n", TITLE, VERSION);
	
	if( argc == 1){
		say ("No service name passed, using default: %s\nYou can also pass --quick to execute a couple of default commands for quick testing. Requires s.txt to exist. \n", NAME);
		sock = initializeClient(NAME);
		usage();
	} else if (argc == 2){
		if( strcmp(argv[1], "--quick") == 0){
			quick = true;
			name=NAME;
		} else{
			name = argv[1];
			usage();
		}
		say ("Connecting to: %s\n", name);
		sock = initializeClient(name);

	} else if (argc == 3){
		if( strcmp(argv[1], "--quick") == 0 ){
			quick = true;
			name = argv[2];
			say ("Connecting to: %s\n", name);
			sock = initializeClient(name);
			usage();
		} else{
			die(-1, "xftp [--quick] [SID]");
		}
		
	} else{
		die(-1, "xftp [--quick] [SID]"); 
	}
	
	int i = 0;


	
//		This is for quick testing with a couple of commands

	while(i < NUM_PROMPTS){
		say(">>");
		cmd[0] = '\n';
		fin[0] = '\n';
		fout[0] = '\n';
		params = -1;
		
		if(quick){
			if( i==0 )
				strcpy(cmd, "put s.txt r.txt");
			else if( i==1 )
				strcpy(cmd, "get r.txt sr.txt\n");
			i++;
		}else{
			fgets(cmd, 511, stdin);
		}

//		enable this if you want to limit how many times this is done
// 		i++;
		
		if (strncmp(cmd, "get", 3) == 0){
			params = sscanf(cmd,"get %s %s", fin, fout);
			
			if(params !=2 ){
				sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
				warn(reply);
				usage();
				continue;
			}
			
			if( strcmp(fin, fout) == 0){
				warn("Since both applications write to the same folder (local case) the names should be different.\n");
				continue;
			}
			
			getFile(sock, s_ad, s_hid, fin, fout);
			
		}
		else if (strncmp(cmd, "put", 3) == 0){
			params = sscanf(cmd,"put %s %s", fin, fout);


			if(params !=2 ){
				sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
				warn(reply);
				usage();
				continue;
			}

			
			if(strcmp(fin, fout) == 0){
				warn("Since both applications write to the same folder (local case) the names should be different.\n");
				continue;
			}
			if(!file_exists(fin)){
				warn("Source file: %s doesn't exist\n", fin);
				continue;
			}
				
			
			putFile(sock, my_ad, my_hid, fin, fout);
			
		}
		else{
			sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
			warn(reply);
			usage();
		}
		
	}	
	return 1;
}
Beispiel #23
0
int main(int argc, char **argv)
{
    MLan *mlan=NULL;
    uchar serial[MLAN_SERIAL_SIZE];
    char *serial_in=NULL;
    int ch;
    int flag=NO_FLAG;
    char *cmd=NULL, *filename=NULL;

    /* save the command */
    cmd=argv[0];

    while( (ch=getopt(argc, argv, "rwde")) != -1) {
        switch(ch) {
        case 'r':
            if(flag!=NO_FLAG) {
                fprintf(stderr, "Flag already given.\n");
                usage(cmd);
            }
            flag=READ_FLAG;
            break;
        case 'w':
            if(flag!=NO_FLAG) {
                fprintf(stderr, "Flag already given.\n");
                usage(cmd);
            }
            flag=WRITE_FLAG;
            break;
        case 'd':
            if(flag!=NO_FLAG) {
                fprintf(stderr, "Flag already given.\n");
                usage(cmd);
            }
            flag=DUMP_FLAG;
            break;
        case 'e':
            if(flag!=NO_FLAG) {
                fprintf(stderr, "Flag already given.\n");
                usage(cmd);
            }
            flag=ERASE_FLAG;
            break;
        case '?':
            usage(cmd);
        }
    }

    /* Adjust the argv and argc */
    argc-=optind;
    argv+=optind;

    if(flag==NO_FLAG) {
        fprintf(stderr, "No flag given given.\n");
        usage(cmd);
    }

    if(argc<1) {
        fprintf(stderr, "Need a serial number.\n");
        exit(1);
    }
    serial_in=argv[0];

    /* Get the right stuff if we're doing a read or write operation */
    if(flag == READ_FLAG || flag == WRITE_FLAG) {
        if(argc<2) {
            fprintf(stderr, "Need a filename.\n");
            usage(cmd);
        }
        filename=argv[1];
    }

    /* mlan=mlan_init(dev, PARMSET_9600); */
    mlan=mlan_init(mlan_get_port(), PARMSET_115200);

    assert(mlan);
    mlan->debug=0;

    mlan->parseSerial(mlan, serial_in, serial);

    if(mlan->ds2480detect(mlan)!=TRUE) {
        fprintf(stderr, "Found no DS2480\n");
        exit(-1);
    }

    /* Was there a file argument? */
    if(flag==WRITE_FLAG) {
        printf("Writing...");
        fflush(stdout);
        putFile(mlan, serial, filename);
        printf("done.\n");
    } else if(flag==READ_FLAG) {
        printf("Reading...");
        fflush(stdout);
        getFile(mlan, serial, filename);
        printf("done.\n");
    } else if(flag==DUMP_FLAG) {
        dumpData(mlan, serial);
    } else if(flag==ERASE_FLAG) {
        printf("Erasing...");
        fflush(stdout);
        erase(mlan, serial);
        printf("done.\n");
    } else {
        printf("How did you get here?\n");
    }

    mlan->destroy(mlan);

    exit(0);
}
Beispiel #24
0
int
rcDataObjPut( rcComm_t *conn, dataObjInp_t *dataObjInp, char *locFilePath ) {
    int status;
    portalOprOut_t *portalOprOut = NULL;
    bytesBuf_t dataObjInpBBuf;

    if ( dataObjInp->dataSize <= 0 ) {
        dataObjInp->dataSize = getFileSize( locFilePath );
        if ( dataObjInp->dataSize < 0 ) {
            return USER_FILE_DOES_NOT_EXIST;
        }
    }

    memset( &conn->transStat, 0, sizeof( transStat_t ) );
    memset( &dataObjInpBBuf, 0, sizeof( dataObjInpBBuf ) );

    rodsEnv env;
    getRodsEnv( &env );
    int single_buff_sz = env.irodsMaxSizeForSingleBuffer * 1024 * 1024;
    if ( getValByKey( &dataObjInp->condInput, DATA_INCLUDED_KW ) != NULL ) {
        if ( dataObjInp->dataSize > single_buff_sz ) {
            rmKeyVal( &dataObjInp->condInput, DATA_INCLUDED_KW );
        }
        else {
            status = fillBBufWithFile( conn, &dataObjInpBBuf, locFilePath,
                                       dataObjInp->dataSize );
            if ( status < 0 ) {
                rodsLog( LOG_NOTICE,
                         "rcDataObjPut: fileBBufWithFile error for %s", locFilePath );
                return status;
            }
        }
    }
    else if ( dataObjInp->dataSize < single_buff_sz ) {
        addKeyVal( &dataObjInp->condInput, DATA_INCLUDED_KW, "" );
        status = fillBBufWithFile( conn, &dataObjInpBBuf, locFilePath,
                                   dataObjInp->dataSize );
        if ( status < 0 ) {
            rodsLog( LOG_NOTICE,
                     "rcDataObjPut: fileBBufWithFile error for %s", locFilePath );
            return status;
        }
    }

    dataObjInp->oprType = PUT_OPR;

    status = _rcDataObjPut( conn, dataObjInp, &dataObjInpBBuf, &portalOprOut );

    clearBBuf( &dataObjInpBBuf );

    if ( status < 0 ||
            getValByKey( &dataObjInp->condInput, DATA_INCLUDED_KW ) != NULL ) {
        if ( portalOprOut != NULL ) {
            free( portalOprOut );
        }
        return status;
    }

    if ( portalOprOut->numThreads <= 0 ) {
        status = putFile( conn, portalOprOut->l1descInx,
                          locFilePath, dataObjInp->objPath, dataObjInp->dataSize );
    }
    else if ( getUdpPortFromPortList( &portalOprOut->portList ) != 0 ) {
        int veryVerbose;
        /* rbudp transfer */
        /* some sanity check */
        if ( portalOprOut->numThreads != 1 ) {
            rcOprComplete( conn, SYS_INVALID_PORTAL_OPR );
            free( portalOprOut );
            return SYS_INVALID_PORTAL_OPR;
        }
        conn->transStat.numThreads = portalOprOut->numThreads;
        if ( getValByKey( &dataObjInp->condInput, VERY_VERBOSE_KW ) != NULL ) {
            printf( "From server: NumThreads=%d, addr:%s, port:%d, cookie=%d\n",
                    portalOprOut->numThreads, portalOprOut->portList.hostAddr,
                    portalOprOut->portList.portNum, portalOprOut->portList.cookie );
            veryVerbose = 2;
        }
        else {
            veryVerbose = 0;
        }

        if ( irods::CS_NEG_USE_SSL == conn->negotiation_results ) {
            // =-=-=-=-=-=-=-
            // if a secret has been negotiated then we must be using
            // encryption.  given that RBUDP is not supported in an
            // encrypted capacity this is considered an error
            rodsLog(
                LOG_ERROR,
                "putFileToPortal: Encryption is not supported with RBUDP" );
            return SYS_INVALID_PORTAL_OPR;

        }
        else {
            status = putFileToPortalRbudp(
                         portalOprOut,
                         locFilePath,
                         -1,
                         veryVerbose,
                         0, 0 );
        }
    }
    else {
        if ( getValByKey( &dataObjInp->condInput, VERY_VERBOSE_KW ) != NULL ) {
            printf( "From server: NumThreads=%d, addr:%s, port:%d, cookie=%d\n",
                    portalOprOut->numThreads, portalOprOut->portList.hostAddr,
                    portalOprOut->portList.portNum, portalOprOut->portList.cookie );
        }
        /* some sanity check */
        rodsEnv env;
        getRodsEnv( &env );
        if ( portalOprOut->numThreads >= 20 * env.irodsDefaultNumberTransferThreads ) {
            rcOprComplete( conn, SYS_INVALID_PORTAL_OPR );
            free( portalOprOut );
            return SYS_INVALID_PORTAL_OPR;
        }

        conn->transStat.numThreads = portalOprOut->numThreads;
        status = putFileToPortal( conn, portalOprOut, locFilePath,
                                  dataObjInp->objPath, dataObjInp->dataSize );
    }

    /* just send a complete msg */
    if ( status < 0 ) {
        rcOprComplete( conn, status );
    }
    else {
        status = rcOprComplete( conn, portalOprOut->l1descInx );
    }
    free( portalOprOut );

    if ( status >= 0 && conn->fileRestart.info.numSeg > 0 ) { /* file restart */
        clearLfRestartFile( &conn->fileRestart );
    }

    return status;
}