Esempio n. 1
0
//Receive a file from File Client
bool CFileServer::ReceiveFileFromClient()
{
	try
	{
		SendMessage(m_hWnd, WM_SETRECEIVE, 1, 0);
		State fstate;
		fstate = State::Receiving;
		SendMessage(m_hWnd, WM_SETLISTITEM, 0, (LPARAM)&fstate);

		CString DestFileName(m_strReceivePath);
		if(DestFileName.GetAt(DestFileName.GetLength()-1) != '\\')
			DestFileName += "\\";
		//DestFileName += fileInfo.FileName;
		DestFileName += m_strRecFileName;
		ULONGLONG ullSize = 0;
		if (gl_mapllSize.find(m_hWnd) != gl_mapllSize.end())
		{
			ullSize = gl_mapllSize[m_hWnd];
		}
		FileState state = ReceiveFile(m_pServerSocket->GetWorkingSocket(), m_hWnd, DestFileName, ullSize);
		if (gl_pLogger) gl_pLogger->log_info("ReceiveFile return %d", state);
		return ::ProcessState(state, m_hWnd, false);
	}
	catch(...)
	{
		if (gl_pLogger)
			gl_pLogger->log_info("CFileServer::ReceiveFileFromClient() unkown exception.");
	}
	return false;
}
Esempio n. 2
0
void TCPClient::DownloadFile(string fileName)
{
	auto file = new fstream();
	OpenFile(file, GetLocalFileName(fileName));
	fpos_t currentProgress = file->tellp();
	fpos_t fileSize = 0;

	auto done = false;
	cout << "Download started." << endl;
	while (!done)
	{
		try {
			SendMessage(this->_tcp_socket, CreateFileInfo(fileName, currentProgress));
			fileSize = ReceiveFileSize();
			ReceiveFile(file, currentProgress, fileSize);
			done = true;
		}
		catch (ConnectionInterrupted e) {
			currentProgress = e.GetProgress();
			Reconnect();
		}
		catch (ServerError) {
			file->close();
			throw;
		}
		catch (runtime_error e) {
			cout << e.what() << endl;
			Reconnect();
		}
	}
	file->close();
	cout << "Done." << endl;
}
Esempio n. 3
0
int main(int argc, char ** argv)
{
   if (argc < 4) UsageExit();

#ifdef WIN32
   // Windows requires this to start up the networking API
   WORD versionWanted = MAKEWORD(1, 1);
   WSADATA wsaData;
   (void) WSAStartup(versionWanted, &wsaData);
#else 
   // avoid SIGPIPE signals caused by sending on a closed socket
   signal(SIGPIPE, SIG_IGN);
#endif

   bool isSend = false;
        if (strcmp(argv[1], "send")    == 0) isSend = true;
   else if (strcmp(argv[1], "receive") != 0) UsageExit();

   const char * fileName = argv[2];

   ip_address ip = isSend ? GetHostByName(argv[3]) : 0;
   uint16 port = 0;
   const char * portColon = strchr(argv[3], ':');
   port = portColon ? atoi(portColon+1) : 0;
   if (port == 0) port = 9999;

   if (isSend) SendFile(ip, port, fileName);
          else ReceiveFile(port, fileName);

   printf("Exiting, bye!\n");
   return 0;
}
void HomebrewReceiver::CheckIncoming()
{
	if(!IsNetworkInit())
		return;
	
	if (GetCheckIncomming() && !loaded)
	{
		ResumeNetworkWait();
		loaded = true;
	}
	
	if (infilesize > 0 && loaded)
	{
		if (ReceiveFile() != 0)
			return;
		CloseConnection();
		ResumeNetworkWait();
	}
}
Esempio n. 5
0
int FileTransfer(int domid, int port, char *fileName, char *operation, int connect)
{
    int returnValue = false;
    int connection = 0;
    BounceType bounceType = 0;

    printf("%s begin.\n", __FUNCTION__);

    bounceType = WorkOutBounceType(operation);
    //Let's start listening for our socket.
    if (!connect)
        connection = WaitForIncomingConnection(port, domid);
    else
        connection = ConnectionToRemote(port, domid);

    if (connection > 0)
    {
	printf("We are connected... Now can do data transfer\n");
	if (!strcmp(OPERATION_RECEIVE, operation))
	{
	    printf("Now going to receive file to %s\n", fileName);
	    ReceiveFile(connection, fileName);
	}
	else if (!strcmp(OPERATION_SEND, operation))
	{
	    printf("Now going to send file to %s\n", fileName);
	    SendFile(connection, fileName);
	}
	else if (!strncmp(OPERATION_BOUNCE_BASE, operation, OPERATION_BOUNCE_BASE_LENGTH))
	{
	    printf("Now going to bounce data with other side\n");
	    BounceData(connection, bounceType);
	}
    }

    CloseConnection(connection);

    printf("%s end. return %d.\n", __FUNCTION__, returnValue);
    return returnValue;

}
Esempio n. 6
0
/**
* ReceiveFolder
*
* Description: Download a folder and all of its contents to the local store.
*
* Param: con - describes the ftp server to connect to.
*		 file - describes the folder path + (folder)name to download.
*		 waitDialog - notification recipient.
*
* Return: bool - TODO...
*/
bool CFtpManager::ReceiveFolder(CConnection * con, CFileContainer & file, CWaitDialog & waitDialog) 
{
	bool result = false;
	
	CString localStorePath;
	GetLocalStorePath(con, localStorePath); // could always use file.localPath
	
	CString localStoreFolder = localStorePath + CString(file.path + file.name) + _T("\\");
	localStoreFolder.Replace('/', '\\');

	// Check
	if(file.dir == false)
	{
		return false;
	}

	// Create local folder
	WIN32_FIND_DATA  data; 
	//HANDLE handle = FindFirstFile(localStoreFolder, &data); 
	//if ( handle == INVALID_HANDLE_VALUE )
	if( GetFileAttributes(localStoreFolder) == INVALID_FILE_ATTRIBUTES )
	{
		int i = 0;
		CreateDirectory(localStoreFolder, NULL);
	}

	CFtpManager ftp;
	std::vector<CFileContainer> files;
	bool r = ftp.ReadLocalDirectory(con, CString(file.path + file.name + _T("/")) , files);
	if(r == false) // directory information not present.
	{
		GetFtpDirectory(con, CString(file.path + file.name + _T("/")), NULL);
		ftp.ReadLocalDirectory(con, CString(file.path + file.name + _T("/")) , files);
	}

	int i = 0;
	for(i = 0; i < files.size(); i++)
	{
		CFileContainer f;
		f = (CFileContainer)files[i];

		if(f.dir)
		{

			ReceiveFolder(con, f, waitDialog);
		}
		else 
		{
			// does the file exist, and is it current?
			bool download = false;
			CString localFile(localStorePath + f.path + f.name);
			localFile.Replace('/', '\\');
			if ( 0xFFFFFFFF == GetFileAttributes ( localFile ) && GetLastError() == ERROR_FILE_NOT_FOUND )
			{
				download = true;
			}

			if(download)
			{
				ReceiveFile(con, f, waitDialog);
			}
		}
	}
	return result;
}
Esempio n. 7
0
int main(int argc, char *argv[]) {
	FILE *fp, *out;
	char line[256];
	struct input_t * doc = (struct input_t *) malloc(sizeof(struct input_t));

	char *line_pointer;

	int line_already_counted;
	int multi_line_comment;
	int total_lines;
	int lines_of_code;
	int code, port = 0;
	int list_s; /*  listening socket          */
	int conn_s; /*  connection socket         */
	char * szPort = SERVER_PORT;

	unsigned char i;

	char * input_name = NULL;
	char * output_name = NULL;
	uint16_t len;

	struct sockaddr_in sin;

	//input_t * doc;
	int opts = 1;

	extern char *optarg;
	extern int optind;

	for (;;) {
		int c = getopt(argc, argv, "hp:o:");
		if (c == -1)
			break;
		switch (c) {
		case 'h':
			usage(argv[0]);
			return 0;
		case 'o':
			output_name = optarg;
			break;
		case 'p':
			szPort = optarg;
			break;
		}
	}

	/* SMC - avoid NULL deref if output name isn't provided. */
	if (output_name == NULL) {
		fprintf(stderr, "No output file specified with -o option\n");
		exit(EXIT_FAILURE);
	}

	if ((port = atoi(szPort)) == 0) {
		fprintf(stderr, "Error reading port value with -p option\n");
		exit(EXIT_FAILURE);
	}

	/*Initialize socket values*/
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(port);

	/*Create server listening socket*/
	if ((list_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
		fprintf(stderr, "socket failed with error\n");
		exit(EXIT_FAILURE);
	}

	/*Allow this port to be reused*/
	if (setsockopt(list_s, SOL_SOCKET, SO_REUSEADDR, (char *) &opts,
			sizeof(opts)) < 0) {
		fprintf(stderr, "setsockopt failed with error\n");
		exit(EXIT_FAILURE);
	}

	/*Bind to the specified port and address*/
	if (bind(list_s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		fprintf(stderr, "bind failed with an error\n");
		perror("ERROR");
		exit(EXIT_FAILURE);
	}

	/*Listen for incoming connections*/
	if (listen(list_s, LISTENQ) < 0) {
		fprintf(stderr, "listen failed with error\n");
		exit(EXIT_FAILURE);
	}

	fprintf(stderr, "Socket created.  Ready to accept on port %d.\n", port);
	fflush(stderr);

	fprintf(stderr, "WAVESRV: waiting for a connection\n");
	fflush(stderr);

	/*  Wait for a connection, then accept() it  */

	if ((conn_s = accept(list_s, NULL, NULL)) < 0) {
		fprintf(stderr, "ECHOSERV: Error calling accept()\n");
		exit(EXIT_FAILURE);
	}

	fprintf(stderr, "WAVESRV: Connected!\n");
	fflush(stderr);

	/*  Retrieve an input line from the connected socket
	 then simply write it back to the same socket.     */
	doc = ReceiveFile(conn_s); // STONESOUP:DATA_FLOW:ADDRESS_AS_A_FUNCTION_RETURN_VALUE

	/*  Close the connected socket  */

	if (close(conn_s) < 0) {
		fprintf(stderr, "WAVESRV: Error calling close()\n");
		exit(EXIT_FAILURE);
	}

	if (doc == NULL) {
		fprintf(stderr, "No valid document received\n");
		exit(EXIT_FAILURE);
	}

	// Open the output file.

	//fp = openFile(input_name, "r");
	out = openFile(output_name, "w+");


	// After initializing variables, loop through each line of the file using fgets().  The function
	// fgets(str, num, fp) reads up to num - 1 characters from the file stream fp and dumps them
	// into str. fgets() will stop when it reaches the end of a line, in which case str will be
	// terminated with a newline. If fgets() reaches num - 1 characters or encounters the EOF,
	// str will be null-terminated. fgets() returns str on success, and NULL on an error.

	multi_line_comment = 0;
	total_lines = 0;
	lines_of_code = 0;

	memset(line, '\0', 256);

	for (; doc != NULL; doc = (struct input_t *) doc->next_line) {
		strcpy(line, doc->data);
		total_lines++;

		// We are reading a new line so we need to reset the line_already_counted flag since
		// it obviously hasn't been counted yet.

		line_already_counted = 0;

		// Since fgets() may terminate a string with a newline ... we need to strip any trailing
		// '\n' and replace it with a NULL character.

		if (line[strlen(line) - 1] == '\n')
			line[strlen(line) - 1] = '\0';

		// Set the line_pointer to the first character of the line.

		line_pointer = line;

		// We are now ready to parse the line character by character.

		while (*line_pointer != '\0') {
			// If we are currently in a multi line scenario, then we need to check if we have hit
			// an end tag.  Otherwise we just advance the pointer and keep looping.

			if (multi_line_comment == 1) {
				if (*line_pointer == '*') {
					// Advance the line_pointer.  We need to check for the NULL character
					// and break if found. If we don't do this, then the next line_pointer++
					//call (before the start of the next iteration) will advance us out of bounds.

					line_pointer++;
					if (*line_pointer == '\0')
						break;

					if (*line_pointer == '/') {
						// An end tag has been found!  Reset the multi_line_comment.
						// Note that we still need to advance the pointer and continue
						// the loop.

						multi_line_comment = 0;
					}
				}

				line_pointer++;
				continue;
			}

			// If the current character is a whitespace, then skip it and continue the loop
			// inorder to examine the next character.

			if (isspace(*line_pointer) != 0) {
				line_pointer++;
				continue;
			}

			// If the current character is a slash, then we need to look at the following
			// character to see if the line is a Java comment.  If we are looking at a Java
			// comment line, then just break out of the loop without incrementing the
			// line counter.

			if (*line_pointer == '/') {
				// Advance the line_pointer.  We need to check for the NULL character
				// and break if found. If we don't do this, then the next line_pointer++
				//call (before the start of the next iteration) will advance us out of bounds.

				line_pointer++;
				if (*line_pointer == '\0')
					break;

				// If the next character is a slash as well, then a single line comment has
				// been found.  The rest of this line is not code, so break out of this loop.

				if (*line_pointer == '/')
					break;

				// If the next character is an asterisk, then a multi-line comment has been
				// found.  We now need to skip every line until the end of the comment. To
				// do this, we will turn on the multi_line_comment flag and continue
				// processing this line (and any following line) looking for the closing tag.
				//Note that the end of the comment may contain code on the rest of the
				// line after the closing comment tag.

				if (*line_pointer == '*') {
					multi_line_comment = 1;
					line_pointer++;
					continue;
				}

				// Note that if we reach here, a Java comment was NOT found, so we should
				// fall through to the default processing and count the current line as a
				// valid line of code.
			}

			// A line of Java code has been found!  If the line has not already been counted, then
			// increment the line counter.

			if (line_already_counted == 0) {
				if (DEBUG)
					printf("DEBUG: %s\n", line_pointer);
				lines_of_code++;
				line_already_counted = 1;
				len = istrlen(line) + 1;
				char * lineout = (char *) malloc(len);
				memcpy(lineout, line, len);
				printf("3\n");
				strcat(lineout, "\n");
				fputs(lineout, out);
			}

			// copy this line to the output


			// Move the line pointer to the next character in the line so that the next
			// iteration of the current loop doesn't try to process the same character.

			line_pointer++;
		}
	}

	// We are done with the file so close it.

	if (fclose(out)) {
		printf("\nERROR: File close error.\n");
		return (EXIT_FAILURE);
	}

	// We have finished looking at each line in the file, and now have the line count.  So print it!!

	if (DEBUG)
		printf(
				"\nDEBUG: The file '%s' contains %d total lines, of which %d are code.\n\n",
				input_name, total_lines, lines_of_code);
	printf("\nRESULT: %d", lines_of_code);

	return (EXIT_SUCCESS);
}